]>
Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/f4m.py
   1 from __future__ 
import unicode_literals
 
   8 import xml
.etree
.ElementTree 
as etree
 
  10 from .common 
import FileDownloader
 
  11 from .http 
import HttpFD
 
  12 from ..compat 
import ( 
  25 class FlvReader(io
.BytesIO
): 
  28     The file format is documented in https://www.adobe.com/devnet/f4v.html 
  31     # Utility functions for reading numbers and strings 
  32     def read_unsigned_long_long(self
): 
  33         return struct_unpack('!Q', self
.read(8))[0] 
  35     def read_unsigned_int(self
): 
  36         return struct_unpack('!I', self
.read(4))[0] 
  38     def read_unsigned_char(self
): 
  39         return struct_unpack('!B', self
.read(1))[0] 
  41     def read_string(self
): 
  50     def read_box_info(self
): 
  52         Read a box and return the info as a tuple: (box_size, box_type, box_data) 
  54         real_size 
= size 
= self
.read_unsigned_int() 
  55         box_type 
= self
.read(4) 
  58             real_size 
= self
.read_unsigned_long_long() 
  60         return real_size
, box_type
, self
.read(real_size 
- header_end
) 
  64         self
.read_unsigned_char() 
  67         quality_entry_count 
= self
.read_unsigned_char() 
  69         for i 
in range(quality_entry_count
): 
  72         segment_run_count 
= self
.read_unsigned_int() 
  74         for i 
in range(segment_run_count
): 
  75             first_segment 
= self
.read_unsigned_int() 
  76             fragments_per_segment 
= self
.read_unsigned_int() 
  77             segments
.append((first_segment
, fragments_per_segment
)) 
  80             'segment_run': segments
, 
  85         self
.read_unsigned_char() 
  89         self
.read_unsigned_int() 
  91         quality_entry_count 
= self
.read_unsigned_char() 
  92         # QualitySegmentUrlModifiers 
  93         for i 
in range(quality_entry_count
): 
  96         fragments_count 
= self
.read_unsigned_int() 
  98         for i 
in range(fragments_count
): 
  99             first 
= self
.read_unsigned_int() 
 100             first_ts 
= self
.read_unsigned_long_long() 
 101             duration 
= self
.read_unsigned_int() 
 103                 discontinuity_indicator 
= self
.read_unsigned_char() 
 105                 discontinuity_indicator 
= None 
 109                 'duration': duration
, 
 110                 'discontinuity_indicator': discontinuity_indicator
, 
 114             'fragments': fragments
, 
 119         self
.read_unsigned_char() 
 123         self
.read_unsigned_int()  # BootstrapinfoVersion 
 124         # Profile,Live,Update,Reserved 
 127         self
.read_unsigned_int() 
 129         self
.read_unsigned_long_long() 
 130         # SmpteTimeCodeOffset 
 131         self
.read_unsigned_long_long() 
 133         self
.read_string()  # MovieIdentifier 
 134         server_count 
= self
.read_unsigned_char() 
 136         for i 
in range(server_count
): 
 138         quality_count 
= self
.read_unsigned_char() 
 140         for i 
in range(quality_count
): 
 147         segments_count 
= self
.read_unsigned_char() 
 149         for i 
in range(segments_count
): 
 150             box_size
, box_type
, box_data 
= self
.read_box_info() 
 151             assert box_type 
== b
'asrt' 
 152             segment 
= FlvReader(box_data
).read_asrt() 
 153             segments
.append(segment
) 
 154         fragments_run_count 
= self
.read_unsigned_char() 
 156         for i 
in range(fragments_run_count
): 
 157             box_size
, box_type
, box_data 
= self
.read_box_info() 
 158             assert box_type 
== b
'afrt' 
 159             fragments
.append(FlvReader(box_data
).read_afrt()) 
 162             'segments': segments
, 
 163             'fragments': fragments
, 
 166     def read_bootstrap_info(self
): 
 167         total_size
, box_type
, box_data 
= self
.read_box_info() 
 168         assert box_type 
== b
'abst' 
 169         return FlvReader(box_data
).read_abst() 
 172 def read_bootstrap_info(bootstrap_bytes
): 
 173     return FlvReader(bootstrap_bytes
).read_bootstrap_info() 
 176 def build_fragments_list(boot_info
): 
 177     """ Return a list of (segment, fragment) for each fragment in the video """ 
 179     segment_run_table 
= boot_info
['segments'][0] 
 180     # I've only found videos with one segment 
 181     segment_run_entry 
= segment_run_table
['segment_run'][0] 
 182     n_frags 
= segment_run_entry
[1] 
 183     fragment_run_entry_table 
= boot_info
['fragments'][0]['fragments'] 
 184     first_frag_number 
= fragment_run_entry_table
[0]['first'] 
 185     for (i
, frag_number
) in zip(range(1, n_frags 
+ 1), itertools
.count(first_frag_number
)): 
 186         res
.append((1, frag_number
)) 
 190 def write_unsigned_int(stream
, val
): 
 191     stream
.write(struct_pack('!I', val
)) 
 194 def write_unsigned_int_24(stream
, val
): 
 195     stream
.write(struct_pack('!I', val
)[1:]) 
 198 def write_flv_header(stream
): 
 199     """Writes the FLV header to stream""" 
 201     stream
.write(b
'FLV\x01') 
 202     stream
.write(b
'\x05') 
 203     stream
.write(b
'\x00\x00\x00\x09') 
 204     stream
.write(b
'\x00\x00\x00\x00') 
 207 def write_metadata_tag(stream
, metadata
): 
 208     """Writes optional metadata tag to stream""" 
 210     FLV_TAG_HEADER_LEN 
= 11 
 213         stream
.write(SCRIPT_TAG
) 
 214         write_unsigned_int_24(stream
, len(metadata
)) 
 215         stream
.write(b
'\x00\x00\x00\x00\x00\x00\x00') 
 216         stream
.write(metadata
) 
 217         write_unsigned_int(stream
, FLV_TAG_HEADER_LEN 
+ len(metadata
)) 
 221     return '{http://ns.adobe.com/f4m/1.0}%s' % prop
 
 224 class HttpQuietDownloader(HttpFD
): 
 225     def to_screen(self
, *args
, **kargs
): 
 229 class F4mFD(FileDownloader
): 
 231     A downloader for f4m manifests or AdobeHDS. 
 234     def real_download(self
, filename
, info_dict
): 
 235         man_url 
= info_dict
['url'] 
 236         requested_bitrate 
= info_dict
.get('tbr') 
 237         self
.to_screen('[download] Downloading f4m manifest') 
 238         manifest 
= self
.ydl
.urlopen(man_url
).read() 
 239         self
.report_destination(filename
) 
 240         http_dl 
= HttpQuietDownloader( 
 246                 'ratelimit': self
.params
.get('ratelimit', None), 
 247                 'test': self
.params
.get('test', False), 
 251         doc 
= etree
.fromstring(manifest
) 
 252         formats 
= [(int(f
.attrib
.get('bitrate', -1)), f
) for f 
in doc
.findall(_add_ns('media'))] 
 253         if requested_bitrate 
is None: 
 254             # get the best format 
 255             formats 
= sorted(formats
, key
=lambda f
: f
[0]) 
 256             rate
, media 
= formats
[-1] 
 258             rate
, media 
= list(filter( 
 259                 lambda f
: int(f
[0]) == requested_bitrate
, formats
))[0] 
 261         base_url 
= compat_urlparse
.urljoin(man_url
, media
.attrib
['url']) 
 262         bootstrap_node 
= doc
.find(_add_ns('bootstrapInfo')) 
 263         if bootstrap_node
.text 
is None: 
 264             bootstrap_url 
= compat_urlparse
.urljoin( 
 265                 base_url
, bootstrap_node
.attrib
['url']) 
 266             bootstrap 
= self
.ydl
.urlopen(bootstrap_url
).read() 
 268             bootstrap 
= base64
.b64decode(bootstrap_node
.text
) 
 269         metadata_node 
= media
.find(_add_ns('metadata')) 
 270         if metadata_node 
is not None: 
 271             metadata 
= base64
.b64decode(metadata_node
.text
) 
 274         boot_info 
= read_bootstrap_info(bootstrap
) 
 276         fragments_list 
= build_fragments_list(boot_info
) 
 277         if self
.params
.get('test', False): 
 278             # We only download the first fragment 
 279             fragments_list 
= fragments_list
[:1] 
 280         total_frags 
= len(fragments_list
) 
 281         # For some akamai manifests we'll need to add a query to the fragment url 
 282         akamai_pv 
= xpath_text(doc
, _add_ns('pv-2.0')) 
 284         tmpfilename 
= self
.temp_name(filename
) 
 285         (dest_stream
, tmpfilename
) = sanitize_open(tmpfilename
, 'wb') 
 286         write_flv_header(dest_stream
) 
 287         write_metadata_tag(dest_stream
, metadata
) 
 289         # This dict stores the download progress, it's updated by the progress 
 292             'downloaded_bytes': 0, 
 297         def frag_progress_hook(status
): 
 298             frag_total_bytes 
= status
.get('total_bytes', 0) 
 299             estimated_size 
= (state
['downloaded_bytes'] + 
 300                               (total_frags 
- state
['frag_counter']) * frag_total_bytes
) 
 301             if status
['status'] == 'finished': 
 302                 state
['downloaded_bytes'] += frag_total_bytes
 
 303                 state
['frag_counter'] += 1 
 304                 progress 
= self
.calc_percent(state
['frag_counter'], total_frags
) 
 305                 byte_counter 
= state
['downloaded_bytes'] 
 307                 frag_downloaded_bytes 
= status
['downloaded_bytes'] 
 308                 byte_counter 
= state
['downloaded_bytes'] + frag_downloaded_bytes
 
 309                 frag_progress 
= self
.calc_percent(frag_downloaded_bytes
, 
 311                 progress 
= self
.calc_percent(state
['frag_counter'], total_frags
) 
 312                 progress 
+= frag_progress 
/ float(total_frags
) 
 314             eta 
= self
.calc_eta(start
, time
.time(), estimated_size
, byte_counter
) 
 315             self
.report_progress(progress
, format_bytes(estimated_size
), 
 316                                  status
.get('speed'), eta
) 
 317         http_dl
.add_progress_hook(frag_progress_hook
) 
 320         for (seg_i
, frag_i
) in fragments_list
: 
 321             name 
= 'Seg%d-Frag%d' % (seg_i
, frag_i
) 
 322             url 
= base_url 
+ name
 
 324                 url 
+= '?' + akamai_pv
.strip(';') 
 325             frag_filename 
= '%s-%s' % (tmpfilename
, name
) 
 326             success 
= http_dl
.download(frag_filename
, {'url': url
}) 
 329             with open(frag_filename
, 'rb') as down
: 
 330                 down_data 
= down
.read() 
 331                 reader 
= FlvReader(down_data
) 
 333                     _
, box_type
, box_data 
= reader
.read_box_info() 
 334                     if box_type 
== b
'mdat': 
 335                         dest_stream
.write(box_data
) 
 337             frags_filenames
.append(frag_filename
) 
 340         self
.report_finish(format_bytes(state
['downloaded_bytes']), time
.time() - start
) 
 342         self
.try_rename(tmpfilename
, filename
) 
 343         for frag_file 
in frags_filenames
: 
 346         fsize 
= os
.path
.getsize(encodeFilename(filename
)) 
 347         self
._hook
_progress
({ 
 348             'downloaded_bytes': fsize
, 
 349             'total_bytes': fsize
, 
 350             'filename': filename
, 
 351             'status': 'finished',