3 * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
5 * This file is part of FFmpeg.
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.
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.
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
24 * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
25 * SMPTE 377M MXF File Format Specifications
26 * SMPTE 378M Operational Pattern 1a
27 * SMPTE 379M MXF Generic Container
28 * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29 * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
30 * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
33 * Search for Track numbers which will identify essence element KLV packets.
34 * Search for SourcePackage which define tracks which contains Track numbers.
35 * Material Package contains tracks with reference to SourcePackage tracks.
36 * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
37 * Assign Descriptors to correct Tracks.
39 * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
40 * Metadata parsing resolves Strong References to objects.
42 * Simple demuxer, only OP1A supported and some files might not work at all.
43 * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
48 #include "libavutil/aes.h"
49 #include "libavutil/mathematics.h"
50 #include "libavcodec/bytestream.h"
72 OPSONYOpt, /* FATE sample, violates the spec in places */
78 MXFPartitionType type;
79 uint64_t previous_partition;
82 int64_t this_partition;
83 int64_t essence_offset; /* absolute offset of essence */
84 int64_t essence_length;
86 int64_t header_byte_count;
87 int64_t index_byte_count;
93 enum MXFMetadataSetType type;
94 UID source_container_ul;
99 enum MXFMetadataSetType type;
100 UID source_package_uid;
101 UID data_definition_ul;
103 int64_t start_position;
105 } MXFStructuralComponent;
109 enum MXFMetadataSetType type;
110 UID data_definition_ul;
111 UID *structural_components_refs;
112 int structural_components_count;
118 enum MXFMetadataSetType type;
119 MXFSequence *sequence; /* mandatory, and only one */
122 uint8_t track_number[4];
123 AVRational edit_rate;
128 enum MXFMetadataSetType type;
129 UID essence_container_ul;
130 UID essence_codec_ul;
131 AVRational sample_rate;
132 AVRational aspect_ratio;
137 UID *sub_descriptors_refs;
138 int sub_descriptors_count;
142 enum PixelFormat pix_fmt;
147 enum MXFMetadataSetType type;
148 int edit_unit_byte_count;
152 AVRational index_edit_rate;
153 uint64_t index_start_position;
154 uint64_t index_duration;
157 int nb_delta_entries;
158 int8_t *temporal_offset_entries;
160 uint64_t *stream_offset_entries;
161 uint32_t **slice_offset_entries;
162 int nb_index_entries;
163 } MXFIndexTableSegment;
167 enum MXFMetadataSetType type;
171 MXFDescriptor *descriptor; /* only one */
177 enum MXFMetadataSetType type;
181 MXFPartition *partitions;
182 unsigned partitions_count;
186 MXFMetadataSet **metadata_sets;
187 int metadata_sets_count;
191 int local_tags_count;
192 uint64_t footer_partition;
193 KLVPacket current_klv_data;
194 int current_klv_index;
196 MXFPartition *current_partition;
197 int parsing_backward;
198 int64_t last_forward_tell;
199 int last_forward_partition;
200 int current_edit_unit;
205 enum MXFWrappingScheme {
210 /* NOTE: klv_offset is not set (-1) for local keys */
211 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
215 MXFMetadataReadFunc *read;
217 enum MXFMetadataSetType type;
218 } MXFMetadataReadTableEntry;
220 /* partial keys to match */
221 static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
222 static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
223 static const uint8_t mxf_system_item_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
224 static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
225 /* complete keys to match */
226 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 };
227 static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
228 static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
229 static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
231 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
233 static int64_t klv_decode_ber_length(AVIOContext *pb)
235 uint64_t size = avio_r8(pb);
236 if (size & 0x80) { /* long form */
237 int bytes_num = size & 0x7f;
238 /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
243 size = size << 8 | avio_r8(pb);
248 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
251 for (i = 0; i < size && !url_feof(pb); i++) {
255 else if (b != key[i])
261 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
263 if (!mxf_read_sync(pb, mxf_klv_key, 4))
265 klv->offset = avio_tell(pb) - 4;
266 memcpy(klv->key, mxf_klv_key, 4);
267 avio_read(pb, klv->key + 4, 12);
268 klv->length = klv_decode_ber_length(pb);
269 return klv->length == -1 ? -1 : 0;
272 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
276 for (i = 0; i < s->nb_streams; i++) {
277 MXFTrack *track = s->streams[i]->priv_data;
279 if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
282 /* return 0 if only one stream, for OP Atom files with 0 as track number */
283 return s->nb_streams == 1 ? 0 : -1;
286 /* XXX: use AVBitStreamFilter */
287 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
289 const uint8_t *buf_ptr, *end_ptr;
293 if (length > 61444) /* worst case PAL 1920 samples 8 channels */
295 length = av_get_packet(pb, pkt, length);
298 data_ptr = pkt->data;
299 end_ptr = pkt->data + length;
300 buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
301 for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
302 for (i = 0; i < st->codec->channels; i++) {
303 uint32_t sample = bytestream_get_le32(&buf_ptr);
304 if (st->codec->bits_per_coded_sample == 24)
305 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
307 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
309 buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
311 av_shrink_packet(pkt, data_ptr - pkt->data);
315 static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
317 static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
318 MXFContext *mxf = s->priv_data;
319 AVIOContext *pb = s->pb;
320 int64_t end = avio_tell(pb) + klv->length;
323 uint64_t plaintext_size;
328 if (!mxf->aesc && s->key && s->keylen == 16) {
329 mxf->aesc = av_malloc(av_aes_size);
332 av_aes_init(mxf->aesc, s->key, 128, 1);
335 avio_skip(pb, klv_decode_ber_length(pb));
337 klv_decode_ber_length(pb);
338 plaintext_size = avio_rb64(pb);
340 klv_decode_ber_length(pb);
341 avio_read(pb, klv->key, 16);
342 if (!IS_KLV_KEY(klv, mxf_essence_element_key))
344 index = mxf_get_stream_index(s, klv);
348 klv_decode_ber_length(pb);
349 orig_size = avio_rb64(pb);
350 if (orig_size < plaintext_size)
353 size = klv_decode_ber_length(pb);
354 if (size < 32 || size - 32 < orig_size)
356 avio_read(pb, ivec, 16);
357 avio_read(pb, tmpbuf, 16);
359 av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
360 if (memcmp(tmpbuf, checkv, 16))
361 av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
363 size = av_get_packet(pb, pkt, size);
366 else if (size < plaintext_size)
367 return AVERROR_INVALIDDATA;
368 size -= plaintext_size;
370 av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
371 &pkt->data[plaintext_size], size >> 4, ivec, 1);
372 av_shrink_packet(pkt, orig_size);
373 pkt->stream_index = index;
374 avio_skip(pb, end - avio_tell(pb));
378 static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
382 while (!url_feof(s->pb)) {
383 if (klv_read_packet(&klv, s->pb) < 0)
385 PRINT_KEY(s, "read packet", klv.key);
386 av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
387 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
388 int res = mxf_decrypt_triplet(s, pkt, &klv);
390 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
395 if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
396 int index = mxf_get_stream_index(s, &klv);
398 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
401 if (s->streams[index]->discard == AVDISCARD_ALL)
403 /* check for 8 channels AES3 element */
404 if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
405 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
406 av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
410 int ret = av_get_packet(s->pb, pkt, klv.length);
414 pkt->stream_index = index;
415 pkt->pos = klv.offset;
419 avio_skip(s->pb, klv.length);
424 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
426 MXFContext *mxf = s->priv_data;
433 /* TODO: better logic for this?
434 * only files that lack all index segments prior to the essence need this */
435 if (!s->pb->seekable && mxf->op != OPAtom || mxf->d10)
436 return mxf_read_packet_old(s, pkt);
438 if (mxf->current_stream >= s->nb_streams) {
439 mxf->current_edit_unit++;
440 mxf->current_stream = 0;
443 st = s->streams[mxf->current_stream];
445 if (mxf->current_edit_unit >= st->nb_index_entries)
448 e = &st->index_entries[mxf->current_edit_unit];
450 if ((ret64 = avio_seek(s->pb, e->pos, SEEK_SET)) < 0)
453 if (mxf->op == OPAtom) {
454 /* OPAtom - no KL, just essence */
455 if ((ret = av_get_packet(s->pb, pkt, e->size)) != e->size)
456 return ret < 0 ? ret : AVERROR_EOF;
458 /* read KL, read L bytes of essence */
459 if ((ret = klv_read_packet(&klv, s->pb)) < 0)
462 /* untested, but looks OK */
463 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
464 int res = mxf_decrypt_triplet(s, pkt, &klv);
466 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
472 if ((ret = av_get_packet(s->pb, pkt, klv.length)) != klv.length)
473 return ret < 0 ? ret : AVERROR_EOF;
478 pkt->stream_index = mxf->current_stream++;
483 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
485 MXFContext *mxf = arg;
486 int item_num = avio_rb32(pb);
487 int item_len = avio_rb32(pb);
489 if (item_len != 18) {
490 av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
493 if (item_num > UINT_MAX / item_len)
495 mxf->local_tags_count = item_num;
496 mxf->local_tags = av_malloc(item_num*item_len);
497 if (!mxf->local_tags)
499 avio_read(pb, mxf->local_tags, item_num*item_len);
503 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
505 MXFContext *mxf = arg;
506 MXFPartition *partition;
508 uint64_t footer_partition;
510 if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
511 return AVERROR(ENOMEM);
513 mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
514 if (!mxf->partitions)
515 return AVERROR(ENOMEM);
517 if (mxf->parsing_backward) {
518 /* insert the new partition pack in the middle
519 * this makes the entries in mxf->partitions sorted by offset */
520 memmove(&mxf->partitions[mxf->last_forward_partition+1],
521 &mxf->partitions[mxf->last_forward_partition],
522 (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
523 partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
525 mxf->last_forward_partition++;
526 partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
529 memset(partition, 0, sizeof(*partition));
530 mxf->partitions_count++;
531 partition->pack_length = avio_tell(pb) - klv_offset + size;
535 partition->type = Header;
538 partition->type = BodyPartition;
541 partition->type = Footer;
544 av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
545 return AVERROR_INVALIDDATA;
548 /* consider both footers to be closed (there is only Footer and CompleteFooter) */
549 partition->closed = partition->type == Footer || !(uid[14] & 1);
550 partition->complete = uid[14] > 2;
552 partition->kag_size = avio_rb32(pb);
553 partition->this_partition = avio_rb64(pb);
554 partition->previous_partition = avio_rb64(pb);
555 footer_partition = avio_rb64(pb);
556 partition->header_byte_count = avio_rb64(pb);
557 partition->index_byte_count = avio_rb64(pb);
558 partition->index_sid = avio_rb32(pb);
560 partition->body_sid = avio_rb32(pb);
561 avio_read(pb, op, sizeof(UID));
563 /* some files don'thave FooterPartition set in every partition */
564 if (footer_partition) {
565 if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
566 av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",
567 mxf->footer_partition, footer_partition);
569 mxf->footer_partition = footer_partition;
573 av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%lx, PreviousPartition = 0x%lx, "
574 "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
575 partition->this_partition,
576 partition->previous_partition, footer_partition,
577 partition->index_sid, partition->body_sid);
579 if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
580 else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
581 else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
582 else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
583 else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
584 else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
585 else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
586 else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
587 else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
588 else if (op[12] == 0x10) mxf->op = OPAtom;
589 else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
591 av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
595 if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
596 av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
598 if (mxf->op == OPSONYOpt)
599 partition->kag_size = 512;
601 partition->kag_size = 1;
603 av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
609 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
611 if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
612 return AVERROR(ENOMEM);
613 mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
614 if (!mxf->metadata_sets)
616 mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
617 mxf->metadata_sets_count++;
621 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
623 MXFCryptoContext *cryptocontext = arg;
626 if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
627 avio_read(pb, cryptocontext->source_container_ul, 16);
631 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
633 MXFContext *mxf = arg;
636 mxf->packages_count = avio_rb32(pb);
637 if (mxf->packages_count >= UINT_MAX / sizeof(UID))
639 mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
640 if (!mxf->packages_refs)
642 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
643 avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
649 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
651 MXFStructuralComponent *source_clip = arg;
654 source_clip->duration = avio_rb64(pb);
657 source_clip->start_position = avio_rb64(pb);
660 /* UMID, only get last 16 bytes */
662 avio_read(pb, source_clip->source_package_uid, 16);
665 source_clip->source_track_id = avio_rb32(pb);
671 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
673 MXFPackage *package = arg;
676 package->tracks_count = avio_rb32(pb);
677 if (package->tracks_count >= UINT_MAX / sizeof(UID))
679 package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
680 if (!package->tracks_refs)
682 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
683 avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
689 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
691 MXFTrack *track = arg;
694 track->track_id = avio_rb32(pb);
697 avio_read(pb, track->track_number, 4);
700 track->edit_rate.den = avio_rb32(pb);
701 track->edit_rate.num = avio_rb32(pb);
704 avio_read(pb, track->sequence_ref, 16);
710 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
712 MXFSequence *sequence = arg;
715 sequence->duration = avio_rb64(pb);
718 avio_read(pb, sequence->data_definition_ul, 16);
721 sequence->structural_components_count = avio_rb32(pb);
722 if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
724 sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
725 if (!sequence->structural_components_refs)
727 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
728 avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
734 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
736 MXFPackage *package = arg;
739 package->tracks_count = avio_rb32(pb);
740 if (package->tracks_count >= UINT_MAX / sizeof(UID))
742 package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
743 if (!package->tracks_refs)
745 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
746 avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
749 /* UMID, only get last 16 bytes */
751 avio_read(pb, package->package_uid, 16);
754 avio_read(pb, package->descriptor_ref, 16);
760 static int mxf_read_delta_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
764 segment->nb_delta_entries = avio_rb32(pb);
765 length = avio_rb32(pb);
767 if (!(segment->slice = av_calloc(segment->nb_delta_entries, sizeof(*segment->slice))) ||
768 !(segment->element_delta = av_calloc(segment->nb_delta_entries, sizeof(*segment->element_delta))))
769 return AVERROR(ENOMEM);
771 for (i = 0; i < segment->nb_delta_entries; i++) {
772 avio_r8(pb); /* PosTableIndex */
773 segment->slice[i] = avio_r8(pb);
774 segment->element_delta[i] = avio_rb32(pb);
779 static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
783 segment->nb_index_entries = avio_rb32(pb);
784 length = avio_rb32(pb);
786 if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
787 !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
788 !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
789 return AVERROR(ENOMEM);
791 if (segment->slice_count &&
792 !(segment->slice_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->slice_offset_entries))))
793 return AVERROR(ENOMEM);
795 for (i = 0; i < segment->nb_index_entries; i++) {
796 segment->temporal_offset_entries[i] = avio_r8(pb);
797 avio_r8(pb); /* KeyFrameOffset */
798 segment->flag_entries[i] = avio_r8(pb);
799 segment->stream_offset_entries[i] = avio_rb64(pb);
800 if (segment->slice_count) {
801 if (!(segment->slice_offset_entries[i] = av_calloc(segment->slice_count, sizeof(**segment->slice_offset_entries))))
802 return AVERROR(ENOMEM);
804 for (j = 0; j < segment->slice_count; j++)
805 segment->slice_offset_entries[i][j] = avio_rb32(pb);
808 avio_skip(pb, length - 11 - 4 * segment->slice_count);
813 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
815 MXFIndexTableSegment *segment = arg;
818 segment->edit_unit_byte_count = avio_rb32(pb);
819 av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
822 segment->index_sid = avio_rb32(pb);
823 av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
826 segment->body_sid = avio_rb32(pb);
827 av_dlog(NULL, "BodySID %d\n", segment->body_sid);
830 segment->slice_count = avio_r8(pb);
831 av_dlog(NULL, "SliceCount %d\n", segment->slice_count);
834 av_dlog(NULL, "DeltaEntryArray found\n");
835 return mxf_read_delta_entry_array(pb, segment);
837 av_dlog(NULL, "IndexEntryArray found\n");
838 return mxf_read_index_entry_array(pb, segment);
840 segment->index_edit_rate.num = avio_rb32(pb);
841 segment->index_edit_rate.den = avio_rb32(pb);
842 av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
843 segment->index_edit_rate.den);
846 segment->index_start_position = avio_rb64(pb);
847 av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
850 segment->index_duration = avio_rb64(pb);
851 av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
857 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
859 int code, value, ofs = 0;
860 char layout[16] = {0};
865 av_dlog(NULL, "pixel layout: code %#x\n", code);
868 layout[ofs++] = code;
869 layout[ofs++] = value;
871 } while (code != 0); /* SMPTE 377M E.2.46 */
873 ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
876 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
878 MXFDescriptor *descriptor = arg;
881 descriptor->sub_descriptors_count = avio_rb32(pb);
882 if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
884 descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
885 if (!descriptor->sub_descriptors_refs)
887 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
888 avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
891 avio_read(pb, descriptor->essence_container_ul, 16);
894 descriptor->linked_track_id = avio_rb32(pb);
896 case 0x3201: /* PictureEssenceCoding */
897 avio_read(pb, descriptor->essence_codec_ul, 16);
900 descriptor->width = avio_rb32(pb);
903 descriptor->height = avio_rb32(pb);
906 descriptor->aspect_ratio.num = avio_rb32(pb);
907 descriptor->aspect_ratio.den = avio_rb32(pb);
910 descriptor->sample_rate.num = avio_rb32(pb);
911 descriptor->sample_rate.den = avio_rb32(pb);
913 case 0x3D06: /* SoundEssenceCompression */
914 avio_read(pb, descriptor->essence_codec_ul, 16);
917 descriptor->channels = avio_rb32(pb);
920 descriptor->bits_per_sample = avio_rb32(pb);
923 mxf_read_pixel_layout(pb, descriptor);
926 /* Private uid used by SONY C0023S01.mxf */
927 if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
928 descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
929 if (!descriptor->extradata)
931 descriptor->extradata_size = size;
932 avio_read(pb, descriptor->extradata, size);
940 * Match an uid independently of the version byte and up to len common bytes
943 static int mxf_match_uid(const UID key, const UID uid, int len)
946 for (i = 0; i < len; i++) {
947 if (i != 7 && key[i] != uid[i])
953 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
955 while (uls->uid[0]) {
956 if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
963 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
969 for (i = 0; i < mxf->metadata_sets_count; i++) {
970 if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
971 (type == AnyType || mxf->metadata_sets[i]->type == type)) {
972 return mxf->metadata_sets[i];
978 static const MXFCodecUL mxf_essence_container_uls[] = {
979 // video essence container uls
980 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
981 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
982 // sound essence container uls
983 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
984 { { 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 */
985 { { 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 */
986 { { 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 */
987 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
990 static UID mxf_d10_ul = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 };
992 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
994 int i, j, nb_segments = 0;
995 MXFIndexTableSegment **unsorted_segments;
996 int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
998 /* count number of segments, allocate arrays and copy unsorted segments */
999 for (i = 0; i < mxf->metadata_sets_count; i++)
1000 if (mxf->metadata_sets[i]->type == IndexTableSegment)
1003 if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
1004 !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
1005 av_free(unsorted_segments);
1006 return AVERROR(ENOMEM);
1009 for (i = j = 0; i < mxf->metadata_sets_count; i++)
1010 if (mxf->metadata_sets[i]->type == IndexTableSegment)
1011 unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
1013 *nb_sorted_segments = 0;
1015 /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
1016 for (i = 0; i < nb_segments; i++) {
1017 int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
1019 for (j = 0; j < nb_segments; j++) {
1020 MXFIndexTableSegment *s = unsorted_segments[j];
1022 /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
1023 * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
1025 if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
1026 (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
1028 best_body_sid = s->body_sid;
1029 best_index_sid = s->index_sid;
1030 best_index_start = s->index_start_position;
1034 /* no suitable entry found -> we're done */
1038 (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
1039 last_body_sid = best_body_sid;
1040 last_index_sid = best_index_sid;
1041 last_index_start = best_index_start;
1044 av_free(unsorted_segments);
1050 * Computes the absolute file offset of the given essence container offset
1052 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
1055 int64_t offset_in = offset; /* for logging */
1057 for (x = 0; x < mxf->partitions_count; x++) {
1058 MXFPartition *p = &mxf->partitions[x];
1060 if (p->body_sid != body_sid)
1063 if (offset < p->essence_length || !p->essence_length) {
1064 *offset_out = p->essence_offset + offset;
1068 offset -= p->essence_length;
1071 av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %lx in BodySID %i - partial file?\n",
1072 offset_in, body_sid);
1074 return AVERROR_INVALIDDATA;
1077 static int mxf_parse_index(MXFContext *mxf, int track_id, AVStream *st)
1079 int j, k, ret, nb_sorted_segments;
1080 MXFIndexTableSegment **sorted_segments;
1081 int n_delta = track_id - 1; /* TrackID = 1-based stream index */
1084 av_log(mxf->fc, AV_LOG_ERROR, "TrackID not positive: %i\n", track_id);
1085 return AVERROR_INVALIDDATA;
1088 if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)))
1091 for (j = 0; j < nb_sorted_segments; j++) {
1092 int duration, sample_duration = 1, last_sample_size = 0;
1093 int64_t segment_size;
1094 MXFIndexTableSegment *tableseg = sorted_segments[j];
1096 if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
1098 duration = tableseg->index_duration > 0 ? tableseg->index_duration :
1099 st->duration - st->nb_index_entries;
1100 segment_size = tableseg->edit_unit_byte_count * duration;
1101 /* check small EditUnitByteCount for audio */
1102 if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
1103 && !tableseg->index_duration) {
1104 /* duration might be prime relative to the new sample_duration,
1105 * which means we need to handle the last frame differently */
1106 sample_duration = 8192;
1107 last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
1108 tableseg->edit_unit_byte_count *= sample_duration;
1109 duration /= sample_duration;
1110 if (last_sample_size) duration++;
1113 for (k = 0; k < duration; k++) {
1115 int size, flags = 0;
1117 if (k < tableseg->nb_index_entries) {
1118 pos = tableseg->stream_offset_entries[k];
1119 if (n_delta < tableseg->nb_delta_entries) {
1120 if (n_delta < tableseg->nb_delta_entries - 1) {
1122 tableseg->slice_offset_entries[k][tableseg->slice[n_delta+1]-1] +
1123 tableseg->element_delta[n_delta+1] -
1124 tableseg->element_delta[n_delta];
1125 if (tableseg->slice[n_delta] > 0)
1126 size -= tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1127 } else if (k < duration - 1) {
1128 size = tableseg->stream_offset_entries[k+1] -
1129 tableseg->stream_offset_entries[k] -
1130 tableseg->slice_offset_entries[k][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
1131 tableseg->element_delta[tableseg->nb_delta_entries-1];
1134 if (tableseg->slice[n_delta] > 0)
1135 pos += tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1136 pos += tableseg->element_delta[n_delta];
1139 flags = !(tableseg->flag_entries[k] & 0x30) ? AVINDEX_KEYFRAME : 0;
1141 pos = (int64_t)(tableseg->index_start_position + k) * tableseg->edit_unit_byte_count;
1142 if (n_delta < tableseg->nb_delta_entries - 1)
1143 size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
1145 /* use smaller size for last sample if we should */
1146 if (last_sample_size && k == duration - 1)
1147 size = last_sample_size;
1149 size = tableseg->edit_unit_byte_count;
1150 if (tableseg->nb_delta_entries)
1151 size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
1153 if (n_delta < tableseg->nb_delta_entries)
1154 pos += tableseg->element_delta[n_delta];
1155 flags = AVINDEX_KEYFRAME;
1158 if (mxf_absolute_bodysid_offset(mxf, tableseg->body_sid, pos, &pos) < 0) {
1159 /* probably partial file - no point going further for this stream */
1163 av_dlog(mxf->fc, "Stream %d IndexEntry %d TrackID %d Offset %"PRIx64" Timestamp %"PRId64"\n",
1164 st->index, st->nb_index_entries, track_id, pos, sample_duration * st->nb_index_entries);
1166 if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
1171 av_free(sorted_segments);
1176 static int mxf_parse_structural_metadata(MXFContext *mxf)
1178 MXFPackage *material_package = NULL;
1179 MXFPackage *temp_package = NULL;
1182 av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
1183 /* TODO: handle multiple material packages (OP3x) */
1184 for (i = 0; i < mxf->packages_count; i++) {
1185 material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
1186 if (material_package) break;
1188 if (!material_package) {
1189 av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
1193 for (i = 0; i < material_package->tracks_count; i++) {
1194 MXFPackage *source_package = NULL;
1195 MXFTrack *material_track = NULL;
1196 MXFTrack *source_track = NULL;
1197 MXFTrack *temp_track = NULL;
1198 MXFDescriptor *descriptor = NULL;
1199 MXFStructuralComponent *component = NULL;
1200 UID *essence_container_ul = NULL;
1201 const MXFCodecUL *codec_ul = NULL;
1202 const MXFCodecUL *container_ul = NULL;
1205 if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
1206 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
1210 if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
1211 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
1215 /* TODO: handle multiple source clips */
1216 for (j = 0; j < material_track->sequence->structural_components_count; j++) {
1217 /* TODO: handle timecode component */
1218 component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
1222 for (k = 0; k < mxf->packages_count; k++) {
1223 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
1226 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
1227 source_package = temp_package;
1231 if (!source_package) {
1232 av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
1235 for (k = 0; k < source_package->tracks_count; k++) {
1236 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
1237 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
1240 if (temp_track->track_id == component->source_track_id) {
1241 source_track = temp_track;
1245 if (!source_track) {
1246 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
1253 if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
1254 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
1258 /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
1259 * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
1260 if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
1261 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
1265 st = avformat_new_stream(mxf->fc, NULL);
1267 av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
1270 st->id = source_track->track_id;
1271 st->priv_data = source_track;
1272 st->duration = component->duration;
1273 if (st->duration == -1)
1274 st->duration = AV_NOPTS_VALUE;
1275 st->start_time = component->start_position;
1276 avpriv_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
1278 PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
1279 codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
1280 st->codec->codec_type = codec_ul->id;
1282 source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
1283 if (source_package->descriptor) {
1284 if (source_package->descriptor->type == MultipleDescriptor) {
1285 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
1286 MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
1288 if (!sub_descriptor) {
1289 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
1292 if (sub_descriptor->linked_track_id == source_track->track_id) {
1293 descriptor = sub_descriptor;
1297 } else if (source_package->descriptor->type == Descriptor)
1298 descriptor = source_package->descriptor;
1301 av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
1304 PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
1305 PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
1306 essence_container_ul = &descriptor->essence_container_ul;
1307 /* HACK: replacing the original key with mxf_encrypted_essence_container
1308 * is not allowed according to s429-6, try to find correct information anyway */
1309 if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
1310 av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
1311 for (k = 0; k < mxf->metadata_sets_count; k++) {
1312 MXFMetadataSet *metadata = mxf->metadata_sets[k];
1313 if (metadata->type == CryptoContext) {
1314 essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
1320 /* HACK: revert to the old demuxing/seeking scode for D-10 for now */
1321 if (mxf_match_uid(essence_container_ul, mxf_d10_ul, 14))
1324 /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
1325 codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
1326 st->codec->codec_id = codec_ul->id;
1327 if (descriptor->extradata) {
1328 st->codec->extradata = descriptor->extradata;
1329 st->codec->extradata_size = descriptor->extradata_size;
1331 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1332 container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
1333 if (st->codec->codec_id == CODEC_ID_NONE)
1334 st->codec->codec_id = container_ul->id;
1335 st->codec->width = descriptor->width;
1336 st->codec->height = descriptor->height;
1337 if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
1338 st->codec->pix_fmt = descriptor->pix_fmt;
1339 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1340 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1341 container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
1342 if (st->codec->codec_id == CODEC_ID_NONE)
1343 st->codec->codec_id = container_ul->id;
1344 st->codec->channels = descriptor->channels;
1345 st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
1346 st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
1347 /* TODO: implement CODEC_ID_RAWAUDIO */
1348 if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
1349 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1350 st->codec->codec_id = CODEC_ID_PCM_S24LE;
1351 else if (descriptor->bits_per_sample == 32)
1352 st->codec->codec_id = CODEC_ID_PCM_S32LE;
1353 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
1354 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1355 st->codec->codec_id = CODEC_ID_PCM_S24BE;
1356 else if (descriptor->bits_per_sample == 32)
1357 st->codec->codec_id = CODEC_ID_PCM_S32BE;
1358 } else if (st->codec->codec_id == CODEC_ID_MP2) {
1359 st->need_parsing = AVSTREAM_PARSE_FULL;
1362 if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
1363 /* TODO: decode timestamps */
1364 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
1367 if ((ret = mxf_parse_index(mxf, material_track->track_id, st)))
1373 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
1374 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
1375 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
1376 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
1377 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
1378 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
1379 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
1380 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
1381 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
1382 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
1383 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
1384 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
1385 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
1386 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
1387 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
1388 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
1389 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
1390 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
1391 { { 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 */
1392 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
1393 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
1394 { { 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 */
1395 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
1396 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
1397 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
1398 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
1399 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
1400 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
1401 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
1404 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
1406 AVIOContext *pb = mxf->fc->pb;
1407 MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
1408 uint64_t klv_end = avio_tell(pb) + klv->length;
1412 while (avio_tell(pb) + 4 < klv_end) {
1413 int tag = avio_rb16(pb);
1414 int size = avio_rb16(pb); /* KLV specified by 0x53 */
1415 uint64_t next = avio_tell(pb) + size;
1418 av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
1419 if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
1420 av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
1423 if (tag > 0x7FFF) { /* dynamic tag */
1425 for (i = 0; i < mxf->local_tags_count; i++) {
1426 int local_tag = AV_RB16(mxf->local_tags+i*18);
1427 if (local_tag == tag) {
1428 memcpy(uid, mxf->local_tags+i*18+2, 16);
1429 av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
1430 PRINT_KEY(mxf->fc, "uid", uid);
1434 if (ctx_size && tag == 0x3C0A)
1435 avio_read(pb, ctx->uid, 16);
1436 else if (read_child(ctx, pb, tag, size, uid, -1) < 0)
1439 avio_seek(pb, next, SEEK_SET);
1441 if (ctx_size) ctx->type = type;
1442 return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
1446 * Seeks to the previous partition, if possible
1447 * @return <= 0 if we should stop parsing, > 0 if we should keep going
1449 static int mxf_seek_to_previous_partition(MXFContext *mxf)
1451 AVIOContext *pb = mxf->fc->pb;
1453 if (!mxf->current_partition ||
1454 mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
1455 return 0; /* we've parsed all partitions */
1457 /* seek to previous partition */
1458 avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
1459 mxf->current_partition = NULL;
1461 av_dlog(mxf->fc, "seeking to previous partition\n");
1467 * Called when essence is encountered
1468 * @return <= 0 if we should stop parsing, > 0 if we should keep going
1470 static int mxf_parse_handle_essence(MXFContext *mxf)
1472 AVIOContext *pb = mxf->fc->pb;
1475 if (!mxf->current_partition) {
1476 av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to PartitionPack\n");
1477 return AVERROR_INVALIDDATA;
1480 if (mxf->parsing_backward) {
1481 return mxf_seek_to_previous_partition(mxf);
1483 if (!mxf->footer_partition) {
1484 av_dlog(mxf->fc, "no footer\n");
1488 av_dlog(mxf->fc, "seeking to footer\n");
1490 /* remember where we were so we don't end up seeking further back than this */
1491 mxf->last_forward_tell = avio_tell(pb);
1493 if (!pb->seekable) {
1494 av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
1498 /* seek to footer partition and parse backward */
1499 if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
1500 av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
1501 mxf->run_in + mxf->footer_partition, ret);
1505 mxf->current_partition = NULL;
1506 mxf->parsing_backward = 1;
1513 * Called when the next partition or EOF is encountered
1514 * @return <= 0 if we should stop parsing, > 0 if we should keep going
1516 static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
1518 return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
1522 * Figures out the proper offset and length of the essence container in each partition
1524 static void mxf_compute_essence_containers(MXFContext *mxf)
1528 /* everything is already correct */
1529 if (mxf->op == OPAtom)
1532 for (x = 0; x < mxf->partitions_count; x++) {
1533 MXFPartition *p = &mxf->partitions[x];
1536 continue; /* BodySID == 0 -> no essence */
1538 if (x >= mxf->partitions_count - 1)
1539 break; /* last partition - can't compute length (and we don't need to) */
1541 /* essence container spans to the next partition */
1542 p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
1544 if (p->essence_length < 0) {
1545 /* next ThisPartition < essence_offset */
1546 p->essence_length = 0;
1547 av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %lx\n",
1548 x+1, mxf->partitions[x+1].this_partition);
1553 static int64_t round_to_kag(int64_t position, int kag_size)
1555 /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
1556 /* NOTE: kag_size may be any integer between 1 - 2^10 */
1557 int64_t ret = (position / kag_size) * kag_size;
1558 return ret == position ? ret : ret + kag_size;
1561 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
1563 MXFContext *mxf = s->priv_data;
1565 int64_t essence_offset = 0;
1567 mxf->last_forward_tell = INT64_MAX;
1569 if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
1570 av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
1573 avio_seek(s->pb, -14, SEEK_CUR);
1575 mxf->run_in = avio_tell(s->pb);
1577 while (!url_feof(s->pb)) {
1578 const MXFMetadataReadTableEntry *metadata;
1580 if (klv_read_packet(&klv, s->pb) < 0) {
1581 /* EOF - seek to previous partition or stop */
1582 if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1588 PRINT_KEY(s, "read header", klv.key);
1589 av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
1590 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
1591 IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
1592 IS_KLV_KEY(klv.key, mxf_system_item_key)) {
1593 if (!mxf->current_partition->essence_offset) {
1594 /* for OP1a we compute essence_offset
1595 * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
1596 * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
1597 * for OPAtom we still need the actual essence_offset though (the KL's length can vary)
1599 int64_t op1a_essence_offset =
1600 round_to_kag(mxf->current_partition->this_partition +
1601 mxf->current_partition->pack_length, mxf->current_partition->kag_size) +
1602 round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
1603 round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size);
1605 if (mxf->op == OPAtom) {
1606 /* point essence_offset to the actual data
1607 * OPAtom has all the essence in one big KLV
1609 mxf->current_partition->essence_offset = avio_tell(s->pb);
1610 mxf->current_partition->essence_length = klv.length;
1612 /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */
1613 mxf->current_partition->essence_offset = op1a_essence_offset;
1617 if (!essence_offset)
1618 essence_offset = klv.offset;
1620 /* seek to footer, previous partition or stop */
1621 if (mxf_parse_handle_essence(mxf) <= 0)
1624 } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
1625 klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
1626 /* next partition pack - keep going, seek to previous partition or stop */
1627 if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1631 for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
1632 if (IS_KLV_KEY(klv.key, metadata->key)) {
1634 if (klv.key[5] == 0x53) {
1635 res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
1637 uint64_t next = avio_tell(s->pb) + klv.length;
1638 res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
1639 avio_seek(s->pb, next, SEEK_SET);
1642 av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
1648 if (!metadata->read)
1649 avio_skip(s->pb, klv.length);
1651 /* FIXME avoid seek */
1652 if (!essence_offset) {
1653 av_log(s, AV_LOG_ERROR, "no essence\n");
1654 return AVERROR_INVALIDDATA;
1656 avio_seek(s->pb, essence_offset, SEEK_SET);
1658 mxf_compute_essence_containers(mxf);
1660 return mxf_parse_structural_metadata(mxf);
1663 static int mxf_read_close(AVFormatContext *s)
1665 MXFContext *mxf = s->priv_data;
1666 MXFIndexTableSegment *seg;
1669 av_freep(&mxf->packages_refs);
1671 for (i = 0; i < s->nb_streams; i++)
1672 s->streams[i]->priv_data = NULL;
1674 for (i = 0; i < mxf->metadata_sets_count; i++) {
1675 switch (mxf->metadata_sets[i]->type) {
1676 case MultipleDescriptor:
1677 av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
1680 av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
1683 case MaterialPackage:
1684 av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
1686 case IndexTableSegment:
1687 seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
1688 for (j = 0; j < seg->nb_index_entries; j++)
1689 av_freep(&seg->slice_offset_entries[j]);
1690 av_freep(&seg->slice);
1691 av_freep(&seg->element_delta);
1692 av_freep(&seg->temporal_offset_entries);
1693 av_freep(&seg->flag_entries);
1694 av_freep(&seg->stream_offset_entries);
1695 av_freep(&seg->slice_offset_entries);
1700 av_freep(&mxf->metadata_sets[i]);
1702 av_freep(&mxf->partitions);
1703 av_freep(&mxf->metadata_sets);
1704 av_freep(&mxf->aesc);
1705 av_freep(&mxf->local_tags);
1709 static int mxf_probe(AVProbeData *p) {
1710 uint8_t *bufp = p->buf;
1711 uint8_t *end = p->buf + p->buf_size;
1713 if (p->buf_size < sizeof(mxf_header_partition_pack_key))
1716 /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
1717 end -= sizeof(mxf_header_partition_pack_key);
1718 for (; bufp < end; bufp++) {
1719 if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
1720 return AVPROBE_SCORE_MAX;
1725 /* rudimentary byte seek */
1726 /* XXX: use MXF Index */
1727 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1729 AVStream *st = s->streams[stream_index];
1731 MXFContext* mxf = s->priv_data;
1738 if (sample_time < 0)
1740 seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
1741 if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
1743 ff_update_cur_dts(s, st, sample_time);
1745 if (st->nb_index_entries <= 0)
1748 index = av_index_search_timestamp(st, sample_time, flags);
1750 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, sample_time, index);
1753 if (sample_time < st->index_entries[0].timestamp)
1759 seekpos = st->index_entries[index].pos;
1760 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1761 mxf->current_edit_unit = st->index_entries[index].timestamp;
1762 mxf->current_stream = 0;
1763 avio_seek(s->pb, seekpos, SEEK_SET);
1768 AVInputFormat ff_mxf_demuxer = {
1770 .long_name = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1771 .priv_data_size = sizeof(MXFContext),
1772 .read_probe = mxf_probe,
1773 .read_header = mxf_read_header,
1774 .read_packet = mxf_read_packet,
1775 .read_close = mxf_read_close,
1776 .read_seek = mxf_read_seek,