Accept requested formats to be in the format 35/best (closes #1552)
[youtube-dl] / youtube_dl / YoutubeDL.py
index 829a70ec929af547c01f37436d5033dabbe25b72..bc69214e75e5bf98eb9e3abc07d64b6d729fb970 100644 (file)
@@ -71,6 +71,7 @@ class YoutubeDL(object):
     logtostderr:       Log messages to stderr instead of stdout.
     writedescription:  Write the video description to a .description file
     writeinfojson:     Write the video description to a .info.json file
+    writeannotations:  Write the video annotations to a .annotations.xml file
     writethumbnail:    Write the thumbnail image to a file
     writesubtitles:    Write the video subtitles to a file
     writeautomaticsub: Write the automatic subtitles to a file
@@ -258,6 +259,10 @@ class YoutubeDL(object):
         """ Report that the metadata file has been written """
         self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
 
+    def report_writeannotations(self, annofn):
+        """ Report that the annotations file has been written. """
+        self.to_screen(u'[info] Writing video annotations to: ' + annofn)
+
     def report_file_already_downloaded(self, file_name):
         """Report file has already been fully downloaded."""
         try:
@@ -443,6 +448,17 @@ class YoutubeDL(object):
         else:
             raise Exception('Invalid result type: %s' % result_type)
 
+    def select_format(self, format_spec, available_formats):
+        if format_spec == 'best' or format_spec is None:
+            return available_formats[-1]
+        elif format_spec == 'worst':
+            return available_formats[0]
+        else:
+            matches = list(filter(lambda f:f['format_id'] == format_spec ,available_formats))
+            if matches:
+                return matches[-1]
+        return None
+
     def process_video_result(self, info_dict, download=True):
         assert info_dict.get('_type', 'video') == 'video'
 
@@ -472,10 +488,10 @@ class YoutubeDL(object):
                     else:
                         format_desc = u'%sp' % format['height']
                 else:
-                    format_desc = compat_str(i)
+                    format_desc = '???'
                 format['format'] = format_desc
             if format.get('format_id') is None:
-                format['format_id'] = '???'
+                format['format_id'] = compat_str(i)
 
         if self.params.get('listformats', None):
             self.list_formats(info_dict)
@@ -483,25 +499,34 @@ class YoutubeDL(object):
 
         format_limit = self.params.get('format_limit', None)
         if format_limit:
-            formats = [f for f in formats if f['format_id'] <= format_limit]
+            formats = list(takewhile_inclusive(
+                lambda f: f['format_id'] != format_limit, formats
+            ))
+        if self.params.get('prefer_free_formats'):
+            def _free_formats_key(f):
+                try:
+                    ext_ord = [u'flv', u'mp4', u'webm'].index(f['ext'])
+                except ValueError:
+                    ext_ord = -1
+                # We only compare the extension if they have the same height and width
+                return (f.get('height'), f.get('width'), ext_ord)
+            formats = sorted(formats, key=_free_formats_key)
 
         req_format = self.params.get('format', 'best')
+        if req_format is None:
+            req_format = 'best'
         formats_to_download = []
-        if req_format == 'best' or req_format is None:
-            formats_to_download = [formats[-1]]
-        elif req_format == 'worst':
-            formats_to_download = [formats[0]]
         # The -1 is for supporting YoutubeIE
-        elif req_format in ('-1', 'all'):
+        if req_format in ('-1', 'all'):
             formats_to_download = formats
         else:
-            # We can accept formats requestd in the format: 34/10/5, we pick
-            # the first that is availble, starting from left
+            # We can accept formats requestd in the format: 34/5/best, we pick
+            # the first that is available, starting from left
             req_formats = req_format.split('/')
             for rf in req_formats:
-                matches = filter(lambda f:f['format_id'] == rf ,formats)
-                if matches:
-                    formats_to_download = [matches[0]]
+                selected_format = self.select_format(rf, formats)
+                if selected_format is not None:
+                    formats_to_download = [selected_format]
                     break
         if not formats_to_download:
             raise ExtractorError(u'requested format not available')
@@ -590,6 +615,18 @@ class YoutubeDL(object):
                 self.report_error(u'Cannot write description file ' + descfn)
                 return
 
+        if self.params.get('writeannotations', False):
+            try:
+               annofn = filename + u'.annotations.xml'
+               self.report_writeannotations(annofn)
+               with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
+                   annofile.write(info_dict['annotations'])
+            except (KeyError, TypeError):
+                self.report_warning(u'There are no annotations to write.')
+            except (OSError, IOError):
+                 self.report_error(u'Cannot write annotations file: ' + annofn)
+                 return
+
         subtitles_are_requested = any([self.params.get('writesubtitles', False),
                                        self.params.get('writeautomaticsub')])