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.

271 lines
11 KiB

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