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;
206 enum MXFWrappingScheme {
211 /* NOTE: klv_offset is not set (-1) for local keys */
212 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
216 MXFMetadataReadFunc *read;
218 enum MXFMetadataSetType type;
219 } MXFMetadataReadTableEntry;
221 /* partial keys to match */
222 static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
223 static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
224 static const uint8_t mxf_system_item_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
225 static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
226 /* complete keys to match */
227 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 };
228 static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
229 static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
230 static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
232 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
234 static int64_t klv_decode_ber_length(AVIOContext *pb)
236 uint64_t size = avio_r8(pb);
237 if (size & 0x80) { /* long form */
238 int bytes_num = size & 0x7f;
239 /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
244 size = size << 8 | avio_r8(pb);
249 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
252 for (i = 0; i < size && !url_feof(pb); i++) {
256 else if (b != key[i])
262 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
264 if (!mxf_read_sync(pb, mxf_klv_key, 4))
266 klv->offset = avio_tell(pb) - 4;
267 memcpy(klv->key, mxf_klv_key, 4);
268 avio_read(pb, klv->key + 4, 12);
269 klv->length = klv_decode_ber_length(pb);
270 return klv->length == -1 ? -1 : 0;
273 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
277 for (i = 0; i < s->nb_streams; i++) {
278 MXFTrack *track = s->streams[i]->priv_data;
280 if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
283 /* return 0 if only one stream, for OP Atom files with 0 as track number */
284 return s->nb_streams == 1 ? 0 : -1;
287 /* XXX: use AVBitStreamFilter */
288 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
290 const uint8_t *buf_ptr, *end_ptr;
294 if (length > 61444) /* worst case PAL 1920 samples 8 channels */
296 length = av_get_packet(pb, pkt, length);
299 data_ptr = pkt->data;
300 end_ptr = pkt->data + length;
301 buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
302 for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
303 for (i = 0; i < st->codec->channels; i++) {
304 uint32_t sample = bytestream_get_le32(&buf_ptr);
305 if (st->codec->bits_per_coded_sample == 24)
306 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
308 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
310 buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
312 av_shrink_packet(pkt, data_ptr - pkt->data);
316 static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
318 static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
319 MXFContext *mxf = s->priv_data;
320 AVIOContext *pb = s->pb;
321 int64_t end = avio_tell(pb) + klv->length;
324 uint64_t plaintext_size;
329 if (!mxf->aesc && s->key && s->keylen == 16) {
330 mxf->aesc = av_malloc(av_aes_size);
333 av_aes_init(mxf->aesc, s->key, 128, 1);
336 avio_skip(pb, klv_decode_ber_length(pb));
338 klv_decode_ber_length(pb);
339 plaintext_size = avio_rb64(pb);
341 klv_decode_ber_length(pb);
342 avio_read(pb, klv->key, 16);
343 if (!IS_KLV_KEY(klv, mxf_essence_element_key))
345 index = mxf_get_stream_index(s, klv);
349 klv_decode_ber_length(pb);
350 orig_size = avio_rb64(pb);
351 if (orig_size < plaintext_size)
354 size = klv_decode_ber_length(pb);
355 if (size < 32 || size - 32 < orig_size)
357 avio_read(pb, ivec, 16);
358 avio_read(pb, tmpbuf, 16);
360 av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
361 if (memcmp(tmpbuf, checkv, 16))
362 av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
364 size = av_get_packet(pb, pkt, size);
367 else if (size < plaintext_size)
368 return AVERROR_INVALIDDATA;
369 size -= plaintext_size;
371 av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
372 &pkt->data[plaintext_size], size >> 4, ivec, 1);
373 av_shrink_packet(pkt, orig_size);
374 pkt->stream_index = index;
375 avio_skip(pb, end - avio_tell(pb));
379 static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
383 while (!url_feof(s->pb)) {
384 if (klv_read_packet(&klv, s->pb) < 0)
386 PRINT_KEY(s, "read packet", klv.key);
387 av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
388 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
389 int res = mxf_decrypt_triplet(s, pkt, &klv);
391 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
396 if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
397 int index = mxf_get_stream_index(s, &klv);
399 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
402 if (s->streams[index]->discard == AVDISCARD_ALL)
404 /* check for 8 channels AES3 element */
405 if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
406 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
407 av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
411 int ret = av_get_packet(s->pb, pkt, klv.length);
415 pkt->stream_index = index;
416 pkt->pos = klv.offset;
420 avio_skip(s->pb, klv.length);
425 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
427 MXFContext *mxf = s->priv_data;
434 /* TODO: better logic for this?
435 * only files that lack all index segments prior to the essence need this */
436 if (!s->pb->seekable && mxf->op != OPAtom || mxf->d10 || mxf->broken_index)
437 return mxf_read_packet_old(s, pkt);
439 if (mxf->current_stream >= s->nb_streams) {
440 mxf->current_edit_unit++;
441 mxf->current_stream = 0;
444 st = s->streams[mxf->current_stream];
446 if (mxf->current_edit_unit >= st->nb_index_entries)
449 e = &st->index_entries[mxf->current_edit_unit];
451 if ((ret64 = avio_seek(s->pb, e->pos, SEEK_SET)) < 0)
454 if (mxf->op == OPAtom) {
455 /* OPAtom - no KL, just essence */
456 if ((ret = av_get_packet(s->pb, pkt, e->size)) != e->size)
457 return ret < 0 ? ret : AVERROR_EOF;
459 /* read KL, read L bytes of essence */
460 if ((ret = klv_read_packet(&klv, s->pb)) < 0)
463 /* untested, but looks OK */
464 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
465 int res = mxf_decrypt_triplet(s, pkt, &klv);
467 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
473 if ((ret = av_get_packet(s->pb, pkt, klv.length)) != klv.length)
474 return ret < 0 ? ret : AVERROR_EOF;
479 pkt->stream_index = mxf->current_stream++;
484 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
486 MXFContext *mxf = arg;
487 int item_num = avio_rb32(pb);
488 int item_len = avio_rb32(pb);
490 if (item_len != 18) {
491 av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
494 if (item_num > UINT_MAX / item_len)
496 mxf->local_tags_count = item_num;
497 mxf->local_tags = av_malloc(item_num*item_len);
498 if (!mxf->local_tags)
500 avio_read(pb, mxf->local_tags, item_num*item_len);
504 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
506 MXFContext *mxf = arg;
507 MXFPartition *partition;
509 uint64_t footer_partition;
511 if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
512 return AVERROR(ENOMEM);
514 mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
515 if (!mxf->partitions)
516 return AVERROR(ENOMEM);
518 if (mxf->parsing_backward) {
519 /* insert the new partition pack in the middle
520 * this makes the entries in mxf->partitions sorted by offset */
521 memmove(&mxf->partitions[mxf->last_forward_partition+1],
522 &mxf->partitions[mxf->last_forward_partition],
523 (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
524 partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
526 mxf->last_forward_partition++;
527 partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
530 memset(partition, 0, sizeof(*partition));
531 mxf->partitions_count++;
532 partition->pack_length = avio_tell(pb) - klv_offset + size;
536 partition->type = Header;
539 partition->type = BodyPartition;
542 partition->type = Footer;
545 av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
546 return AVERROR_INVALIDDATA;
549 /* consider both footers to be closed (there is only Footer and CompleteFooter) */
550 partition->closed = partition->type == Footer || !(uid[14] & 1);
551 partition->complete = uid[14] > 2;
553 partition->kag_size = avio_rb32(pb);
554 partition->this_partition = avio_rb64(pb);
555 partition->previous_partition = avio_rb64(pb);
556 footer_partition = avio_rb64(pb);
557 partition->header_byte_count = avio_rb64(pb);
558 partition->index_byte_count = avio_rb64(pb);
559 partition->index_sid = avio_rb32(pb);
561 partition->body_sid = avio_rb32(pb);
562 avio_read(pb, op, sizeof(UID));
564 /* some files don'thave FooterPartition set in every partition */
565 if (footer_partition) {
566 if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
567 av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",
568 mxf->footer_partition, footer_partition);
570 mxf->footer_partition = footer_partition;
574 av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%lx, PreviousPartition = 0x%lx, "
575 "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
576 partition->this_partition,
577 partition->previous_partition, footer_partition,
578 partition->index_sid, partition->body_sid);
580 if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
581 else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
582 else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
583 else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
584 else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
585 else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
586 else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
587 else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
588 else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
589 else if (op[12] == 0x10) mxf->op = OPAtom;
590 else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
592 av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
596 if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
597 av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
599 if (mxf->op == OPSONYOpt)
600 partition->kag_size = 512;
602 partition->kag_size = 1;
604 av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
610 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
612 if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
613 return AVERROR(ENOMEM);
614 mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
615 if (!mxf->metadata_sets)
617 mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
618 mxf->metadata_sets_count++;
622 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
624 MXFCryptoContext *cryptocontext = arg;
627 if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
628 avio_read(pb, cryptocontext->source_container_ul, 16);
632 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
634 MXFContext *mxf = arg;
637 mxf->packages_count = avio_rb32(pb);
638 if (mxf->packages_count >= UINT_MAX / sizeof(UID))
640 mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
641 if (!mxf->packages_refs)
643 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
644 avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
650 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
652 MXFStructuralComponent *source_clip = arg;
655 source_clip->duration = avio_rb64(pb);
658 source_clip->start_position = avio_rb64(pb);
661 /* UMID, only get last 16 bytes */
663 avio_read(pb, source_clip->source_package_uid, 16);
666 source_clip->source_track_id = avio_rb32(pb);
672 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
674 MXFPackage *package = arg;
677 package->tracks_count = avio_rb32(pb);
678 if (package->tracks_count >= UINT_MAX / sizeof(UID))
680 package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
681 if (!package->tracks_refs)
683 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
684 avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
690 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
692 MXFTrack *track = arg;
695 track->track_id = avio_rb32(pb);
698 avio_read(pb, track->track_number, 4);
701 track->edit_rate.den = avio_rb32(pb);
702 track->edit_rate.num = avio_rb32(pb);
705 avio_read(pb, track->sequence_ref, 16);
711 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
713 MXFSequence *sequence = arg;
716 sequence->duration = avio_rb64(pb);
719 avio_read(pb, sequence->data_definition_ul, 16);
722 sequence->structural_components_count = avio_rb32(pb);
723 if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
725 sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
726 if (!sequence->structural_components_refs)
728 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
729 avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
735 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
737 MXFPackage *package = arg;
740 package->tracks_count = avio_rb32(pb);
741 if (package->tracks_count >= UINT_MAX / sizeof(UID))
743 package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
744 if (!package->tracks_refs)
746 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
747 avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
750 /* UMID, only get last 16 bytes */
752 avio_read(pb, package->package_uid, 16);
755 avio_read(pb, package->descriptor_ref, 16);
761 static int mxf_read_delta_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
765 segment->nb_delta_entries = avio_rb32(pb);
766 length = avio_rb32(pb);
768 if (!(segment->slice = av_calloc(segment->nb_delta_entries, sizeof(*segment->slice))) ||
769 !(segment->element_delta = av_calloc(segment->nb_delta_entries, sizeof(*segment->element_delta))))
770 return AVERROR(ENOMEM);
772 for (i = 0; i < segment->nb_delta_entries; i++) {
773 avio_r8(pb); /* PosTableIndex */
774 segment->slice[i] = avio_r8(pb);
775 segment->element_delta[i] = avio_rb32(pb);
780 static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
784 segment->nb_index_entries = avio_rb32(pb);
785 length = avio_rb32(pb);
787 if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
788 !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
789 !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
790 return AVERROR(ENOMEM);
792 if (segment->slice_count &&
793 !(segment->slice_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->slice_offset_entries))))
794 return AVERROR(ENOMEM);
796 for (i = 0; i < segment->nb_index_entries; i++) {
797 segment->temporal_offset_entries[i] = avio_r8(pb);
798 avio_r8(pb); /* KeyFrameOffset */
799 segment->flag_entries[i] = avio_r8(pb);
800 segment->stream_offset_entries[i] = avio_rb64(pb);
801 if (segment->slice_count) {
802 if (!(segment->slice_offset_entries[i] = av_calloc(segment->slice_count, sizeof(**segment->slice_offset_entries))))
803 return AVERROR(ENOMEM);
805 for (j = 0; j < segment->slice_count; j++)
806 segment->slice_offset_entries[i][j] = avio_rb32(pb);
809 avio_skip(pb, length - 11 - 4 * segment->slice_count);
814 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
816 MXFIndexTableSegment *segment = arg;
819 segment->edit_unit_byte_count = avio_rb32(pb);
820 av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
823 segment->index_sid = avio_rb32(pb);
824 av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
827 segment->body_sid = avio_rb32(pb);
828 av_dlog(NULL, "BodySID %d\n", segment->body_sid);
831 segment->slice_count = avio_r8(pb);
832 av_dlog(NULL, "SliceCount %d\n", segment->slice_count);
835 av_dlog(NULL, "DeltaEntryArray found\n");
836 return mxf_read_delta_entry_array(pb, segment);
838 av_dlog(NULL, "IndexEntryArray found\n");
839 return mxf_read_index_entry_array(pb, segment);
841 segment->index_edit_rate.num = avio_rb32(pb);
842 segment->index_edit_rate.den = avio_rb32(pb);
843 av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
844 segment->index_edit_rate.den);
847 segment->index_start_position = avio_rb64(pb);
848 av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
851 segment->index_duration = avio_rb64(pb);
852 av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
858 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
860 int code, value, ofs = 0;
861 char layout[16] = {0};
866 av_dlog(NULL, "pixel layout: code %#x\n", code);
869 layout[ofs++] = code;
870 layout[ofs++] = value;
872 } while (code != 0); /* SMPTE 377M E.2.46 */
874 ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
877 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
879 MXFDescriptor *descriptor = arg;
882 descriptor->sub_descriptors_count = avio_rb32(pb);
883 if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
885 descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
886 if (!descriptor->sub_descriptors_refs)
888 avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
889 avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
892 avio_read(pb, descriptor->essence_container_ul, 16);
895 descriptor->linked_track_id = avio_rb32(pb);
897 case 0x3201: /* PictureEssenceCoding */
898 avio_read(pb, descriptor->essence_codec_ul, 16);
901 descriptor->width = avio_rb32(pb);
904 descriptor->height = avio_rb32(pb);
907 descriptor->aspect_ratio.num = avio_rb32(pb);
908 descriptor->aspect_ratio.den = avio_rb32(pb);
911 descriptor->sample_rate.num = avio_rb32(pb);
912 descriptor->sample_rate.den = avio_rb32(pb);
914 case 0x3D06: /* SoundEssenceCompression */
915 avio_read(pb, descriptor->essence_codec_ul, 16);
918 descriptor->channels = avio_rb32(pb);
921 descriptor->bits_per_sample = avio_rb32(pb);
924 mxf_read_pixel_layout(pb, descriptor);
927 /* Private uid used by SONY C0023S01.mxf */
928 if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
929 descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
930 if (!descriptor->extradata)
932 descriptor->extradata_size = size;
933 avio_read(pb, descriptor->extradata, size);
941 * Match an uid independently of the version byte and up to len common bytes
944 static int mxf_match_uid(const UID key, const UID uid, int len)
947 for (i = 0; i < len; i++) {
948 if (i != 7 && key[i] != uid[i])
954 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
956 while (uls->uid[0]) {
957 if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
964 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
970 for (i = 0; i < mxf->metadata_sets_count; i++) {
971 if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
972 (type == AnyType || mxf->metadata_sets[i]->type == type)) {
973 return mxf->metadata_sets[i];
979 static const MXFCodecUL mxf_picture_essence_container_uls[] = {
980 // video essence container uls
981 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
982 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
983 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
985 static const MXFCodecUL mxf_sound_essence_container_uls[] = {
986 // sound essence container uls
987 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
988 { { 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 */
989 { { 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 */
990 { { 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 */
991 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
994 static UID mxf_d10_ul = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 };
996 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
998 int i, j, nb_segments = 0;
999 MXFIndexTableSegment **unsorted_segments;
1000 int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
1002 /* count number of segments, allocate arrays and copy unsorted segments */
1003 for (i = 0; i < mxf->metadata_sets_count; i++)
1004 if (mxf->metadata_sets[i]->type == IndexTableSegment)
1007 if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
1008 !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
1009 av_free(unsorted_segments);
1010 return AVERROR(ENOMEM);
1013 for (i = j = 0; i < mxf->metadata_sets_count; i++)
1014 if (mxf->metadata_sets[i]->type == IndexTableSegment)
1015 unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
1017 *nb_sorted_segments = 0;
1019 /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
1020 for (i = 0; i < nb_segments; i++) {
1021 int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
1023 for (j = 0; j < nb_segments; j++) {
1024 MXFIndexTableSegment *s = unsorted_segments[j];
1026 /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
1027 * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
1029 if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
1030 (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
1032 best_body_sid = s->body_sid;
1033 best_index_sid = s->index_sid;
1034 best_index_start = s->index_start_position;
1038 /* no suitable entry found -> we're done */
1042 (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
1043 last_body_sid = best_body_sid;
1044 last_index_sid = best_index_sid;
1045 last_index_start = best_index_start;
1048 av_free(unsorted_segments);
1054 * Computes the absolute file offset of the given essence container offset
1056 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
1059 int64_t offset_in = offset; /* for logging */
1061 for (x = 0; x < mxf->partitions_count; x++) {
1062 MXFPartition *p = &mxf->partitions[x];
1064 if (p->body_sid != body_sid)
1067 if (offset < p->essence_length || !p->essence_length) {
1068 *offset_out = p->essence_offset + offset;
1072 offset -= p->essence_length;
1075 av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %lx in BodySID %i - partial file?\n",
1076 offset_in, body_sid);
1078 return AVERROR_INVALIDDATA;
1081 static int mxf_parse_index(MXFContext *mxf, int track_id, AVStream *st)
1083 int j, k, ret, nb_sorted_segments;
1084 MXFIndexTableSegment **sorted_segments = NULL;
1085 int n_delta = track_id - 1; /* TrackID = 1-based stream index */
1088 av_log(mxf->fc, AV_LOG_ERROR, "TrackID not positive: %i\n", track_id);
1089 ret = AVERROR_INVALIDDATA;
1093 if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)))
1096 if (nb_sorted_segments <= 0) {
1097 av_log(mxf->fc, AV_LOG_WARNING, "Empty index for stream %i\n", st->index);
1102 for (j = 0; j < nb_sorted_segments; j++) {
1103 int duration, sample_duration = 1, last_sample_size = 0;
1104 int64_t segment_size;
1105 MXFIndexTableSegment *tableseg = sorted_segments[j];
1107 if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
1109 duration = tableseg->index_duration > 0 ? tableseg->index_duration :
1110 st->duration - st->nb_index_entries;
1111 segment_size = tableseg->edit_unit_byte_count * duration;
1112 /* check small EditUnitByteCount for audio */
1113 if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
1114 && !tableseg->index_duration) {
1115 /* duration might be prime relative to the new sample_duration,
1116 * which means we need to handle the last frame differently */
1117 sample_duration = 8192;
1118 last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
1119 tableseg->edit_unit_byte_count *= sample_duration;
1120 duration /= sample_duration;
1121 if (last_sample_size) duration++;
1124 if (duration <= 0) {
1125 av_log(mxf->fc, AV_LOG_WARNING, "0 duration in index for stream %i\n", st->index);
1130 for (k = 0; k < duration; k++) {
1132 int size, flags = 0;
1134 if (k < tableseg->nb_index_entries) {
1135 pos = tableseg->stream_offset_entries[k];
1136 if (n_delta < tableseg->nb_delta_entries) {
1137 if (n_delta < tableseg->nb_delta_entries - 1) {
1139 tableseg->slice_offset_entries[k][tableseg->slice[n_delta+1]-1] +
1140 tableseg->element_delta[n_delta+1] -
1141 tableseg->element_delta[n_delta];
1142 if (tableseg->slice[n_delta] > 0)
1143 size -= tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1144 } else if (k < duration - 1) {
1145 size = tableseg->stream_offset_entries[k+1] -
1146 tableseg->stream_offset_entries[k] -
1147 tableseg->slice_offset_entries[k][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
1148 tableseg->element_delta[tableseg->nb_delta_entries-1];
1151 if (tableseg->slice[n_delta] > 0)
1152 pos += tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1153 pos += tableseg->element_delta[n_delta];
1156 flags = !(tableseg->flag_entries[k] & 0x30) ? AVINDEX_KEYFRAME : 0;
1158 pos = (int64_t)(tableseg->index_start_position + k) * tableseg->edit_unit_byte_count;
1159 if (n_delta < tableseg->nb_delta_entries - 1)
1160 size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
1162 /* use smaller size for last sample if we should */
1163 if (last_sample_size && k == duration - 1)
1164 size = last_sample_size;
1166 size = tableseg->edit_unit_byte_count;
1167 if (tableseg->nb_delta_entries)
1168 size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
1170 if (n_delta < tableseg->nb_delta_entries)
1171 pos += tableseg->element_delta[n_delta];
1172 flags = AVINDEX_KEYFRAME;
1175 if (mxf_absolute_bodysid_offset(mxf, tableseg->body_sid, pos, &pos) < 0) {
1176 /* probably partial file - no point going further for this stream */
1180 av_dlog(mxf->fc, "Stream %d IndexEntry %d TrackID %d Offset %"PRIx64" Timestamp %"PRId64"\n",
1181 st->index, st->nb_index_entries, track_id, pos, sample_duration * st->nb_index_entries);
1183 if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
1188 av_free(sorted_segments);
1193 av_free(sorted_segments);
1194 mxf->broken_index = 1;
1198 static int mxf_parse_structural_metadata(MXFContext *mxf)
1200 MXFPackage *material_package = NULL;
1201 MXFPackage *temp_package = NULL;
1204 av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
1205 /* TODO: handle multiple material packages (OP3x) */
1206 for (i = 0; i < mxf->packages_count; i++) {
1207 material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
1208 if (material_package) break;
1210 if (!material_package) {
1211 av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
1215 for (i = 0; i < material_package->tracks_count; i++) {
1216 MXFPackage *source_package = NULL;
1217 MXFTrack *material_track = NULL;
1218 MXFTrack *source_track = NULL;
1219 MXFTrack *temp_track = NULL;
1220 MXFDescriptor *descriptor = NULL;
1221 MXFStructuralComponent *component = NULL;
1222 UID *essence_container_ul = NULL;
1223 const MXFCodecUL *codec_ul = NULL;
1224 const MXFCodecUL *container_ul = NULL;
1227 if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
1228 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
1232 if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
1233 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
1237 /* TODO: handle multiple source clips */
1238 for (j = 0; j < material_track->sequence->structural_components_count; j++) {
1239 /* TODO: handle timecode component */
1240 component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
1244 for (k = 0; k < mxf->packages_count; k++) {
1245 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
1248 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
1249 source_package = temp_package;
1253 if (!source_package) {
1254 av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
1257 for (k = 0; k < source_package->tracks_count; k++) {
1258 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
1259 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
1262 if (temp_track->track_id == component->source_track_id) {
1263 source_track = temp_track;
1267 if (!source_track) {
1268 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
1275 if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
1276 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
1280 /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
1281 * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
1282 if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
1283 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
1287 st = avformat_new_stream(mxf->fc, NULL);
1289 av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
1292 st->id = source_track->track_id;
1293 st->priv_data = source_track;
1294 st->duration = component->duration;
1295 if (st->duration == -1)
1296 st->duration = AV_NOPTS_VALUE;
1297 st->start_time = component->start_position;
1298 avpriv_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
1300 PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
1301 codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
1302 st->codec->codec_type = codec_ul->id;
1304 source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
1305 if (source_package->descriptor) {
1306 if (source_package->descriptor->type == MultipleDescriptor) {
1307 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
1308 MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
1310 if (!sub_descriptor) {
1311 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
1314 if (sub_descriptor->linked_track_id == source_track->track_id) {
1315 descriptor = sub_descriptor;
1319 } else if (source_package->descriptor->type == Descriptor)
1320 descriptor = source_package->descriptor;
1323 av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
1326 PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
1327 PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
1328 essence_container_ul = &descriptor->essence_container_ul;
1329 /* HACK: replacing the original key with mxf_encrypted_essence_container
1330 * is not allowed according to s429-6, try to find correct information anyway */
1331 if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
1332 av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
1333 for (k = 0; k < mxf->metadata_sets_count; k++) {
1334 MXFMetadataSet *metadata = mxf->metadata_sets[k];
1335 if (metadata->type == CryptoContext) {
1336 essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
1342 /* HACK: revert to the old demuxing/seeking scode for D-10 for now */
1343 if (mxf_match_uid(essence_container_ul, mxf_d10_ul, 14))
1346 /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
1347 codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
1348 st->codec->codec_id = codec_ul->id;
1349 if (descriptor->extradata) {
1350 st->codec->extradata = descriptor->extradata;
1351 st->codec->extradata_size = descriptor->extradata_size;
1353 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1354 container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
1355 if (st->codec->codec_id == CODEC_ID_NONE)
1356 st->codec->codec_id = container_ul->id;
1357 st->codec->width = descriptor->width;
1358 st->codec->height = descriptor->height;
1359 if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
1360 st->codec->pix_fmt = descriptor->pix_fmt;
1361 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1362 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1363 container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
1364 if (st->codec->codec_id == CODEC_ID_NONE)
1365 st->codec->codec_id = container_ul->id;
1366 st->codec->channels = descriptor->channels;
1367 st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
1368 st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
1369 /* TODO: implement CODEC_ID_RAWAUDIO */
1370 if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
1371 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1372 st->codec->codec_id = CODEC_ID_PCM_S24LE;
1373 else if (descriptor->bits_per_sample == 32)
1374 st->codec->codec_id = CODEC_ID_PCM_S32LE;
1375 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
1376 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1377 st->codec->codec_id = CODEC_ID_PCM_S24BE;
1378 else if (descriptor->bits_per_sample == 32)
1379 st->codec->codec_id = CODEC_ID_PCM_S32BE;
1380 } else if (st->codec->codec_id == CODEC_ID_MP2) {
1381 st->need_parsing = AVSTREAM_PARSE_FULL;
1384 if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
1385 /* TODO: decode timestamps */
1386 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
1389 if ((ret = mxf_parse_index(mxf, material_track->track_id, st)))
1395 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
1396 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
1397 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
1398 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
1399 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
1400 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
1401 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
1402 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
1403 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
1404 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
1405 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
1406 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
1407 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
1408 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
1409 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
1410 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
1411 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
1412 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
1413 { { 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 */
1414 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
1415 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
1416 { { 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 */
1417 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
1418 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
1419 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
1420 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
1421 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
1422 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
1423 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
1426 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
1428 AVIOContext *pb = mxf->fc->pb;
1429 MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
1430 uint64_t klv_end = avio_tell(pb) + klv->length;
1434 while (avio_tell(pb) + 4 < klv_end) {
1435 int tag = avio_rb16(pb);
1436 int size = avio_rb16(pb); /* KLV specified by 0x53 */
1437 uint64_t next = avio_tell(pb) + size;
1440 av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
1441 if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
1442 av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
1445 if (tag > 0x7FFF) { /* dynamic tag */
1447 for (i = 0; i < mxf->local_tags_count; i++) {
1448 int local_tag = AV_RB16(mxf->local_tags+i*18);
1449 if (local_tag == tag) {
1450 memcpy(uid, mxf->local_tags+i*18+2, 16);
1451 av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
1452 PRINT_KEY(mxf->fc, "uid", uid);
1456 if (ctx_size && tag == 0x3C0A)
1457 avio_read(pb, ctx->uid, 16);
1458 else if (read_child(ctx, pb, tag, size, uid, -1) < 0)
1461 avio_seek(pb, next, SEEK_SET);
1463 if (ctx_size) ctx->type = type;
1464 return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
1468 * Seeks to the previous partition, if possible
1469 * @return <= 0 if we should stop parsing, > 0 if we should keep going
1471 static int mxf_seek_to_previous_partition(MXFContext *mxf)
1473 AVIOContext *pb = mxf->fc->pb;
1475 if (!mxf->current_partition ||
1476 mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
1477 return 0; /* we've parsed all partitions */
1479 /* seek to previous partition */
1480 avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
1481 mxf->current_partition = NULL;
1483 av_dlog(mxf->fc, "seeking to previous partition\n");
1489 * Called when essence is encountered
1490 * @return <= 0 if we should stop parsing, > 0 if we should keep going
1492 static int mxf_parse_handle_essence(MXFContext *mxf)
1494 AVIOContext *pb = mxf->fc->pb;
1497 if (!mxf->current_partition) {
1498 av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to PartitionPack\n");
1499 return AVERROR_INVALIDDATA;
1502 if (mxf->parsing_backward) {
1503 return mxf_seek_to_previous_partition(mxf);
1505 if (!mxf->footer_partition) {
1506 av_dlog(mxf->fc, "no footer\n");
1510 av_dlog(mxf->fc, "seeking to footer\n");
1512 /* remember where we were so we don't end up seeking further back than this */
1513 mxf->last_forward_tell = avio_tell(pb);
1515 if (!pb->seekable) {
1516 av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
1520 /* seek to footer partition and parse backward */
1521 if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
1522 av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
1523 mxf->run_in + mxf->footer_partition, ret);
1527 mxf->current_partition = NULL;
1528 mxf->parsing_backward = 1;
1535 * Called when the next partition or EOF is encountered
1536 * @return <= 0 if we should stop parsing, > 0 if we should keep going
1538 static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
1540 return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
1544 * Figures out the proper offset and length of the essence container in each partition
1546 static void mxf_compute_essence_containers(MXFContext *mxf)
1550 /* everything is already correct */
1551 if (mxf->op == OPAtom)
1554 for (x = 0; x < mxf->partitions_count; x++) {
1555 MXFPartition *p = &mxf->partitions[x];
1558 continue; /* BodySID == 0 -> no essence */
1560 if (x >= mxf->partitions_count - 1)
1561 break; /* last partition - can't compute length (and we don't need to) */
1563 /* essence container spans to the next partition */
1564 p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
1566 if (p->essence_length < 0) {
1567 /* next ThisPartition < essence_offset */
1568 p->essence_length = 0;
1569 av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %lx\n",
1570 x+1, mxf->partitions[x+1].this_partition);
1575 static int64_t round_to_kag(int64_t position, int kag_size)
1577 /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
1578 /* NOTE: kag_size may be any integer between 1 - 2^10 */
1579 int64_t ret = (position / kag_size) * kag_size;
1580 return ret == position ? ret : ret + kag_size;
1583 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
1585 MXFContext *mxf = s->priv_data;
1587 int64_t essence_offset = 0;
1589 mxf->last_forward_tell = INT64_MAX;
1591 if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
1592 av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
1595 avio_seek(s->pb, -14, SEEK_CUR);
1597 mxf->run_in = avio_tell(s->pb);
1599 while (!url_feof(s->pb)) {
1600 const MXFMetadataReadTableEntry *metadata;
1602 if (klv_read_packet(&klv, s->pb) < 0) {
1603 /* EOF - seek to previous partition or stop */
1604 if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1610 PRINT_KEY(s, "read header", klv.key);
1611 av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
1612 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
1613 IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
1614 IS_KLV_KEY(klv.key, mxf_system_item_key)) {
1615 if (!mxf->current_partition->essence_offset) {
1616 /* for OP1a we compute essence_offset
1617 * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
1618 * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
1619 * for OPAtom we still need the actual essence_offset though (the KL's length can vary)
1621 int64_t op1a_essence_offset =
1622 round_to_kag(mxf->current_partition->this_partition +
1623 mxf->current_partition->pack_length, mxf->current_partition->kag_size) +
1624 round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
1625 round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size);
1627 if (mxf->op == OPAtom) {
1628 /* point essence_offset to the actual data
1629 * OPAtom has all the essence in one big KLV
1631 mxf->current_partition->essence_offset = avio_tell(s->pb);
1632 mxf->current_partition->essence_length = klv.length;
1634 /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */
1635 mxf->current_partition->essence_offset = op1a_essence_offset;
1639 if (!essence_offset)
1640 essence_offset = klv.offset;
1642 /* seek to footer, previous partition or stop */
1643 if (mxf_parse_handle_essence(mxf) <= 0)
1646 } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
1647 klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
1648 /* next partition pack - keep going, seek to previous partition or stop */
1649 if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1653 for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
1654 if (IS_KLV_KEY(klv.key, metadata->key)) {
1656 if (klv.key[5] == 0x53) {
1657 res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
1659 uint64_t next = avio_tell(s->pb) + klv.length;
1660 res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
1661 avio_seek(s->pb, next, SEEK_SET);
1664 av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
1670 if (!metadata->read)
1671 avio_skip(s->pb, klv.length);
1673 /* FIXME avoid seek */
1674 if (!essence_offset) {
1675 av_log(s, AV_LOG_ERROR, "no essence\n");
1676 return AVERROR_INVALIDDATA;
1678 avio_seek(s->pb, essence_offset, SEEK_SET);
1680 mxf_compute_essence_containers(mxf);
1682 return mxf_parse_structural_metadata(mxf);
1685 static int mxf_read_close(AVFormatContext *s)
1687 MXFContext *mxf = s->priv_data;
1688 MXFIndexTableSegment *seg;
1691 av_freep(&mxf->packages_refs);
1693 for (i = 0; i < s->nb_streams; i++)
1694 s->streams[i]->priv_data = NULL;
1696 for (i = 0; i < mxf->metadata_sets_count; i++) {
1697 switch (mxf->metadata_sets[i]->type) {
1698 case MultipleDescriptor:
1699 av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
1702 av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
1705 case MaterialPackage:
1706 av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
1708 case IndexTableSegment:
1709 seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
1710 for (j = 0; j < seg->nb_index_entries; j++)
1711 av_freep(&seg->slice_offset_entries[j]);
1712 av_freep(&seg->slice);
1713 av_freep(&seg->element_delta);
1714 av_freep(&seg->temporal_offset_entries);
1715 av_freep(&seg->flag_entries);
1716 av_freep(&seg->stream_offset_entries);
1717 av_freep(&seg->slice_offset_entries);
1722 av_freep(&mxf->metadata_sets[i]);
1724 av_freep(&mxf->partitions);
1725 av_freep(&mxf->metadata_sets);
1726 av_freep(&mxf->aesc);
1727 av_freep(&mxf->local_tags);
1731 static int mxf_probe(AVProbeData *p) {
1732 uint8_t *bufp = p->buf;
1733 uint8_t *end = p->buf + p->buf_size;
1735 if (p->buf_size < sizeof(mxf_header_partition_pack_key))
1738 /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
1739 end -= sizeof(mxf_header_partition_pack_key);
1740 for (; bufp < end; bufp++) {
1741 if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
1742 return AVPROBE_SCORE_MAX;
1747 /* rudimentary byte seek */
1748 /* XXX: use MXF Index */
1749 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1751 AVStream *st = s->streams[stream_index];
1753 MXFContext* mxf = s->priv_data;
1760 if (sample_time < 0)
1762 seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
1763 if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
1765 ff_update_cur_dts(s, st, sample_time);
1767 if (st->nb_index_entries <= 0)
1770 index = av_index_search_timestamp(st, sample_time, flags);
1772 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, sample_time, index);
1775 if (sample_time < st->index_entries[0].timestamp)
1781 seekpos = st->index_entries[index].pos;
1782 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1783 mxf->current_edit_unit = st->index_entries[index].timestamp;
1784 mxf->current_stream = 0;
1785 avio_seek(s->pb, seekpos, SEEK_SET);
1790 AVInputFormat ff_mxf_demuxer = {
1792 .long_name = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1793 .priv_data_size = sizeof(MXFContext),
1794 .read_probe = mxf_probe,
1795 .read_header = mxf_read_header,
1796 .read_packet = mxf_read_packet,
1797 .read_close = mxf_read_close,
1798 .read_seek = mxf_read_seek,