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.

1800 lines
67KB

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