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.

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