libavformat/mxfdec.c
Go to the documentation of this file.
00001 /*
00002  * MXF demuxer.
00003  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 /*
00023  * References
00024  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
00025  * SMPTE 377M MXF File Format Specifications
00026  * SMPTE 378M Operational Pattern 1a
00027  * SMPTE 379M MXF Generic Container
00028  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
00029  * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
00030  * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
00031  *
00032  * Principle
00033  * Search for Track numbers which will identify essence element KLV packets.
00034  * Search for SourcePackage which define tracks which contains Track numbers.
00035  * Material Package contains tracks with reference to SourcePackage tracks.
00036  * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
00037  * Assign Descriptors to correct Tracks.
00038  *
00039  * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
00040  * Metadata parsing resolves Strong References to objects.
00041  *
00042  * Simple demuxer, only OP1A supported and some files might not work at all.
00043  * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
00044  */
00045 
00046 //#define DEBUG
00047 
00048 #include "libavutil/aes.h"
00049 #include "libavutil/mathematics.h"
00050 #include "libavcodec/bytestream.h"
00051 #include "avformat.h"
00052 #include "internal.h"
00053 #include "mxf.h"
00054 
00055 typedef enum {
00056     Header,
00057     BodyPartition,
00058     Footer
00059 } MXFPartitionType;
00060 
00061 typedef enum {
00062     OP1a = 1,
00063     OP1b,
00064     OP1c,
00065     OP2a,
00066     OP2b,
00067     OP2c,
00068     OP3a,
00069     OP3b,
00070     OP3c,
00071     OPAtom,
00072     OPSONYOpt,  /* FATE sample, violates the spec in places */
00073 } MXFOP;
00074 
00075 typedef struct {
00076     int closed;
00077     int complete;
00078     MXFPartitionType type;
00079     uint64_t previous_partition;
00080     int index_sid;
00081     int body_sid;
00082     int64_t this_partition;
00083     int64_t essence_offset;         
00084     int64_t essence_length;
00085     int32_t kag_size;
00086     int64_t header_byte_count;
00087     int64_t index_byte_count;
00088     int pack_length;
00089 } MXFPartition;
00090 
00091 typedef struct {
00092     UID uid;
00093     enum MXFMetadataSetType type;
00094     UID source_container_ul;
00095 } MXFCryptoContext;
00096 
00097 typedef struct {
00098     UID uid;
00099     enum MXFMetadataSetType type;
00100     UID source_package_uid;
00101     UID data_definition_ul;
00102     int64_t duration;
00103     int64_t start_position;
00104     int source_track_id;
00105 } MXFStructuralComponent;
00106 
00107 typedef struct {
00108     UID uid;
00109     enum MXFMetadataSetType type;
00110     UID data_definition_ul;
00111     UID *structural_components_refs;
00112     int structural_components_count;
00113     int64_t duration;
00114 } MXFSequence;
00115 
00116 typedef struct {
00117     UID uid;
00118     enum MXFMetadataSetType type;
00119     MXFSequence *sequence; /* mandatory, and only one */
00120     UID sequence_ref;
00121     int track_id;
00122     uint8_t track_number[4];
00123     AVRational edit_rate;
00124 } MXFTrack;
00125 
00126 typedef struct {
00127     UID uid;
00128     enum MXFMetadataSetType type;
00129     UID essence_container_ul;
00130     UID essence_codec_ul;
00131     AVRational sample_rate;
00132     AVRational aspect_ratio;
00133     int width;
00134     int height;
00135     int channels;
00136     int bits_per_sample;
00137     UID *sub_descriptors_refs;
00138     int sub_descriptors_count;
00139     int linked_track_id;
00140     uint8_t *extradata;
00141     int extradata_size;
00142     enum PixelFormat pix_fmt;
00143 } MXFDescriptor;
00144 
00145 typedef struct {
00146     UID uid;
00147     enum MXFMetadataSetType type;
00148     int edit_unit_byte_count;
00149     int index_sid;
00150     int body_sid;
00151     AVRational index_edit_rate;
00152     uint64_t index_start_position;
00153     uint64_t index_duration;
00154     int8_t *temporal_offset_entries;
00155     int *flag_entries;
00156     uint64_t *stream_offset_entries;
00157     int nb_index_entries;
00158 } MXFIndexTableSegment;
00159 
00160 typedef struct {
00161     UID uid;
00162     enum MXFMetadataSetType type;
00163     UID package_uid;
00164     UID *tracks_refs;
00165     int tracks_count;
00166     MXFDescriptor *descriptor; /* only one */
00167     UID descriptor_ref;
00168 } MXFPackage;
00169 
00170 typedef struct {
00171     UID uid;
00172     enum MXFMetadataSetType type;
00173 } MXFMetadataSet;
00174 
00175 /* decoded index table */
00176 typedef struct {
00177     int index_sid;
00178     int body_sid;
00179     int nb_ptses;               /* number of PTSes or total duration of index */
00180     int64_t first_dts;          /* DTS = EditUnit + first_dts */
00181     int64_t *ptses;             /* maps EditUnit -> PTS */
00182     int nb_segments;
00183     MXFIndexTableSegment **segments;    /* sorted by IndexStartPosition */
00184     AVIndexEntry *fake_index;   /* used for calling ff_index_search_timestamp() */
00185 } MXFIndexTable;
00186 
00187 typedef struct {
00188     MXFPartition *partitions;
00189     unsigned partitions_count;
00190     MXFOP op;
00191     UID *packages_refs;
00192     int packages_count;
00193     MXFMetadataSet **metadata_sets;
00194     int metadata_sets_count;
00195     AVFormatContext *fc;
00196     struct AVAES *aesc;
00197     uint8_t *local_tags;
00198     int local_tags_count;
00199     uint64_t footer_partition;
00200     KLVPacket current_klv_data;
00201     int current_klv_index;
00202     int run_in;
00203     MXFPartition *current_partition;
00204     int parsing_backward;
00205     int64_t last_forward_tell;
00206     int last_forward_partition;
00207     int current_edit_unit;
00208     int nb_index_tables;
00209     MXFIndexTable *index_tables;
00210     int edit_units_per_packet;      
00211 } MXFContext;
00212 
00213 enum MXFWrappingScheme {
00214     Frame,
00215     Clip,
00216 };
00217 
00218 /* NOTE: klv_offset is not set (-1) for local keys */
00219 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
00220 
00221 typedef struct {
00222     const UID key;
00223     MXFMetadataReadFunc *read;
00224     int ctx_size;
00225     enum MXFMetadataSetType type;
00226 } MXFMetadataReadTableEntry;
00227 
00228 /* partial keys to match */
00229 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
00230 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
00231 static const uint8_t mxf_avid_essence_element_key[]        = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
00232 static const uint8_t mxf_system_item_key[]                 = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
00233 static const uint8_t mxf_klv_key[]                         = { 0x06,0x0e,0x2b,0x34 };
00234 /* complete keys to match */
00235 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 };
00236 static const uint8_t mxf_encrypted_triplet_key[]           = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
00237 static const uint8_t mxf_encrypted_essence_container[]     = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
00238 static const uint8_t mxf_sony_mpeg4_extradata[]            = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
00239 
00240 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
00241 
00242 static int64_t klv_decode_ber_length(AVIOContext *pb)
00243 {
00244     uint64_t size = avio_r8(pb);
00245     if (size & 0x80) { /* long form */
00246         int bytes_num = size & 0x7f;
00247         /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
00248         if (bytes_num > 8)
00249             return AVERROR_INVALIDDATA;
00250         size = 0;
00251         while (bytes_num--)
00252             size = size << 8 | avio_r8(pb);
00253     }
00254     return size;
00255 }
00256 
00257 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
00258 {
00259     int i, b;
00260     for (i = 0; i < size && !url_feof(pb); i++) {
00261         b = avio_r8(pb);
00262         if (b == key[0])
00263             i = 0;
00264         else if (b != key[i])
00265             i = -1;
00266     }
00267     return i == size;
00268 }
00269 
00270 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
00271 {
00272     if (!mxf_read_sync(pb, mxf_klv_key, 4))
00273         return AVERROR_INVALIDDATA;
00274     klv->offset = avio_tell(pb) - 4;
00275     memcpy(klv->key, mxf_klv_key, 4);
00276     avio_read(pb, klv->key + 4, 12);
00277     klv->length = klv_decode_ber_length(pb);
00278     return klv->length == -1 ? -1 : 0;
00279 }
00280 
00281 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
00282 {
00283     int i;
00284 
00285     for (i = 0; i < s->nb_streams; i++) {
00286         MXFTrack *track = s->streams[i]->priv_data;
00287         /* SMPTE 379M 7.3 */
00288         if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
00289             return i;
00290     }
00291     /* return 0 if only one stream, for OP Atom files with 0 as track number */
00292     return s->nb_streams == 1 ? 0 : -1;
00293 }
00294 
00295 /* XXX: use AVBitStreamFilter */
00296 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
00297 {
00298     const uint8_t *buf_ptr, *end_ptr;
00299     uint8_t *data_ptr;
00300     int i;
00301 
00302     if (length > 61444) /* worst case PAL 1920 samples 8 channels */
00303         return AVERROR_INVALIDDATA;
00304     length = av_get_packet(pb, pkt, length);
00305     if (length < 0)
00306         return length;
00307     data_ptr = pkt->data;
00308     end_ptr = pkt->data + length;
00309     buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
00310     for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
00311         for (i = 0; i < st->codec->channels; i++) {
00312             uint32_t sample = bytestream_get_le32(&buf_ptr);
00313             if (st->codec->bits_per_coded_sample == 24)
00314                 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
00315             else
00316                 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
00317         }
00318         buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
00319     }
00320     av_shrink_packet(pkt, data_ptr - pkt->data);
00321     return 0;
00322 }
00323 
00324 static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
00325 {
00326     static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
00327     MXFContext *mxf = s->priv_data;
00328     AVIOContext *pb = s->pb;
00329     int64_t end = avio_tell(pb) + klv->length;
00330     int64_t size;
00331     uint64_t orig_size;
00332     uint64_t plaintext_size;
00333     uint8_t ivec[16];
00334     uint8_t tmpbuf[16];
00335     int index;
00336 
00337     if (!mxf->aesc && s->key && s->keylen == 16) {
00338         mxf->aesc = av_malloc(av_aes_size);
00339         if (!mxf->aesc)
00340             return AVERROR(ENOMEM);
00341         av_aes_init(mxf->aesc, s->key, 128, 1);
00342     }
00343     // crypto context
00344     avio_skip(pb, klv_decode_ber_length(pb));
00345     // plaintext offset
00346     klv_decode_ber_length(pb);
00347     plaintext_size = avio_rb64(pb);
00348     // source klv key
00349     klv_decode_ber_length(pb);
00350     avio_read(pb, klv->key, 16);
00351     if (!IS_KLV_KEY(klv, mxf_essence_element_key))
00352         return AVERROR_INVALIDDATA;
00353     index = mxf_get_stream_index(s, klv);
00354     if (index < 0)
00355         return AVERROR_INVALIDDATA;
00356     // source size
00357     klv_decode_ber_length(pb);
00358     orig_size = avio_rb64(pb);
00359     if (orig_size < plaintext_size)
00360         return AVERROR_INVALIDDATA;
00361     // enc. code
00362     size = klv_decode_ber_length(pb);
00363     if (size < 32 || size - 32 < orig_size)
00364         return AVERROR_INVALIDDATA;
00365     avio_read(pb, ivec, 16);
00366     avio_read(pb, tmpbuf, 16);
00367     if (mxf->aesc)
00368         av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
00369     if (memcmp(tmpbuf, checkv, 16))
00370         av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
00371     size -= 32;
00372     size = av_get_packet(pb, pkt, size);
00373     if (size < 0)
00374         return size;
00375     else if (size < plaintext_size)
00376         return AVERROR_INVALIDDATA;
00377     size -= plaintext_size;
00378     if (mxf->aesc)
00379         av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
00380                      &pkt->data[plaintext_size], size >> 4, ivec, 1);
00381     av_shrink_packet(pkt, orig_size);
00382     pkt->stream_index = index;
00383     avio_skip(pb, end - avio_tell(pb));
00384     return 0;
00385 }
00386 
00387 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00388 {
00389     MXFContext *mxf = arg;
00390     int item_num = avio_rb32(pb);
00391     int item_len = avio_rb32(pb);
00392 
00393     if (item_len != 18) {
00394         av_log_ask_for_sample(pb, "unsupported primer pack item length %d\n",
00395                               item_len);
00396         return AVERROR_PATCHWELCOME;
00397     }
00398     if (item_num > UINT_MAX / item_len)
00399         return AVERROR_INVALIDDATA;
00400     mxf->local_tags_count = item_num;
00401     mxf->local_tags = av_malloc(item_num*item_len);
00402     if (!mxf->local_tags)
00403         return AVERROR(ENOMEM);
00404     avio_read(pb, mxf->local_tags, item_num*item_len);
00405     return 0;
00406 }
00407 
00408 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00409 {
00410     MXFContext *mxf = arg;
00411     MXFPartition *partition, *tmp_part;
00412     UID op;
00413     uint64_t footer_partition;
00414     uint32_t nb_essence_containers;
00415 
00416     if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
00417         return AVERROR(ENOMEM);
00418 
00419     tmp_part = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
00420     if (!tmp_part)
00421         return AVERROR(ENOMEM);
00422     mxf->partitions = tmp_part;
00423 
00424     if (mxf->parsing_backward) {
00425         /* insert the new partition pack in the middle
00426          * this makes the entries in mxf->partitions sorted by offset */
00427         memmove(&mxf->partitions[mxf->last_forward_partition+1],
00428                 &mxf->partitions[mxf->last_forward_partition],
00429                 (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
00430         partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
00431     } else {
00432         mxf->last_forward_partition++;
00433         partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
00434     }
00435 
00436     memset(partition, 0, sizeof(*partition));
00437     mxf->partitions_count++;
00438     partition->pack_length = avio_tell(pb) - klv_offset + size;
00439 
00440     switch(uid[13]) {
00441     case 2:
00442         partition->type = Header;
00443         break;
00444     case 3:
00445         partition->type = BodyPartition;
00446         break;
00447     case 4:
00448         partition->type = Footer;
00449         break;
00450     default:
00451         av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
00452         return AVERROR_INVALIDDATA;
00453     }
00454 
00455     /* consider both footers to be closed (there is only Footer and CompleteFooter) */
00456     partition->closed = partition->type == Footer || !(uid[14] & 1);
00457     partition->complete = uid[14] > 2;
00458     avio_skip(pb, 4);
00459     partition->kag_size = avio_rb32(pb);
00460     partition->this_partition = avio_rb64(pb);
00461     partition->previous_partition = avio_rb64(pb);
00462     footer_partition = avio_rb64(pb);
00463     partition->header_byte_count = avio_rb64(pb);
00464     partition->index_byte_count = avio_rb64(pb);
00465     partition->index_sid = avio_rb32(pb);
00466     avio_skip(pb, 8);
00467     partition->body_sid = avio_rb32(pb);
00468     avio_read(pb, op, sizeof(UID));
00469     nb_essence_containers = avio_rb32(pb);
00470 
00471     /* some files don'thave FooterPartition set in every partition */
00472     if (footer_partition) {
00473         if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
00474             av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %" PRIi64 " != %" PRIi64 "\n",
00475                    mxf->footer_partition, footer_partition);
00476         } else {
00477             mxf->footer_partition = footer_partition;
00478         }
00479     }
00480 
00481     av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%" PRIx64 ", PreviousPartition = 0x%" PRIx64 ", "
00482             "FooterPartition = 0x%" PRIx64 ", IndexSID = %i, BodySID = %i\n",
00483             partition->this_partition,
00484             partition->previous_partition, footer_partition,
00485             partition->index_sid, partition->body_sid);
00486 
00487     /* sanity check PreviousPartition if set */
00488     if (partition->previous_partition &&
00489         mxf->run_in + partition->previous_partition >= klv_offset) {
00490         av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition points to this partition or forward\n");
00491         return AVERROR_INVALIDDATA;
00492     }
00493 
00494     if      (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
00495     else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
00496     else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
00497     else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
00498     else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
00499     else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
00500     else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
00501     else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
00502     else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
00503     else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
00504     else if (op[12] == 0x10) {
00505         /* SMPTE 390m: "There shall be exactly one essence container"
00506          * 2011_DCPTEST_24FPS.V.mxf violates this and is frame wrapped, hence why we assume OP1a */
00507         if (nb_essence_containers != 1) {
00508             /* only nag once */
00509             if (!mxf->op)
00510                 av_log(mxf->fc, AV_LOG_WARNING, "\"OPAtom\" with %u ECs - assuming OP1a\n", nb_essence_containers);
00511 
00512             mxf->op = OP1a;
00513         } else
00514             mxf->op = OPAtom;
00515     } else {
00516         av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
00517         mxf->op = OP1a;
00518     }
00519 
00520     if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
00521         av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
00522 
00523         if (mxf->op == OPSONYOpt)
00524             partition->kag_size = 512;
00525         else
00526             partition->kag_size = 1;
00527 
00528         av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
00529     }
00530 
00531     return 0;
00532 }
00533 
00534 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
00535 {
00536     MXFMetadataSet **tmp;
00537     if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
00538         return AVERROR(ENOMEM);
00539     tmp = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
00540     if (!tmp)
00541         return AVERROR(ENOMEM);
00542     mxf->metadata_sets = tmp;
00543     mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
00544     mxf->metadata_sets_count++;
00545     return 0;
00546 }
00547 
00548 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00549 {
00550     MXFCryptoContext *cryptocontext = arg;
00551     if (size != 16)
00552         return AVERROR_INVALIDDATA;
00553     if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
00554         avio_read(pb, cryptocontext->source_container_ul, 16);
00555     return 0;
00556 }
00557 
00558 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00559 {
00560     MXFContext *mxf = arg;
00561     switch (tag) {
00562     case 0x1901:
00563         mxf->packages_count = avio_rb32(pb);
00564         if (mxf->packages_count >= UINT_MAX / sizeof(UID))
00565             return AVERROR_INVALIDDATA;
00566         mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
00567         if (!mxf->packages_refs)
00568             return AVERROR(ENOMEM);
00569         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
00570         avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
00571         break;
00572     }
00573     return 0;
00574 }
00575 
00576 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00577 {
00578     MXFStructuralComponent *source_clip = arg;
00579     switch(tag) {
00580     case 0x0202:
00581         source_clip->duration = avio_rb64(pb);
00582         break;
00583     case 0x1201:
00584         source_clip->start_position = avio_rb64(pb);
00585         break;
00586     case 0x1101:
00587         /* UMID, only get last 16 bytes */
00588         avio_skip(pb, 16);
00589         avio_read(pb, source_clip->source_package_uid, 16);
00590         break;
00591     case 0x1102:
00592         source_clip->source_track_id = avio_rb32(pb);
00593         break;
00594     }
00595     return 0;
00596 }
00597 
00598 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00599 {
00600     MXFPackage *package = arg;
00601     switch(tag) {
00602     case 0x4403:
00603         package->tracks_count = avio_rb32(pb);
00604         if (package->tracks_count >= UINT_MAX / sizeof(UID))
00605             return AVERROR_INVALIDDATA;
00606         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
00607         if (!package->tracks_refs)
00608             return AVERROR(ENOMEM);
00609         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
00610         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
00611         break;
00612     }
00613     return 0;
00614 }
00615 
00616 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00617 {
00618     MXFTrack *track = arg;
00619     switch(tag) {
00620     case 0x4801:
00621         track->track_id = avio_rb32(pb);
00622         break;
00623     case 0x4804:
00624         avio_read(pb, track->track_number, 4);
00625         break;
00626     case 0x4B01:
00627         track->edit_rate.den = avio_rb32(pb);
00628         track->edit_rate.num = avio_rb32(pb);
00629         break;
00630     case 0x4803:
00631         avio_read(pb, track->sequence_ref, 16);
00632         break;
00633     }
00634     return 0;
00635 }
00636 
00637 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00638 {
00639     MXFSequence *sequence = arg;
00640     switch(tag) {
00641     case 0x0202:
00642         sequence->duration = avio_rb64(pb);
00643         break;
00644     case 0x0201:
00645         avio_read(pb, sequence->data_definition_ul, 16);
00646         break;
00647     case 0x1001:
00648         sequence->structural_components_count = avio_rb32(pb);
00649         if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
00650             return AVERROR_INVALIDDATA;
00651         sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
00652         if (!sequence->structural_components_refs)
00653             return AVERROR(ENOMEM);
00654         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
00655         avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
00656         break;
00657     }
00658     return 0;
00659 }
00660 
00661 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00662 {
00663     MXFPackage *package = arg;
00664     switch(tag) {
00665     case 0x4403:
00666         package->tracks_count = avio_rb32(pb);
00667         if (package->tracks_count >= UINT_MAX / sizeof(UID))
00668             return AVERROR_INVALIDDATA;
00669         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
00670         if (!package->tracks_refs)
00671             return AVERROR(ENOMEM);
00672         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
00673         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
00674         break;
00675     case 0x4401:
00676         /* UMID, only get last 16 bytes */
00677         avio_skip(pb, 16);
00678         avio_read(pb, package->package_uid, 16);
00679         break;
00680     case 0x4701:
00681         avio_read(pb, package->descriptor_ref, 16);
00682         break;
00683     }
00684     return 0;
00685 }
00686 
00687 static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
00688 {
00689     int i, length;
00690 
00691     segment->nb_index_entries = avio_rb32(pb);
00692     length = avio_rb32(pb);
00693 
00694     if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
00695         !(segment->flag_entries          = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
00696         !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
00697         return AVERROR(ENOMEM);
00698 
00699     for (i = 0; i < segment->nb_index_entries; i++) {
00700         segment->temporal_offset_entries[i] = avio_r8(pb);
00701         avio_r8(pb);                                        /* KeyFrameOffset */
00702         segment->flag_entries[i] = avio_r8(pb);
00703         segment->stream_offset_entries[i] = avio_rb64(pb);
00704         avio_skip(pb, length - 11);
00705     }
00706     return 0;
00707 }
00708 
00709 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00710 {
00711     MXFIndexTableSegment *segment = arg;
00712     switch(tag) {
00713     case 0x3F05:
00714         segment->edit_unit_byte_count = avio_rb32(pb);
00715         av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
00716         break;
00717     case 0x3F06:
00718         segment->index_sid = avio_rb32(pb);
00719         av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
00720         break;
00721     case 0x3F07:
00722         segment->body_sid = avio_rb32(pb);
00723         av_dlog(NULL, "BodySID %d\n", segment->body_sid);
00724         break;
00725     case 0x3F0A:
00726         av_dlog(NULL, "IndexEntryArray found\n");
00727         return mxf_read_index_entry_array(pb, segment);
00728     case 0x3F0B:
00729         segment->index_edit_rate.num = avio_rb32(pb);
00730         segment->index_edit_rate.den = avio_rb32(pb);
00731         av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
00732                 segment->index_edit_rate.den);
00733         break;
00734     case 0x3F0C:
00735         segment->index_start_position = avio_rb64(pb);
00736         av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
00737         break;
00738     case 0x3F0D:
00739         segment->index_duration = avio_rb64(pb);
00740         av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
00741         break;
00742     }
00743     return 0;
00744 }
00745 
00746 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
00747 {
00748     int code, value, ofs = 0;
00749     char layout[16] = {0};
00750 
00751     do {
00752         code = avio_r8(pb);
00753         value = avio_r8(pb);
00754         av_dlog(NULL, "pixel layout: code %#x\n", code);
00755 
00756         if (ofs < 16) {
00757             layout[ofs++] = code;
00758             layout[ofs++] = value;
00759         }
00760     } while (code != 0); /* SMPTE 377M E.2.46 */
00761 
00762     ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
00763 }
00764 
00765 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00766 {
00767     MXFDescriptor *descriptor = arg;
00768     switch(tag) {
00769     case 0x3F01:
00770         descriptor->sub_descriptors_count = avio_rb32(pb);
00771         if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
00772             return AVERROR_INVALIDDATA;
00773         descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
00774         if (!descriptor->sub_descriptors_refs)
00775             return AVERROR(ENOMEM);
00776         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
00777         avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
00778         break;
00779     case 0x3004:
00780         avio_read(pb, descriptor->essence_container_ul, 16);
00781         break;
00782     case 0x3006:
00783         descriptor->linked_track_id = avio_rb32(pb);
00784         break;
00785     case 0x3201: /* PictureEssenceCoding */
00786         avio_read(pb, descriptor->essence_codec_ul, 16);
00787         break;
00788     case 0x3203:
00789         descriptor->width = avio_rb32(pb);
00790         break;
00791     case 0x3202:
00792         descriptor->height = avio_rb32(pb);
00793         break;
00794     case 0x320E:
00795         descriptor->aspect_ratio.num = avio_rb32(pb);
00796         descriptor->aspect_ratio.den = avio_rb32(pb);
00797         break;
00798     case 0x3D03:
00799         descriptor->sample_rate.num = avio_rb32(pb);
00800         descriptor->sample_rate.den = avio_rb32(pb);
00801         break;
00802     case 0x3D06: /* SoundEssenceCompression */
00803         avio_read(pb, descriptor->essence_codec_ul, 16);
00804         break;
00805     case 0x3D07:
00806         descriptor->channels = avio_rb32(pb);
00807         break;
00808     case 0x3D01:
00809         descriptor->bits_per_sample = avio_rb32(pb);
00810         break;
00811     case 0x3401:
00812         mxf_read_pixel_layout(pb, descriptor);
00813         break;
00814     default:
00815         /* Private uid used by SONY C0023S01.mxf */
00816         if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
00817             descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
00818             if (!descriptor->extradata)
00819                 return AVERROR(ENOMEM);
00820             descriptor->extradata_size = size;
00821             avio_read(pb, descriptor->extradata, size);
00822         }
00823         break;
00824     }
00825     return 0;
00826 }
00827 
00828 /*
00829  * Match an uid independently of the version byte and up to len common bytes
00830  * Returns: boolean
00831  */
00832 static int mxf_match_uid(const UID key, const UID uid, int len)
00833 {
00834     int i;
00835     for (i = 0; i < len; i++) {
00836         if (i != 7 && key[i] != uid[i])
00837             return 0;
00838     }
00839     return 1;
00840 }
00841 
00842 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
00843 {
00844     while (uls->uid[0]) {
00845         if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
00846             break;
00847         uls++;
00848     }
00849     return uls;
00850 }
00851 
00852 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
00853 {
00854     int i;
00855 
00856     if (!strong_ref)
00857         return NULL;
00858     for (i = 0; i < mxf->metadata_sets_count; i++) {
00859         if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
00860             (type == AnyType || mxf->metadata_sets[i]->type == type)) {
00861             return mxf->metadata_sets[i];
00862         }
00863     }
00864     return NULL;
00865 }
00866 
00867 static const MXFCodecUL mxf_picture_essence_container_uls[] = {
00868     // video essence container uls
00869     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
00870     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14,    CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
00871     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
00872 };
00873 static const MXFCodecUL mxf_sound_essence_container_uls[] = {
00874     // sound essence container uls
00875     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
00876     { { 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 */
00877     { { 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 */
00878     { { 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 */
00879     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
00880 };
00881 
00882 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
00883 {
00884     int i, j, nb_segments = 0;
00885     MXFIndexTableSegment **unsorted_segments;
00886     int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
00887 
00888     /* count number of segments, allocate arrays and copy unsorted segments */
00889     for (i = 0; i < mxf->metadata_sets_count; i++)
00890         if (mxf->metadata_sets[i]->type == IndexTableSegment)
00891             nb_segments++;
00892 
00893     if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
00894         !(*sorted_segments  = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
00895         av_freep(sorted_segments);
00896         av_free(unsorted_segments);
00897         return AVERROR(ENOMEM);
00898     }
00899 
00900     for (i = j = 0; i < mxf->metadata_sets_count; i++)
00901         if (mxf->metadata_sets[i]->type == IndexTableSegment)
00902             unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
00903 
00904     *nb_sorted_segments = 0;
00905 
00906     /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
00907     for (i = 0; i < nb_segments; i++) {
00908         int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
00909 
00910         for (j = 0; j < nb_segments; j++) {
00911             MXFIndexTableSegment *s = unsorted_segments[j];
00912 
00913             /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
00914              * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
00915              */
00916             if ((i == 0     || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
00917                 (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
00918                 best             = j;
00919                 best_body_sid    = s->body_sid;
00920                 best_index_sid   = s->index_sid;
00921                 best_index_start = s->index_start_position;
00922             }
00923         }
00924 
00925         /* no suitable entry found -> we're done */
00926         if (best == -1)
00927             break;
00928 
00929         (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
00930         last_body_sid    = best_body_sid;
00931         last_index_sid   = best_index_sid;
00932         last_index_start = best_index_start;
00933     }
00934 
00935     av_free(unsorted_segments);
00936 
00937     return 0;
00938 }
00939 
00943 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
00944 {
00945     int x;
00946     int64_t offset_in = offset;     /* for logging */
00947 
00948     for (x = 0; x < mxf->partitions_count; x++) {
00949         MXFPartition *p = &mxf->partitions[x];
00950 
00951         if (p->body_sid != body_sid)
00952             continue;
00953 
00954         if (offset < p->essence_length || !p->essence_length) {
00955             *offset_out = p->essence_offset + offset;
00956             return 0;
00957         }
00958 
00959         offset -= p->essence_length;
00960     }
00961 
00962     av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %" PRIx64" in BodySID %i - partial file?\n",
00963            offset_in, body_sid);
00964 
00965     return AVERROR_INVALIDDATA;
00966 }
00967 
00971 static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
00972 {
00973     int x;
00974     int64_t ret = 0;
00975 
00976     for (x = 0; x < mxf->partitions_count; x++) {
00977         MXFPartition *p = &mxf->partitions[x];
00978 
00979         if (p->body_sid != body_sid)
00980             continue;
00981 
00982         if (!p->essence_length)
00983             return 0;
00984 
00985         ret = p->essence_offset + p->essence_length;
00986     }
00987 
00988     return ret;
00989 }
00990 
00991 /* EditUnit -> absolute offset */
00992 static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, int64_t *edit_unit_out, int64_t *offset_out, int nag)
00993 {
00994     int i;
00995     int64_t offset_temp = 0;
00996 
00997     for (i = 0; i < index_table->nb_segments; i++) {
00998         MXFIndexTableSegment *s = index_table->segments[i];
00999 
01000         edit_unit = FFMAX(edit_unit, s->index_start_position);  /* clamp if trying to seek before start */
01001 
01002         if (edit_unit < s->index_start_position + s->index_duration) {
01003             int64_t index = edit_unit - s->index_start_position;
01004 
01005             if (s->edit_unit_byte_count)
01006                 offset_temp += s->edit_unit_byte_count * index;
01007             else if (s->nb_index_entries) {
01008                 if (s->nb_index_entries == 2 * s->index_duration + 1)
01009                     index *= 2;     /* Avid index */
01010 
01011                 if (index < 0 || index > s->nb_index_entries) {
01012                     av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
01013                            index_table->index_sid, s->index_start_position);
01014                     return AVERROR_INVALIDDATA;
01015                 }
01016 
01017                 offset_temp = s->stream_offset_entries[index];
01018             } else {
01019                 av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
01020                        index_table->index_sid, s->index_start_position);
01021                 return AVERROR_INVALIDDATA;
01022             }
01023 
01024             if (edit_unit_out)
01025                 *edit_unit_out = edit_unit;
01026 
01027             return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out);
01028         } else {
01029             /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
01030             offset_temp += s->edit_unit_byte_count * s->index_duration;
01031         }
01032     }
01033 
01034     if (nag)
01035         av_log(mxf->fc, AV_LOG_ERROR, "failed to map EditUnit %"PRId64" in IndexSID %i to an offset\n", edit_unit, index_table->index_sid);
01036 
01037     return AVERROR_INVALIDDATA;
01038 }
01039 
01040 static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
01041 {
01042     int i, j, x;
01043     int8_t max_temporal_offset = -128;
01044 
01045     /* first compute how many entries we have */
01046     for (i = 0; i < index_table->nb_segments; i++) {
01047         MXFIndexTableSegment *s = index_table->segments[i];
01048 
01049         if (!s->nb_index_entries) {
01050             index_table->nb_ptses = 0;
01051             return 0;                               /* no TemporalOffsets */
01052         }
01053 
01054         index_table->nb_ptses += s->index_duration;
01055     }
01056 
01057     /* paranoid check */
01058     if (index_table->nb_ptses <= 0)
01059         return 0;
01060 
01061     if (!(index_table->ptses      = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
01062         !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry)))) {
01063         av_freep(&index_table->ptses);
01064         return AVERROR(ENOMEM);
01065     }
01066 
01067     /* we may have a few bad TemporalOffsets
01068      * make sure the corresponding PTSes don't have the bogus value 0 */
01069     for (x = 0; x < index_table->nb_ptses; x++)
01070         index_table->ptses[x] = AV_NOPTS_VALUE;
01071 
01099     for (i = x = 0; i < index_table->nb_segments; i++) {
01100         MXFIndexTableSegment *s = index_table->segments[i];
01101         int index_delta = 1;
01102         int n = s->nb_index_entries;
01103 
01104         if (s->nb_index_entries == 2 * s->index_duration + 1) {
01105             index_delta = 2;    /* Avid index */
01106 
01107             /* ignore the last entry - it's the size of the essence container */
01108             n--;
01109         }
01110 
01111         for (j = 0; j < n; j += index_delta, x++) {
01112             int offset = s->temporal_offset_entries[j] / index_delta;
01113             int index  = x + offset;
01114 
01115             if (x >= index_table->nb_ptses) {
01116                 av_log(mxf->fc, AV_LOG_ERROR, "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
01117                        s->nb_index_entries, s->index_duration);
01118                 break;
01119             }
01120 
01121             index_table->fake_index[x].timestamp = x;
01122             index_table->fake_index[x].flags = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
01123 
01124             if (index < 0 || index >= index_table->nb_ptses) {
01125                 av_log(mxf->fc, AV_LOG_ERROR,
01126                        "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
01127                        x, offset, index);
01128                 continue;
01129             }
01130 
01131             index_table->ptses[index] = x;
01132             max_temporal_offset = FFMAX(max_temporal_offset, offset);
01133         }
01134     }
01135 
01136     index_table->first_dts = -max_temporal_offset;
01137 
01138     return 0;
01139 }
01140 
01145 static int mxf_compute_index_tables(MXFContext *mxf)
01146 {
01147     int i, j, k, ret, nb_sorted_segments;
01148     MXFIndexTableSegment **sorted_segments = NULL;
01149 
01150     if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
01151         nb_sorted_segments <= 0) {
01152         av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
01153         return 0;
01154     }
01155 
01156     /* sanity check and count unique BodySIDs/IndexSIDs */
01157     for (i = 0; i < nb_sorted_segments; i++) {
01158         if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
01159             mxf->nb_index_tables++;
01160         else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
01161             av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
01162             ret = AVERROR_INVALIDDATA;
01163             goto finish_decoding_index;
01164         }
01165     }
01166 
01167     if (!(mxf->index_tables = av_calloc(mxf->nb_index_tables, sizeof(MXFIndexTable)))) {
01168         av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
01169         ret = AVERROR(ENOMEM);
01170         goto finish_decoding_index;
01171     }
01172 
01173     /* distribute sorted segments to index tables */
01174     for (i = j = 0; i < nb_sorted_segments; i++) {
01175         if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
01176             /* next IndexSID */
01177             j++;
01178         }
01179 
01180         mxf->index_tables[j].nb_segments++;
01181     }
01182 
01183     for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
01184         MXFIndexTable *t = &mxf->index_tables[j];
01185 
01186         if (!(t->segments = av_calloc(t->nb_segments, sizeof(MXFIndexTableSegment*)))) {
01187             av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment pointer array\n");
01188             ret = AVERROR(ENOMEM);
01189             goto finish_decoding_index;
01190         }
01191 
01192         if (sorted_segments[i]->index_start_position)
01193             av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
01194                    sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
01195 
01196         memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
01197         t->index_sid = sorted_segments[i]->index_sid;
01198         t->body_sid = sorted_segments[i]->body_sid;
01199 
01200         if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
01201             goto finish_decoding_index;
01202 
01203         /* fix zero IndexDurations */
01204         for (k = 0; k < t->nb_segments; k++) {
01205             if (t->segments[k]->index_duration)
01206                 continue;
01207 
01208             if (t->nb_segments > 1)
01209                 av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
01210                        t->index_sid, k);
01211 
01212             if (mxf->fc->nb_streams <= 0) {
01213                 av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
01214                 break;
01215             }
01216 
01217             /* assume the first stream's duration is reasonable
01218              * leave index_duration = 0 on further segments in case we have any (unlikely)
01219              */
01220             t->segments[k]->index_duration = mxf->fc->streams[0]->duration;
01221             break;
01222         }
01223     }
01224 
01225     ret = 0;
01226 finish_decoding_index:
01227     av_free(sorted_segments);
01228     return ret;
01229 }
01230 
01231 static int mxf_parse_structural_metadata(MXFContext *mxf)
01232 {
01233     MXFPackage *material_package = NULL;
01234     MXFPackage *temp_package = NULL;
01235     int i, j, k, ret;
01236 
01237     av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
01238     /* TODO: handle multiple material packages (OP3x) */
01239     for (i = 0; i < mxf->packages_count; i++) {
01240         material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
01241         if (material_package) break;
01242     }
01243     if (!material_package) {
01244         av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
01245         return AVERROR_INVALIDDATA;
01246     }
01247 
01248     for (i = 0; i < material_package->tracks_count; i++) {
01249         MXFPackage *source_package = NULL;
01250         MXFTrack *material_track = NULL;
01251         MXFTrack *source_track = NULL;
01252         MXFTrack *temp_track = NULL;
01253         MXFDescriptor *descriptor = NULL;
01254         MXFStructuralComponent *component = NULL;
01255         UID *essence_container_ul = NULL;
01256         const MXFCodecUL *codec_ul = NULL;
01257         const MXFCodecUL *container_ul = NULL;
01258         AVStream *st;
01259 
01260         if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
01261             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
01262             continue;
01263         }
01264 
01265         if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
01266             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
01267             continue;
01268         }
01269 
01270         /* TODO: handle multiple source clips */
01271         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
01272             /* TODO: handle timecode component */
01273             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
01274             if (!component)
01275                 continue;
01276 
01277             for (k = 0; k < mxf->packages_count; k++) {
01278                 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
01279                 if (!temp_package)
01280                     continue;
01281                 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
01282                     source_package = temp_package;
01283                     break;
01284                 }
01285             }
01286             if (!source_package) {
01287                 av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
01288                 break;
01289             }
01290             for (k = 0; k < source_package->tracks_count; k++) {
01291                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
01292                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
01293                     ret = AVERROR_INVALIDDATA;
01294                     goto fail_and_free;
01295                 }
01296                 if (temp_track->track_id == component->source_track_id) {
01297                     source_track = temp_track;
01298                     break;
01299                 }
01300             }
01301             if (!source_track) {
01302                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
01303                 break;
01304             }
01305         }
01306         if (!source_track || !component)
01307             continue;
01308 
01309         if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
01310             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
01311             ret = AVERROR_INVALIDDATA;
01312             goto fail_and_free;
01313         }
01314 
01315         /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
01316          * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
01317         if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
01318             av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
01319             continue;
01320         }
01321 
01322         st = avformat_new_stream(mxf->fc, NULL);
01323         if (!st) {
01324             av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
01325             ret = AVERROR(ENOMEM);
01326             goto fail_and_free;
01327         }
01328         st->id = source_track->track_id;
01329         st->priv_data = source_track;
01330         st->duration = component->duration;
01331         if (st->duration == -1)
01332             st->duration = AV_NOPTS_VALUE;
01333         st->start_time = component->start_position;
01334         avpriv_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
01335 
01336         PRINT_KEY(mxf->fc, "data definition   ul", source_track->sequence->data_definition_ul);
01337         codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
01338         st->codec->codec_type = codec_ul->id;
01339 
01340         source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
01341         if (source_package->descriptor) {
01342             if (source_package->descriptor->type == MultipleDescriptor) {
01343                 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
01344                     MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
01345 
01346                     if (!sub_descriptor) {
01347                         av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
01348                         continue;
01349                     }
01350                     if (sub_descriptor->linked_track_id == source_track->track_id) {
01351                         descriptor = sub_descriptor;
01352                         break;
01353                     }
01354                 }
01355             } else if (source_package->descriptor->type == Descriptor)
01356                 descriptor = source_package->descriptor;
01357         }
01358         if (!descriptor) {
01359             av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
01360             continue;
01361         }
01362         PRINT_KEY(mxf->fc, "essence codec     ul", descriptor->essence_codec_ul);
01363         PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
01364         essence_container_ul = &descriptor->essence_container_ul;
01365         /* HACK: replacing the original key with mxf_encrypted_essence_container
01366          * is not allowed according to s429-6, try to find correct information anyway */
01367         if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
01368             av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
01369             for (k = 0; k < mxf->metadata_sets_count; k++) {
01370                 MXFMetadataSet *metadata = mxf->metadata_sets[k];
01371                 if (metadata->type == CryptoContext) {
01372                     essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
01373                     break;
01374                 }
01375             }
01376         }
01377 
01378         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
01379         codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
01380         st->codec->codec_id = codec_ul->id;
01381         if (descriptor->extradata) {
01382             st->codec->extradata = descriptor->extradata;
01383             st->codec->extradata_size = descriptor->extradata_size;
01384         }
01385         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01386             container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
01387             if (st->codec->codec_id == CODEC_ID_NONE)
01388                 st->codec->codec_id = container_ul->id;
01389             st->codec->width = descriptor->width;
01390             st->codec->height = descriptor->height;
01391             if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
01392                 st->codec->pix_fmt = descriptor->pix_fmt;
01393             st->need_parsing = AVSTREAM_PARSE_HEADERS;
01394         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
01395             container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
01396             if (st->codec->codec_id == CODEC_ID_NONE)
01397                 st->codec->codec_id = container_ul->id;
01398             st->codec->channels = descriptor->channels;
01399             st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
01400             if (descriptor->sample_rate.den > 0)
01401             st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
01402             /* TODO: implement CODEC_ID_RAWAUDIO */
01403             if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
01404                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
01405                     st->codec->codec_id = CODEC_ID_PCM_S24LE;
01406                 else if (descriptor->bits_per_sample == 32)
01407                     st->codec->codec_id = CODEC_ID_PCM_S32LE;
01408             } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
01409                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
01410                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
01411                 else if (descriptor->bits_per_sample == 32)
01412                     st->codec->codec_id = CODEC_ID_PCM_S32BE;
01413             } else if (st->codec->codec_id == CODEC_ID_MP2) {
01414                 st->need_parsing = AVSTREAM_PARSE_FULL;
01415             }
01416         }
01417         if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
01418             /* TODO: decode timestamps */
01419             st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
01420         }
01421     }
01422 
01423     ret = 0;
01424 fail_and_free:
01425     return ret;
01426 }
01427 
01428 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
01429     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
01430     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
01431     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
01432     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
01433     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
01434     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
01435     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
01436     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
01437     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
01438     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
01439     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
01440     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
01441     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
01442     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
01443     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
01444     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
01445     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
01446     { { 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 */
01447     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
01448     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
01449     { { 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 */
01450     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
01451     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
01452     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
01453     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
01454     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
01455     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
01456     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
01457 };
01458 
01459 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
01460 {
01461     AVIOContext *pb = mxf->fc->pb;
01462     MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
01463     uint64_t klv_end = avio_tell(pb) + klv->length;
01464 
01465     if (!ctx)
01466         return AVERROR(ENOMEM);
01467     while (avio_tell(pb) + 4 < klv_end && !url_feof(pb)) {
01468         int ret;
01469         int tag = avio_rb16(pb);
01470         int size = avio_rb16(pb); /* KLV specified by 0x53 */
01471         uint64_t next = avio_tell(pb) + size;
01472         UID uid = {0};
01473 
01474         av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
01475         if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
01476             av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
01477             continue;
01478         }
01479         if (tag > 0x7FFF) { /* dynamic tag */
01480             int i;
01481             for (i = 0; i < mxf->local_tags_count; i++) {
01482                 int local_tag = AV_RB16(mxf->local_tags+i*18);
01483                 if (local_tag == tag) {
01484                     memcpy(uid, mxf->local_tags+i*18+2, 16);
01485                     av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
01486                     PRINT_KEY(mxf->fc, "uid", uid);
01487                 }
01488             }
01489         }
01490         if (ctx_size && tag == 0x3C0A)
01491             avio_read(pb, ctx->uid, 16);
01492         else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0)
01493             return ret;
01494 
01495         /* accept the 64k local set limit being exceeded (Avid)
01496          * don't accept it extending past the end of the KLV though (zzuf5.mxf) */
01497         if (avio_tell(pb) > klv_end) {
01498             av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
01499                    tag, klv->offset);
01500             return AVERROR_INVALIDDATA;
01501         } else if (avio_tell(pb) <= next)   /* only seek forward, else this can loop for a long time */
01502         avio_seek(pb, next, SEEK_SET);
01503     }
01504     if (ctx_size) ctx->type = type;
01505     return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
01506 }
01507 
01512 static int mxf_seek_to_previous_partition(MXFContext *mxf)
01513 {
01514     AVIOContext *pb = mxf->fc->pb;
01515 
01516     if (!mxf->current_partition ||
01517         mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
01518         return 0;   /* we've parsed all partitions */
01519 
01520     /* seek to previous partition */
01521     avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
01522     mxf->current_partition = NULL;
01523 
01524     av_dlog(mxf->fc, "seeking to previous partition\n");
01525 
01526     return 1;
01527 }
01528 
01533 static int mxf_parse_handle_essence(MXFContext *mxf)
01534 {
01535     AVIOContext *pb = mxf->fc->pb;
01536     int64_t ret;
01537 
01538     if (mxf->parsing_backward) {
01539         return mxf_seek_to_previous_partition(mxf);
01540     } else {
01541         if (!mxf->footer_partition) {
01542             av_dlog(mxf->fc, "no footer\n");
01543             return 0;
01544         }
01545 
01546         av_dlog(mxf->fc, "seeking to footer\n");
01547 
01548         /* remember where we were so we don't end up seeking further back than this */
01549         mxf->last_forward_tell = avio_tell(pb);
01550 
01551         if (!pb->seekable) {
01552             av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
01553             return -1;
01554         }
01555 
01556         /* seek to footer partition and parse backward */
01557         if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
01558             av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
01559                    mxf->run_in + mxf->footer_partition, ret);
01560             return ret;
01561         }
01562 
01563         mxf->current_partition = NULL;
01564         mxf->parsing_backward = 1;
01565     }
01566 
01567     return 1;
01568 }
01569 
01574 static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
01575 {
01576     return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
01577 }
01578 
01582 static void mxf_compute_essence_containers(MXFContext *mxf)
01583 {
01584     int x;
01585 
01586     /* everything is already correct */
01587     if (mxf->op == OPAtom)
01588         return;
01589 
01590     for (x = 0; x < mxf->partitions_count; x++) {
01591         MXFPartition *p = &mxf->partitions[x];
01592 
01593         if (!p->body_sid)
01594             continue;       /* BodySID == 0 -> no essence */
01595 
01596         if (x >= mxf->partitions_count - 1)
01597             break;          /* last partition - can't compute length (and we don't need to) */
01598 
01599         /* essence container spans to the next partition */
01600         p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
01601 
01602         if (p->essence_length < 0) {
01603             /* next ThisPartition < essence_offset */
01604             p->essence_length = 0;
01605             av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %" PRIx64 "\n",
01606                    x+1, mxf->partitions[x+1].this_partition);
01607         }
01608     }
01609 }
01610 
01611 static int64_t round_to_kag(int64_t position, int kag_size)
01612 {
01613     /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
01614     /* NOTE: kag_size may be any integer between 1 - 2^10 */
01615     int64_t ret = (position / kag_size) * kag_size;
01616     return ret == position ? ret : ret + kag_size;
01617 }
01618 
01619 static int is_pcm(enum CodecID codec_id)
01620 {
01621     /* we only care about "normal" PCM codecs until we get samples */
01622     return codec_id >= CODEC_ID_PCM_S16LE && codec_id < CODEC_ID_PCM_S24DAUD;
01623 }
01624 
01629 static void mxf_handle_small_eubc(AVFormatContext *s)
01630 {
01631     MXFContext *mxf = s->priv_data;
01632 
01633     /* assuming non-OPAtom == frame wrapped
01634      * no sane writer would wrap 2 byte PCM packets with 20 byte headers.. */
01635     if (mxf->op != OPAtom)
01636         return;
01637 
01638     /* expect PCM with exactly one index table segment and a small (< 32) EUBC */
01639     if (s->nb_streams != 1 || s->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
01640         !is_pcm(s->streams[0]->codec->codec_id) || mxf->nb_index_tables != 1 ||
01641         mxf->index_tables[0].nb_segments != 1 ||
01642         mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32)
01643         return;
01644 
01645     /* arbitrarily default to 48 kHz PAL audio frame size */
01646     /* TODO: we could compute this from the ratio between the audio and video edit rates
01647      *       for 48 kHz NTSC we could use the 1802-1802-1802-1802-1801 pattern */
01648     mxf->edit_units_per_packet = 1920;
01649 }
01650 
01651 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
01652 {
01653     MXFContext *mxf = s->priv_data;
01654     KLVPacket klv;
01655     int64_t essence_offset = 0;
01656     int ret;
01657 
01658     mxf->last_forward_tell = INT64_MAX;
01659     mxf->edit_units_per_packet = 1;
01660 
01661     if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
01662         av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
01663         return AVERROR_INVALIDDATA;
01664     }
01665     avio_seek(s->pb, -14, SEEK_CUR);
01666     mxf->fc = s;
01667     mxf->run_in = avio_tell(s->pb);
01668 
01669     while (!url_feof(s->pb)) {
01670         const MXFMetadataReadTableEntry *metadata;
01671 
01672         if (klv_read_packet(&klv, s->pb) < 0) {
01673             /* EOF - seek to previous partition or stop */
01674             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
01675                 break;
01676             else
01677                 continue;
01678         }
01679 
01680         PRINT_KEY(s, "read header", klv.key);
01681         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
01682         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
01683             IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
01684             IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
01685             IS_KLV_KEY(klv.key, mxf_system_item_key)) {
01686 
01687             if (!mxf->current_partition) {
01688                 av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
01689                 return AVERROR_INVALIDDATA;
01690             }
01691 
01692             if (!mxf->current_partition->essence_offset) {
01693                 /* for OP1a we compute essence_offset
01694                  * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
01695                  * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
01696                  *       for OPAtom we still need the actual essence_offset though (the KL's length can vary)
01697                  */
01698                 int64_t op1a_essence_offset =
01699                     round_to_kag(mxf->current_partition->this_partition +
01700                                  mxf->current_partition->pack_length,       mxf->current_partition->kag_size) +
01701                     round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
01702                     round_to_kag(mxf->current_partition->index_byte_count,  mxf->current_partition->kag_size);
01703 
01704                 if (mxf->op == OPAtom) {
01705                     /* point essence_offset to the actual data
01706                     * OPAtom has all the essence in one big KLV
01707                     */
01708                     mxf->current_partition->essence_offset = avio_tell(s->pb);
01709                     mxf->current_partition->essence_length = klv.length;
01710                 } else {
01711                     /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf)  */
01712                     mxf->current_partition->essence_offset = op1a_essence_offset;
01713                 }
01714             }
01715 
01716             if (!essence_offset)
01717                 essence_offset = klv.offset;
01718 
01719             /* seek to footer, previous partition or stop */
01720             if (mxf_parse_handle_essence(mxf) <= 0)
01721                 break;
01722             continue;
01723         } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
01724                    klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
01725             /* next partition pack - keep going, seek to previous partition or stop */
01726             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
01727                 break;
01728         }
01729 
01730         for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
01731             if (IS_KLV_KEY(klv.key, metadata->key)) {
01732                 int res;
01733                 if (klv.key[5] == 0x53) {
01734                     res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
01735                 } else {
01736                     uint64_t next = avio_tell(s->pb) + klv.length;
01737                     res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
01738 
01739                     /* only seek forward, else this can loop for a long time */
01740                     if (avio_tell(s->pb) > next) {
01741                         av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
01742                                klv.offset);
01743                         return AVERROR_INVALIDDATA;
01744                     }
01745 
01746                     avio_seek(s->pb, next, SEEK_SET);
01747                 }
01748                 if (res < 0) {
01749                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
01750                     return res;
01751                 }
01752                 break;
01753             }
01754         }
01755         if (!metadata->read)
01756             avio_skip(s->pb, klv.length);
01757     }
01758     /* FIXME avoid seek */
01759     if (!essence_offset)  {
01760         av_log(s, AV_LOG_ERROR, "no essence\n");
01761         return AVERROR_INVALIDDATA;
01762     }
01763     avio_seek(s->pb, essence_offset, SEEK_SET);
01764 
01765     mxf_compute_essence_containers(mxf);
01766 
01767     /* we need to do this before computing the index tables
01768      * to be able to fill in zero IndexDurations with st->duration */
01769     if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
01770         return ret;
01771 
01772     if ((ret = mxf_compute_index_tables(mxf)) < 0)
01773         return ret;
01774 
01775     if (mxf->nb_index_tables > 1) {
01776         /* TODO: look up which IndexSID to use via EssenceContainerData */
01777         av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
01778                mxf->nb_index_tables, mxf->index_tables[0].index_sid);
01779     } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
01780         av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
01781         return AVERROR_INVALIDDATA;
01782     }
01783 
01784     mxf_handle_small_eubc(s);
01785 
01786     return 0;
01787 }
01788 
01792 static void mxf_packet_timestamps(MXFContext *mxf, AVPacket *pkt)
01793 {
01794     int64_t last_ofs = -1, next_ofs;
01795     MXFIndexTable *t = &mxf->index_tables[0];
01796 
01797     /* this is called from the OP1a demuxing logic, which means there may be no index tables */
01798     if (mxf->nb_index_tables <= 0)
01799         return;
01800 
01801     /* find mxf->current_edit_unit so that the next edit unit starts ahead of pkt->pos */
01802     while (mxf->current_edit_unit >= 0) {
01803         if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0)
01804             break;
01805 
01806         if (next_ofs <= last_ofs) {
01807             /* large next_ofs didn't change or current_edit_unit wrapped around
01808              * this fixes the infinite loop on zzuf3.mxf */
01809             av_log(mxf->fc, AV_LOG_ERROR, "next_ofs didn't change. not deriving packet timestamps\n");
01810             return;
01811         }
01812 
01813         if (next_ofs > pkt->pos)
01814             break;
01815 
01816         last_ofs = next_ofs;
01817         mxf->current_edit_unit++;
01818     }
01819 
01820     if (mxf->current_edit_unit < 0 || mxf->current_edit_unit >= t->nb_ptses)
01821         return;
01822 
01823     pkt->dts = mxf->current_edit_unit + t->first_dts;
01824     pkt->pts = t->ptses[mxf->current_edit_unit];
01825 }
01826 
01827 static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
01828 {
01829     KLVPacket klv;
01830 
01831     while (!url_feof(s->pb)) {
01832         int ret;
01833         if (klv_read_packet(&klv, s->pb) < 0)
01834             return -1;
01835         PRINT_KEY(s, "read packet", klv.key);
01836         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
01837         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
01838             ret = mxf_decrypt_triplet(s, pkt, &klv);
01839             if (ret < 0) {
01840                 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
01841                 return AVERROR_INVALIDDATA;
01842             }
01843             return 0;
01844         }
01845         if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
01846             IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
01847             int index = mxf_get_stream_index(s, &klv);
01848             if (index < 0) {
01849                 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
01850                 goto skip;
01851             }
01852             if (s->streams[index]->discard == AVDISCARD_ALL)
01853                 goto skip;
01854             /* check for 8 channels AES3 element */
01855             if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
01856                 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
01857                     av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
01858                     return AVERROR_INVALIDDATA;
01859                 }
01860             } else {
01861                 ret = av_get_packet(s->pb, pkt, klv.length);
01862                 if (ret < 0)
01863                     return ret;
01864             }
01865             pkt->stream_index = index;
01866             pkt->pos = klv.offset;
01867 
01868             if (s->streams[index]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
01869                 mxf_packet_timestamps(s->priv_data, pkt);   /* offset -> EditUnit -> DTS/PTS */
01870 
01871             return 0;
01872         } else
01873         skip:
01874             avio_skip(s->pb, klv.length);
01875     }
01876     return AVERROR_EOF;
01877 }
01878 
01879 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
01880 {
01881     MXFContext *mxf = s->priv_data;
01882     int ret, size;
01883     int64_t ret64, pos, next_pos;
01884     AVStream *st;
01885     MXFIndexTable *t;
01886     int edit_units;
01887 
01888     if (mxf->op != OPAtom)
01889         return mxf_read_packet_old(s, pkt);
01890 
01891     /* OPAtom - clip wrapped demuxing */
01892     /* NOTE: mxf_read_header() makes sure nb_index_tables > 0 for OPAtom */
01893     st = s->streams[0];
01894     t = &mxf->index_tables[0];
01895 
01896     if (mxf->current_edit_unit >= st->duration)
01897         return AVERROR_EOF;
01898 
01899     edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit);
01900 
01901     if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0)
01902         return ret;
01903 
01904     /* compute size by finding the next edit unit or the end of the essence container
01905      * not pretty, but it works */
01906     if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 &&
01907         (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
01908         av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
01909         return AVERROR_INVALIDDATA;
01910     }
01911 
01912     if ((size = next_pos - pos) <= 0) {
01913         av_log(s, AV_LOG_ERROR, "bad size: %i\n", size);
01914         return AVERROR_INVALIDDATA;
01915     }
01916 
01917     if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0)
01918         return ret64;
01919 
01920         if ((ret = av_get_packet(s->pb, pkt, size)) != size)
01921             return ret < 0 ? ret : AVERROR_EOF;
01922 
01923     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
01924         mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
01925         pkt->dts = mxf->current_edit_unit + t->first_dts;
01926         pkt->pts = t->ptses[mxf->current_edit_unit];
01927     }
01928 
01929     pkt->stream_index = 0;
01930     mxf->current_edit_unit += edit_units;
01931 
01932     return 0;
01933 }
01934 
01935 static int mxf_read_close(AVFormatContext *s)
01936 {
01937     MXFContext *mxf = s->priv_data;
01938     MXFIndexTableSegment *seg;
01939     int i;
01940 
01941     av_freep(&mxf->packages_refs);
01942 
01943     for (i = 0; i < s->nb_streams; i++)
01944         s->streams[i]->priv_data = NULL;
01945 
01946     for (i = 0; i < mxf->metadata_sets_count; i++) {
01947         switch (mxf->metadata_sets[i]->type) {
01948         case MultipleDescriptor:
01949             av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
01950             break;
01951         case Sequence:
01952             av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
01953             break;
01954         case SourcePackage:
01955         case MaterialPackage:
01956             av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
01957             break;
01958         case IndexTableSegment:
01959             seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
01960             av_freep(&seg->temporal_offset_entries);
01961             av_freep(&seg->flag_entries);
01962             av_freep(&seg->stream_offset_entries);
01963             break;
01964         default:
01965             break;
01966         }
01967         av_freep(&mxf->metadata_sets[i]);
01968     }
01969     av_freep(&mxf->partitions);
01970     av_freep(&mxf->metadata_sets);
01971     av_freep(&mxf->aesc);
01972     av_freep(&mxf->local_tags);
01973 
01974     for (i = 0; i < mxf->nb_index_tables; i++) {
01975         av_freep(&mxf->index_tables[i].segments);
01976         av_freep(&mxf->index_tables[i].ptses);
01977         av_freep(&mxf->index_tables[i].fake_index);
01978     }
01979     av_freep(&mxf->index_tables);
01980 
01981     return 0;
01982 }
01983 
01984 static int mxf_probe(AVProbeData *p) {
01985     uint8_t *bufp = p->buf;
01986     uint8_t *end = p->buf + p->buf_size;
01987 
01988     if (p->buf_size < sizeof(mxf_header_partition_pack_key))
01989         return 0;
01990 
01991     /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
01992     end -= sizeof(mxf_header_partition_pack_key);
01993     for (; bufp < end; bufp++) {
01994         if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
01995             return AVPROBE_SCORE_MAX;
01996     }
01997     return 0;
01998 }
01999 
02000 /* rudimentary byte seek */
02001 /* XXX: use MXF Index */
02002 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
02003 {
02004     AVStream *st = s->streams[stream_index];
02005     int64_t seconds;
02006     MXFContext* mxf = s->priv_data;
02007     int64_t seekpos;
02008     int ret;
02009     MXFIndexTable *t;
02010 
02011     if (mxf->index_tables <= 0) {
02012     if (!s->bit_rate)
02013         return AVERROR_INVALIDDATA;
02014     if (sample_time < 0)
02015         sample_time = 0;
02016     seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
02017 
02018     if ((ret = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET)) < 0)
02019         return ret;
02020     ff_update_cur_dts(s, st, sample_time);
02021     } else {
02022         t = &mxf->index_tables[0];
02023 
02024         /* clamp above zero, else ff_index_search_timestamp() returns negative
02025          * this also means we allow seeking before the start */
02026         sample_time = FFMAX(sample_time, 0);
02027 
02028         if (t->fake_index) {
02029             /* behave as if we have a proper index */
02030             if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
02031                 return sample_time;
02032         } else {
02033             /* no IndexEntryArray (one or more CBR segments)
02034              * make sure we don't seek past the end */
02035             sample_time = FFMIN(sample_time, st->duration - 1);
02036         }
02037 
02038         if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) << 0)
02039             return ret;
02040 
02041         ff_update_cur_dts(s, st, sample_time);
02042         mxf->current_edit_unit = sample_time;
02043         avio_seek(s->pb, seekpos, SEEK_SET);
02044     }
02045     return 0;
02046 }
02047 
02048 AVInputFormat ff_mxf_demuxer = {
02049     .name           = "mxf",
02050     .long_name      = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
02051     .priv_data_size = sizeof(MXFContext),
02052     .read_probe     = mxf_probe,
02053     .read_header    = mxf_read_header,
02054     .read_packet    = mxf_read_packet,
02055     .read_close     = mxf_read_close,
02056     .read_seek      = mxf_read_seek,
02057 };