You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

258 lines
10 KiB

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