00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 
00017 
00018 
00019 
00020 
00021 
00022 
00023 
00024 
00025 
00026 
00027 
00028 
00029 
00030 
00031 
00032 
00033 
00034 
00035 
00036 
00037 
00038 
00039 
00040 
00041 
00042 
00043 
00044 
00045 
00046 
00047 
00048 #include "libavutil/aes.h"
00049 #include "libavutil/mathematics.h"
00050 #include "libavcodec/bytestream.h"
00051 #include "libavutil/timecode.h"
00052 #include "avformat.h"
00053 #include "internal.h"
00054 #include "mxf.h"
00055 
00056 typedef enum {
00057     Header,
00058     BodyPartition,
00059     Footer
00060 } MXFPartitionType;
00061 
00062 typedef enum {
00063     OP1a = 1,
00064     OP1b,
00065     OP1c,
00066     OP2a,
00067     OP2b,
00068     OP2c,
00069     OP3a,
00070     OP3b,
00071     OP3c,
00072     OPAtom,
00073     OPSONYOpt,  
00074 } MXFOP;
00075 
00076 typedef struct {
00077     int closed;
00078     int complete;
00079     MXFPartitionType type;
00080     uint64_t previous_partition;
00081     int index_sid;
00082     int body_sid;
00083     int64_t this_partition;
00084     int64_t essence_offset;         
00085     int64_t essence_length;
00086     int32_t kag_size;
00087     int64_t header_byte_count;
00088     int64_t index_byte_count;
00089     int pack_length;
00090 } MXFPartition;
00091 
00092 typedef struct {
00093     UID uid;
00094     enum MXFMetadataSetType type;
00095     UID source_container_ul;
00096 } MXFCryptoContext;
00097 
00098 typedef struct {
00099     UID uid;
00100     enum MXFMetadataSetType type;
00101     UID source_package_uid;
00102     UID data_definition_ul;
00103     int64_t duration;
00104     int64_t start_position;
00105     int source_track_id;
00106 } MXFStructuralComponent;
00107 
00108 typedef struct {
00109     UID uid;
00110     enum MXFMetadataSetType type;
00111     UID data_definition_ul;
00112     UID *structural_components_refs;
00113     int structural_components_count;
00114     int64_t duration;
00115 } MXFSequence;
00116 
00117 typedef struct {
00118     UID uid;
00119     enum MXFMetadataSetType type;
00120     int drop_frame;
00121     int start_frame;
00122     struct AVRational rate;
00123     AVTimecode tc;
00124 } MXFTimecodeComponent;
00125 
00126 typedef struct {
00127     UID uid;
00128     enum MXFMetadataSetType type;
00129     MXFSequence *sequence; 
00130     UID sequence_ref;
00131     int track_id;
00132     uint8_t track_number[4];
00133     AVRational edit_rate;
00134     int intra_only;
00135 } MXFTrack;
00136 
00137 typedef struct {
00138     UID uid;
00139     enum MXFMetadataSetType type;
00140     UID essence_container_ul;
00141     UID essence_codec_ul;
00142     AVRational sample_rate;
00143     AVRational aspect_ratio;
00144     int width;
00145     int height; 
00146     int frame_layout; 
00147     int channels;
00148     int bits_per_sample;
00149     unsigned int component_depth;
00150     unsigned int horiz_subsampling;
00151     unsigned int vert_subsampling;
00152     UID *sub_descriptors_refs;
00153     int sub_descriptors_count;
00154     int linked_track_id;
00155     uint8_t *extradata;
00156     int extradata_size;
00157     enum PixelFormat pix_fmt;
00158 } MXFDescriptor;
00159 
00160 typedef struct {
00161     UID uid;
00162     enum MXFMetadataSetType type;
00163     int edit_unit_byte_count;
00164     int index_sid;
00165     int body_sid;
00166     AVRational index_edit_rate;
00167     uint64_t index_start_position;
00168     uint64_t index_duration;
00169     int8_t *temporal_offset_entries;
00170     int *flag_entries;
00171     uint64_t *stream_offset_entries;
00172     int nb_index_entries;
00173 } MXFIndexTableSegment;
00174 
00175 typedef struct {
00176     UID uid;
00177     enum MXFMetadataSetType type;
00178     UID package_uid;
00179     UID *tracks_refs;
00180     int tracks_count;
00181     MXFDescriptor *descriptor; 
00182     UID descriptor_ref;
00183 } MXFPackage;
00184 
00185 typedef struct {
00186     UID uid;
00187     enum MXFMetadataSetType type;
00188 } MXFMetadataSet;
00189 
00190 
00191 typedef struct {
00192     int index_sid;
00193     int body_sid;
00194     int nb_ptses;               
00195     int64_t first_dts;          
00196     int64_t *ptses;             
00197     int nb_segments;
00198     MXFIndexTableSegment **segments;    
00199     AVIndexEntry *fake_index;   
00200 } MXFIndexTable;
00201 
00202 typedef struct {
00203     MXFPartition *partitions;
00204     unsigned partitions_count;
00205     MXFOP op;
00206     UID *packages_refs;
00207     int packages_count;
00208     MXFMetadataSet **metadata_sets;
00209     int metadata_sets_count;
00210     AVFormatContext *fc;
00211     struct AVAES *aesc;
00212     uint8_t *local_tags;
00213     int local_tags_count;
00214     uint64_t footer_partition;
00215     KLVPacket current_klv_data;
00216     int current_klv_index;
00217     int run_in;
00218     MXFPartition *current_partition;
00219     int parsing_backward;
00220     int64_t last_forward_tell;
00221     int last_forward_partition;
00222     int current_edit_unit;
00223     int nb_index_tables;
00224     MXFIndexTable *index_tables;
00225     int edit_units_per_packet;      
00226 } MXFContext;
00227 
00228 enum MXFWrappingScheme {
00229     Frame,
00230     Clip,
00231 };
00232 
00233 
00234 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
00235 
00236 typedef struct {
00237     const UID key;
00238     MXFMetadataReadFunc *read;
00239     int ctx_size;
00240     enum MXFMetadataSetType type;
00241 } MXFMetadataReadTableEntry;
00242 
00243 
00244 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
00245 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
00246 static const uint8_t mxf_avid_essence_element_key[]        = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
00247 static const uint8_t mxf_system_item_key[]                 = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
00248 static const uint8_t mxf_klv_key[]                         = { 0x06,0x0e,0x2b,0x34 };
00249 
00250 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 };
00251 static const uint8_t mxf_encrypted_triplet_key[]           = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
00252 static const uint8_t mxf_encrypted_essence_container[]     = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
00253 static const uint8_t mxf_sony_mpeg4_extradata[]            = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
00254 
00255 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
00256 
00257 static int64_t klv_decode_ber_length(AVIOContext *pb)
00258 {
00259     uint64_t size = avio_r8(pb);
00260     if (size & 0x80) { 
00261         int bytes_num = size & 0x7f;
00262         
00263         if (bytes_num > 8)
00264             return AVERROR_INVALIDDATA;
00265         size = 0;
00266         while (bytes_num--)
00267             size = size << 8 | avio_r8(pb);
00268     }
00269     return size;
00270 }
00271 
00272 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
00273 {
00274     int i, b;
00275     for (i = 0; i < size && !url_feof(pb); i++) {
00276         b = avio_r8(pb);
00277         if (b == key[0])
00278             i = 0;
00279         else if (b != key[i])
00280             i = -1;
00281     }
00282     return i == size;
00283 }
00284 
00285 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
00286 {
00287     if (!mxf_read_sync(pb, mxf_klv_key, 4))
00288         return AVERROR_INVALIDDATA;
00289     klv->offset = avio_tell(pb) - 4;
00290     memcpy(klv->key, mxf_klv_key, 4);
00291     avio_read(pb, klv->key + 4, 12);
00292     klv->length = klv_decode_ber_length(pb);
00293     return klv->length == -1 ? -1 : 0;
00294 }
00295 
00296 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
00297 {
00298     int i;
00299 
00300     for (i = 0; i < s->nb_streams; i++) {
00301         MXFTrack *track = s->streams[i]->priv_data;
00302         
00303         if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
00304             return i;
00305     }
00306     
00307     return s->nb_streams == 1 ? 0 : -1;
00308 }
00309 
00310 
00311 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
00312 {
00313     const uint8_t *buf_ptr, *end_ptr;
00314     uint8_t *data_ptr;
00315     int i;
00316 
00317     if (length > 61444) 
00318         return AVERROR_INVALIDDATA;
00319     length = av_get_packet(pb, pkt, length);
00320     if (length < 0)
00321         return length;
00322     data_ptr = pkt->data;
00323     end_ptr = pkt->data + length;
00324     buf_ptr = pkt->data + 4; 
00325     for (; buf_ptr + st->codec->channels*4 <= end_ptr; ) {
00326         for (i = 0; i < st->codec->channels; i++) {
00327             uint32_t sample = bytestream_get_le32(&buf_ptr);
00328             if (st->codec->bits_per_coded_sample == 24)
00329                 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
00330             else
00331                 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
00332         }
00333         buf_ptr += 32 - st->codec->channels*4; 
00334     }
00335     av_shrink_packet(pkt, data_ptr - pkt->data);
00336     return 0;
00337 }
00338 
00339 static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
00340 {
00341     static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
00342     MXFContext *mxf = s->priv_data;
00343     AVIOContext *pb = s->pb;
00344     int64_t end = avio_tell(pb) + klv->length;
00345     int64_t size;
00346     uint64_t orig_size;
00347     uint64_t plaintext_size;
00348     uint8_t ivec[16];
00349     uint8_t tmpbuf[16];
00350     int index;
00351 
00352     if (!mxf->aesc && s->key && s->keylen == 16) {
00353         mxf->aesc = av_malloc(av_aes_size);
00354         if (!mxf->aesc)
00355             return AVERROR(ENOMEM);
00356         av_aes_init(mxf->aesc, s->key, 128, 1);
00357     }
00358     
00359     avio_skip(pb, klv_decode_ber_length(pb));
00360     
00361     klv_decode_ber_length(pb);
00362     plaintext_size = avio_rb64(pb);
00363     
00364     klv_decode_ber_length(pb);
00365     avio_read(pb, klv->key, 16);
00366     if (!IS_KLV_KEY(klv, mxf_essence_element_key))
00367         return AVERROR_INVALIDDATA;
00368     index = mxf_get_stream_index(s, klv);
00369     if (index < 0)
00370         return AVERROR_INVALIDDATA;
00371     
00372     klv_decode_ber_length(pb);
00373     orig_size = avio_rb64(pb);
00374     if (orig_size < plaintext_size)
00375         return AVERROR_INVALIDDATA;
00376     
00377     size = klv_decode_ber_length(pb);
00378     if (size < 32 || size - 32 < orig_size)
00379         return AVERROR_INVALIDDATA;
00380     avio_read(pb, ivec, 16);
00381     avio_read(pb, tmpbuf, 16);
00382     if (mxf->aesc)
00383         av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
00384     if (memcmp(tmpbuf, checkv, 16))
00385         av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
00386     size -= 32;
00387     size = av_get_packet(pb, pkt, size);
00388     if (size < 0)
00389         return size;
00390     else if (size < plaintext_size)
00391         return AVERROR_INVALIDDATA;
00392     size -= plaintext_size;
00393     if (mxf->aesc)
00394         av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
00395                      &pkt->data[plaintext_size], size >> 4, ivec, 1);
00396     av_shrink_packet(pkt, orig_size);
00397     pkt->stream_index = index;
00398     avio_skip(pb, end - avio_tell(pb));
00399     return 0;
00400 }
00401 
00402 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00403 {
00404     MXFContext *mxf = arg;
00405     int item_num = avio_rb32(pb);
00406     int item_len = avio_rb32(pb);
00407 
00408     if (item_len != 18) {
00409         av_log_ask_for_sample(pb, "unsupported primer pack item length %d\n",
00410                               item_len);
00411         return AVERROR_PATCHWELCOME;
00412     }
00413     if (item_num > 65536) {
00414         av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num);
00415         return AVERROR_INVALIDDATA;
00416     }
00417     mxf->local_tags = av_calloc(item_num, item_len);
00418     if (!mxf->local_tags)
00419         return AVERROR(ENOMEM);
00420     mxf->local_tags_count = item_num;
00421     avio_read(pb, mxf->local_tags, item_num*item_len);
00422     return 0;
00423 }
00424 
00425 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00426 {
00427     MXFContext *mxf = arg;
00428     MXFPartition *partition, *tmp_part;
00429     UID op;
00430     uint64_t footer_partition;
00431     uint32_t nb_essence_containers;
00432 
00433     if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
00434         return AVERROR(ENOMEM);
00435 
00436     tmp_part = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
00437     if (!tmp_part)
00438         return AVERROR(ENOMEM);
00439     mxf->partitions = tmp_part;
00440 
00441     if (mxf->parsing_backward) {
00442         
00443 
00444         memmove(&mxf->partitions[mxf->last_forward_partition+1],
00445                 &mxf->partitions[mxf->last_forward_partition],
00446                 (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
00447         partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
00448     } else {
00449         mxf->last_forward_partition++;
00450         partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
00451     }
00452 
00453     memset(partition, 0, sizeof(*partition));
00454     mxf->partitions_count++;
00455     partition->pack_length = avio_tell(pb) - klv_offset + size;
00456 
00457     switch(uid[13]) {
00458     case 2:
00459         partition->type = Header;
00460         break;
00461     case 3:
00462         partition->type = BodyPartition;
00463         break;
00464     case 4:
00465         partition->type = Footer;
00466         break;
00467     default:
00468         av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
00469         return AVERROR_INVALIDDATA;
00470     }
00471 
00472     
00473     partition->closed = partition->type == Footer || !(uid[14] & 1);
00474     partition->complete = uid[14] > 2;
00475     avio_skip(pb, 4);
00476     partition->kag_size = avio_rb32(pb);
00477     partition->this_partition = avio_rb64(pb);
00478     partition->previous_partition = avio_rb64(pb);
00479     footer_partition = avio_rb64(pb);
00480     partition->header_byte_count = avio_rb64(pb);
00481     partition->index_byte_count = avio_rb64(pb);
00482     partition->index_sid = avio_rb32(pb);
00483     avio_skip(pb, 8);
00484     partition->body_sid = avio_rb32(pb);
00485     avio_read(pb, op, sizeof(UID));
00486     nb_essence_containers = avio_rb32(pb);
00487 
00488     
00489     if (footer_partition) {
00490         if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
00491             av_log(mxf->fc, AV_LOG_ERROR,
00492                    "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
00493                    mxf->footer_partition, footer_partition);
00494         } else {
00495             mxf->footer_partition = footer_partition;
00496         }
00497     }
00498 
00499     av_dlog(mxf->fc,
00500             "PartitionPack: ThisPartition = 0x%"PRIX64
00501             ", PreviousPartition = 0x%"PRIX64", "
00502             "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
00503             partition->this_partition,
00504             partition->previous_partition, footer_partition,
00505             partition->index_sid, partition->body_sid);
00506 
00507     
00508     if (partition->previous_partition &&
00509         mxf->run_in + partition->previous_partition >= klv_offset) {
00510         av_log(mxf->fc, AV_LOG_ERROR,
00511                "PreviousPartition points to this partition or forward\n");
00512         return AVERROR_INVALIDDATA;
00513     }
00514 
00515     if      (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
00516     else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
00517     else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
00518     else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
00519     else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
00520     else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
00521     else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
00522     else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
00523     else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
00524     else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
00525     else if (op[12] == 0x10) {
00526         
00527 
00528 
00529 
00530         if (nb_essence_containers != 1) {
00531             MXFOP op = nb_essence_containers ? OP1a : OPAtom;
00532 
00533             
00534             if (!mxf->op)
00535                 av_log(mxf->fc, AV_LOG_WARNING, "\"OPAtom\" with %u ECs - assuming %s\n",
00536                        nb_essence_containers, op == OP1a ? "OP1a" : "OPAtom");
00537 
00538             mxf->op = op;
00539         } else
00540             mxf->op = OPAtom;
00541     } else {
00542         av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
00543         mxf->op = OP1a;
00544     }
00545 
00546     if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
00547         av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
00548 
00549         if (mxf->op == OPSONYOpt)
00550             partition->kag_size = 512;
00551         else
00552             partition->kag_size = 1;
00553 
00554         av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
00555     }
00556 
00557     return 0;
00558 }
00559 
00560 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
00561 {
00562     MXFMetadataSet **tmp;
00563     if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
00564         return AVERROR(ENOMEM);
00565     tmp = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
00566     if (!tmp)
00567         return AVERROR(ENOMEM);
00568     mxf->metadata_sets = tmp;
00569     mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
00570     mxf->metadata_sets_count++;
00571     return 0;
00572 }
00573 
00574 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00575 {
00576     MXFCryptoContext *cryptocontext = arg;
00577     if (size != 16)
00578         return AVERROR_INVALIDDATA;
00579     if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
00580         avio_read(pb, cryptocontext->source_container_ul, 16);
00581     return 0;
00582 }
00583 
00584 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00585 {
00586     MXFContext *mxf = arg;
00587     switch (tag) {
00588     case 0x1901:
00589         mxf->packages_count = avio_rb32(pb);
00590         mxf->packages_refs = av_calloc(mxf->packages_count, sizeof(UID));
00591         if (!mxf->packages_refs)
00592             return AVERROR(ENOMEM);
00593         avio_skip(pb, 4); 
00594         avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
00595         break;
00596     }
00597     return 0;
00598 }
00599 
00600 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00601 {
00602     MXFStructuralComponent *source_clip = arg;
00603     switch(tag) {
00604     case 0x0202:
00605         source_clip->duration = avio_rb64(pb);
00606         break;
00607     case 0x1201:
00608         source_clip->start_position = avio_rb64(pb);
00609         break;
00610     case 0x1101:
00611         
00612         avio_skip(pb, 16);
00613         avio_read(pb, source_clip->source_package_uid, 16);
00614         break;
00615     case 0x1102:
00616         source_clip->source_track_id = avio_rb32(pb);
00617         break;
00618     }
00619     return 0;
00620 }
00621 
00622 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00623 {
00624     MXFPackage *package = arg;
00625     switch(tag) {
00626     case 0x4403:
00627         package->tracks_count = avio_rb32(pb);
00628         package->tracks_refs = av_calloc(package->tracks_count, sizeof(UID));
00629         if (!package->tracks_refs)
00630             return AVERROR(ENOMEM);
00631         avio_skip(pb, 4); 
00632         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
00633         break;
00634     }
00635     return 0;
00636 }
00637 
00638 static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00639 {
00640     MXFTimecodeComponent *mxf_timecode = arg;
00641     switch(tag) {
00642     case 0x1501:
00643         mxf_timecode->start_frame = avio_rb64(pb);
00644         break;
00645     case 0x1502:
00646         mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
00647         break;
00648     case 0x1503:
00649         mxf_timecode->drop_frame = avio_r8(pb);
00650         break;
00651     }
00652     return 0;
00653 }
00654 
00655 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00656 {
00657     MXFTrack *track = arg;
00658     switch(tag) {
00659     case 0x4801:
00660         track->track_id = avio_rb32(pb);
00661         break;
00662     case 0x4804:
00663         avio_read(pb, track->track_number, 4);
00664         break;
00665     case 0x4B01:
00666         track->edit_rate.num = avio_rb32(pb);
00667         track->edit_rate.den = avio_rb32(pb);
00668         break;
00669     case 0x4803:
00670         avio_read(pb, track->sequence_ref, 16);
00671         break;
00672     }
00673     return 0;
00674 }
00675 
00676 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00677 {
00678     MXFSequence *sequence = arg;
00679     switch(tag) {
00680     case 0x0202:
00681         sequence->duration = avio_rb64(pb);
00682         break;
00683     case 0x0201:
00684         avio_read(pb, sequence->data_definition_ul, 16);
00685         break;
00686     case 0x1001:
00687         sequence->structural_components_count = avio_rb32(pb);
00688         sequence->structural_components_refs = av_calloc(sequence->structural_components_count, sizeof(UID));
00689         if (!sequence->structural_components_refs)
00690             return AVERROR(ENOMEM);
00691         avio_skip(pb, 4); 
00692         avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
00693         break;
00694     }
00695     return 0;
00696 }
00697 
00698 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00699 {
00700     MXFPackage *package = arg;
00701     switch(tag) {
00702     case 0x4403:
00703         package->tracks_count = avio_rb32(pb);
00704         package->tracks_refs = av_calloc(package->tracks_count, sizeof(UID));
00705         if (!package->tracks_refs)
00706             return AVERROR(ENOMEM);
00707         avio_skip(pb, 4); 
00708         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
00709         break;
00710     case 0x4401:
00711         
00712         avio_skip(pb, 16);
00713         avio_read(pb, package->package_uid, 16);
00714         break;
00715     case 0x4701:
00716         avio_read(pb, package->descriptor_ref, 16);
00717         break;
00718     }
00719     return 0;
00720 }
00721 
00722 static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
00723 {
00724     int i, length;
00725 
00726     segment->nb_index_entries = avio_rb32(pb);
00727 
00728     length = avio_rb32(pb);
00729 
00730     if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
00731         !(segment->flag_entries          = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
00732         !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
00733         return AVERROR(ENOMEM);
00734 
00735     for (i = 0; i < segment->nb_index_entries; i++) {
00736         segment->temporal_offset_entries[i] = avio_r8(pb);
00737         avio_r8(pb);                                        
00738         segment->flag_entries[i] = avio_r8(pb);
00739         segment->stream_offset_entries[i] = avio_rb64(pb);
00740         avio_skip(pb, length - 11);
00741     }
00742     return 0;
00743 }
00744 
00745 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00746 {
00747     MXFIndexTableSegment *segment = arg;
00748     switch(tag) {
00749     case 0x3F05:
00750         segment->edit_unit_byte_count = avio_rb32(pb);
00751         av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
00752         break;
00753     case 0x3F06:
00754         segment->index_sid = avio_rb32(pb);
00755         av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
00756         break;
00757     case 0x3F07:
00758         segment->body_sid = avio_rb32(pb);
00759         av_dlog(NULL, "BodySID %d\n", segment->body_sid);
00760         break;
00761     case 0x3F0A:
00762         av_dlog(NULL, "IndexEntryArray found\n");
00763         return mxf_read_index_entry_array(pb, segment);
00764     case 0x3F0B:
00765         segment->index_edit_rate.num = avio_rb32(pb);
00766         segment->index_edit_rate.den = avio_rb32(pb);
00767         av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
00768                 segment->index_edit_rate.den);
00769         break;
00770     case 0x3F0C:
00771         segment->index_start_position = avio_rb64(pb);
00772         av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
00773         break;
00774     case 0x3F0D:
00775         segment->index_duration = avio_rb64(pb);
00776         av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
00777         break;
00778     }
00779     return 0;
00780 }
00781 
00782 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
00783 {
00784     int code, value, ofs = 0;
00785     char layout[16] = {0};
00786 
00787     do {
00788         code = avio_r8(pb);
00789         value = avio_r8(pb);
00790         av_dlog(NULL, "pixel layout: code %#x\n", code);
00791 
00792         if (ofs < 16) {
00793             layout[ofs++] = code;
00794             layout[ofs++] = value;
00795         }
00796     } while (code != 0); 
00797 
00798     ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
00799 }
00800 
00801 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
00802 {
00803     MXFDescriptor *descriptor = arg;
00804     descriptor->pix_fmt = PIX_FMT_NONE;
00805     switch(tag) {
00806     case 0x3F01:
00807         descriptor->sub_descriptors_count = avio_rb32(pb);
00808         descriptor->sub_descriptors_refs = av_calloc(descriptor->sub_descriptors_count, sizeof(UID));
00809         if (!descriptor->sub_descriptors_refs)
00810             return AVERROR(ENOMEM);
00811         avio_skip(pb, 4); 
00812         avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
00813         break;
00814     case 0x3004:
00815         avio_read(pb, descriptor->essence_container_ul, 16);
00816         break;
00817     case 0x3006:
00818         descriptor->linked_track_id = avio_rb32(pb);
00819         break;
00820     case 0x3201: 
00821         avio_read(pb, descriptor->essence_codec_ul, 16);
00822         break;
00823     case 0x3203:
00824         descriptor->width = avio_rb32(pb);
00825         break;
00826     case 0x3202:
00827         descriptor->height = avio_rb32(pb);
00828         break;
00829     case 0x320C:
00830         descriptor->frame_layout = avio_r8(pb);
00831         break;
00832     case 0x320E:
00833         descriptor->aspect_ratio.num = avio_rb32(pb);
00834         descriptor->aspect_ratio.den = avio_rb32(pb);
00835         break;
00836     case 0x3301:
00837         descriptor->component_depth = avio_rb32(pb);
00838         break;
00839     case 0x3302:
00840         descriptor->horiz_subsampling = avio_rb32(pb);
00841         break;
00842     case 0x3308:
00843         descriptor->vert_subsampling = avio_rb32(pb);
00844         break;
00845     case 0x3D03:
00846         descriptor->sample_rate.num = avio_rb32(pb);
00847         descriptor->sample_rate.den = avio_rb32(pb);
00848         break;
00849     case 0x3D06: 
00850         avio_read(pb, descriptor->essence_codec_ul, 16);
00851         break;
00852     case 0x3D07:
00853         descriptor->channels = avio_rb32(pb);
00854         break;
00855     case 0x3D01:
00856         descriptor->bits_per_sample = avio_rb32(pb);
00857         break;
00858     case 0x3401:
00859         mxf_read_pixel_layout(pb, descriptor);
00860         break;
00861     default:
00862         
00863         if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
00864             descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
00865             if (!descriptor->extradata)
00866                 return AVERROR(ENOMEM);
00867             descriptor->extradata_size = size;
00868             avio_read(pb, descriptor->extradata, size);
00869         }
00870         break;
00871     }
00872     return 0;
00873 }
00874 
00875 
00876 
00877 
00878 
00879 static int mxf_match_uid(const UID key, const UID uid, int len)
00880 {
00881     int i;
00882     for (i = 0; i < len; i++) {
00883         if (i != 7 && key[i] != uid[i])
00884             return 0;
00885     }
00886     return 1;
00887 }
00888 
00889 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
00890 {
00891     while (uls->uid[0]) {
00892         if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
00893             break;
00894         uls++;
00895     }
00896     return uls;
00897 }
00898 
00899 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
00900 {
00901     int i;
00902 
00903     if (!strong_ref)
00904         return NULL;
00905     for (i = 0; i < mxf->metadata_sets_count; i++) {
00906         if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
00907             (type == AnyType || mxf->metadata_sets[i]->type == type)) {
00908             return mxf->metadata_sets[i];
00909         }
00910     }
00911     return NULL;
00912 }
00913 
00914 static const MXFCodecUL mxf_picture_essence_container_uls[] = {
00915     
00916     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, 
00917     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14,    AV_CODEC_ID_DVVIDEO }, 
00918     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14,   AV_CODEC_ID_RAWVIDEO }, 
00919     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      AV_CODEC_ID_NONE },
00920 };
00921 
00922 
00923 static const MXFCodecUL mxf_intra_only_essence_container_uls[] = {
00924     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, AV_CODEC_ID_MPEG2VIDEO }, 
00925     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,       AV_CODEC_ID_NONE },
00926 };
00927 
00928 
00929 static const MXFCodecUL mxf_intra_only_picture_essence_coding_uls[] = {
00930     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14,       AV_CODEC_ID_H264 }, 
00931     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,       AV_CODEC_ID_NONE },
00932 };
00933 
00934 static const MXFCodecUL mxf_sound_essence_container_uls[] = {
00935     
00936     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE }, 
00937     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14,       AV_CODEC_ID_MP2 }, 
00938     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE }, 
00939     { { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0xFF,0x4B,0x46,0x41,0x41,0x00,0x0D,0x4D,0x4F }, 14, AV_CODEC_ID_PCM_S16LE }, 
00940     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      AV_CODEC_ID_NONE },
00941 };
00942 
00943 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
00944 {
00945     int i, j, nb_segments = 0;
00946     MXFIndexTableSegment **unsorted_segments;
00947     int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
00948 
00949     
00950     for (i = 0; i < mxf->metadata_sets_count; i++)
00951         if (mxf->metadata_sets[i]->type == IndexTableSegment)
00952             nb_segments++;
00953 
00954     if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
00955         !(*sorted_segments  = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
00956         av_freep(sorted_segments);
00957         av_free(unsorted_segments);
00958         return AVERROR(ENOMEM);
00959     }
00960 
00961     for (i = j = 0; i < mxf->metadata_sets_count; i++)
00962         if (mxf->metadata_sets[i]->type == IndexTableSegment)
00963             unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
00964 
00965     *nb_sorted_segments = 0;
00966 
00967     
00968     for (i = 0; i < nb_segments; i++) {
00969         int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
00970         uint64_t best_index_duration = 0;
00971 
00972         for (j = 0; j < nb_segments; j++) {
00973             MXFIndexTableSegment *s = unsorted_segments[j];
00974 
00975             
00976 
00977 
00978 
00979             if ((i == 0     || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
00980                 (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start ||
00981                 (s->index_start_position == best_index_start && s->index_duration > best_index_duration))) {
00982                 best             = j;
00983                 best_body_sid    = s->body_sid;
00984                 best_index_sid   = s->index_sid;
00985                 best_index_start = s->index_start_position;
00986                 best_index_duration = s->index_duration;
00987             }
00988         }
00989 
00990         
00991         if (best == -1)
00992             break;
00993 
00994         (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
00995         last_body_sid    = best_body_sid;
00996         last_index_sid   = best_index_sid;
00997         last_index_start = best_index_start;
00998     }
00999 
01000     av_free(unsorted_segments);
01001 
01002     return 0;
01003 }
01004 
01008 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
01009 {
01010     int x;
01011     int64_t offset_in = offset;     
01012 
01013     for (x = 0; x < mxf->partitions_count; x++) {
01014         MXFPartition *p = &mxf->partitions[x];
01015 
01016         if (p->body_sid != body_sid)
01017             continue;
01018 
01019         if (offset < p->essence_length || !p->essence_length) {
01020             *offset_out = p->essence_offset + offset;
01021             return 0;
01022         }
01023 
01024         offset -= p->essence_length;
01025     }
01026 
01027     av_log(mxf->fc, AV_LOG_ERROR,
01028            "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
01029            offset_in, body_sid);
01030 
01031     return AVERROR_INVALIDDATA;
01032 }
01033 
01037 static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
01038 {
01039     int x;
01040     int64_t ret = 0;
01041 
01042     for (x = 0; x < mxf->partitions_count; x++) {
01043         MXFPartition *p = &mxf->partitions[x];
01044 
01045         if (p->body_sid != body_sid)
01046             continue;
01047 
01048         if (!p->essence_length)
01049             return 0;
01050 
01051         ret = p->essence_offset + p->essence_length;
01052     }
01053 
01054     return ret;
01055 }
01056 
01057 
01058 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)
01059 {
01060     int i;
01061     int64_t offset_temp = 0;
01062 
01063     for (i = 0; i < index_table->nb_segments; i++) {
01064         MXFIndexTableSegment *s = index_table->segments[i];
01065 
01066         edit_unit = FFMAX(edit_unit, s->index_start_position);  
01067 
01068         if (edit_unit < s->index_start_position + s->index_duration) {
01069             int64_t index = edit_unit - s->index_start_position;
01070 
01071             if (s->edit_unit_byte_count)
01072                 offset_temp += s->edit_unit_byte_count * index;
01073             else if (s->nb_index_entries) {
01074                 if (s->nb_index_entries == 2 * s->index_duration + 1)
01075                     index *= 2;     
01076 
01077                 if (index < 0 || index >= s->nb_index_entries) {
01078                     av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
01079                            index_table->index_sid, s->index_start_position);
01080                     return AVERROR_INVALIDDATA;
01081                 }
01082 
01083                 offset_temp = s->stream_offset_entries[index];
01084             } else {
01085                 av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
01086                        index_table->index_sid, s->index_start_position);
01087                 return AVERROR_INVALIDDATA;
01088             }
01089 
01090             if (edit_unit_out)
01091                 *edit_unit_out = edit_unit;
01092 
01093             return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out);
01094         } else {
01095             
01096             offset_temp += s->edit_unit_byte_count * s->index_duration;
01097         }
01098     }
01099 
01100     if (nag)
01101         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);
01102 
01103     return AVERROR_INVALIDDATA;
01104 }
01105 
01106 static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
01107 {
01108     int i, j, x;
01109     int8_t max_temporal_offset = -128;
01110 
01111     
01112     for (i = 0; i < index_table->nb_segments; i++) {
01113         MXFIndexTableSegment *s = index_table->segments[i];
01114 
01115         if (!s->nb_index_entries) {
01116             index_table->nb_ptses = 0;
01117             return 0;                               
01118         }
01119 
01120         index_table->nb_ptses += s->index_duration;
01121     }
01122 
01123     
01124     if (index_table->nb_ptses <= 0)
01125         return 0;
01126 
01127     if (!(index_table->ptses      = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
01128         !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry)))) {
01129         av_freep(&index_table->ptses);
01130         return AVERROR(ENOMEM);
01131     }
01132 
01133     
01134 
01135     for (x = 0; x < index_table->nb_ptses; x++)
01136         index_table->ptses[x] = AV_NOPTS_VALUE;
01137 
01165     for (i = x = 0; i < index_table->nb_segments; i++) {
01166         MXFIndexTableSegment *s = index_table->segments[i];
01167         int index_delta = 1;
01168         int n = s->nb_index_entries;
01169 
01170         if (s->nb_index_entries == 2 * s->index_duration + 1) {
01171             index_delta = 2;    
01172             
01173             n--;
01174         }
01175 
01176         for (j = 0; j < n; j += index_delta, x++) {
01177             int offset = s->temporal_offset_entries[j] / index_delta;
01178             int index  = x + offset;
01179 
01180             if (x >= index_table->nb_ptses) {
01181                 av_log(mxf->fc, AV_LOG_ERROR,
01182                        "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
01183                        s->nb_index_entries, s->index_duration);
01184                 break;
01185             }
01186 
01187             index_table->fake_index[x].timestamp = x;
01188             index_table->fake_index[x].flags = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
01189 
01190             if (index < 0 || index >= index_table->nb_ptses) {
01191                 av_log(mxf->fc, AV_LOG_ERROR,
01192                        "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
01193                        x, offset, index);
01194                 continue;
01195             }
01196 
01197             index_table->ptses[index] = x;
01198             max_temporal_offset = FFMAX(max_temporal_offset, offset);
01199         }
01200     }
01201 
01202     index_table->first_dts = -max_temporal_offset;
01203 
01204     return 0;
01205 }
01206 
01211 static int mxf_compute_index_tables(MXFContext *mxf)
01212 {
01213     int i, j, k, ret, nb_sorted_segments;
01214     MXFIndexTableSegment **sorted_segments = NULL;
01215 
01216     if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
01217         nb_sorted_segments <= 0) {
01218         av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
01219         return 0;
01220     }
01221 
01222     
01223     for (i = 0; i < nb_sorted_segments; i++) {
01224         if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
01225             mxf->nb_index_tables++;
01226         else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
01227             av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
01228             ret = AVERROR_INVALIDDATA;
01229             goto finish_decoding_index;
01230         }
01231     }
01232 
01233     if (!(mxf->index_tables = av_calloc(mxf->nb_index_tables, sizeof(MXFIndexTable)))) {
01234         av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
01235         ret = AVERROR(ENOMEM);
01236         goto finish_decoding_index;
01237     }
01238 
01239     
01240     for (i = j = 0; i < nb_sorted_segments; i++) {
01241         if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
01242             
01243             j++;
01244         }
01245 
01246         mxf->index_tables[j].nb_segments++;
01247     }
01248 
01249     for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
01250         MXFIndexTable *t = &mxf->index_tables[j];
01251 
01252         if (!(t->segments = av_calloc(t->nb_segments, sizeof(MXFIndexTableSegment*)))) {
01253             av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment pointer array\n");
01254             ret = AVERROR(ENOMEM);
01255             goto finish_decoding_index;
01256         }
01257 
01258         if (sorted_segments[i]->index_start_position)
01259             av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
01260                    sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
01261 
01262         memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
01263         t->index_sid = sorted_segments[i]->index_sid;
01264         t->body_sid = sorted_segments[i]->body_sid;
01265 
01266         if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
01267             goto finish_decoding_index;
01268 
01269         
01270         for (k = 0; k < t->nb_segments; k++) {
01271             if (t->segments[k]->index_duration)
01272                 continue;
01273 
01274             if (t->nb_segments > 1)
01275                 av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
01276                        t->index_sid, k);
01277 
01278             if (mxf->fc->nb_streams <= 0) {
01279                 av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
01280                 break;
01281             }
01282 
01283             
01284 
01285 
01286             t->segments[k]->index_duration = mxf->fc->streams[0]->duration;
01287             break;
01288         }
01289     }
01290 
01291     ret = 0;
01292 finish_decoding_index:
01293     av_free(sorted_segments);
01294     return ret;
01295 }
01296 
01297 static int mxf_is_intra_only(MXFDescriptor *descriptor)
01298 {
01299     return mxf_get_codec_ul(mxf_intra_only_essence_container_uls,
01300                             &descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE ||
01301            mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls,
01302                             &descriptor->essence_codec_ul)->id     != AV_CODEC_ID_NONE;
01303 }
01304 
01305 static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
01306 {
01307     char buf[AV_TIMECODE_STR_SIZE];
01308     av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
01309 
01310     return 0;
01311 }
01312 
01313 static int mxf_parse_structural_metadata(MXFContext *mxf)
01314 {
01315     MXFPackage *material_package = NULL;
01316     MXFPackage *temp_package = NULL;
01317     int i, j, k, ret;
01318 
01319     av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
01320     
01321     for (i = 0; i < mxf->packages_count; i++) {
01322         material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
01323         if (material_package) break;
01324     }
01325     if (!material_package) {
01326         av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
01327         return AVERROR_INVALIDDATA;
01328     }
01329 
01330     for (i = 0; i < material_package->tracks_count; i++) {
01331         MXFPackage *source_package = NULL;
01332         MXFTrack *material_track = NULL;
01333         MXFTrack *source_track = NULL;
01334         MXFTrack *temp_track = NULL;
01335         MXFDescriptor *descriptor = NULL;
01336         MXFStructuralComponent *component = NULL;
01337         MXFTimecodeComponent *mxf_tc = NULL;
01338         UID *essence_container_ul = NULL;
01339         const MXFCodecUL *codec_ul = NULL;
01340         const MXFCodecUL *container_ul = NULL;
01341         const MXFCodecUL *pix_fmt_ul = NULL;
01342         AVStream *st;
01343         AVTimecode tc;
01344         int flags;
01345 
01346         if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
01347             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
01348             continue;
01349         }
01350 
01351         if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
01352             mxf_tc = (MXFTimecodeComponent*)component;
01353             flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
01354             if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
01355                 mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
01356             }
01357         }
01358 
01359         if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
01360             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
01361             continue;
01362         }
01363 
01364         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
01365             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
01366             if (!component)
01367                 continue;
01368 
01369             mxf_tc = (MXFTimecodeComponent*)component;
01370             flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
01371             if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
01372                 mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
01373                 break;
01374             }
01375         }
01376 
01377         
01378         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
01379             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
01380             if (!component)
01381                 continue;
01382 
01383             for (k = 0; k < mxf->packages_count; k++) {
01384                 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
01385                 if (!temp_package)
01386                     continue;
01387                 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
01388                     source_package = temp_package;
01389                     break;
01390                 }
01391             }
01392             if (!source_package) {
01393                 av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
01394                 break;
01395             }
01396             for (k = 0; k < source_package->tracks_count; k++) {
01397                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
01398                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
01399                     ret = AVERROR_INVALIDDATA;
01400                     goto fail_and_free;
01401                 }
01402                 if (temp_track->track_id == component->source_track_id) {
01403                     source_track = temp_track;
01404                     break;
01405                 }
01406             }
01407             if (!source_track) {
01408                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
01409                 break;
01410             }
01411         }
01412         if (!source_track || !component)
01413             continue;
01414 
01415         if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
01416             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
01417             ret = AVERROR_INVALIDDATA;
01418             goto fail_and_free;
01419         }
01420 
01421         
01422 
01423         if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
01424             av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
01425             continue;
01426         }
01427 
01428         st = avformat_new_stream(mxf->fc, NULL);
01429         if (!st) {
01430             av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
01431             ret = AVERROR(ENOMEM);
01432             goto fail_and_free;
01433         }
01434         st->id = source_track->track_id;
01435         st->priv_data = source_track;
01436         st->duration = component->duration;
01437         if (st->duration == -1)
01438             st->duration = AV_NOPTS_VALUE;
01439         st->start_time = component->start_position;
01440         avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
01441 
01442         PRINT_KEY(mxf->fc, "data definition   ul", source_track->sequence->data_definition_ul);
01443         codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
01444         st->codec->codec_type = codec_ul->id;
01445 
01446         source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
01447         if (source_package->descriptor) {
01448             if (source_package->descriptor->type == MultipleDescriptor) {
01449                 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
01450                     MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
01451 
01452                     if (!sub_descriptor) {
01453                         av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
01454                         continue;
01455                     }
01456                     if (sub_descriptor->linked_track_id == source_track->track_id) {
01457                         descriptor = sub_descriptor;
01458                         break;
01459                     }
01460                 }
01461             } else if (source_package->descriptor->type == Descriptor)
01462                 descriptor = source_package->descriptor;
01463         }
01464         if (!descriptor) {
01465             av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
01466             continue;
01467         }
01468         PRINT_KEY(mxf->fc, "essence codec     ul", descriptor->essence_codec_ul);
01469         PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
01470         essence_container_ul = &descriptor->essence_container_ul;
01471         
01472 
01473         if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
01474             av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
01475             for (k = 0; k < mxf->metadata_sets_count; k++) {
01476                 MXFMetadataSet *metadata = mxf->metadata_sets[k];
01477                 if (metadata->type == CryptoContext) {
01478                     essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
01479                     break;
01480                 }
01481             }
01482         }
01483 
01484         
01485         codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
01486         st->codec->codec_id = codec_ul->id;
01487         if (descriptor->extradata) {
01488             st->codec->extradata = descriptor->extradata;
01489             st->codec->extradata_size = descriptor->extradata_size;
01490         }
01491         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01492             source_track->intra_only = mxf_is_intra_only(descriptor);
01493             container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
01494             if (st->codec->codec_id == AV_CODEC_ID_NONE)
01495                 st->codec->codec_id = container_ul->id;
01496             st->codec->width = descriptor->width;
01497             st->codec->height = descriptor->height; 
01498             switch (descriptor->frame_layout) {
01499                 case SegmentedFrame:
01500                     
01501                     av_log(mxf->fc, AV_LOG_INFO, "SegmentedFrame layout isn't currently supported\n");
01502                     break;
01503                 case FullFrame:
01504                     break;
01505                 case OneField:
01506                     
01507                     av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
01508                     break; 
01509 
01510 
01511                 case MixedFields:
01512                     break;
01513                 case SeparateFields:
01514                     st->codec->height *= 2; 
01515                     break;
01516                 default:
01517                     av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
01518             }
01519             if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
01520                 st->codec->pix_fmt = descriptor->pix_fmt;
01521                 if (st->codec->pix_fmt == PIX_FMT_NONE) {
01522                     pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls,
01523                                                   &descriptor->essence_codec_ul);
01524                     st->codec->pix_fmt = pix_fmt_ul->id;
01525                     if (st->codec->pix_fmt == PIX_FMT_NONE) {
01526                         
01527 
01528                         if (descriptor->horiz_subsampling == 2 &&
01529                             descriptor->vert_subsampling == 1 &&
01530                             descriptor->component_depth == 8) {
01531                             st->codec->pix_fmt = PIX_FMT_UYVY422;
01532                         }
01533                     }
01534                 }
01535             }
01536             st->need_parsing = AVSTREAM_PARSE_HEADERS;
01537         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
01538             container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
01539             
01540             if (st->codec->codec_id == AV_CODEC_ID_NONE || (st->codec->codec_id == AV_CODEC_ID_PCM_ALAW && container_ul->id != AV_CODEC_ID_NONE))
01541                 st->codec->codec_id = container_ul->id;
01542             st->codec->channels = descriptor->channels;
01543             st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
01544 
01545             if (descriptor->sample_rate.den > 0)
01546                 st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
01547 
01548             
01549             if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
01550                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
01551                     st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
01552                 else if (descriptor->bits_per_sample == 32)
01553                     st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
01554             } else if (st->codec->codec_id == AV_CODEC_ID_PCM_S16BE) {
01555                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
01556                     st->codec->codec_id = AV_CODEC_ID_PCM_S24BE;
01557                 else if (descriptor->bits_per_sample == 32)
01558                     st->codec->codec_id = AV_CODEC_ID_PCM_S32BE;
01559             } else if (st->codec->codec_id == AV_CODEC_ID_MP2) {
01560                 st->need_parsing = AVSTREAM_PARSE_FULL;
01561             }
01562         }
01563         if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
01564             
01565             st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
01566         }
01567     }
01568 
01569     ret = 0;
01570 fail_and_free:
01571     return ret;
01572 }
01573 
01574 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
01575     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
01576     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
01577     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
01578     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
01579     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
01580     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
01581     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
01582     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
01583     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
01584     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
01585     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
01586     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
01587     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
01588     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
01589     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
01590     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
01591     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
01592     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, 
01593     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, 
01594     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, 
01595     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, 
01596     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, 
01597     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, 
01598     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, 
01599     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, 
01600     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
01601     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
01602     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
01603     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
01604 };
01605 
01606 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
01607 {
01608     AVIOContext *pb = mxf->fc->pb;
01609     MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
01610     uint64_t klv_end = avio_tell(pb) + klv->length;
01611 
01612     if (!ctx)
01613         return AVERROR(ENOMEM);
01614     while (avio_tell(pb) + 4 < klv_end && !url_feof(pb)) {
01615         int ret;
01616         int tag = avio_rb16(pb);
01617         int size = avio_rb16(pb); 
01618         uint64_t next = avio_tell(pb) + size;
01619         UID uid = {0};
01620 
01621         av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
01622         if (!size) { 
01623             av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
01624             continue;
01625         }
01626         if (tag > 0x7FFF) { 
01627             int i;
01628             for (i = 0; i < mxf->local_tags_count; i++) {
01629                 int local_tag = AV_RB16(mxf->local_tags+i*18);
01630                 if (local_tag == tag) {
01631                     memcpy(uid, mxf->local_tags+i*18+2, 16);
01632                     av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
01633                     PRINT_KEY(mxf->fc, "uid", uid);
01634                 }
01635             }
01636         }
01637         if (ctx_size && tag == 0x3C0A)
01638             avio_read(pb, ctx->uid, 16);
01639         else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0)
01640             return ret;
01641 
01642         
01643 
01644         if (avio_tell(pb) > klv_end) {
01645             av_log(mxf->fc, AV_LOG_ERROR,
01646                    "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
01647                    tag, klv->offset);
01648             return AVERROR_INVALIDDATA;
01649         } else if (avio_tell(pb) <= next)   
01650             avio_seek(pb, next, SEEK_SET);
01651     }
01652     if (ctx_size) ctx->type = type;
01653     return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
01654 }
01655 
01660 static int mxf_seek_to_previous_partition(MXFContext *mxf)
01661 {
01662     AVIOContext *pb = mxf->fc->pb;
01663 
01664     if (!mxf->current_partition ||
01665         mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
01666         return 0;   
01667 
01668     
01669     avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
01670     mxf->current_partition = NULL;
01671 
01672     av_dlog(mxf->fc, "seeking to previous partition\n");
01673 
01674     return 1;
01675 }
01676 
01681 static int mxf_parse_handle_essence(MXFContext *mxf)
01682 {
01683     AVIOContext *pb = mxf->fc->pb;
01684     int64_t ret;
01685 
01686     if (mxf->parsing_backward) {
01687         return mxf_seek_to_previous_partition(mxf);
01688     } else {
01689         if (!mxf->footer_partition) {
01690             av_dlog(mxf->fc, "no footer\n");
01691             return 0;
01692         }
01693 
01694         av_dlog(mxf->fc, "seeking to footer\n");
01695 
01696         
01697         mxf->last_forward_tell = avio_tell(pb);
01698 
01699         if (!pb->seekable) {
01700             av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
01701             return -1;
01702         }
01703 
01704         
01705         if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
01706             av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
01707                    mxf->run_in + mxf->footer_partition, ret);
01708             return ret;
01709         }
01710 
01711         mxf->current_partition = NULL;
01712         mxf->parsing_backward = 1;
01713     }
01714 
01715     return 1;
01716 }
01717 
01722 static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
01723 {
01724     return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
01725 }
01726 
01730 static void mxf_compute_essence_containers(MXFContext *mxf)
01731 {
01732     int x;
01733 
01734     
01735     if (mxf->op == OPAtom)
01736         return;
01737 
01738     for (x = 0; x < mxf->partitions_count; x++) {
01739         MXFPartition *p = &mxf->partitions[x];
01740 
01741         if (!p->body_sid)
01742             continue;       
01743 
01744         if (x >= mxf->partitions_count - 1)
01745             break;          
01746 
01747         
01748         p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
01749 
01750         if (p->essence_length < 0) {
01751             
01752             p->essence_length = 0;
01753             av_log(mxf->fc, AV_LOG_ERROR,
01754                    "partition %i: bad ThisPartition = %"PRIX64"\n",
01755                    x+1, mxf->partitions[x+1].this_partition);
01756         }
01757     }
01758 }
01759 
01760 static int64_t round_to_kag(int64_t position, int kag_size)
01761 {
01762     
01763     
01764     int64_t ret = (position / kag_size) * kag_size;
01765     return ret == position ? ret : ret + kag_size;
01766 }
01767 
01768 static int is_pcm(enum AVCodecID codec_id)
01769 {
01770     
01771     return codec_id >= AV_CODEC_ID_PCM_S16LE && codec_id < AV_CODEC_ID_PCM_S24DAUD;
01772 }
01773 
01779 static void mxf_handle_small_eubc(AVFormatContext *s)
01780 {
01781     MXFContext *mxf = s->priv_data;
01782 
01783     
01784 
01785     if (mxf->op != OPAtom)
01786         return;
01787 
01788     
01789     if (s->nb_streams != 1                                     ||
01790         s->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
01791         !is_pcm(s->streams[0]->codec->codec_id)                ||
01792         mxf->nb_index_tables != 1                              ||
01793         mxf->index_tables[0].nb_segments != 1                  ||
01794         mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32)
01795         return;
01796 
01797     
01798     
01799 
01800 
01801     mxf->edit_units_per_packet = 1920;
01802 }
01803 
01804 static int mxf_read_header(AVFormatContext *s)
01805 {
01806     MXFContext *mxf = s->priv_data;
01807     KLVPacket klv;
01808     int64_t essence_offset = 0;
01809     int ret;
01810 
01811     mxf->last_forward_tell = INT64_MAX;
01812     mxf->edit_units_per_packet = 1;
01813 
01814     if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
01815         av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
01816         return AVERROR_INVALIDDATA;
01817     }
01818     avio_seek(s->pb, -14, SEEK_CUR);
01819     mxf->fc = s;
01820     mxf->run_in = avio_tell(s->pb);
01821 
01822     while (!url_feof(s->pb)) {
01823         const MXFMetadataReadTableEntry *metadata;
01824 
01825         if (klv_read_packet(&klv, s->pb) < 0) {
01826             
01827             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
01828                 break;
01829             else
01830                 continue;
01831         }
01832 
01833         PRINT_KEY(s, "read header", klv.key);
01834         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
01835         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
01836             IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
01837             IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
01838             IS_KLV_KEY(klv.key, mxf_system_item_key)) {
01839 
01840             if (!mxf->current_partition) {
01841                 av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
01842                 return AVERROR_INVALIDDATA;
01843             }
01844 
01845             if (!mxf->current_partition->essence_offset) {
01846                 
01847 
01848 
01849 
01850 
01851                 int64_t op1a_essence_offset =
01852                     round_to_kag(mxf->current_partition->this_partition +
01853                                  mxf->current_partition->pack_length,       mxf->current_partition->kag_size) +
01854                     round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
01855                     round_to_kag(mxf->current_partition->index_byte_count,  mxf->current_partition->kag_size);
01856 
01857                 if (mxf->op == OPAtom) {
01858                     
01859 
01860 
01861                     mxf->current_partition->essence_offset = avio_tell(s->pb);
01862                     mxf->current_partition->essence_length = klv.length;
01863                 } else {
01864                     
01865                     mxf->current_partition->essence_offset = op1a_essence_offset;
01866                 }
01867             }
01868 
01869             if (!essence_offset)
01870                 essence_offset = klv.offset;
01871 
01872             
01873             if (mxf_parse_handle_essence(mxf) <= 0)
01874                 break;
01875             continue;
01876         } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
01877                    klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
01878             
01879             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
01880                 break;
01881             else if (mxf->parsing_backward)
01882                 continue;
01883             
01884         }
01885 
01886         for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
01887             if (IS_KLV_KEY(klv.key, metadata->key)) {
01888                 int res;
01889                 if (klv.key[5] == 0x53) {
01890                     res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
01891                 } else {
01892                     uint64_t next = avio_tell(s->pb) + klv.length;
01893                     res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
01894 
01895                     
01896                     if (avio_tell(s->pb) > next) {
01897                         av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
01898                                klv.offset);
01899                         return AVERROR_INVALIDDATA;
01900                     }
01901 
01902                     avio_seek(s->pb, next, SEEK_SET);
01903                 }
01904                 if (res < 0) {
01905                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
01906                     return res;
01907                 }
01908                 break;
01909             }
01910         }
01911         if (!metadata->read)
01912             avio_skip(s->pb, klv.length);
01913     }
01914     
01915     if (!essence_offset)  {
01916         av_log(s, AV_LOG_ERROR, "no essence\n");
01917         return AVERROR_INVALIDDATA;
01918     }
01919     avio_seek(s->pb, essence_offset, SEEK_SET);
01920 
01921     mxf_compute_essence_containers(mxf);
01922 
01923     
01924 
01925     if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
01926         return ret;
01927 
01928     if ((ret = mxf_compute_index_tables(mxf)) < 0)
01929         return ret;
01930 
01931     if (mxf->nb_index_tables > 1) {
01932         
01933         av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
01934                mxf->nb_index_tables, mxf->index_tables[0].index_sid);
01935     } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
01936         av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
01937         return AVERROR_INVALIDDATA;
01938     }
01939 
01940     mxf_handle_small_eubc(s);
01941 
01942     return 0;
01943 }
01944 
01949 static int64_t mxf_set_current_edit_unit(MXFContext *mxf, int64_t current_offset)
01950 {
01951     int64_t last_ofs = -1, next_ofs = -1;
01952     MXFIndexTable *t = &mxf->index_tables[0];
01953 
01954     
01955 
01956     if (mxf->nb_index_tables <= 0)
01957         return -1;
01958 
01959     
01960     while (mxf->current_edit_unit >= 0) {
01961         if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0)
01962             return -1;
01963 
01964         if (next_ofs <= last_ofs) {
01965             
01966 
01967             av_log(mxf->fc, AV_LOG_ERROR,
01968                    "next_ofs didn't change. not deriving packet timestamps\n");
01969             return -1;
01970         }
01971 
01972         if (next_ofs > current_offset)
01973             break;
01974 
01975         last_ofs = next_ofs;
01976         mxf->current_edit_unit++;
01977     }
01978 
01979     
01980     if (mxf->current_edit_unit < 0)
01981         return -1;
01982 
01983     return next_ofs;
01984 }
01985 
01986 static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
01987 {
01988     KLVPacket klv;
01989     MXFContext *mxf = s->priv_data;
01990 
01991     while (!url_feof(s->pb)) {
01992         int ret;
01993         if (klv_read_packet(&klv, s->pb) < 0)
01994             return -1;
01995         PRINT_KEY(s, "read packet", klv.key);
01996         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
01997         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
01998             ret = mxf_decrypt_triplet(s, pkt, &klv);
01999             if (ret < 0) {
02000                 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
02001                 return AVERROR_INVALIDDATA;
02002             }
02003             return 0;
02004         }
02005         if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
02006             IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
02007             int index = mxf_get_stream_index(s, &klv);
02008             int64_t next_ofs, next_klv;
02009             AVStream *st;
02010             MXFTrack *track;
02011 
02012             if (index < 0) {
02013                 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
02014                 goto skip;
02015             }
02016 
02017             st = s->streams[index];
02018             track = st->priv_data;
02019 
02020             if (s->streams[index]->discard == AVDISCARD_ALL)
02021                 goto skip;
02022 
02023             next_klv = avio_tell(s->pb) + klv.length;
02024             next_ofs = mxf_set_current_edit_unit(mxf, klv.offset);
02025 
02026             if (next_ofs >= 0 && next_klv > next_ofs) {
02027                 
02028 
02029                 av_log_ask_for_sample(s,
02030                     "KLV for edit unit %i extends into next edit unit - OPAtom misinterpreted as OP1a?\n",
02031                     mxf->current_edit_unit);
02032                 klv.length = next_ofs - avio_tell(s->pb);
02033             }
02034 
02035             
02036             if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
02037                 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
02038                     av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
02039                     return AVERROR_INVALIDDATA;
02040                 }
02041             } else {
02042                 ret = av_get_packet(s->pb, pkt, klv.length);
02043                 if (ret < 0)
02044                     return ret;
02045             }
02046             pkt->stream_index = index;
02047             pkt->pos = klv.offset;
02048 
02049             if (s->streams[index]->codec->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
02050                 
02051                 MXFIndexTable *t = &mxf->index_tables[0];
02052 
02053                 if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) {
02054                     pkt->dts = mxf->current_edit_unit + t->first_dts;
02055                     pkt->pts = t->ptses[mxf->current_edit_unit];
02056                 } else if (track->intra_only) {
02057                     
02058 
02059                     pkt->pts = mxf->current_edit_unit;
02060                 }
02061             }
02062 
02063             
02064             avio_seek(s->pb, next_klv, SEEK_SET);
02065 
02066             return 0;
02067         } else
02068         skip:
02069             avio_skip(s->pb, klv.length);
02070     }
02071     return AVERROR_EOF;
02072 }
02073 
02074 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
02075 {
02076     MXFContext *mxf = s->priv_data;
02077     int ret, size;
02078     int64_t ret64, pos, next_pos;
02079     AVStream *st;
02080     MXFIndexTable *t;
02081     int edit_units;
02082 
02083     if (mxf->op != OPAtom)
02084         return mxf_read_packet_old(s, pkt);
02085 
02086     
02087     
02088     st = s->streams[0];
02089     t = &mxf->index_tables[0];
02090 
02091     if (mxf->current_edit_unit >= st->duration)
02092         return AVERROR_EOF;
02093 
02094     edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit);
02095 
02096     if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0)
02097         return ret;
02098 
02099     
02100 
02101     if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 &&
02102         (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
02103         av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
02104         return AVERROR_INVALIDDATA;
02105     }
02106 
02107     if ((size = next_pos - pos) <= 0) {
02108         av_log(s, AV_LOG_ERROR, "bad size: %i\n", size);
02109         return AVERROR_INVALIDDATA;
02110     }
02111 
02112     if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0)
02113         return ret64;
02114 
02115     if ((size = av_get_packet(s->pb, pkt, size)) < 0)
02116         return size;
02117 
02118     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
02119         mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
02120         pkt->dts = mxf->current_edit_unit + t->first_dts;
02121         pkt->pts = t->ptses[mxf->current_edit_unit];
02122     }
02123 
02124     pkt->stream_index = 0;
02125     mxf->current_edit_unit += edit_units;
02126 
02127     return 0;
02128 }
02129 
02130 static int mxf_read_close(AVFormatContext *s)
02131 {
02132     MXFContext *mxf = s->priv_data;
02133     MXFIndexTableSegment *seg;
02134     int i;
02135 
02136     av_freep(&mxf->packages_refs);
02137 
02138     for (i = 0; i < s->nb_streams; i++)
02139         s->streams[i]->priv_data = NULL;
02140 
02141     for (i = 0; i < mxf->metadata_sets_count; i++) {
02142         switch (mxf->metadata_sets[i]->type) {
02143         case MultipleDescriptor:
02144             av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
02145             break;
02146         case Sequence:
02147             av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
02148             break;
02149         case SourcePackage:
02150         case MaterialPackage:
02151             av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
02152             break;
02153         case IndexTableSegment:
02154             seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
02155             av_freep(&seg->temporal_offset_entries);
02156             av_freep(&seg->flag_entries);
02157             av_freep(&seg->stream_offset_entries);
02158             break;
02159         default:
02160             break;
02161         }
02162         av_freep(&mxf->metadata_sets[i]);
02163     }
02164     av_freep(&mxf->partitions);
02165     av_freep(&mxf->metadata_sets);
02166     av_freep(&mxf->aesc);
02167     av_freep(&mxf->local_tags);
02168 
02169     for (i = 0; i < mxf->nb_index_tables; i++) {
02170         av_freep(&mxf->index_tables[i].segments);
02171         av_freep(&mxf->index_tables[i].ptses);
02172         av_freep(&mxf->index_tables[i].fake_index);
02173     }
02174     av_freep(&mxf->index_tables);
02175 
02176     return 0;
02177 }
02178 
02179 static int mxf_probe(AVProbeData *p) {
02180     uint8_t *bufp = p->buf;
02181     uint8_t *end = p->buf + p->buf_size;
02182 
02183     if (p->buf_size < sizeof(mxf_header_partition_pack_key))
02184         return 0;
02185 
02186     
02187     end -= sizeof(mxf_header_partition_pack_key);
02188     for (; bufp < end; bufp++) {
02189         if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
02190             return AVPROBE_SCORE_MAX;
02191     }
02192     return 0;
02193 }
02194 
02195 
02196 
02197 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
02198 {
02199     AVStream *st = s->streams[stream_index];
02200     int64_t seconds;
02201     MXFContext* mxf = s->priv_data;
02202     int64_t seekpos;
02203     int ret;
02204     MXFIndexTable *t;
02205 
02206     if (mxf->nb_index_tables <= 0) {
02207     if (!s->bit_rate)
02208         return AVERROR_INVALIDDATA;
02209     if (sample_time < 0)
02210         sample_time = 0;
02211     seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
02212 
02213     if ((ret = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET)) < 0)
02214         return ret;
02215     ff_update_cur_dts(s, st, sample_time);
02216     } else {
02217         t = &mxf->index_tables[0];
02218 
02219         
02220 
02221         sample_time = FFMAX(sample_time, 0);
02222 
02223         if (t->fake_index) {
02224             
02225             if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
02226                 return sample_time;
02227         } else {
02228             
02229 
02230             sample_time = FFMIN(sample_time, st->duration - 1);
02231         }
02232 
02233         if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) << 0)
02234             return ret;
02235 
02236         ff_update_cur_dts(s, st, sample_time);
02237         mxf->current_edit_unit = sample_time;
02238         avio_seek(s->pb, seekpos, SEEK_SET);
02239     }
02240     return 0;
02241 }
02242 
02243 AVInputFormat ff_mxf_demuxer = {
02244     .name           = "mxf",
02245     .long_name      = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
02246     .priv_data_size = sizeof(MXFContext),
02247     .read_probe     = mxf_probe,
02248     .read_header    = mxf_read_header,
02249     .read_packet    = mxf_read_packet,
02250     .read_close     = mxf_read_close,
02251     .read_seek      = mxf_read_seek,
02252 };