ism.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. from __future__ import unicode_literals
  2. import time
  3. import binascii
  4. import io
  5. from .fragment import FragmentFD
  6. from ..compat import (
  7. compat_Struct,
  8. compat_urllib_error,
  9. )
  10. u8 = compat_Struct('>B')
  11. u88 = compat_Struct('>Bx')
  12. u16 = compat_Struct('>H')
  13. u1616 = compat_Struct('>Hxx')
  14. u32 = compat_Struct('>I')
  15. u64 = compat_Struct('>Q')
  16. s88 = compat_Struct('>bx')
  17. s16 = compat_Struct('>h')
  18. s1616 = compat_Struct('>hxx')
  19. s32 = compat_Struct('>i')
  20. unity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000)
  21. TRACK_ENABLED = 0x1
  22. TRACK_IN_MOVIE = 0x2
  23. TRACK_IN_PREVIEW = 0x4
  24. SELF_CONTAINED = 0x1
  25. def box(box_type, payload):
  26. return u32.pack(8 + len(payload)) + box_type + payload
  27. def full_box(box_type, version, flags, payload):
  28. return box(box_type, u8.pack(version) + u32.pack(flags)[1:] + payload)
  29. def write_piff_header(stream, params):
  30. track_id = params['track_id']
  31. fourcc = params['fourcc']
  32. duration = params['duration']
  33. timescale = params.get('timescale', 10000000)
  34. language = params.get('language', 'und')
  35. height = params.get('height', 0)
  36. width = params.get('width', 0)
  37. is_audio = width == 0 and height == 0
  38. creation_time = modification_time = int(time.time())
  39. ftyp_payload = b'isml' # major brand
  40. ftyp_payload += u32.pack(1) # minor version
  41. ftyp_payload += b'piff' + b'iso2' # compatible brands
  42. stream.write(box(b'ftyp', ftyp_payload)) # File Type Box
  43. mvhd_payload = u64.pack(creation_time)
  44. mvhd_payload += u64.pack(modification_time)
  45. mvhd_payload += u32.pack(timescale)
  46. mvhd_payload += u64.pack(duration)
  47. mvhd_payload += s1616.pack(1) # rate
  48. mvhd_payload += s88.pack(1) # volume
  49. mvhd_payload += u16.pack(0) # reserved
  50. mvhd_payload += u32.pack(0) * 2 # reserved
  51. mvhd_payload += unity_matrix
  52. mvhd_payload += u32.pack(0) * 6 # pre defined
  53. mvhd_payload += u32.pack(0xffffffff) # next track id
  54. moov_payload = full_box(b'mvhd', 1, 0, mvhd_payload) # Movie Header Box
  55. tkhd_payload = u64.pack(creation_time)
  56. tkhd_payload += u64.pack(modification_time)
  57. tkhd_payload += u32.pack(track_id) # track id
  58. tkhd_payload += u32.pack(0) # reserved
  59. tkhd_payload += u64.pack(duration)
  60. tkhd_payload += u32.pack(0) * 2 # reserved
  61. tkhd_payload += s16.pack(0) # layer
  62. tkhd_payload += s16.pack(0) # alternate group
  63. tkhd_payload += s88.pack(1 if is_audio else 0) # volume
  64. tkhd_payload += u16.pack(0) # reserved
  65. tkhd_payload += unity_matrix
  66. tkhd_payload += u1616.pack(width)
  67. tkhd_payload += u1616.pack(height)
  68. trak_payload = full_box(b'tkhd', 1, TRACK_ENABLED | TRACK_IN_MOVIE | TRACK_IN_PREVIEW, tkhd_payload) # Track Header Box
  69. mdhd_payload = u64.pack(creation_time)
  70. mdhd_payload += u64.pack(modification_time)
  71. mdhd_payload += u32.pack(timescale)
  72. mdhd_payload += u64.pack(duration)
  73. mdhd_payload += u16.pack(((ord(language[0]) - 0x60) << 10) | ((ord(language[1]) - 0x60) << 5) | (ord(language[2]) - 0x60))
  74. mdhd_payload += u16.pack(0) # pre defined
  75. mdia_payload = full_box(b'mdhd', 1, 0, mdhd_payload) # Media Header Box
  76. hdlr_payload = u32.pack(0) # pre defined
  77. hdlr_payload += b'soun' if is_audio else b'vide' # handler type
  78. hdlr_payload += u32.pack(0) * 3 # reserved
  79. hdlr_payload += (b'Sound' if is_audio else b'Video') + b'Handler\0' # name
  80. mdia_payload += full_box(b'hdlr', 0, 0, hdlr_payload) # Handler Reference Box
  81. if is_audio:
  82. smhd_payload = s88.pack(0) # balance
  83. smhd_payload += u16.pack(0) # reserved
  84. media_header_box = full_box(b'smhd', 0, 0, smhd_payload) # Sound Media Header
  85. else:
  86. vmhd_payload = u16.pack(0) # graphics mode
  87. vmhd_payload += u16.pack(0) * 3 # opcolor
  88. media_header_box = full_box(b'vmhd', 0, 1, vmhd_payload) # Video Media Header
  89. minf_payload = media_header_box
  90. dref_payload = u32.pack(1) # entry count
  91. dref_payload += full_box(b'url ', 0, SELF_CONTAINED, b'') # Data Entry URL Box
  92. dinf_payload = full_box(b'dref', 0, 0, dref_payload) # Data Reference Box
  93. minf_payload += box(b'dinf', dinf_payload) # Data Information Box
  94. stsd_payload = u32.pack(1) # entry count
  95. sample_entry_payload = u8.pack(0) * 6 # reserved
  96. sample_entry_payload += u16.pack(1) # data reference index
  97. if is_audio:
  98. sample_entry_payload += u32.pack(0) * 2 # reserved
  99. sample_entry_payload += u16.pack(params.get('channels', 2))
  100. sample_entry_payload += u16.pack(params.get('bits_per_sample', 16))
  101. sample_entry_payload += u16.pack(0) # pre defined
  102. sample_entry_payload += u16.pack(0) # reserved
  103. sample_entry_payload += u1616.pack(params['sampling_rate'])
  104. if fourcc == 'AACL':
  105. sample_entry_box = box(b'mp4a', sample_entry_payload)
  106. else:
  107. sample_entry_payload += u16.pack(0) # pre defined
  108. sample_entry_payload += u16.pack(0) # reserved
  109. sample_entry_payload += u32.pack(0) * 3 # pre defined
  110. sample_entry_payload += u16.pack(width)
  111. sample_entry_payload += u16.pack(height)
  112. sample_entry_payload += u1616.pack(0x48) # horiz resolution 72 dpi
  113. sample_entry_payload += u1616.pack(0x48) # vert resolution 72 dpi
  114. sample_entry_payload += u32.pack(0) # reserved
  115. sample_entry_payload += u16.pack(1) # frame count
  116. sample_entry_payload += u8.pack(0) * 32 # compressor name
  117. sample_entry_payload += u16.pack(0x18) # depth
  118. sample_entry_payload += s16.pack(-1) # pre defined
  119. codec_private_data = binascii.unhexlify(params['codec_private_data'].encode('utf-8'))
  120. if fourcc in ('H264', 'AVC1'):
  121. sps, pps = codec_private_data.split(u32.pack(1))[1:]
  122. avcc_payload = u8.pack(1) # configuration version
  123. avcc_payload += sps[1:4] # avc profile indication + profile compatibility + avc level indication
  124. avcc_payload += u8.pack(0xfc | (params.get('nal_unit_length_field', 4) - 1)) # complete representation (1) + reserved (11111) + length size minus one
  125. avcc_payload += u8.pack(1) # reserved (0) + number of sps (0000001)
  126. avcc_payload += u16.pack(len(sps))
  127. avcc_payload += sps
  128. avcc_payload += u8.pack(1) # number of pps
  129. avcc_payload += u16.pack(len(pps))
  130. avcc_payload += pps
  131. sample_entry_payload += box(b'avcC', avcc_payload) # AVC Decoder Configuration Record
  132. sample_entry_box = box(b'avc1', sample_entry_payload) # AVC Simple Entry
  133. stsd_payload += sample_entry_box
  134. stbl_payload = full_box(b'stsd', 0, 0, stsd_payload) # Sample Description Box
  135. stts_payload = u32.pack(0) # entry count
  136. stbl_payload += full_box(b'stts', 0, 0, stts_payload) # Decoding Time to Sample Box
  137. stsc_payload = u32.pack(0) # entry count
  138. stbl_payload += full_box(b'stsc', 0, 0, stsc_payload) # Sample To Chunk Box
  139. stco_payload = u32.pack(0) # entry count
  140. stbl_payload += full_box(b'stco', 0, 0, stco_payload) # Chunk Offset Box
  141. minf_payload += box(b'stbl', stbl_payload) # Sample Table Box
  142. mdia_payload += box(b'minf', minf_payload) # Media Information Box
  143. trak_payload += box(b'mdia', mdia_payload) # Media Box
  144. moov_payload += box(b'trak', trak_payload) # Track Box
  145. mehd_payload = u64.pack(duration)
  146. mvex_payload = full_box(b'mehd', 1, 0, mehd_payload) # Movie Extends Header Box
  147. trex_payload = u32.pack(track_id) # track id
  148. trex_payload += u32.pack(1) # default sample description index
  149. trex_payload += u32.pack(0) # default sample duration
  150. trex_payload += u32.pack(0) # default sample size
  151. trex_payload += u32.pack(0) # default sample flags
  152. mvex_payload += full_box(b'trex', 0, 0, trex_payload) # Track Extends Box
  153. moov_payload += box(b'mvex', mvex_payload) # Movie Extends Box
  154. stream.write(box(b'moov', moov_payload)) # Movie Box
  155. def extract_box_data(data, box_sequence):
  156. data_reader = io.BytesIO(data)
  157. while True:
  158. box_size = u32.unpack(data_reader.read(4))[0]
  159. box_type = data_reader.read(4)
  160. if box_type == box_sequence[0]:
  161. box_data = data_reader.read(box_size - 8)
  162. if len(box_sequence) == 1:
  163. return box_data
  164. return extract_box_data(box_data, box_sequence[1:])
  165. data_reader.seek(box_size - 8, 1)
  166. class IsmFD(FragmentFD):
  167. """
  168. Download segments in a ISM manifest
  169. """
  170. FD_NAME = 'ism'
  171. def real_download(self, filename, info_dict):
  172. segments = info_dict['fragments'][:1] if self.params.get(
  173. 'test', False) else info_dict['fragments']
  174. ctx = {
  175. 'filename': filename,
  176. 'total_frags': len(segments),
  177. }
  178. self._prepare_and_start_frag_download(ctx)
  179. fragment_retries = self.params.get('fragment_retries', 0)
  180. skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
  181. track_written = False
  182. frag_index = 0
  183. for i, segment in enumerate(segments):
  184. frag_index += 1
  185. if frag_index <= ctx['fragment_index']:
  186. continue
  187. count = 0
  188. while count <= fragment_retries:
  189. try:
  190. success, frag_content = self._download_fragment(ctx, segment['url'], info_dict)
  191. if not success:
  192. return False
  193. if not track_written:
  194. tfhd_data = extract_box_data(frag_content, [b'moof', b'traf', b'tfhd'])
  195. info_dict['_download_params']['track_id'] = u32.unpack(tfhd_data[4:8])[0]
  196. write_piff_header(ctx['dest_stream'], info_dict['_download_params'])
  197. track_written = True
  198. self._append_fragment(ctx, frag_content)
  199. break
  200. except compat_urllib_error.HTTPError as err:
  201. count += 1
  202. if count <= fragment_retries:
  203. self.report_retry_fragment(err, frag_index, count, fragment_retries)
  204. if count > fragment_retries:
  205. if skip_unavailable_fragments:
  206. self.report_skip_fragment(frag_index)
  207. continue
  208. self.report_error('giving up after %s fragment retries' % fragment_retries)
  209. return False
  210. self._finish_frag_download(ctx)
  211. return True