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.

1946 lines
72KB

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