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.

2077 lines
77KB

  1. /*
  2. * MXF demuxer.
  3. * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /*
  22. * References
  23. * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
  24. * SMPTE 377M MXF File Format Specifications
  25. * SMPTE 378M Operational Pattern 1a
  26. * SMPTE 379M MXF Generic Container
  27. * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
  28. * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
  29. * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
  30. *
  31. * Principle
  32. * Search for Track numbers which will identify essence element KLV packets.
  33. * Search for SourcePackage which define tracks which contains Track numbers.
  34. * Material Package contains tracks with reference to SourcePackage tracks.
  35. * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
  36. * Assign Descriptors to correct Tracks.
  37. *
  38. * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
  39. * Metadata parsing resolves Strong References to objects.
  40. *
  41. * Simple demuxer, only OP1A supported and some files might not work at all.
  42. * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
  43. */
  44. //#define DEBUG
  45. #include "libavutil/aes.h"
  46. #include "libavutil/mathematics.h"
  47. #include "libavcodec/bytestream.h"
  48. #include "avformat.h"
  49. #include "internal.h"
  50. #include "mxf.h"
  51. typedef enum {
  52. Header,
  53. BodyPartition,
  54. Footer
  55. } MXFPartitionType;
  56. typedef enum {
  57. OP1a,
  58. OP1b,
  59. OP1c,
  60. OP2a,
  61. OP2b,
  62. OP2c,
  63. OP3a,
  64. OP3b,
  65. OP3c,
  66. OPAtom,
  67. OPSONYOpt, /* FATE sample, violates the spec in places */
  68. } MXFOP;
  69. typedef struct {
  70. int closed;
  71. int complete;
  72. MXFPartitionType type;
  73. uint64_t previous_partition;
  74. int index_sid;
  75. int body_sid;
  76. int64_t this_partition;
  77. int64_t essence_offset; /* absolute offset of essence */
  78. int64_t essence_length;
  79. int32_t kag_size;
  80. int64_t header_byte_count;
  81. int64_t index_byte_count;
  82. int pack_length;
  83. } MXFPartition;
  84. typedef struct {
  85. UID uid;
  86. enum MXFMetadataSetType type;
  87. UID source_container_ul;
  88. } MXFCryptoContext;
  89. typedef struct {
  90. UID uid;
  91. enum MXFMetadataSetType type;
  92. UID source_package_uid;
  93. UID data_definition_ul;
  94. int64_t duration;
  95. int64_t start_position;
  96. int source_track_id;
  97. } MXFStructuralComponent;
  98. typedef struct {
  99. UID uid;
  100. enum MXFMetadataSetType type;
  101. UID data_definition_ul;
  102. UID *structural_components_refs;
  103. int structural_components_count;
  104. int64_t duration;
  105. } MXFSequence;
  106. typedef struct {
  107. UID uid;
  108. enum MXFMetadataSetType type;
  109. MXFSequence *sequence; /* mandatory, and only one */
  110. UID sequence_ref;
  111. int track_id;
  112. uint8_t track_number[4];
  113. AVRational edit_rate;
  114. } MXFTrack;
  115. typedef struct {
  116. UID uid;
  117. enum MXFMetadataSetType type;
  118. UID essence_container_ul;
  119. UID essence_codec_ul;
  120. AVRational sample_rate;
  121. AVRational aspect_ratio;
  122. int width;
  123. int height;
  124. int channels;
  125. int bits_per_sample;
  126. UID *sub_descriptors_refs;
  127. int sub_descriptors_count;
  128. int linked_track_id;
  129. uint8_t *extradata;
  130. int extradata_size;
  131. enum PixelFormat pix_fmt;
  132. } MXFDescriptor;
  133. typedef struct {
  134. UID uid;
  135. enum MXFMetadataSetType type;
  136. int edit_unit_byte_count;
  137. int index_sid;
  138. int body_sid;
  139. int slice_count;
  140. AVRational index_edit_rate;
  141. uint64_t index_start_position;
  142. uint64_t index_duration;
  143. int *slice;
  144. int *element_delta;
  145. int nb_delta_entries;
  146. int8_t *temporal_offset_entries;
  147. int *flag_entries;
  148. uint64_t *stream_offset_entries;
  149. uint32_t **slice_offset_entries;
  150. int nb_index_entries;
  151. } MXFIndexTableSegment;
  152. typedef struct {
  153. UID uid;
  154. enum MXFMetadataSetType type;
  155. UID package_uid;
  156. UID *tracks_refs;
  157. int tracks_count;
  158. MXFDescriptor *descriptor; /* only one */
  159. UID descriptor_ref;
  160. } MXFPackage;
  161. typedef struct {
  162. UID uid;
  163. enum MXFMetadataSetType type;
  164. } MXFMetadataSet;
  165. /* decoded index table */
  166. typedef struct {
  167. int index_sid;
  168. int body_sid;
  169. int nb_ptses; /* number of PTSes or total duration of index */
  170. int64_t first_dts; /* DTS = EditUnit + first_dts */
  171. int64_t *ptses; /* maps EditUnit -> PTS */
  172. int nb_segments;
  173. MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
  174. AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
  175. } MXFIndexTable;
  176. typedef struct {
  177. MXFPartition *partitions;
  178. unsigned partitions_count;
  179. MXFOP op;
  180. UID *packages_refs;
  181. int packages_count;
  182. MXFMetadataSet **metadata_sets;
  183. int metadata_sets_count;
  184. AVFormatContext *fc;
  185. struct AVAES *aesc;
  186. uint8_t *local_tags;
  187. int local_tags_count;
  188. uint64_t footer_partition;
  189. KLVPacket current_klv_data;
  190. int current_klv_index;
  191. int run_in;
  192. MXFPartition *current_partition;
  193. int parsing_backward;
  194. int64_t last_forward_tell;
  195. int last_forward_partition;
  196. int current_edit_unit;
  197. int current_stream;
  198. int d10;
  199. int broken_index;
  200. int64_t first_dts; /* DTS = EditUnit + first_dts */
  201. int64_t *ptses; /* maps EditUnit -> PTS */
  202. int nb_ptses;
  203. int nb_index_tables;
  204. MXFIndexTable *index_tables;
  205. } MXFContext;
  206. enum MXFWrappingScheme {
  207. Frame,
  208. Clip,
  209. };
  210. /* NOTE: klv_offset is not set (-1) for local keys */
  211. typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
  212. typedef struct {
  213. const UID key;
  214. MXFMetadataReadFunc *read;
  215. int ctx_size;
  216. enum MXFMetadataSetType type;
  217. } MXFMetadataReadTableEntry;
  218. /* partial keys to match */
  219. static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
  220. static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
  221. static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
  222. static const uint8_t mxf_system_item_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
  223. static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
  224. /* complete keys to match */
  225. static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 };
  226. static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
  227. static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
  228. static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
  229. #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
  230. static int64_t klv_decode_ber_length(AVIOContext *pb)
  231. {
  232. uint64_t size = avio_r8(pb);
  233. if (size & 0x80) { /* long form */
  234. int bytes_num = size & 0x7f;
  235. /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
  236. if (bytes_num > 8)
  237. return -1;
  238. size = 0;
  239. while (bytes_num--)
  240. size = size << 8 | avio_r8(pb);
  241. }
  242. return size;
  243. }
  244. static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
  245. {
  246. int i, b;
  247. for (i = 0; i < size && !url_feof(pb); i++) {
  248. b = avio_r8(pb);
  249. if (b == key[0])
  250. i = 0;
  251. else if (b != key[i])
  252. i = -1;
  253. }
  254. return i == size;
  255. }
  256. static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
  257. {
  258. if (!mxf_read_sync(pb, mxf_klv_key, 4))
  259. return -1;
  260. klv->offset = avio_tell(pb) - 4;
  261. memcpy(klv->key, mxf_klv_key, 4);
  262. avio_read(pb, klv->key + 4, 12);
  263. klv->length = klv_decode_ber_length(pb);
  264. return klv->length == -1 ? -1 : 0;
  265. }
  266. static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
  267. {
  268. int i;
  269. for (i = 0; i < s->nb_streams; i++) {
  270. MXFTrack *track = s->streams[i]->priv_data;
  271. /* SMPTE 379M 7.3 */
  272. if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
  273. return i;
  274. }
  275. /* return 0 if only one stream, for OP Atom files with 0 as track number */
  276. return s->nb_streams == 1 ? 0 : -1;
  277. }
  278. /* XXX: use AVBitStreamFilter */
  279. static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
  280. {
  281. const uint8_t *buf_ptr, *end_ptr;
  282. uint8_t *data_ptr;
  283. int i;
  284. if (length > 61444) /* worst case PAL 1920 samples 8 channels */
  285. return -1;
  286. length = av_get_packet(pb, pkt, length);
  287. if (length < 0)
  288. return length;
  289. data_ptr = pkt->data;
  290. end_ptr = pkt->data + length;
  291. buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
  292. for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
  293. for (i = 0; i < st->codec->channels; i++) {
  294. uint32_t sample = bytestream_get_le32(&buf_ptr);
  295. if (st->codec->bits_per_coded_sample == 24)
  296. bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
  297. else
  298. bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
  299. }
  300. buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
  301. }
  302. av_shrink_packet(pkt, data_ptr - pkt->data);
  303. return 0;
  304. }
  305. static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
  306. {
  307. static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
  308. MXFContext *mxf = s->priv_data;
  309. AVIOContext *pb = s->pb;
  310. int64_t end = avio_tell(pb) + klv->length;
  311. int64_t size;
  312. uint64_t orig_size;
  313. uint64_t plaintext_size;
  314. uint8_t ivec[16];
  315. uint8_t tmpbuf[16];
  316. int index;
  317. if (!mxf->aesc && s->key && s->keylen == 16) {
  318. mxf->aesc = av_malloc(av_aes_size);
  319. if (!mxf->aesc)
  320. return -1;
  321. av_aes_init(mxf->aesc, s->key, 128, 1);
  322. }
  323. // crypto context
  324. avio_skip(pb, klv_decode_ber_length(pb));
  325. // plaintext offset
  326. klv_decode_ber_length(pb);
  327. plaintext_size = avio_rb64(pb);
  328. // source klv key
  329. klv_decode_ber_length(pb);
  330. avio_read(pb, klv->key, 16);
  331. if (!IS_KLV_KEY(klv, mxf_essence_element_key))
  332. return -1;
  333. index = mxf_get_stream_index(s, klv);
  334. if (index < 0)
  335. return -1;
  336. // source size
  337. klv_decode_ber_length(pb);
  338. orig_size = avio_rb64(pb);
  339. if (orig_size < plaintext_size)
  340. return -1;
  341. // enc. code
  342. size = klv_decode_ber_length(pb);
  343. if (size < 32 || size - 32 < orig_size)
  344. return -1;
  345. avio_read(pb, ivec, 16);
  346. avio_read(pb, tmpbuf, 16);
  347. if (mxf->aesc)
  348. av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
  349. if (memcmp(tmpbuf, checkv, 16))
  350. av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
  351. size -= 32;
  352. size = av_get_packet(pb, pkt, size);
  353. if (size < 0)
  354. return size;
  355. else if (size < plaintext_size)
  356. return AVERROR_INVALIDDATA;
  357. size -= plaintext_size;
  358. if (mxf->aesc)
  359. av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
  360. &pkt->data[plaintext_size], size >> 4, ivec, 1);
  361. av_shrink_packet(pkt, orig_size);
  362. pkt->stream_index = index;
  363. avio_skip(pb, end - avio_tell(pb));
  364. return 0;
  365. }
  366. static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  367. {
  368. MXFContext *mxf = arg;
  369. int item_num = avio_rb32(pb);
  370. int item_len = avio_rb32(pb);
  371. if (item_len != 18) {
  372. av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
  373. return -1;
  374. }
  375. if (item_num > UINT_MAX / item_len)
  376. return -1;
  377. mxf->local_tags_count = item_num;
  378. mxf->local_tags = av_malloc(item_num*item_len);
  379. if (!mxf->local_tags)
  380. return -1;
  381. avio_read(pb, mxf->local_tags, item_num*item_len);
  382. return 0;
  383. }
  384. static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  385. {
  386. MXFContext *mxf = arg;
  387. MXFPartition *partition;
  388. UID op;
  389. uint64_t footer_partition;
  390. if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
  391. return AVERROR(ENOMEM);
  392. mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
  393. if (!mxf->partitions)
  394. return AVERROR(ENOMEM);
  395. if (mxf->parsing_backward) {
  396. /* insert the new partition pack in the middle
  397. * this makes the entries in mxf->partitions sorted by offset */
  398. memmove(&mxf->partitions[mxf->last_forward_partition+1],
  399. &mxf->partitions[mxf->last_forward_partition],
  400. (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
  401. partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
  402. } else {
  403. mxf->last_forward_partition++;
  404. partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
  405. }
  406. memset(partition, 0, sizeof(*partition));
  407. mxf->partitions_count++;
  408. partition->pack_length = avio_tell(pb) - klv_offset + size;
  409. switch(uid[13]) {
  410. case 2:
  411. partition->type = Header;
  412. break;
  413. case 3:
  414. partition->type = BodyPartition;
  415. break;
  416. case 4:
  417. partition->type = Footer;
  418. break;
  419. default:
  420. av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
  421. return AVERROR_INVALIDDATA;
  422. }
  423. /* consider both footers to be closed (there is only Footer and CompleteFooter) */
  424. partition->closed = partition->type == Footer || !(uid[14] & 1);
  425. partition->complete = uid[14] > 2;
  426. avio_skip(pb, 4);
  427. partition->kag_size = avio_rb32(pb);
  428. partition->this_partition = avio_rb64(pb);
  429. partition->previous_partition = avio_rb64(pb);
  430. footer_partition = avio_rb64(pb);
  431. partition->header_byte_count = avio_rb64(pb);
  432. partition->index_byte_count = avio_rb64(pb);
  433. partition->index_sid = avio_rb32(pb);
  434. avio_skip(pb, 8);
  435. partition->body_sid = avio_rb32(pb);
  436. avio_read(pb, op, sizeof(UID));
  437. /* some files don'thave FooterPartition set in every partition */
  438. if (footer_partition) {
  439. if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
  440. av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",
  441. mxf->footer_partition, footer_partition);
  442. } else {
  443. mxf->footer_partition = footer_partition;
  444. }
  445. }
  446. av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%lx, PreviousPartition = 0x%lx, "
  447. "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
  448. partition->this_partition,
  449. partition->previous_partition, footer_partition,
  450. partition->index_sid, partition->body_sid);
  451. if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
  452. else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
  453. else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
  454. else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
  455. else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
  456. else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
  457. else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
  458. else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
  459. else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
  460. else if (op[12] == 0x10) mxf->op = OPAtom;
  461. else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
  462. else {
  463. av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
  464. mxf->op = OP1a;
  465. }
  466. if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
  467. av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
  468. if (mxf->op == OPSONYOpt)
  469. partition->kag_size = 512;
  470. else
  471. partition->kag_size = 1;
  472. av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
  473. }
  474. return 0;
  475. }
  476. static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
  477. {
  478. if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
  479. return AVERROR(ENOMEM);
  480. mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
  481. if (!mxf->metadata_sets)
  482. return -1;
  483. mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
  484. mxf->metadata_sets_count++;
  485. return 0;
  486. }
  487. static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  488. {
  489. MXFCryptoContext *cryptocontext = arg;
  490. if (size != 16)
  491. return -1;
  492. if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
  493. avio_read(pb, cryptocontext->source_container_ul, 16);
  494. return 0;
  495. }
  496. static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  497. {
  498. MXFContext *mxf = arg;
  499. switch (tag) {
  500. case 0x1901:
  501. mxf->packages_count = avio_rb32(pb);
  502. if (mxf->packages_count >= UINT_MAX / sizeof(UID))
  503. return -1;
  504. mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
  505. if (!mxf->packages_refs)
  506. return -1;
  507. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  508. avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
  509. break;
  510. }
  511. return 0;
  512. }
  513. static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  514. {
  515. MXFStructuralComponent *source_clip = arg;
  516. switch(tag) {
  517. case 0x0202:
  518. source_clip->duration = avio_rb64(pb);
  519. break;
  520. case 0x1201:
  521. source_clip->start_position = avio_rb64(pb);
  522. break;
  523. case 0x1101:
  524. /* UMID, only get last 16 bytes */
  525. avio_skip(pb, 16);
  526. avio_read(pb, source_clip->source_package_uid, 16);
  527. break;
  528. case 0x1102:
  529. source_clip->source_track_id = avio_rb32(pb);
  530. break;
  531. }
  532. return 0;
  533. }
  534. static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  535. {
  536. MXFPackage *package = arg;
  537. switch(tag) {
  538. case 0x4403:
  539. package->tracks_count = avio_rb32(pb);
  540. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  541. return -1;
  542. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  543. if (!package->tracks_refs)
  544. return -1;
  545. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  546. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  547. break;
  548. }
  549. return 0;
  550. }
  551. static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  552. {
  553. MXFTrack *track = arg;
  554. switch(tag) {
  555. case 0x4801:
  556. track->track_id = avio_rb32(pb);
  557. break;
  558. case 0x4804:
  559. avio_read(pb, track->track_number, 4);
  560. break;
  561. case 0x4B01:
  562. track->edit_rate.den = avio_rb32(pb);
  563. track->edit_rate.num = avio_rb32(pb);
  564. break;
  565. case 0x4803:
  566. avio_read(pb, track->sequence_ref, 16);
  567. break;
  568. }
  569. return 0;
  570. }
  571. static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  572. {
  573. MXFSequence *sequence = arg;
  574. switch(tag) {
  575. case 0x0202:
  576. sequence->duration = avio_rb64(pb);
  577. break;
  578. case 0x0201:
  579. avio_read(pb, sequence->data_definition_ul, 16);
  580. break;
  581. case 0x1001:
  582. sequence->structural_components_count = avio_rb32(pb);
  583. if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
  584. return -1;
  585. sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
  586. if (!sequence->structural_components_refs)
  587. return -1;
  588. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  589. avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
  590. break;
  591. }
  592. return 0;
  593. }
  594. static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  595. {
  596. MXFPackage *package = arg;
  597. switch(tag) {
  598. case 0x4403:
  599. package->tracks_count = avio_rb32(pb);
  600. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  601. return -1;
  602. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  603. if (!package->tracks_refs)
  604. return -1;
  605. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  606. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  607. break;
  608. case 0x4401:
  609. /* UMID, only get last 16 bytes */
  610. avio_skip(pb, 16);
  611. avio_read(pb, package->package_uid, 16);
  612. break;
  613. case 0x4701:
  614. avio_read(pb, package->descriptor_ref, 16);
  615. break;
  616. }
  617. return 0;
  618. }
  619. static int mxf_read_delta_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
  620. {
  621. int i, length;
  622. segment->nb_delta_entries = avio_rb32(pb);
  623. length = avio_rb32(pb);
  624. if (!(segment->slice = av_calloc(segment->nb_delta_entries, sizeof(*segment->slice))) ||
  625. !(segment->element_delta = av_calloc(segment->nb_delta_entries, sizeof(*segment->element_delta))))
  626. return AVERROR(ENOMEM);
  627. for (i = 0; i < segment->nb_delta_entries; i++) {
  628. avio_r8(pb); /* PosTableIndex */
  629. segment->slice[i] = avio_r8(pb);
  630. segment->element_delta[i] = avio_rb32(pb);
  631. }
  632. return 0;
  633. }
  634. static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
  635. {
  636. int i, j, length;
  637. segment->nb_index_entries = avio_rb32(pb);
  638. length = avio_rb32(pb);
  639. if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
  640. !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
  641. !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
  642. return AVERROR(ENOMEM);
  643. if (segment->slice_count &&
  644. !(segment->slice_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->slice_offset_entries))))
  645. return AVERROR(ENOMEM);
  646. for (i = 0; i < segment->nb_index_entries; i++) {
  647. segment->temporal_offset_entries[i] = avio_r8(pb);
  648. avio_r8(pb); /* KeyFrameOffset */
  649. segment->flag_entries[i] = avio_r8(pb);
  650. segment->stream_offset_entries[i] = avio_rb64(pb);
  651. if (segment->slice_count) {
  652. if (!(segment->slice_offset_entries[i] = av_calloc(segment->slice_count, sizeof(**segment->slice_offset_entries))))
  653. return AVERROR(ENOMEM);
  654. for (j = 0; j < segment->slice_count; j++)
  655. segment->slice_offset_entries[i][j] = avio_rb32(pb);
  656. }
  657. avio_skip(pb, length - 11 - 4 * segment->slice_count);
  658. }
  659. return 0;
  660. }
  661. static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  662. {
  663. MXFIndexTableSegment *segment = arg;
  664. switch(tag) {
  665. case 0x3F05:
  666. segment->edit_unit_byte_count = avio_rb32(pb);
  667. av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
  668. break;
  669. case 0x3F06:
  670. segment->index_sid = avio_rb32(pb);
  671. av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
  672. break;
  673. case 0x3F07:
  674. segment->body_sid = avio_rb32(pb);
  675. av_dlog(NULL, "BodySID %d\n", segment->body_sid);
  676. break;
  677. case 0x3F08:
  678. segment->slice_count = avio_r8(pb);
  679. av_dlog(NULL, "SliceCount %d\n", segment->slice_count);
  680. break;
  681. case 0x3F09:
  682. av_dlog(NULL, "DeltaEntryArray found\n");
  683. return mxf_read_delta_entry_array(pb, segment);
  684. case 0x3F0A:
  685. av_dlog(NULL, "IndexEntryArray found\n");
  686. return mxf_read_index_entry_array(pb, segment);
  687. case 0x3F0B:
  688. segment->index_edit_rate.num = avio_rb32(pb);
  689. segment->index_edit_rate.den = avio_rb32(pb);
  690. av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
  691. segment->index_edit_rate.den);
  692. break;
  693. case 0x3F0C:
  694. segment->index_start_position = avio_rb64(pb);
  695. av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
  696. break;
  697. case 0x3F0D:
  698. segment->index_duration = avio_rb64(pb);
  699. av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
  700. break;
  701. }
  702. return 0;
  703. }
  704. static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
  705. {
  706. int code, value, ofs = 0;
  707. char layout[16] = {0};
  708. do {
  709. code = avio_r8(pb);
  710. value = avio_r8(pb);
  711. av_dlog(NULL, "pixel layout: code %#x\n", code);
  712. if (ofs < 16) {
  713. layout[ofs++] = code;
  714. layout[ofs++] = value;
  715. }
  716. } while (code != 0); /* SMPTE 377M E.2.46 */
  717. ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
  718. }
  719. static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  720. {
  721. MXFDescriptor *descriptor = arg;
  722. switch(tag) {
  723. case 0x3F01:
  724. descriptor->sub_descriptors_count = avio_rb32(pb);
  725. if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
  726. return -1;
  727. descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
  728. if (!descriptor->sub_descriptors_refs)
  729. return -1;
  730. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  731. avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
  732. break;
  733. case 0x3004:
  734. avio_read(pb, descriptor->essence_container_ul, 16);
  735. break;
  736. case 0x3006:
  737. descriptor->linked_track_id = avio_rb32(pb);
  738. break;
  739. case 0x3201: /* PictureEssenceCoding */
  740. avio_read(pb, descriptor->essence_codec_ul, 16);
  741. break;
  742. case 0x3203:
  743. descriptor->width = avio_rb32(pb);
  744. break;
  745. case 0x3202:
  746. descriptor->height = avio_rb32(pb);
  747. break;
  748. case 0x320E:
  749. descriptor->aspect_ratio.num = avio_rb32(pb);
  750. descriptor->aspect_ratio.den = avio_rb32(pb);
  751. break;
  752. case 0x3D03:
  753. descriptor->sample_rate.num = avio_rb32(pb);
  754. descriptor->sample_rate.den = avio_rb32(pb);
  755. break;
  756. case 0x3D06: /* SoundEssenceCompression */
  757. avio_read(pb, descriptor->essence_codec_ul, 16);
  758. break;
  759. case 0x3D07:
  760. descriptor->channels = avio_rb32(pb);
  761. break;
  762. case 0x3D01:
  763. descriptor->bits_per_sample = avio_rb32(pb);
  764. break;
  765. case 0x3401:
  766. mxf_read_pixel_layout(pb, descriptor);
  767. break;
  768. default:
  769. /* Private uid used by SONY C0023S01.mxf */
  770. if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
  771. descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
  772. if (!descriptor->extradata)
  773. return -1;
  774. descriptor->extradata_size = size;
  775. avio_read(pb, descriptor->extradata, size);
  776. }
  777. break;
  778. }
  779. return 0;
  780. }
  781. /*
  782. * Match an uid independently of the version byte and up to len common bytes
  783. * Returns: boolean
  784. */
  785. static int mxf_match_uid(const UID key, const UID uid, int len)
  786. {
  787. int i;
  788. for (i = 0; i < len; i++) {
  789. if (i != 7 && key[i] != uid[i])
  790. return 0;
  791. }
  792. return 1;
  793. }
  794. static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
  795. {
  796. while (uls->uid[0]) {
  797. if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
  798. break;
  799. uls++;
  800. }
  801. return uls;
  802. }
  803. static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
  804. {
  805. int i;
  806. if (!strong_ref)
  807. return NULL;
  808. for (i = 0; i < mxf->metadata_sets_count; i++) {
  809. if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
  810. (type == AnyType || mxf->metadata_sets[i]->type == type)) {
  811. return mxf->metadata_sets[i];
  812. }
  813. }
  814. return NULL;
  815. }
  816. static const MXFCodecUL mxf_picture_essence_container_uls[] = {
  817. // video essence container uls
  818. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
  819. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
  820. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
  821. };
  822. static const MXFCodecUL mxf_sound_essence_container_uls[] = {
  823. // sound essence container uls
  824. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
  825. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
  826. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
  827. { { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0xFF,0x4B,0x46,0x41,0x41,0x00,0x0D,0x4D,0x4F }, 14, CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
  828. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
  829. };
  830. static UID mxf_d10_ul = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 };
  831. static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
  832. {
  833. int i, j, nb_segments = 0;
  834. MXFIndexTableSegment **unsorted_segments;
  835. int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
  836. /* count number of segments, allocate arrays and copy unsorted segments */
  837. for (i = 0; i < mxf->metadata_sets_count; i++)
  838. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  839. nb_segments++;
  840. if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
  841. !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
  842. av_free(unsorted_segments);
  843. return AVERROR(ENOMEM);
  844. }
  845. for (i = j = 0; i < mxf->metadata_sets_count; i++)
  846. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  847. unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
  848. *nb_sorted_segments = 0;
  849. /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
  850. for (i = 0; i < nb_segments; i++) {
  851. int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
  852. for (j = 0; j < nb_segments; j++) {
  853. MXFIndexTableSegment *s = unsorted_segments[j];
  854. /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
  855. * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
  856. */
  857. if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
  858. (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
  859. best = j;
  860. best_body_sid = s->body_sid;
  861. best_index_sid = s->index_sid;
  862. best_index_start = s->index_start_position;
  863. }
  864. }
  865. /* no suitable entry found -> we're done */
  866. if (best == -1)
  867. break;
  868. (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
  869. last_body_sid = best_body_sid;
  870. last_index_sid = best_index_sid;
  871. last_index_start = best_index_start;
  872. }
  873. av_free(unsorted_segments);
  874. return 0;
  875. }
  876. /**
  877. * Computes the absolute file offset of the given essence container offset
  878. */
  879. static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
  880. {
  881. int x;
  882. int64_t offset_in = offset; /* for logging */
  883. for (x = 0; x < mxf->partitions_count; x++) {
  884. MXFPartition *p = &mxf->partitions[x];
  885. if (p->body_sid != body_sid)
  886. continue;
  887. if (offset < p->essence_length || !p->essence_length) {
  888. *offset_out = p->essence_offset + offset;
  889. return 0;
  890. }
  891. offset -= p->essence_length;
  892. }
  893. av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %lx in BodySID %i - partial file?\n",
  894. offset_in, body_sid);
  895. return AVERROR_INVALIDDATA;
  896. }
  897. /**
  898. * Returns the length of the essence container with given BodySID, or zero if unknown
  899. */
  900. static int64_t mxf_essence_container_length(MXFContext *mxf, int body_sid)
  901. {
  902. int x;
  903. int64_t ret = 0;
  904. for (x = 0; x < mxf->partitions_count; x++) {
  905. MXFPartition *p = &mxf->partitions[x];
  906. if (p->body_sid != body_sid)
  907. continue;
  908. if (!p->essence_length)
  909. return 0;
  910. ret += p->essence_length;
  911. }
  912. return ret;
  913. }
  914. static int mxf_parse_index(MXFContext *mxf, int track_id, AVStream *st, MXFIndexTableSegment **sorted_segments, int nb_sorted_segments)
  915. {
  916. int64_t accumulated_offset = 0;
  917. int j, k, l, ret;
  918. int n_delta = track_id - 1; /* TrackID = 1-based stream index */
  919. if (track_id < 1) {
  920. av_log(mxf->fc, AV_LOG_ERROR, "TrackID not positive: %i\n", track_id);
  921. return AVERROR_INVALIDDATA;
  922. }
  923. for (j = 0; j < nb_sorted_segments; j++) {
  924. int duration, sample_duration = 1, last_sample_size = 0;
  925. int64_t segment_size;
  926. MXFIndexTableSegment *tableseg = sorted_segments[j];
  927. int index_delta = 1, last_size_unknown = 0;
  928. int64_t last_pos = 0;
  929. /* reset accumulated_offset on BodySID change */
  930. if (j > 0 && tableseg->body_sid != sorted_segments[j-1]->body_sid)
  931. accumulated_offset = 0;
  932. if (tableseg->nb_index_entries == 2 * tableseg->index_duration + 1) {
  933. /* Avid index - duplicate entries and total size as last entry */
  934. index_delta = 2;
  935. }
  936. if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
  937. continue;
  938. duration = tableseg->index_duration > 0 ? tableseg->index_duration :
  939. st->duration - st->nb_index_entries;
  940. segment_size = tableseg->edit_unit_byte_count * duration;
  941. /* check small EditUnitByteCount for audio */
  942. if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
  943. && !tableseg->index_duration) {
  944. /* duration might be prime relative to the new sample_duration,
  945. * which means we need to handle the last frame differently */
  946. sample_duration = 8192;
  947. last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
  948. tableseg->edit_unit_byte_count *= sample_duration;
  949. duration /= sample_duration;
  950. if (last_sample_size) duration++;
  951. }
  952. if (duration <= 0) {
  953. av_log(mxf->fc, AV_LOG_WARNING, "0 duration in index for stream %i\n", st->index);
  954. mxf->broken_index = 1;
  955. return 0;
  956. }
  957. for (k = l = 0; k < duration; k++, l += index_delta) {
  958. int64_t pos;
  959. int size, flags = 0;
  960. if (l < tableseg->nb_index_entries) {
  961. pos = tableseg->stream_offset_entries[l];
  962. if (n_delta < tableseg->nb_delta_entries) {
  963. if (n_delta < tableseg->nb_delta_entries - 1) {
  964. size =
  965. tableseg->slice_offset_entries[l][tableseg->slice[n_delta+1]-1] +
  966. tableseg->element_delta[n_delta+1] -
  967. tableseg->element_delta[n_delta];
  968. if (tableseg->slice[n_delta] > 0)
  969. size -= tableseg->slice_offset_entries[l][tableseg->slice[n_delta]-1];
  970. } else if (l < tableseg->nb_index_entries - 1) {
  971. size = tableseg->stream_offset_entries[l+1] -
  972. tableseg->stream_offset_entries[l] -
  973. tableseg->slice_offset_entries[l][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
  974. tableseg->element_delta[tableseg->nb_delta_entries-1];
  975. } else
  976. size = 0;
  977. if (tableseg->slice[n_delta] > 0)
  978. pos += tableseg->slice_offset_entries[l][tableseg->slice[n_delta]-1];
  979. pos += tableseg->element_delta[n_delta];
  980. } else
  981. size = 0;
  982. flags = !(tableseg->flag_entries[l] & 0x30) ? AVINDEX_KEYFRAME : 0;
  983. } else {
  984. pos = (int64_t)k * tableseg->edit_unit_byte_count + accumulated_offset;
  985. if (n_delta < tableseg->nb_delta_entries - 1)
  986. size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
  987. else {
  988. /* use smaller size for last sample if we should */
  989. if (last_sample_size && k == duration - 1)
  990. size = last_sample_size;
  991. else
  992. size = tableseg->edit_unit_byte_count;
  993. if (tableseg->nb_delta_entries)
  994. size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
  995. }
  996. if (n_delta < tableseg->nb_delta_entries)
  997. pos += tableseg->element_delta[n_delta];
  998. flags = AVINDEX_KEYFRAME;
  999. }
  1000. if (last_size_unknown)
  1001. st->index_entries[st->nb_index_entries-1].size = pos - last_pos;
  1002. last_size_unknown = size == 0;
  1003. last_pos = pos;
  1004. if (mxf_absolute_bodysid_offset(mxf, tableseg->body_sid, pos, &pos) < 0) {
  1005. /* probably partial file - no point going further for this stream */
  1006. break;
  1007. }
  1008. av_dlog(mxf->fc, "Stream %d IndexEntry %d TrackID %d Offset %"PRIx64" Timestamp %"PRId64"\n",
  1009. st->index, st->nb_index_entries, track_id, pos, sample_duration * st->nb_index_entries);
  1010. if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
  1011. return ret;
  1012. }
  1013. if (last_size_unknown) {
  1014. int64_t ecl = mxf_essence_container_length(mxf, tableseg->body_sid);
  1015. if (ecl > 0)
  1016. st->index_entries[st->nb_index_entries-1].size = ecl - last_pos;
  1017. }
  1018. accumulated_offset += segment_size;
  1019. }
  1020. return 0;
  1021. }
  1022. static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
  1023. {
  1024. int i, j, x;
  1025. int8_t max_temporal_offset = -128;
  1026. /* first compute how many entries we have */
  1027. for (i = 0; i < index_table->nb_segments; i++) {
  1028. MXFIndexTableSegment *s = index_table->segments[i];
  1029. if (!s->nb_index_entries)
  1030. return 0; /* no TemporalOffsets */
  1031. index_table->nb_ptses += s->index_duration;
  1032. }
  1033. /* paranoid check */
  1034. if (index_table->nb_ptses <= 0)
  1035. return 0;
  1036. if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
  1037. !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry)))) {
  1038. av_freep(&index_table->ptses);
  1039. return AVERROR(ENOMEM);
  1040. }
  1041. /* we may have a few bad TemporalOffsets
  1042. * make sure the corresponding PTSes don't have the bogus value 0 */
  1043. for (x = 0; x < index_table->nb_ptses; x++)
  1044. index_table->ptses[x] = AV_NOPTS_VALUE;
  1045. /**
  1046. * We have this:
  1047. *
  1048. * x TemporalOffset
  1049. * 0: 0
  1050. * 1: 1
  1051. * 2: 1
  1052. * 3: -2
  1053. * 4: 1
  1054. * 5: 1
  1055. * 6: -2
  1056. *
  1057. * We want to transform it into this:
  1058. *
  1059. * x DTS PTS
  1060. * 0: -1 0
  1061. * 1: 0 3
  1062. * 2: 1 1
  1063. * 3: 2 2
  1064. * 4: 3 6
  1065. * 5: 4 4
  1066. * 6: 5 5
  1067. *
  1068. * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
  1069. * then settings mxf->first_dts = -max(TemporalOffset[x]).
  1070. * The latter makes DTS <= PTS.
  1071. */
  1072. for (i = x = 0; i < index_table->nb_segments; i++) {
  1073. MXFIndexTableSegment *s = index_table->segments[i];
  1074. int index_delta = 1;
  1075. if (s->nb_index_entries == 2 * s->index_duration + 1)
  1076. index_delta = 2; /* Avid index */
  1077. for (j = 0; j < s->nb_index_entries; j += index_delta, x++) {
  1078. int offset = s->temporal_offset_entries[j] / index_delta;
  1079. int index = x + offset;
  1080. index_table->fake_index[x].timestamp = x;
  1081. index_table->fake_index[x].flags = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
  1082. if (index < 0 || index >= index_table->nb_ptses) {
  1083. av_log(mxf->fc, AV_LOG_ERROR,
  1084. "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
  1085. x, offset, index);
  1086. continue;
  1087. }
  1088. index_table->ptses[index] = x;
  1089. max_temporal_offset = FFMAX(max_temporal_offset, offset);
  1090. }
  1091. }
  1092. index_table->first_dts = -max_temporal_offset;
  1093. return 0;
  1094. }
  1095. /**
  1096. * Sorts and collects index table segments into index tables.
  1097. * Also computes PTSes if possible.
  1098. */
  1099. static int mxf_compute_index_tables(MXFContext *mxf)
  1100. {
  1101. int i, j, k, ret, nb_sorted_segments;
  1102. MXFIndexTableSegment **sorted_segments = NULL;
  1103. if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
  1104. nb_sorted_segments <= 0) {
  1105. av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
  1106. return 0;
  1107. }
  1108. /* sanity check and count unique BodySIDs/IndexSIDs */
  1109. for (i = 0; i < nb_sorted_segments; i++) {
  1110. if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
  1111. mxf->nb_index_tables++;
  1112. else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
  1113. av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
  1114. ret = AVERROR_INVALIDDATA;
  1115. goto finish_decoding_index;
  1116. }
  1117. }
  1118. if (!(mxf->index_tables = av_calloc(mxf->nb_index_tables, sizeof(MXFIndexTable)))) {
  1119. av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
  1120. ret = AVERROR(ENOMEM);
  1121. goto finish_decoding_index;
  1122. }
  1123. /* distribute sorted segments to index tables */
  1124. for (i = j = 0; i < nb_sorted_segments; i++) {
  1125. if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
  1126. /* next IndexSID */
  1127. j++;
  1128. }
  1129. mxf->index_tables[j].nb_segments++;
  1130. }
  1131. for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
  1132. MXFIndexTable *t = &mxf->index_tables[j];
  1133. if (!(t->segments = av_calloc(t->nb_segments, sizeof(MXFIndexTableSegment*)))) {
  1134. av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment pointer array\n");
  1135. ret = AVERROR(ENOMEM);
  1136. goto finish_decoding_index;
  1137. }
  1138. if (sorted_segments[i]->index_start_position)
  1139. av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
  1140. sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
  1141. memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
  1142. t->index_sid = sorted_segments[i]->index_sid;
  1143. t->body_sid = sorted_segments[i]->body_sid;
  1144. if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
  1145. goto finish_decoding_index;
  1146. /* fix zero IndexDurations */
  1147. for (k = 0; k < t->nb_segments; k++) {
  1148. if (t->segments[k]->index_duration)
  1149. continue;
  1150. if (t->nb_segments > 1)
  1151. av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
  1152. t->index_sid, k);
  1153. if (mxf->fc->nb_streams <= 0) {
  1154. av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
  1155. break;
  1156. }
  1157. /* assume the first stream's duration is reasonable
  1158. * leave index_duration = 0 on further segments in case we have any (unlikely)
  1159. */
  1160. t->segments[k]->index_duration = mxf->fc->streams[0]->duration;
  1161. break;
  1162. }
  1163. }
  1164. ret = 0;
  1165. finish_decoding_index:
  1166. av_free(sorted_segments);
  1167. return ret;
  1168. }
  1169. static int mxf_parse_structural_metadata(MXFContext *mxf)
  1170. {
  1171. MXFPackage *material_package = NULL;
  1172. MXFPackage *temp_package = NULL;
  1173. int i, j, k, ret, nb_sorted_segments;
  1174. MXFIndexTableSegment **sorted_segments = NULL;
  1175. av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
  1176. /* TODO: handle multiple material packages (OP3x) */
  1177. for (i = 0; i < mxf->packages_count; i++) {
  1178. material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
  1179. if (material_package) break;
  1180. }
  1181. if (!material_package) {
  1182. av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
  1183. return -1;
  1184. }
  1185. if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
  1186. nb_sorted_segments <= 0) {
  1187. av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
  1188. mxf->broken_index = 1;
  1189. }
  1190. for (i = 0; i < material_package->tracks_count; i++) {
  1191. MXFPackage *source_package = NULL;
  1192. MXFTrack *material_track = NULL;
  1193. MXFTrack *source_track = NULL;
  1194. MXFTrack *temp_track = NULL;
  1195. MXFDescriptor *descriptor = NULL;
  1196. MXFStructuralComponent *component = NULL;
  1197. UID *essence_container_ul = NULL;
  1198. const MXFCodecUL *codec_ul = NULL;
  1199. const MXFCodecUL *container_ul = NULL;
  1200. AVStream *st;
  1201. if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
  1202. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
  1203. continue;
  1204. }
  1205. if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
  1206. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
  1207. continue;
  1208. }
  1209. /* TODO: handle multiple source clips */
  1210. for (j = 0; j < material_track->sequence->structural_components_count; j++) {
  1211. /* TODO: handle timecode component */
  1212. component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
  1213. if (!component)
  1214. continue;
  1215. for (k = 0; k < mxf->packages_count; k++) {
  1216. temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
  1217. if (!temp_package)
  1218. continue;
  1219. if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
  1220. source_package = temp_package;
  1221. break;
  1222. }
  1223. }
  1224. if (!source_package) {
  1225. av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
  1226. break;
  1227. }
  1228. for (k = 0; k < source_package->tracks_count; k++) {
  1229. if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
  1230. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
  1231. ret = -1;
  1232. goto fail_and_free;
  1233. }
  1234. if (temp_track->track_id == component->source_track_id) {
  1235. source_track = temp_track;
  1236. break;
  1237. }
  1238. }
  1239. if (!source_track) {
  1240. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
  1241. break;
  1242. }
  1243. }
  1244. if (!source_track)
  1245. continue;
  1246. if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
  1247. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
  1248. ret = -1;
  1249. goto fail_and_free;
  1250. }
  1251. /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
  1252. * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
  1253. if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
  1254. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
  1255. continue;
  1256. }
  1257. st = avformat_new_stream(mxf->fc, NULL);
  1258. if (!st) {
  1259. av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
  1260. ret = AVERROR(ENOMEM);
  1261. goto fail_and_free;
  1262. }
  1263. st->id = source_track->track_id;
  1264. st->priv_data = source_track;
  1265. st->duration = component->duration;
  1266. if (st->duration == -1)
  1267. st->duration = AV_NOPTS_VALUE;
  1268. st->start_time = component->start_position;
  1269. avpriv_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
  1270. PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
  1271. codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
  1272. st->codec->codec_type = codec_ul->id;
  1273. source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
  1274. if (source_package->descriptor) {
  1275. if (source_package->descriptor->type == MultipleDescriptor) {
  1276. for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
  1277. MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
  1278. if (!sub_descriptor) {
  1279. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
  1280. continue;
  1281. }
  1282. if (sub_descriptor->linked_track_id == source_track->track_id) {
  1283. descriptor = sub_descriptor;
  1284. break;
  1285. }
  1286. }
  1287. } else if (source_package->descriptor->type == Descriptor)
  1288. descriptor = source_package->descriptor;
  1289. }
  1290. if (!descriptor) {
  1291. av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
  1292. continue;
  1293. }
  1294. PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
  1295. PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
  1296. essence_container_ul = &descriptor->essence_container_ul;
  1297. /* HACK: replacing the original key with mxf_encrypted_essence_container
  1298. * is not allowed according to s429-6, try to find correct information anyway */
  1299. if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
  1300. av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
  1301. for (k = 0; k < mxf->metadata_sets_count; k++) {
  1302. MXFMetadataSet *metadata = mxf->metadata_sets[k];
  1303. if (metadata->type == CryptoContext) {
  1304. essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. /* HACK: revert to the old demuxing/seeking scode for D-10 for now */
  1310. if (mxf_match_uid(essence_container_ul, mxf_d10_ul, 14))
  1311. mxf->d10 = 1;
  1312. /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
  1313. codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
  1314. st->codec->codec_id = codec_ul->id;
  1315. if (descriptor->extradata) {
  1316. st->codec->extradata = descriptor->extradata;
  1317. st->codec->extradata_size = descriptor->extradata_size;
  1318. }
  1319. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1320. container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
  1321. if (st->codec->codec_id == CODEC_ID_NONE)
  1322. st->codec->codec_id = container_ul->id;
  1323. st->codec->width = descriptor->width;
  1324. st->codec->height = descriptor->height;
  1325. if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
  1326. st->codec->pix_fmt = descriptor->pix_fmt;
  1327. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1328. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  1329. container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
  1330. if (st->codec->codec_id == CODEC_ID_NONE)
  1331. st->codec->codec_id = container_ul->id;
  1332. st->codec->channels = descriptor->channels;
  1333. st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
  1334. st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
  1335. /* TODO: implement CODEC_ID_RAWAUDIO */
  1336. if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
  1337. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1338. st->codec->codec_id = CODEC_ID_PCM_S24LE;
  1339. else if (descriptor->bits_per_sample == 32)
  1340. st->codec->codec_id = CODEC_ID_PCM_S32LE;
  1341. } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
  1342. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1343. st->codec->codec_id = CODEC_ID_PCM_S24BE;
  1344. else if (descriptor->bits_per_sample == 32)
  1345. st->codec->codec_id = CODEC_ID_PCM_S32BE;
  1346. } else if (st->codec->codec_id == CODEC_ID_MP2) {
  1347. st->need_parsing = AVSTREAM_PARSE_FULL;
  1348. }
  1349. }
  1350. if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
  1351. /* TODO: decode timestamps */
  1352. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  1353. }
  1354. if (!mxf->broken_index &&
  1355. (ret = mxf_parse_index(mxf, material_track->track_id, st, sorted_segments, nb_sorted_segments)))
  1356. goto fail_and_free;
  1357. }
  1358. ret = 0;
  1359. fail_and_free:
  1360. av_free(sorted_segments);
  1361. return ret;
  1362. }
  1363. static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
  1364. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
  1365. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
  1366. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
  1367. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
  1368. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
  1369. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
  1370. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
  1371. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
  1372. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
  1373. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
  1374. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
  1375. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
  1376. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
  1377. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
  1378. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
  1379. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
  1380. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
  1381. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */
  1382. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
  1383. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
  1384. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG 2 Video */
  1385. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
  1386. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
  1387. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
  1388. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
  1389. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
  1390. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
  1391. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
  1392. };
  1393. static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
  1394. {
  1395. AVIOContext *pb = mxf->fc->pb;
  1396. MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
  1397. uint64_t klv_end = avio_tell(pb) + klv->length;
  1398. if (!ctx)
  1399. return -1;
  1400. while (avio_tell(pb) + 4 < klv_end) {
  1401. int tag = avio_rb16(pb);
  1402. int size = avio_rb16(pb); /* KLV specified by 0x53 */
  1403. uint64_t next = avio_tell(pb) + size;
  1404. UID uid = {0};
  1405. av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
  1406. if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
  1407. av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
  1408. continue;
  1409. }
  1410. if (tag > 0x7FFF) { /* dynamic tag */
  1411. int i;
  1412. for (i = 0; i < mxf->local_tags_count; i++) {
  1413. int local_tag = AV_RB16(mxf->local_tags+i*18);
  1414. if (local_tag == tag) {
  1415. memcpy(uid, mxf->local_tags+i*18+2, 16);
  1416. av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
  1417. PRINT_KEY(mxf->fc, "uid", uid);
  1418. }
  1419. }
  1420. }
  1421. if (ctx_size && tag == 0x3C0A)
  1422. avio_read(pb, ctx->uid, 16);
  1423. else if (read_child(ctx, pb, tag, size, uid, -1) < 0)
  1424. return -1;
  1425. avio_seek(pb, next, SEEK_SET);
  1426. }
  1427. if (ctx_size) ctx->type = type;
  1428. return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
  1429. }
  1430. /**
  1431. * Seeks to the previous partition, if possible
  1432. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1433. */
  1434. static int mxf_seek_to_previous_partition(MXFContext *mxf)
  1435. {
  1436. AVIOContext *pb = mxf->fc->pb;
  1437. if (!mxf->current_partition ||
  1438. mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
  1439. return 0; /* we've parsed all partitions */
  1440. /* seek to previous partition */
  1441. avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
  1442. mxf->current_partition = NULL;
  1443. av_dlog(mxf->fc, "seeking to previous partition\n");
  1444. return 1;
  1445. }
  1446. /**
  1447. * Called when essence is encountered
  1448. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1449. */
  1450. static int mxf_parse_handle_essence(MXFContext *mxf)
  1451. {
  1452. AVIOContext *pb = mxf->fc->pb;
  1453. int64_t ret;
  1454. if (!mxf->current_partition) {
  1455. av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to PartitionPack\n");
  1456. return AVERROR_INVALIDDATA;
  1457. }
  1458. if (mxf->parsing_backward) {
  1459. return mxf_seek_to_previous_partition(mxf);
  1460. } else {
  1461. if (!mxf->footer_partition) {
  1462. av_dlog(mxf->fc, "no footer\n");
  1463. return 0;
  1464. }
  1465. av_dlog(mxf->fc, "seeking to footer\n");
  1466. /* remember where we were so we don't end up seeking further back than this */
  1467. mxf->last_forward_tell = avio_tell(pb);
  1468. if (!pb->seekable) {
  1469. av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
  1470. return -1;
  1471. }
  1472. /* seek to footer partition and parse backward */
  1473. if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
  1474. av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
  1475. mxf->run_in + mxf->footer_partition, ret);
  1476. return ret;
  1477. }
  1478. mxf->current_partition = NULL;
  1479. mxf->parsing_backward = 1;
  1480. }
  1481. return 1;
  1482. }
  1483. /**
  1484. * Called when the next partition or EOF is encountered
  1485. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1486. */
  1487. static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
  1488. {
  1489. return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
  1490. }
  1491. /**
  1492. * Figures out the proper offset and length of the essence container in each partition
  1493. */
  1494. static void mxf_compute_essence_containers(MXFContext *mxf)
  1495. {
  1496. int x;
  1497. /* everything is already correct */
  1498. if (mxf->op == OPAtom)
  1499. return;
  1500. for (x = 0; x < mxf->partitions_count; x++) {
  1501. MXFPartition *p = &mxf->partitions[x];
  1502. if (!p->body_sid)
  1503. continue; /* BodySID == 0 -> no essence */
  1504. if (x >= mxf->partitions_count - 1)
  1505. break; /* last partition - can't compute length (and we don't need to) */
  1506. /* essence container spans to the next partition */
  1507. p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
  1508. if (p->essence_length < 0) {
  1509. /* next ThisPartition < essence_offset */
  1510. p->essence_length = 0;
  1511. av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %lx\n",
  1512. x+1, mxf->partitions[x+1].this_partition);
  1513. }
  1514. }
  1515. }
  1516. static int64_t round_to_kag(int64_t position, int kag_size)
  1517. {
  1518. /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
  1519. /* NOTE: kag_size may be any integer between 1 - 2^10 */
  1520. int64_t ret = (position / kag_size) * kag_size;
  1521. return ret == position ? ret : ret + kag_size;
  1522. }
  1523. static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1524. {
  1525. MXFContext *mxf = s->priv_data;
  1526. KLVPacket klv;
  1527. int64_t essence_offset = 0;
  1528. int ret;
  1529. mxf->last_forward_tell = INT64_MAX;
  1530. if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
  1531. av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
  1532. return -1;
  1533. }
  1534. avio_seek(s->pb, -14, SEEK_CUR);
  1535. mxf->fc = s;
  1536. mxf->run_in = avio_tell(s->pb);
  1537. while (!url_feof(s->pb)) {
  1538. const MXFMetadataReadTableEntry *metadata;
  1539. if (klv_read_packet(&klv, s->pb) < 0) {
  1540. /* EOF - seek to previous partition or stop */
  1541. if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
  1542. break;
  1543. else
  1544. continue;
  1545. }
  1546. PRINT_KEY(s, "read header", klv.key);
  1547. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  1548. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
  1549. IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
  1550. IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
  1551. IS_KLV_KEY(klv.key, mxf_system_item_key)) {
  1552. if (!mxf->current_partition->essence_offset) {
  1553. /* for OP1a we compute essence_offset
  1554. * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
  1555. * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
  1556. * for OPAtom we still need the actual essence_offset though (the KL's length can vary)
  1557. */
  1558. int64_t op1a_essence_offset =
  1559. round_to_kag(mxf->current_partition->this_partition +
  1560. mxf->current_partition->pack_length, mxf->current_partition->kag_size) +
  1561. round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
  1562. round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size);
  1563. if (mxf->op == OPAtom) {
  1564. /* point essence_offset to the actual data
  1565. * OPAtom has all the essence in one big KLV
  1566. */
  1567. mxf->current_partition->essence_offset = avio_tell(s->pb);
  1568. mxf->current_partition->essence_length = klv.length;
  1569. } else {
  1570. /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */
  1571. mxf->current_partition->essence_offset = op1a_essence_offset;
  1572. }
  1573. }
  1574. if (!essence_offset)
  1575. essence_offset = klv.offset;
  1576. /* seek to footer, previous partition or stop */
  1577. if (mxf_parse_handle_essence(mxf) <= 0)
  1578. break;
  1579. continue;
  1580. } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
  1581. klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
  1582. /* next partition pack - keep going, seek to previous partition or stop */
  1583. if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
  1584. break;
  1585. }
  1586. for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
  1587. if (IS_KLV_KEY(klv.key, metadata->key)) {
  1588. int res;
  1589. if (klv.key[5] == 0x53) {
  1590. res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
  1591. } else {
  1592. uint64_t next = avio_tell(s->pb) + klv.length;
  1593. res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
  1594. avio_seek(s->pb, next, SEEK_SET);
  1595. }
  1596. if (res < 0) {
  1597. av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
  1598. return -1;
  1599. }
  1600. break;
  1601. }
  1602. }
  1603. if (!metadata->read)
  1604. avio_skip(s->pb, klv.length);
  1605. }
  1606. /* FIXME avoid seek */
  1607. if (!essence_offset) {
  1608. av_log(s, AV_LOG_ERROR, "no essence\n");
  1609. return AVERROR_INVALIDDATA;
  1610. }
  1611. avio_seek(s->pb, essence_offset, SEEK_SET);
  1612. mxf_compute_essence_containers(mxf);
  1613. /* we need to do this before computing the index tables
  1614. * to be able to fill in zero IndexDurations with st->duration */
  1615. if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
  1616. return ret;
  1617. if ((ret = mxf_compute_index_tables(mxf)) < 0)
  1618. return ret;
  1619. if (mxf->nb_index_tables > 1) {
  1620. /* TODO: look up which IndexSID to use via EssenceContainerData */
  1621. av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
  1622. mxf->nb_index_tables, mxf->index_tables[0].index_sid);
  1623. } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
  1624. av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
  1625. return AVERROR_INVALIDDATA;
  1626. }
  1627. return 0;
  1628. }
  1629. static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
  1630. {
  1631. KLVPacket klv;
  1632. while (!url_feof(s->pb)) {
  1633. if (klv_read_packet(&klv, s->pb) < 0)
  1634. return -1;
  1635. PRINT_KEY(s, "read packet", klv.key);
  1636. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  1637. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
  1638. int res = mxf_decrypt_triplet(s, pkt, &klv);
  1639. if (res < 0) {
  1640. av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
  1641. return -1;
  1642. }
  1643. return 0;
  1644. }
  1645. if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
  1646. IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
  1647. int index = mxf_get_stream_index(s, &klv);
  1648. if (index < 0) {
  1649. av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
  1650. goto skip;
  1651. }
  1652. if (s->streams[index]->discard == AVDISCARD_ALL)
  1653. goto skip;
  1654. /* check for 8 channels AES3 element */
  1655. if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
  1656. if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
  1657. av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
  1658. return -1;
  1659. }
  1660. } else {
  1661. int ret = av_get_packet(s->pb, pkt, klv.length);
  1662. if (ret < 0)
  1663. return ret;
  1664. }
  1665. pkt->stream_index = index;
  1666. pkt->pos = klv.offset;
  1667. return 0;
  1668. } else
  1669. skip:
  1670. avio_skip(s->pb, klv.length);
  1671. }
  1672. return AVERROR_EOF;
  1673. }
  1674. static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
  1675. {
  1676. MXFContext *mxf = s->priv_data;
  1677. AVIndexEntry *e;
  1678. int ret;
  1679. int64_t ret64;
  1680. KLVPacket klv;
  1681. AVStream *st;
  1682. /* TODO: better logic for this?
  1683. * only files that lack all index segments prior to the essence need this */
  1684. if (!s->pb->seekable && mxf->op != OPAtom || mxf->d10 || mxf->broken_index)
  1685. return mxf_read_packet_old(s, pkt);
  1686. if (mxf->current_stream >= s->nb_streams) {
  1687. mxf->current_edit_unit++;
  1688. mxf->current_stream = 0;
  1689. }
  1690. st = s->streams[mxf->current_stream];
  1691. if (mxf->current_edit_unit >= st->nb_index_entries)
  1692. return AVERROR_EOF;
  1693. e = &st->index_entries[mxf->current_edit_unit];
  1694. if ((ret64 = avio_seek(s->pb, e->pos, SEEK_SET)) < 0)
  1695. return ret64;
  1696. if (mxf->op == OPAtom) {
  1697. /* OPAtom - no KL, just essence */
  1698. if ((ret = av_get_packet(s->pb, pkt, e->size)) != e->size)
  1699. return ret < 0 ? ret : AVERROR_EOF;
  1700. } else {
  1701. /* read KL, read L bytes of essence */
  1702. if ((ret = klv_read_packet(&klv, s->pb)) < 0)
  1703. return ret;
  1704. /* untested, but looks OK */
  1705. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
  1706. int res = mxf_decrypt_triplet(s, pkt, &klv);
  1707. if (res < 0) {
  1708. av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
  1709. return -1;
  1710. }
  1711. return 0;
  1712. }
  1713. if ((ret = av_get_packet(s->pb, pkt, klv.length)) != klv.length)
  1714. return ret < 0 ? ret : AVERROR_EOF;
  1715. pkt->pos = e->pos;
  1716. }
  1717. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && mxf->ptses && mxf->current_edit_unit < mxf->nb_ptses) {
  1718. pkt->dts = mxf->current_edit_unit + mxf->first_dts;
  1719. pkt->pts = mxf->ptses[mxf->current_edit_unit];
  1720. }
  1721. pkt->stream_index = mxf->current_stream++;
  1722. return 0;
  1723. }
  1724. static int mxf_read_close(AVFormatContext *s)
  1725. {
  1726. MXFContext *mxf = s->priv_data;
  1727. MXFIndexTableSegment *seg;
  1728. int i, j;
  1729. av_freep(&mxf->packages_refs);
  1730. for (i = 0; i < s->nb_streams; i++)
  1731. s->streams[i]->priv_data = NULL;
  1732. for (i = 0; i < mxf->metadata_sets_count; i++) {
  1733. switch (mxf->metadata_sets[i]->type) {
  1734. case MultipleDescriptor:
  1735. av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
  1736. break;
  1737. case Sequence:
  1738. av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
  1739. break;
  1740. case SourcePackage:
  1741. case MaterialPackage:
  1742. av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
  1743. break;
  1744. case IndexTableSegment:
  1745. seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
  1746. if (seg->slice_count)
  1747. for (j = 0; j < seg->nb_index_entries; j++)
  1748. av_freep(&seg->slice_offset_entries[j]);
  1749. av_freep(&seg->slice);
  1750. av_freep(&seg->element_delta);
  1751. av_freep(&seg->temporal_offset_entries);
  1752. av_freep(&seg->flag_entries);
  1753. av_freep(&seg->stream_offset_entries);
  1754. av_freep(&seg->slice_offset_entries);
  1755. break;
  1756. default:
  1757. break;
  1758. }
  1759. av_freep(&mxf->metadata_sets[i]);
  1760. }
  1761. av_freep(&mxf->partitions);
  1762. av_freep(&mxf->metadata_sets);
  1763. av_freep(&mxf->aesc);
  1764. av_freep(&mxf->local_tags);
  1765. av_freep(&mxf->ptses);
  1766. for (i = 0; i < mxf->nb_index_tables; i++) {
  1767. av_freep(&mxf->index_tables[i].segments);
  1768. av_freep(&mxf->index_tables[i].fake_index);
  1769. }
  1770. av_freep(&mxf->index_tables);
  1771. return 0;
  1772. }
  1773. static int mxf_probe(AVProbeData *p) {
  1774. uint8_t *bufp = p->buf;
  1775. uint8_t *end = p->buf + p->buf_size;
  1776. if (p->buf_size < sizeof(mxf_header_partition_pack_key))
  1777. return 0;
  1778. /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
  1779. end -= sizeof(mxf_header_partition_pack_key);
  1780. for (; bufp < end; bufp++) {
  1781. if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
  1782. return AVPROBE_SCORE_MAX;
  1783. }
  1784. return 0;
  1785. }
  1786. /* rudimentary byte seek */
  1787. /* XXX: use MXF Index */
  1788. static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  1789. {
  1790. AVStream *st = s->streams[stream_index];
  1791. int64_t seconds;
  1792. MXFContext* mxf = s->priv_data;
  1793. int64_t seekpos;
  1794. int index;
  1795. if (mxf->d10) {
  1796. if (!s->bit_rate)
  1797. return -1;
  1798. if (sample_time < 0)
  1799. sample_time = 0;
  1800. seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
  1801. if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
  1802. return -1;
  1803. ff_update_cur_dts(s, st, sample_time);
  1804. } else {
  1805. if (st->nb_index_entries <= 0)
  1806. return -1;
  1807. index = av_index_search_timestamp(st, sample_time, flags);
  1808. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, sample_time, index);
  1809. if (index < 0) {
  1810. if (sample_time < st->index_entries[0].timestamp)
  1811. index = 0;
  1812. else
  1813. return -1;
  1814. }
  1815. seekpos = st->index_entries[index].pos;
  1816. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1817. mxf->current_edit_unit = st->index_entries[index].timestamp;
  1818. mxf->current_stream = 0;
  1819. avio_seek(s->pb, seekpos, SEEK_SET);
  1820. }
  1821. return 0;
  1822. }
  1823. AVInputFormat ff_mxf_demuxer = {
  1824. .name = "mxf",
  1825. .long_name = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
  1826. .priv_data_size = sizeof(MXFContext),
  1827. .read_probe = mxf_probe,
  1828. .read_header = mxf_read_header,
  1829. .read_packet = mxf_read_packet,
  1830. .read_close = mxf_read_close,
  1831. .read_seek = mxf_read_seek,
  1832. };