FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
mxfdec.c
Go to the documentation of this file.
1 /*
2  * MXF demuxer.
3  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /*
23  * References
24  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
25  * SMPTE 377M MXF File Format Specifications
26  * SMPTE 378M Operational Pattern 1a
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
30  * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
31  *
32  * Principle
33  * Search for Track numbers which will identify essence element KLV packets.
34  * Search for SourcePackage which define tracks which contains Track numbers.
35  * Material Package contains tracks with reference to SourcePackage tracks.
36  * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
37  * Assign Descriptors to correct Tracks.
38  *
39  * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
40  * Metadata parsing resolves Strong References to objects.
41  *
42  * Simple demuxer, only OP1A supported and some files might not work at all.
43  * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
44  */
45 
46 #include <inttypes.h>
47 
48 #include "libavutil/aes.h"
49 #include "libavutil/avassert.h"
50 #include "libavutil/mathematics.h"
51 #include "libavcodec/bytestream.h"
52 #include "libavutil/intreadwrite.h"
53 #include "libavutil/timecode.h"
54 #include "avformat.h"
55 #include "internal.h"
56 #include "mxf.h"
57 
58 typedef enum {
63 
64 typedef enum {
65  OP1a = 1,
75  OPSONYOpt, /* FATE sample, violates the spec in places */
76 } MXFOP;
77 
78 typedef struct {
79  int closed;
80  int complete;
83  int index_sid;
84  int body_sid;
85  int64_t this_partition;
86  int64_t essence_offset; ///< absolute offset of essence
87  int64_t essence_length;
92 } MXFPartition;
93 
94 typedef struct {
99 
100 typedef struct {
105  int64_t duration;
106  int64_t start_position;
109 
110 typedef struct {
116  int64_t duration;
118 } MXFSequence;
119 
120 typedef struct {
125  struct AVRational rate;
128 
129 typedef struct {
132  MXFSequence *sequence; /* mandatory, and only one */
134  int track_id;
135  uint8_t track_number[4];
138  uint64_t sample_count;
139  int64_t original_duration; /* st->duration in SampleRate/EditRate units */
140 } MXFTrack;
141 
142 typedef struct {
149  int width;
150  int height; /* Field height, not frame height */
151  int frame_layout; /* See MXFFrameLayout enum */
152 #define MXF_TFF 1
153 #define MXF_BFF 2
155  int channels;
157  unsigned int component_depth;
158  unsigned int horiz_subsampling;
159  unsigned int vert_subsampling;
166 } MXFDescriptor;
167 
168 typedef struct {
173  int body_sid;
176  uint64_t index_duration;
182 
183 typedef struct {
189  MXFDescriptor *descriptor; /* only one */
191  char *name;
192 } MXFPackage;
193 
194 typedef struct {
198 
199 /* decoded index table */
200 typedef struct {
202  int body_sid;
203  int nb_ptses; /* number of PTSes or total duration of index */
204  int64_t first_dts; /* DTS = EditUnit + first_dts */
205  int64_t *ptses; /* maps EditUnit -> PTS */
207  MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
208  AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
209 } MXFIndexTable;
210 
211 typedef struct {
220  struct AVAES *aesc;
223  uint64_t last_partition;
227  int run_in;
235  int edit_units_per_packet; ///< how many edit units to read at a time (PCM, OPAtom)
236 } MXFContext;
237 
241 };
242 
243 /* NOTE: klv_offset is not set (-1) for local keys */
244 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
245 
246 typedef struct {
247  const UID key;
249  int ctx_size;
252 
253 static int mxf_read_close(AVFormatContext *s);
254 
255 /* partial keys to match */
256 static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
257 static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
258 static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
259 static const uint8_t mxf_system_item_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 };
260 static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
261 /* complete keys to match */
262 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 };
263 static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
264 static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
265 static const uint8_t mxf_random_index_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
266 static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
267 
268 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
269 
271 {
272  uint64_t size = avio_r8(pb);
273  if (size & 0x80) { /* long form */
274  int bytes_num = size & 0x7f;
275  /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
276  if (bytes_num > 8)
277  return AVERROR_INVALIDDATA;
278  size = 0;
279  while (bytes_num--)
280  size = size << 8 | avio_r8(pb);
281  }
282  return size;
283 }
284 
285 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
286 {
287  int i, b;
288  for (i = 0; i < size && !avio_feof(pb); i++) {
289  b = avio_r8(pb);
290  if (b == key[0])
291  i = 0;
292  else if (b != key[i])
293  i = -1;
294  }
295  return i == size;
296 }
297 
298 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
299 {
300  if (!mxf_read_sync(pb, mxf_klv_key, 4))
301  return AVERROR_INVALIDDATA;
302  klv->offset = avio_tell(pb) - 4;
303  memcpy(klv->key, mxf_klv_key, 4);
304  avio_read(pb, klv->key + 4, 12);
305  klv->length = klv_decode_ber_length(pb);
306  return klv->length == -1 ? -1 : 0;
307 }
308 
310 {
311  int i;
312 
313  for (i = 0; i < s->nb_streams; i++) {
314  MXFTrack *track = s->streams[i]->priv_data;
315  /* SMPTE 379M 7.3 */
316  if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
317  return i;
318  }
319  /* return 0 if only one stream, for OP Atom files with 0 as track number */
320  return s->nb_streams == 1 ? 0 : -1;
321 }
322 
323 /* XXX: use AVBitStreamFilter */
325 {
326  const uint8_t *buf_ptr, *end_ptr;
327  uint8_t *data_ptr;
328  int i;
329 
330  if (length > 61444) /* worst case PAL 1920 samples 8 channels */
331  return AVERROR_INVALIDDATA;
332  length = av_get_packet(pb, pkt, length);
333  if (length < 0)
334  return length;
335  data_ptr = pkt->data;
336  end_ptr = pkt->data + length;
337  buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
338  for (; end_ptr - buf_ptr >= st->codec->channels * 4; ) {
339  for (i = 0; i < st->codec->channels; i++) {
340  uint32_t sample = bytestream_get_le32(&buf_ptr);
341  if (st->codec->bits_per_coded_sample == 24)
342  bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
343  else
344  bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
345  }
346  buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
347  }
348  av_shrink_packet(pkt, data_ptr - pkt->data);
349  return 0;
350 }
351 
353 {
354  static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
355  MXFContext *mxf = s->priv_data;
356  AVIOContext *pb = s->pb;
357  int64_t end = avio_tell(pb) + klv->length;
358  int64_t size;
359  uint64_t orig_size;
360  uint64_t plaintext_size;
361  uint8_t ivec[16];
362  uint8_t tmpbuf[16];
363  int index;
364 
365  if (!mxf->aesc && s->key && s->keylen == 16) {
366  mxf->aesc = av_aes_alloc();
367  if (!mxf->aesc)
368  return AVERROR(ENOMEM);
369  av_aes_init(mxf->aesc, s->key, 128, 1);
370  }
371  // crypto context
373  // plaintext offset
375  plaintext_size = avio_rb64(pb);
376  // source klv key
378  avio_read(pb, klv->key, 16);
380  return AVERROR_INVALIDDATA;
381  index = mxf_get_stream_index(s, klv);
382  if (index < 0)
383  return AVERROR_INVALIDDATA;
384  // source size
386  orig_size = avio_rb64(pb);
387  if (orig_size < plaintext_size)
388  return AVERROR_INVALIDDATA;
389  // enc. code
390  size = klv_decode_ber_length(pb);
391  if (size < 32 || size - 32 < orig_size)
392  return AVERROR_INVALIDDATA;
393  avio_read(pb, ivec, 16);
394  avio_read(pb, tmpbuf, 16);
395  if (mxf->aesc)
396  av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
397  if (memcmp(tmpbuf, checkv, 16))
398  av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
399  size -= 32;
400  size = av_get_packet(pb, pkt, size);
401  if (size < 0)
402  return size;
403  else if (size < plaintext_size)
404  return AVERROR_INVALIDDATA;
405  size -= plaintext_size;
406  if (mxf->aesc)
407  av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
408  &pkt->data[plaintext_size], size >> 4, ivec, 1);
409  av_shrink_packet(pkt, orig_size);
410  pkt->stream_index = index;
411  avio_skip(pb, end - avio_tell(pb));
412  return 0;
413 }
414 
415 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
416 {
417  MXFContext *mxf = arg;
418  int item_num = avio_rb32(pb);
419  int item_len = avio_rb32(pb);
420 
421  if (item_len != 18) {
422  avpriv_request_sample(pb, "Primer pack item length %d", item_len);
423  return AVERROR_PATCHWELCOME;
424  }
425  if (item_num > 65536) {
426  av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num);
427  return AVERROR_INVALIDDATA;
428  }
429  if (mxf->local_tags)
430  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n");
431  av_free(mxf->local_tags);
432  mxf->local_tags_count = 0;
433  mxf->local_tags = av_calloc(item_num, item_len);
434  if (!mxf->local_tags)
435  return AVERROR(ENOMEM);
436  mxf->local_tags_count = item_num;
437  avio_read(pb, mxf->local_tags, item_num*item_len);
438  return 0;
439 }
440 
441 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
442 {
443  MXFContext *mxf = arg;
444  MXFPartition *partition, *tmp_part;
445  UID op;
446  uint64_t footer_partition;
447  uint32_t nb_essence_containers;
448 
449  tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions));
450  if (!tmp_part)
451  return AVERROR(ENOMEM);
452  mxf->partitions = tmp_part;
453 
454  if (mxf->parsing_backward) {
455  /* insert the new partition pack in the middle
456  * this makes the entries in mxf->partitions sorted by offset */
457  memmove(&mxf->partitions[mxf->last_forward_partition+1],
459  (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
460  partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
461  } else {
462  mxf->last_forward_partition++;
463  partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
464  }
465 
466  memset(partition, 0, sizeof(*partition));
467  mxf->partitions_count++;
468  partition->pack_length = avio_tell(pb) - klv_offset + size;
469 
470  switch(uid[13]) {
471  case 2:
472  partition->type = Header;
473  break;
474  case 3:
475  partition->type = BodyPartition;
476  break;
477  case 4:
478  partition->type = Footer;
479  break;
480  default:
481  av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
482  return AVERROR_INVALIDDATA;
483  }
484 
485  /* consider both footers to be closed (there is only Footer and CompleteFooter) */
486  partition->closed = partition->type == Footer || !(uid[14] & 1);
487  partition->complete = uid[14] > 2;
488  avio_skip(pb, 4);
489  partition->kag_size = avio_rb32(pb);
490  partition->this_partition = avio_rb64(pb);
491  partition->previous_partition = avio_rb64(pb);
492  footer_partition = avio_rb64(pb);
493  partition->header_byte_count = avio_rb64(pb);
494  partition->index_byte_count = avio_rb64(pb);
495  partition->index_sid = avio_rb32(pb);
496  avio_skip(pb, 8);
497  partition->body_sid = avio_rb32(pb);
498  if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) {
499  av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n");
500  return AVERROR_INVALIDDATA;
501  }
502  nb_essence_containers = avio_rb32(pb);
503 
504  if (partition->this_partition &&
505  partition->previous_partition == partition->this_partition) {
506  av_log(mxf->fc, AV_LOG_ERROR,
507  "PreviousPartition equal to ThisPartition %"PRIx64"\n",
508  partition->previous_partition);
509  /* override with the actual previous partition offset */
510  if (!mxf->parsing_backward && mxf->last_forward_partition > 1) {
511  MXFPartition *prev =
512  mxf->partitions + mxf->last_forward_partition - 2;
513  partition->previous_partition = prev->this_partition;
514  }
515  /* if no previous body partition are found point to the header
516  * partition */
517  if (partition->previous_partition == partition->this_partition)
518  partition->previous_partition = 0;
519  av_log(mxf->fc, AV_LOG_ERROR,
520  "Overriding PreviousPartition with %"PRIx64"\n",
521  partition->previous_partition);
522  }
523 
524  /* some files don'thave FooterPartition set in every partition */
525  if (footer_partition) {
526  if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
527  av_log(mxf->fc, AV_LOG_ERROR,
528  "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
529  mxf->footer_partition, footer_partition);
530  } else {
531  mxf->footer_partition = footer_partition;
532  }
533  }
534 
535  av_dlog(mxf->fc,
536  "PartitionPack: ThisPartition = 0x%"PRIX64
537  ", PreviousPartition = 0x%"PRIX64", "
538  "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
539  partition->this_partition,
540  partition->previous_partition, footer_partition,
541  partition->index_sid, partition->body_sid);
542 
543  /* sanity check PreviousPartition if set */
544  if (partition->previous_partition &&
545  mxf->run_in + partition->previous_partition >= klv_offset) {
546  av_log(mxf->fc, AV_LOG_ERROR,
547  "PreviousPartition points to this partition or forward\n");
548  return AVERROR_INVALIDDATA;
549  }
550 
551  if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
552  else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
553  else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
554  else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
555  else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
556  else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
557  else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
558  else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
559  else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
560  else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
561  else if (op[12] == 0x10) {
562  /* SMPTE 390m: "There shall be exactly one essence container"
563  * The following block deals with files that violate this, namely:
564  * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
565  * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
566  if (nb_essence_containers != 1) {
567  MXFOP op = nb_essence_containers ? OP1a : OPAtom;
568 
569  /* only nag once */
570  if (!mxf->op)
571  av_log(mxf->fc, AV_LOG_WARNING,
572  "\"OPAtom\" with %"PRIu32" ECs - assuming %s\n",
573  nb_essence_containers,
574  op == OP1a ? "OP1a" : "OPAtom");
575 
576  mxf->op = op;
577  } else
578  mxf->op = OPAtom;
579  } else {
580  av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
581  mxf->op = OP1a;
582  }
583 
584  if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
585  av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ",
586  partition->kag_size);
587 
588  if (mxf->op == OPSONYOpt)
589  partition->kag_size = 512;
590  else
591  partition->kag_size = 1;
592 
593  av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size);
594  }
595 
596  return 0;
597 }
598 
599 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
600 {
601  MXFMetadataSet **tmp;
602 
603  tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets));
604  if (!tmp)
605  return AVERROR(ENOMEM);
606  mxf->metadata_sets = tmp;
607  mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
608  mxf->metadata_sets_count++;
609  return 0;
610 }
611 
612 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
613 {
614  MXFCryptoContext *cryptocontext = arg;
615  if (size != 16)
616  return AVERROR_INVALIDDATA;
618  avio_read(pb, cryptocontext->source_container_ul, 16);
619  return 0;
620 }
621 
622 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
623 {
624  MXFContext *mxf = arg;
625  switch (tag) {
626  case 0x1901:
627  if (mxf->packages_refs)
628  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n");
629  av_free(mxf->packages_refs);
630  mxf->packages_count = avio_rb32(pb);
631  mxf->packages_refs = av_calloc(mxf->packages_count, sizeof(UID));
632  if (!mxf->packages_refs)
633  return AVERROR(ENOMEM);
634  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
635  avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
636  break;
637  }
638  return 0;
639 }
640 
641 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
642 {
643  MXFStructuralComponent *source_clip = arg;
644  switch(tag) {
645  case 0x0202:
646  source_clip->duration = avio_rb64(pb);
647  break;
648  case 0x1201:
649  source_clip->start_position = avio_rb64(pb);
650  break;
651  case 0x1101:
652  /* UMID, only get last 16 bytes */
653  avio_skip(pb, 16);
654  avio_read(pb, source_clip->source_package_uid, 16);
655  break;
656  case 0x1102:
657  source_clip->source_track_id = avio_rb32(pb);
658  break;
659  }
660  return 0;
661 }
662 
663 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
664 {
665  MXFPackage *package = arg;
666  switch(tag) {
667  case 0x4403:
668  package->tracks_count = avio_rb32(pb);
669  package->tracks_refs = av_calloc(package->tracks_count, sizeof(UID));
670  if (!package->tracks_refs)
671  return AVERROR(ENOMEM);
672  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
673  avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
674  break;
675  }
676  return 0;
677 }
678 
679 static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
680 {
681  MXFTimecodeComponent *mxf_timecode = arg;
682  switch(tag) {
683  case 0x1501:
684  mxf_timecode->start_frame = avio_rb64(pb);
685  break;
686  case 0x1502:
687  mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
688  break;
689  case 0x1503:
690  mxf_timecode->drop_frame = avio_r8(pb);
691  break;
692  }
693  return 0;
694 }
695 
696 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
697 {
698  MXFTrack *track = arg;
699  switch(tag) {
700  case 0x4801:
701  track->track_id = avio_rb32(pb);
702  break;
703  case 0x4804:
704  avio_read(pb, track->track_number, 4);
705  break;
706  case 0x4b01:
707  track->edit_rate.num = avio_rb32(pb);
708  track->edit_rate.den = avio_rb32(pb);
709  break;
710  case 0x4803:
711  avio_read(pb, track->sequence_ref, 16);
712  break;
713  }
714  return 0;
715 }
716 
717 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
718 {
719  MXFSequence *sequence = arg;
720  switch(tag) {
721  case 0x0202:
722  sequence->duration = avio_rb64(pb);
723  break;
724  case 0x0201:
725  avio_read(pb, sequence->data_definition_ul, 16);
726  break;
727  case 0x4b02:
728  sequence->origin = avio_r8(pb);
729  break;
730  case 0x1001:
731  sequence->structural_components_count = avio_rb32(pb);
733  if (!sequence->structural_components_refs)
734  return AVERROR(ENOMEM);
735  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
736  avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
737  break;
738  }
739  return 0;
740 }
741 
742 static int mxf_read_utf16_string(AVIOContext *pb, int size, char** str)
743 {
744  int ret;
745  size_t buf_size;
746 
747  if (size < 0)
748  return AVERROR(EINVAL);
749 
750  buf_size = size + size / 2 + 1;
751  *str = av_malloc(buf_size);
752  if (!*str)
753  return AVERROR(ENOMEM);
754 
755  if ((ret = avio_get_str16be(pb, size, *str, buf_size)) < 0) {
756  av_freep(str);
757  return ret;
758  }
759 
760  return ret;
761 }
762 
763 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
764 {
765  MXFPackage *package = arg;
766  switch(tag) {
767  case 0x4403:
768  package->tracks_count = avio_rb32(pb);
769  package->tracks_refs = av_calloc(package->tracks_count, sizeof(UID));
770  if (!package->tracks_refs)
771  return AVERROR(ENOMEM);
772  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
773  avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
774  break;
775  case 0x4401:
776  /* UMID, only get last 16 bytes */
777  avio_skip(pb, 16);
778  avio_read(pb, package->package_uid, 16);
779  break;
780  case 0x4701:
781  avio_read(pb, package->descriptor_ref, 16);
782  break;
783  case 0x4402:
784  return mxf_read_utf16_string(pb, size, &package->name);
785  }
786  return 0;
787 }
788 
790 {
791  int i, length;
792 
793  segment->nb_index_entries = avio_rb32(pb);
794 
795  length = avio_rb32(pb);
796 
797  if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
798  !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
799  !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
800  return AVERROR(ENOMEM);
801 
802  for (i = 0; i < segment->nb_index_entries; i++) {
803  segment->temporal_offset_entries[i] = avio_r8(pb);
804  avio_r8(pb); /* KeyFrameOffset */
805  segment->flag_entries[i] = avio_r8(pb);
806  segment->stream_offset_entries[i] = avio_rb64(pb);
807  avio_skip(pb, length - 11);
808  }
809  return 0;
810 }
811 
812 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
813 {
815  switch(tag) {
816  case 0x3F05:
817  segment->edit_unit_byte_count = avio_rb32(pb);
818  av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
819  break;
820  case 0x3F06:
821  segment->index_sid = avio_rb32(pb);
822  av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
823  break;
824  case 0x3F07:
825  segment->body_sid = avio_rb32(pb);
826  av_dlog(NULL, "BodySID %d\n", segment->body_sid);
827  break;
828  case 0x3F0A:
829  av_dlog(NULL, "IndexEntryArray found\n");
830  return mxf_read_index_entry_array(pb, segment);
831  case 0x3F0B:
832  segment->index_edit_rate.num = avio_rb32(pb);
833  segment->index_edit_rate.den = avio_rb32(pb);
834  av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
835  segment->index_edit_rate.den);
836  break;
837  case 0x3F0C:
838  segment->index_start_position = avio_rb64(pb);
839  av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
840  break;
841  case 0x3F0D:
842  segment->index_duration = avio_rb64(pb);
843  av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
844  break;
845  }
846  return 0;
847 }
848 
849 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
850 {
851  int code, value, ofs = 0;
852  char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */
853 
854  do {
855  code = avio_r8(pb);
856  value = avio_r8(pb);
857  av_dlog(NULL, "pixel layout: code %#x\n", code);
858 
859  if (ofs <= 14) {
860  layout[ofs++] = code;
861  layout[ofs++] = value;
862  } else
863  break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */
864  } while (code != 0); /* SMPTE 377M E.2.46 */
865 
866  ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
867 }
868 
869 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
870 {
871  MXFDescriptor *descriptor = arg;
872  descriptor->pix_fmt = AV_PIX_FMT_NONE;
873  switch(tag) {
874  case 0x3F01:
875  descriptor->sub_descriptors_count = avio_rb32(pb);
876  descriptor->sub_descriptors_refs = av_calloc(descriptor->sub_descriptors_count, sizeof(UID));
877  if (!descriptor->sub_descriptors_refs)
878  return AVERROR(ENOMEM);
879  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
880  avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
881  break;
882  case 0x3004:
883  avio_read(pb, descriptor->essence_container_ul, 16);
884  break;
885  case 0x3006:
886  descriptor->linked_track_id = avio_rb32(pb);
887  break;
888  case 0x3201: /* PictureEssenceCoding */
889  avio_read(pb, descriptor->essence_codec_ul, 16);
890  break;
891  case 0x3203:
892  descriptor->width = avio_rb32(pb);
893  break;
894  case 0x3202:
895  descriptor->height = avio_rb32(pb);
896  break;
897  case 0x320C:
898  descriptor->frame_layout = avio_r8(pb);
899  break;
900  case 0x320E:
901  descriptor->aspect_ratio.num = avio_rb32(pb);
902  descriptor->aspect_ratio.den = avio_rb32(pb);
903  break;
904  case 0x3212:
905  descriptor->field_dominance = avio_r8(pb);
906  break;
907  case 0x3301:
908  descriptor->component_depth = avio_rb32(pb);
909  break;
910  case 0x3302:
911  descriptor->horiz_subsampling = avio_rb32(pb);
912  break;
913  case 0x3308:
914  descriptor->vert_subsampling = avio_rb32(pb);
915  break;
916  case 0x3D03:
917  descriptor->sample_rate.num = avio_rb32(pb);
918  descriptor->sample_rate.den = avio_rb32(pb);
919  break;
920  case 0x3D06: /* SoundEssenceCompression */
921  avio_read(pb, descriptor->essence_codec_ul, 16);
922  break;
923  case 0x3D07:
924  descriptor->channels = avio_rb32(pb);
925  break;
926  case 0x3D01:
927  descriptor->bits_per_sample = avio_rb32(pb);
928  break;
929  case 0x3401:
930  mxf_read_pixel_layout(pb, descriptor);
931  break;
932  default:
933  /* Private uid used by SONY C0023S01.mxf */
935  if (descriptor->extradata)
936  av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n");
937  av_free(descriptor->extradata);
938  descriptor->extradata_size = 0;
939  descriptor->extradata = av_malloc(size);
940  if (!descriptor->extradata)
941  return AVERROR(ENOMEM);
942  descriptor->extradata_size = size;
943  avio_read(pb, descriptor->extradata, size);
944  }
945  break;
946  }
947  return 0;
948 }
949 
950 /*
951  * Match an uid independently of the version byte and up to len common bytes
952  * Returns: boolean
953  */
954 static int mxf_match_uid(const UID key, const UID uid, int len)
955 {
956  int i;
957  for (i = 0; i < len; i++) {
958  if (i != 7 && key[i] != uid[i])
959  return 0;
960  }
961  return 1;
962 }
963 
964 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
965 {
966  while (uls->uid[0]) {
967  if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
968  break;
969  uls++;
970  }
971  return uls;
972 }
973 
974 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
975 {
976  int i;
977 
978  if (!strong_ref)
979  return NULL;
980  for (i = 0; i < mxf->metadata_sets_count; i++) {
981  if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
982  (type == AnyType || mxf->metadata_sets[i]->type == type)) {
983  return mxf->metadata_sets[i];
984  }
985  }
986  return NULL;
987 }
988 
990  // video essence container uls
991  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
992  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
993  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO }, /* Uncompressed Picture */
994  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
995 };
996 
997 /* EC ULs for intra-only formats */
999  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MXF-GC SMPTE D-10 Mappings */
1000  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1001 };
1002 
1003 /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
1005  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14, AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra Profiles */
1006  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG2000 Codestream */
1007  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1008 };
1009 
1011  // sound essence container uls
1012  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
1013  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
1014  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
1015  { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4F }, 14, AV_CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
1016  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14, AV_CODEC_ID_AAC }, /* MPEG2 AAC ADTS (legacy) */
1017  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1018 };
1019 
1021  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 }, 16, 0 },
1022  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1023 };
1024 
1025 static const char* const mxf_data_essence_descriptor[] = {
1026  "vbi_vanc_smpte_436M",
1027 };
1028 
1029 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
1030 {
1031  int i, j, nb_segments = 0;
1032  MXFIndexTableSegment **unsorted_segments;
1033  int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
1034 
1035  /* count number of segments, allocate arrays and copy unsorted segments */
1036  for (i = 0; i < mxf->metadata_sets_count; i++)
1037  if (mxf->metadata_sets[i]->type == IndexTableSegment)
1038  nb_segments++;
1039 
1040  if (!nb_segments)
1041  return AVERROR_INVALIDDATA;
1042 
1043  if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
1044  !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
1045  av_freep(sorted_segments);
1046  av_free(unsorted_segments);
1047  return AVERROR(ENOMEM);
1048  }
1049 
1050  for (i = j = 0; i < mxf->metadata_sets_count; i++)
1051  if (mxf->metadata_sets[i]->type == IndexTableSegment)
1052  unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
1053 
1054  *nb_sorted_segments = 0;
1055 
1056  /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
1057  for (i = 0; i < nb_segments; i++) {
1058  int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
1059  uint64_t best_index_duration = 0;
1060 
1061  for (j = 0; j < nb_segments; j++) {
1062  MXFIndexTableSegment *s = unsorted_segments[j];
1063 
1064  /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
1065  * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
1066  * If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have.
1067  */
1068  if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
1069  (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start ||
1070  (s->index_start_position == best_index_start && s->index_duration > best_index_duration))) {
1071  best = j;
1072  best_body_sid = s->body_sid;
1073  best_index_sid = s->index_sid;
1074  best_index_start = s->index_start_position;
1075  best_index_duration = s->index_duration;
1076  }
1077  }
1078 
1079  /* no suitable entry found -> we're done */
1080  if (best == -1)
1081  break;
1082 
1083  (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
1084  last_body_sid = best_body_sid;
1085  last_index_sid = best_index_sid;
1086  last_index_start = best_index_start;
1087  }
1088 
1089  av_free(unsorted_segments);
1090 
1091  return 0;
1092 }
1093 
1094 /**
1095  * Computes the absolute file offset of the given essence container offset
1096  */
1097 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
1098 {
1099  int x;
1100  int64_t offset_in = offset; /* for logging */
1101 
1102  for (x = 0; x < mxf->partitions_count; x++) {
1103  MXFPartition *p = &mxf->partitions[x];
1104 
1105  if (p->body_sid != body_sid)
1106  continue;
1107 
1108  if (offset < p->essence_length || !p->essence_length) {
1109  *offset_out = p->essence_offset + offset;
1110  return 0;
1111  }
1112 
1113  offset -= p->essence_length;
1114  }
1115 
1116  av_log(mxf->fc, AV_LOG_ERROR,
1117  "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
1118  offset_in, body_sid);
1119 
1120  return AVERROR_INVALIDDATA;
1121 }
1122 
1123 /**
1124  * Returns the end position of the essence container with given BodySID, or zero if unknown
1125  */
1126 static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
1127 {
1128  int x;
1129  int64_t ret = 0;
1130 
1131  for (x = 0; x < mxf->partitions_count; x++) {
1132  MXFPartition *p = &mxf->partitions[x];
1133 
1134  if (p->body_sid != body_sid)
1135  continue;
1136 
1137  if (!p->essence_length)
1138  return 0;
1139 
1140  ret = p->essence_offset + p->essence_length;
1141  }
1142 
1143  return ret;
1144 }
1145 
1146 /* EditUnit -> absolute offset */
1147 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)
1148 {
1149  int i;
1150  int64_t offset_temp = 0;
1151 
1152  for (i = 0; i < index_table->nb_segments; i++) {
1153  MXFIndexTableSegment *s = index_table->segments[i];
1154 
1155  edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
1156 
1157  if (edit_unit < s->index_start_position + s->index_duration) {
1158  int64_t index = edit_unit - s->index_start_position;
1159 
1160  if (s->edit_unit_byte_count)
1161  offset_temp += s->edit_unit_byte_count * index;
1162  else if (s->nb_index_entries) {
1163  if (s->nb_index_entries == 2 * s->index_duration + 1)
1164  index *= 2; /* Avid index */
1165 
1166  if (index < 0 || index >= s->nb_index_entries) {
1167  av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
1168  index_table->index_sid, s->index_start_position);
1169  return AVERROR_INVALIDDATA;
1170  }
1171 
1172  offset_temp = s->stream_offset_entries[index];
1173  } else {
1174  av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
1175  index_table->index_sid, s->index_start_position);
1176  return AVERROR_INVALIDDATA;
1177  }
1178 
1179  if (edit_unit_out)
1180  *edit_unit_out = edit_unit;
1181 
1182  return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out);
1183  } else {
1184  /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
1185  offset_temp += s->edit_unit_byte_count * s->index_duration;
1186  }
1187  }
1188 
1189  if (nag)
1190  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);
1191 
1192  return AVERROR_INVALIDDATA;
1193 }
1194 
1196 {
1197  int i, j, x;
1198  int8_t max_temporal_offset = -128;
1199 
1200  /* first compute how many entries we have */
1201  for (i = 0; i < index_table->nb_segments; i++) {
1202  MXFIndexTableSegment *s = index_table->segments[i];
1203 
1204  if (!s->nb_index_entries) {
1205  index_table->nb_ptses = 0;
1206  return 0; /* no TemporalOffsets */
1207  }
1208 
1209  index_table->nb_ptses += s->index_duration;
1210  }
1211 
1212  /* paranoid check */
1213  if (index_table->nb_ptses <= 0)
1214  return 0;
1215 
1216  if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
1217  !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry)))) {
1218  av_freep(&index_table->ptses);
1219  return AVERROR(ENOMEM);
1220  }
1221 
1222  /* we may have a few bad TemporalOffsets
1223  * make sure the corresponding PTSes don't have the bogus value 0 */
1224  for (x = 0; x < index_table->nb_ptses; x++)
1225  index_table->ptses[x] = AV_NOPTS_VALUE;
1226 
1227  /**
1228  * We have this:
1229  *
1230  * x TemporalOffset
1231  * 0: 0
1232  * 1: 1
1233  * 2: 1
1234  * 3: -2
1235  * 4: 1
1236  * 5: 1
1237  * 6: -2
1238  *
1239  * We want to transform it into this:
1240  *
1241  * x DTS PTS
1242  * 0: -1 0
1243  * 1: 0 3
1244  * 2: 1 1
1245  * 3: 2 2
1246  * 4: 3 6
1247  * 5: 4 4
1248  * 6: 5 5
1249  *
1250  * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
1251  * then settings mxf->first_dts = -max(TemporalOffset[x]).
1252  * The latter makes DTS <= PTS.
1253  */
1254  for (i = x = 0; i < index_table->nb_segments; i++) {
1255  MXFIndexTableSegment *s = index_table->segments[i];
1256  int index_delta = 1;
1257  int n = s->nb_index_entries;
1258 
1259  if (s->nb_index_entries == 2 * s->index_duration + 1) {
1260  index_delta = 2; /* Avid index */
1261  /* ignore the last entry - it's the size of the essence container */
1262  n--;
1263  }
1264 
1265  for (j = 0; j < n; j += index_delta, x++) {
1266  int offset = s->temporal_offset_entries[j] / index_delta;
1267  int index = x + offset;
1268 
1269  if (x >= index_table->nb_ptses) {
1270  av_log(mxf->fc, AV_LOG_ERROR,
1271  "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
1273  break;
1274  }
1275 
1276  index_table->fake_index[x].timestamp = x;
1277  index_table->fake_index[x].flags = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
1278 
1279  if (index < 0 || index >= index_table->nb_ptses) {
1280  av_log(mxf->fc, AV_LOG_ERROR,
1281  "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
1282  x, offset, index);
1283  continue;
1284  }
1285 
1286  index_table->ptses[index] = x;
1287  max_temporal_offset = FFMAX(max_temporal_offset, offset);
1288  }
1289  }
1290 
1291  index_table->first_dts = -max_temporal_offset;
1292 
1293  return 0;
1294 }
1295 
1296 /**
1297  * Sorts and collects index table segments into index tables.
1298  * Also computes PTSes if possible.
1299  */
1301 {
1302  int i, j, k, ret, nb_sorted_segments;
1303  MXFIndexTableSegment **sorted_segments = NULL;
1304 
1305  if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
1306  nb_sorted_segments <= 0) {
1307  av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
1308  return 0;
1309  }
1310 
1311  /* sanity check and count unique BodySIDs/IndexSIDs */
1312  for (i = 0; i < nb_sorted_segments; i++) {
1313  if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
1314  mxf->nb_index_tables++;
1315  else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
1316  av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
1317  ret = AVERROR_INVALIDDATA;
1318  goto finish_decoding_index;
1319  }
1320  }
1321 
1323  sizeof(*mxf->index_tables));
1324  if (!mxf->index_tables) {
1325  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
1326  ret = AVERROR(ENOMEM);
1327  goto finish_decoding_index;
1328  }
1329 
1330  /* distribute sorted segments to index tables */
1331  for (i = j = 0; i < nb_sorted_segments; i++) {
1332  if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
1333  /* next IndexSID */
1334  j++;
1335  }
1336 
1337  mxf->index_tables[j].nb_segments++;
1338  }
1339 
1340  for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
1341  MXFIndexTable *t = &mxf->index_tables[j];
1342 
1344  sizeof(*t->segments));
1345 
1346  if (!t->segments) {
1347  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment"
1348  " pointer array\n");
1349  ret = AVERROR(ENOMEM);
1350  goto finish_decoding_index;
1351  }
1352 
1353  if (sorted_segments[i]->index_start_position)
1354  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
1355  sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
1356 
1357  memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
1358  t->index_sid = sorted_segments[i]->index_sid;
1359  t->body_sid = sorted_segments[i]->body_sid;
1360 
1361  if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
1362  goto finish_decoding_index;
1363 
1364  /* fix zero IndexDurations */
1365  for (k = 0; k < t->nb_segments; k++) {
1366  if (t->segments[k]->index_duration)
1367  continue;
1368 
1369  if (t->nb_segments > 1)
1370  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
1371  t->index_sid, k);
1372 
1373  if (mxf->fc->nb_streams <= 0) {
1374  av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
1375  break;
1376  }
1377 
1378  /* assume the first stream's duration is reasonable
1379  * leave index_duration = 0 on further segments in case we have any (unlikely)
1380  */
1381  t->segments[k]->index_duration = mxf->fc->streams[0]->duration;
1382  break;
1383  }
1384  }
1385 
1386  ret = 0;
1387 finish_decoding_index:
1388  av_free(sorted_segments);
1389  return ret;
1390 }
1391 
1392 static int mxf_is_intra_only(MXFDescriptor *descriptor)
1393 {
1394  return mxf_get_codec_ul(mxf_intra_only_essence_container_uls,
1395  &descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE ||
1396  mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls,
1397  &descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE;
1398 }
1399 
1400 static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
1401 {
1402  char buf[AV_TIMECODE_STR_SIZE];
1403  av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
1404 
1405  return 0;
1406 }
1407 
1409 {
1410  MXFPackage *temp_package = NULL;
1411  MXFPackage *physical_package = NULL;
1412  MXFTrack *physical_track = NULL;
1413  MXFStructuralComponent *component = NULL;
1414  MXFStructuralComponent *sourceclip = NULL;
1415  MXFTimecodeComponent *mxf_tc = NULL;
1416  int i, j, k;
1417  AVTimecode tc;
1418  int flags;
1419  int64_t start_position;
1420 
1421  for (i = 0; i < source_track->sequence->structural_components_count; i++) {
1422  component = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip);
1423  if (!component)
1424  continue;
1425 
1426  for (j = 0; j < mxf->packages_count; j++) {
1427  temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[j], SourcePackage);
1428  if (!temp_package)
1429  continue;
1430  if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)){
1431  physical_package = temp_package;
1432  sourceclip = component;
1433  break;
1434  }
1435  }
1436  if (!physical_package)
1437  break;
1438 
1439  /* the name of physical source package is name of the reel or tape */
1440  if (physical_package->name[0])
1441  av_dict_set(&st->metadata, "reel_name", physical_package->name, 0);
1442 
1443  /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track
1444  * to the start_frame of the timecode component located on one of the tracks of the physical source package.
1445  */
1446  for (j = 0; j < physical_package->tracks_count; j++) {
1447  if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) {
1448  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
1449  continue;
1450  }
1451 
1452  if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) {
1453  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
1454  continue;
1455  }
1456 
1457  for (k = 0; k < physical_track->sequence->structural_components_count; k++) {
1458  component = mxf_resolve_strong_ref(mxf, &physical_track->sequence->structural_components_refs[k], TimecodeComponent);
1459  if (!component)
1460  continue;
1461 
1462  mxf_tc = (MXFTimecodeComponent*)component;
1463  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
1464  /* scale sourceclip start_position to match physical track edit rate */
1465  start_position = av_rescale_q(sourceclip->start_position,
1466  physical_track->edit_rate,
1467  source_track->edit_rate);
1468 
1469  if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) {
1470  mxf_add_timecode_metadata(&st->metadata, "timecode", &tc);
1471  return 0;
1472  }
1473  }
1474  }
1475  }
1476 
1477  return 0;
1478 }
1479 
1481 {
1482  MXFPackage *material_package = NULL;
1483  MXFPackage *temp_package = NULL;
1484  int i, j, k, ret;
1485 
1486  av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
1487  /* TODO: handle multiple material packages (OP3x) */
1488  for (i = 0; i < mxf->packages_count; i++) {
1489  material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
1490  if (material_package) break;
1491  }
1492  if (!material_package) {
1493  av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
1494  return AVERROR_INVALIDDATA;
1495  }
1496 
1497  for (i = 0; i < material_package->tracks_count; i++) {
1498  MXFPackage *source_package = NULL;
1499  MXFTrack *material_track = NULL;
1500  MXFTrack *source_track = NULL;
1501  MXFTrack *temp_track = NULL;
1502  MXFDescriptor *descriptor = NULL;
1503  MXFStructuralComponent *component = NULL;
1504  MXFTimecodeComponent *mxf_tc = NULL;
1505  UID *essence_container_ul = NULL;
1506  const MXFCodecUL *codec_ul = NULL;
1507  const MXFCodecUL *container_ul = NULL;
1508  const MXFCodecUL *pix_fmt_ul = NULL;
1509  AVStream *st;
1510  AVTimecode tc;
1511  int flags;
1512 
1513  if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
1514  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
1515  continue;
1516  }
1517 
1518  if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
1519  mxf_tc = (MXFTimecodeComponent*)component;
1520  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
1521  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
1522  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
1523  }
1524  }
1525 
1526  if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
1527  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
1528  continue;
1529  }
1530 
1531  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
1532  component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
1533  if (!component)
1534  continue;
1535 
1536  mxf_tc = (MXFTimecodeComponent*)component;
1537  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
1538  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
1539  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
1540  break;
1541  }
1542  }
1543 
1544  /* TODO: handle multiple source clips */
1545  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
1546  component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
1547  if (!component)
1548  continue;
1549 
1550  for (k = 0; k < mxf->packages_count; k++) {
1551  temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
1552  if (!temp_package)
1553  continue;
1554  if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
1555  source_package = temp_package;
1556  break;
1557  }
1558  }
1559  if (!source_package) {
1560  av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
1561  break;
1562  }
1563  for (k = 0; k < source_package->tracks_count; k++) {
1564  if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
1565  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
1566  ret = AVERROR_INVALIDDATA;
1567  goto fail_and_free;
1568  }
1569  if (temp_track->track_id == component->source_track_id) {
1570  source_track = temp_track;
1571  break;
1572  }
1573  }
1574  if (!source_track) {
1575  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
1576  break;
1577  }
1578  }
1579  if (!source_track || !component)
1580  continue;
1581 
1582  if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
1583  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
1584  ret = AVERROR_INVALIDDATA;
1585  goto fail_and_free;
1586  }
1587 
1588  /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
1589  * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
1590  if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
1591  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
1592  continue;
1593  }
1594 
1595  st = avformat_new_stream(mxf->fc, NULL);
1596  if (!st) {
1597  av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
1598  ret = AVERROR(ENOMEM);
1599  goto fail_and_free;
1600  }
1601  st->id = source_track->track_id;
1602  st->priv_data = source_track;
1603  source_track->original_duration = st->duration = component->duration;
1604  if (st->duration == -1)
1605  st->duration = AV_NOPTS_VALUE;
1606  st->start_time = component->start_position;
1607  if (material_track->edit_rate.num <= 0 ||
1608  material_track->edit_rate.den <= 0) {
1609  av_log(mxf->fc, AV_LOG_WARNING,
1610  "Invalid edit rate (%d/%d) found on stream #%d, "
1611  "defaulting to 25/1\n",
1612  material_track->edit_rate.num,
1613  material_track->edit_rate.den, st->index);
1614  material_track->edit_rate = (AVRational){25, 1};
1615  }
1616  avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
1617 
1618  /* ensure SourceTrack EditRate == MaterialTrack EditRate since only
1619  * the former is accessible via st->priv_data */
1620  source_track->edit_rate = material_track->edit_rate;
1621 
1622  PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
1624  st->codec->codec_type = codec_ul->id;
1625 
1626  source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
1627  if (source_package->descriptor) {
1628  if (source_package->descriptor->type == MultipleDescriptor) {
1629  for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
1630  MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
1631 
1632  if (!sub_descriptor) {
1633  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
1634  continue;
1635  }
1636  if (sub_descriptor->linked_track_id == source_track->track_id) {
1637  descriptor = sub_descriptor;
1638  break;
1639  }
1640  }
1641  } else if (source_package->descriptor->type == Descriptor)
1642  descriptor = source_package->descriptor;
1643  }
1644  if (!descriptor) {
1645  av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
1646  continue;
1647  }
1648  PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
1649  PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
1650  essence_container_ul = &descriptor->essence_container_ul;
1651  /* HACK: replacing the original key with mxf_encrypted_essence_container
1652  * is not allowed according to s429-6, try to find correct information anyway */
1653  if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
1654  av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
1655  for (k = 0; k < mxf->metadata_sets_count; k++) {
1656  MXFMetadataSet *metadata = mxf->metadata_sets[k];
1657  if (metadata->type == CryptoContext) {
1658  essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
1659  break;
1660  }
1661  }
1662  }
1663 
1664  /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
1665  codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
1666  st->codec->codec_id = (enum AVCodecID)codec_ul->id;
1667  av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
1669  for (k = 0; k < 16; k++) {
1670  av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
1671  descriptor->essence_codec_ul[k]);
1672  if (!(k+1 & 19) || k == 5)
1673  av_log(mxf->fc, AV_LOG_VERBOSE, ".");
1674  }
1675  av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
1676 
1677  mxf_parse_physical_source_package(mxf, source_track, st);
1678 
1679  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1680  source_track->intra_only = mxf_is_intra_only(descriptor);
1681  container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
1682  if (st->codec->codec_id == AV_CODEC_ID_NONE)
1683  st->codec->codec_id = container_ul->id;
1684  st->codec->width = descriptor->width;
1685  st->codec->height = descriptor->height; /* Field height, not frame height */
1686  switch (descriptor->frame_layout) {
1687  case SegmentedFrame:
1688  /* This one is a weird layout I don't fully understand. */
1689  av_log(mxf->fc, AV_LOG_INFO, "SegmentedFrame layout isn't currently supported\n");
1690  break;
1691  case FullFrame:
1693  break;
1694  case OneField:
1695  /* Every other line is stored and needs to be duplicated. */
1696  av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
1697  break; /* The correct thing to do here is fall through, but by breaking we might be
1698  able to decode some streams at half the vertical resolution, rather than not al all.
1699  It's also for compatibility with the old behavior. */
1700  case MixedFields:
1701  break;
1702  case SeparateFields:
1703  switch (descriptor->field_dominance) {
1704  case MXF_TFF:
1705  st->codec->field_order = AV_FIELD_TT;
1706  break;
1707  case MXF_BFF:
1708  st->codec->field_order = AV_FIELD_BB;
1709  break;
1710  default:
1712  "Field dominance %d support",
1713  descriptor->field_dominance);
1714  break;
1715  }
1716  /* Turn field height into frame height. */
1717  st->codec->height *= 2;
1718  break;
1719  default:
1720  av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
1721  }
1722  if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
1723  st->codec->pix_fmt = descriptor->pix_fmt;
1724  if (st->codec->pix_fmt == AV_PIX_FMT_NONE) {
1726  &descriptor->essence_codec_ul);
1727  st->codec->pix_fmt = (enum AVPixelFormat)pix_fmt_ul->id;
1728  if (st->codec->pix_fmt == AV_PIX_FMT_NONE) {
1729  /* support files created before RP224v10 by defaulting to UYVY422
1730  if subsampling is 4:2:2 and component depth is 8-bit */
1731  if (descriptor->horiz_subsampling == 2 &&
1732  descriptor->vert_subsampling == 1 &&
1733  descriptor->component_depth == 8) {
1735  }
1736  }
1737  }
1738  }
1740  if (material_track->sequence->origin) {
1741  av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
1742  }
1743  if (source_track->sequence->origin) {
1744  av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
1745  }
1746  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1747  container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
1748  /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
1749  if (st->codec->codec_id == AV_CODEC_ID_NONE || (st->codec->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE))
1750  st->codec->codec_id = (enum AVCodecID)container_ul->id;
1751  st->codec->channels = descriptor->channels;
1752  st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
1753 
1754  if (descriptor->sample_rate.den > 0) {
1755  st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
1756  avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
1757  } else {
1758  av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
1759  "found for stream #%d, time base forced to 1/48000\n",
1760  descriptor->sample_rate.num, descriptor->sample_rate.den,
1761  st->index);
1762  avpriv_set_pts_info(st, 64, 1, 48000);
1763  }
1764 
1765  /* if duration is set, rescale it from EditRate to SampleRate */
1766  if (st->duration != AV_NOPTS_VALUE)
1767  st->duration = av_rescale_q(st->duration,
1768  av_inv_q(material_track->edit_rate),
1769  st->time_base);
1770 
1771  /* TODO: implement AV_CODEC_ID_RAWAUDIO */
1772  if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
1773  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1775  else if (descriptor->bits_per_sample == 32)
1777  } else if (st->codec->codec_id == AV_CODEC_ID_PCM_S16BE) {
1778  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1780  else if (descriptor->bits_per_sample == 32)
1782  } else if (st->codec->codec_id == AV_CODEC_ID_MP2) {
1784  }
1785  } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1786  int codec_id = mxf_get_codec_ul(mxf_data_essence_container_uls,
1787  essence_container_ul)->id;
1788  if (codec_id >= 0 &&
1789  codec_id < FF_ARRAY_ELEMS(mxf_data_essence_descriptor)) {
1790  av_dict_set(&st->metadata, "data_type",
1791  mxf_data_essence_descriptor[codec_id], 0);
1792  }
1793  }
1794  if (descriptor->extradata) {
1795  if (!ff_alloc_extradata(st->codec, descriptor->extradata_size)) {
1796  memcpy(st->codec->extradata, descriptor->extradata, descriptor->extradata_size);
1797  }
1798  } else if (st->codec->codec_id == AV_CODEC_ID_H264) {
1799  ret = ff_generate_avci_extradata(st);
1800  if (ret < 0)
1801  return ret;
1802  }
1803  if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
1804  /* TODO: decode timestamps */
1806  }
1807  }
1808 
1809  ret = 0;
1810 fail_and_free:
1811  return ret;
1812 }
1813 
1814 static int mxf_uid_to_str(UID uid, char **str)
1815 {
1816  int i;
1817  char *p;
1818  p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1);
1819  if (!p)
1820  return AVERROR(ENOMEM);
1821  for (i = 0; i < sizeof(UID); i++) {
1822  snprintf(p, 2 + 1, "%.2x", uid[i]);
1823  p += 2;
1824  if (i == 3 || i == 5 || i == 7 || i == 9) {
1825  snprintf(p, 1 + 1, "-");
1826  p++;
1827  }
1828  }
1829  return 0;
1830 }
1831 
1832 static int mxf_timestamp_to_str(uint64_t timestamp, char **str)
1833 {
1834  struct tm time = { 0 };
1835  time.tm_year = (timestamp >> 48) - 1900;
1836  time.tm_mon = (timestamp >> 40 & 0xFF) - 1;
1837  time.tm_mday = (timestamp >> 32 & 0xFF);
1838  time.tm_hour = (timestamp >> 24 & 0xFF);
1839  time.tm_min = (timestamp >> 16 & 0xFF);
1840  time.tm_sec = (timestamp >> 8 & 0xFF);
1841 
1842  /* msvcrt versions of strftime calls the invalid parameter handler
1843  * (aborting the process if one isn't set) if the parameters are out
1844  * of range. */
1845  time.tm_mon = av_clip(time.tm_mon, 0, 11);
1846  time.tm_mday = av_clip(time.tm_mday, 1, 31);
1847  time.tm_hour = av_clip(time.tm_hour, 0, 23);
1848  time.tm_min = av_clip(time.tm_min, 0, 59);
1849  time.tm_sec = av_clip(time.tm_sec, 0, 59);
1850 
1851  *str = av_mallocz(32);
1852  if (!*str)
1853  return AVERROR(ENOMEM);
1854  strftime(*str, 32, "%Y-%m-%d %H:%M:%S", &time);
1855 
1856  return 0;
1857 }
1858 
1859 #define SET_STR_METADATA(pb, name, str) do { \
1860  if ((ret = mxf_read_utf16_string(pb, size, &str)) < 0) \
1861  return ret; \
1862  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
1863 } while (0)
1864 
1865 #define SET_UID_METADATA(pb, name, var, str) do { \
1866  avio_read(pb, var, 16); \
1867  if ((ret = mxf_uid_to_str(var, &str)) < 0) \
1868  return ret; \
1869  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
1870 } while (0)
1871 
1872 #define SET_TS_METADATA(pb, name, var, str) do { \
1873  var = avio_rb64(pb); \
1874  if ((ret = mxf_timestamp_to_str(var, &str)) < 0) \
1875  return ret; \
1876  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
1877 } while (0)
1878 
1879 static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
1880 {
1881  MXFContext *mxf = arg;
1882  AVFormatContext *s = mxf->fc;
1883  int ret;
1884  UID uid = { 0 };
1885  char *str = NULL;
1886  uint64_t ts;
1887  switch (tag) {
1888  case 0x3C01:
1889  SET_STR_METADATA(pb, "company_name", str);
1890  break;
1891  case 0x3C02:
1892  SET_STR_METADATA(pb, "product_name", str);
1893  break;
1894  case 0x3C04:
1895  SET_STR_METADATA(pb, "product_version", str);
1896  break;
1897  case 0x3C05:
1898  SET_UID_METADATA(pb, "product_uid", uid, str);
1899  break;
1900  case 0x3C06:
1901  SET_TS_METADATA(pb, "modification_date", ts, str);
1902  break;
1903  case 0x3C08:
1904  SET_STR_METADATA(pb, "application_platform", str);
1905  break;
1906  case 0x3C09:
1907  SET_UID_METADATA(pb, "generation_uid", uid, str);
1908  break;
1909  case 0x3C0A:
1910  SET_UID_METADATA(pb, "uid", uid, str);
1911  break;
1912  }
1913  return 0;
1914 }
1915 
1917  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
1918  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
1919  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
1920  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
1921  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
1922  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
1923  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
1924  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
1925  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
1926  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
1927  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
1928  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata },
1929  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
1930  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
1931  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
1932  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
1933  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
1934  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
1935  { { 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 */
1936  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
1937  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
1938  { { 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 */
1939  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
1940  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
1941  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */
1942  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VANC/VBI - SMPTE 436M */
1943  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */
1944  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
1945  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
1946  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
1947  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
1948  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
1949  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
1950 };
1951 
1952 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
1953 {
1954  AVIOContext *pb = mxf->fc->pb;
1955  MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
1956  uint64_t klv_end = avio_tell(pb) + klv->length;
1957 
1958  if (!ctx)
1959  return AVERROR(ENOMEM);
1960  while (avio_tell(pb) + 4 < klv_end && !avio_feof(pb)) {
1961  int ret;
1962  int tag = avio_rb16(pb);
1963  int size = avio_rb16(pb); /* KLV specified by 0x53 */
1964  uint64_t next = avio_tell(pb) + size;
1965  UID uid = {0};
1966 
1967  av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
1968  if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
1969  av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
1970  continue;
1971  }
1972  if (tag > 0x7FFF) { /* dynamic tag */
1973  int i;
1974  for (i = 0; i < mxf->local_tags_count; i++) {
1975  int local_tag = AV_RB16(mxf->local_tags+i*18);
1976  if (local_tag == tag) {
1977  memcpy(uid, mxf->local_tags+i*18+2, 16);
1978  av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
1979  PRINT_KEY(mxf->fc, "uid", uid);
1980  }
1981  }
1982  }
1983  if (ctx_size && tag == 0x3C0A)
1984  avio_read(pb, ctx->uid, 16);
1985  else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0)
1986  return ret;
1987 
1988  /* Accept the 64k local set limit being exceeded (Avid). Don't accept
1989  * it extending past the end of the KLV though (zzuf5.mxf). */
1990  if (avio_tell(pb) > klv_end) {
1991  if (ctx_size)
1992  av_free(ctx);
1993 
1994  av_log(mxf->fc, AV_LOG_ERROR,
1995  "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
1996  tag, klv->offset);
1997  return AVERROR_INVALIDDATA;
1998  } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
1999  avio_seek(pb, next, SEEK_SET);
2000  }
2001  if (ctx_size) ctx->type = type;
2002  return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
2003 }
2004 
2005 /**
2006  * Seeks to the previous partition, if possible
2007  * @return <= 0 if we should stop parsing, > 0 if we should keep going
2008  */
2010 {
2011  AVIOContext *pb = mxf->fc->pb;
2012 
2013  if (!mxf->current_partition ||
2015  return 0; /* we've parsed all partitions */
2016 
2017  /* seek to previous partition */
2018  avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
2019  mxf->current_partition = NULL;
2020 
2021  av_dlog(mxf->fc, "seeking to previous partition\n");
2022 
2023  return 1;
2024 }
2025 
2026 /**
2027  * Called when essence is encountered
2028  * @return <= 0 if we should stop parsing, > 0 if we should keep going
2029  */
2031 {
2032  AVIOContext *pb = mxf->fc->pb;
2033  int64_t ret;
2034 
2035  if (mxf->parsing_backward) {
2036  return mxf_seek_to_previous_partition(mxf);
2037  } else {
2038  uint64_t offset = mxf->footer_partition ? mxf->footer_partition
2039  : mxf->last_partition;
2040 
2041  if (!offset) {
2042  av_dlog(mxf->fc, "no last partition\n");
2043  return 0;
2044  }
2045 
2046  av_dlog(mxf->fc, "seeking to last partition\n");
2047 
2048  /* remember where we were so we don't end up seeking further back than this */
2049  mxf->last_forward_tell = avio_tell(pb);
2050 
2051  if (!pb->seekable) {
2052  av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing last partition\n");
2053  return -1;
2054  }
2055 
2056  /* seek to last partition and parse backward */
2057  if ((ret = avio_seek(pb, mxf->run_in + offset, SEEK_SET)) < 0) {
2058  av_log(mxf->fc, AV_LOG_ERROR,
2059  "failed to seek to last partition @ 0x%" PRIx64
2060  " (%"PRId64") - partial file?\n",
2061  mxf->run_in + offset, ret);
2062  return ret;
2063  }
2064 
2065  mxf->current_partition = NULL;
2066  mxf->parsing_backward = 1;
2067  }
2068 
2069  return 1;
2070 }
2071 
2072 /**
2073  * Called when the next partition or EOF is encountered
2074  * @return <= 0 if we should stop parsing, > 0 if we should keep going
2075  */
2077 {
2078  return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
2079 }
2080 
2081 /**
2082  * Figures out the proper offset and length of the essence container in each partition
2083  */
2085 {
2086  int x;
2087 
2088  /* everything is already correct */
2089  if (mxf->op == OPAtom)
2090  return;
2091 
2092  for (x = 0; x < mxf->partitions_count; x++) {
2093  MXFPartition *p = &mxf->partitions[x];
2094 
2095  if (!p->body_sid)
2096  continue; /* BodySID == 0 -> no essence */
2097 
2098  if (x >= mxf->partitions_count - 1)
2099  break; /* last partition - can't compute length (and we don't need to) */
2100 
2101  /* essence container spans to the next partition */
2103 
2104  if (p->essence_length < 0) {
2105  /* next ThisPartition < essence_offset */
2106  p->essence_length = 0;
2107  av_log(mxf->fc, AV_LOG_ERROR,
2108  "partition %i: bad ThisPartition = %"PRIX64"\n",
2109  x+1, mxf->partitions[x+1].this_partition);
2110  }
2111  }
2112 }
2113 
2114 static int64_t round_to_kag(int64_t position, int kag_size)
2115 {
2116  /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
2117  /* NOTE: kag_size may be any integer between 1 - 2^10 */
2118  int64_t ret = (position / kag_size) * kag_size;
2119  return ret == position ? ret : ret + kag_size;
2120 }
2121 
2122 static int is_pcm(enum AVCodecID codec_id)
2123 {
2124  /* we only care about "normal" PCM codecs until we get samples */
2125  return codec_id >= AV_CODEC_ID_PCM_S16LE && codec_id < AV_CODEC_ID_PCM_S24DAUD;
2126 }
2127 
2128 /**
2129  * Deal with the case where for some audio atoms EditUnitByteCount is
2130  * very small (2, 4..). In those cases we should read more than one
2131  * sample per call to mxf_read_packet().
2132  */
2134 {
2135  MXFContext *mxf = s->priv_data;
2136 
2137  /* assuming non-OPAtom == frame wrapped
2138  * no sane writer would wrap 2 byte PCM packets with 20 byte headers.. */
2139  if (mxf->op != OPAtom)
2140  return;
2141 
2142  /* expect PCM with exactly one index table segment and a small (< 32) EUBC */
2143  if (s->nb_streams != 1 ||
2145  !is_pcm(s->streams[0]->codec->codec_id) ||
2146  mxf->nb_index_tables != 1 ||
2147  mxf->index_tables[0].nb_segments != 1 ||
2148  mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32)
2149  return;
2150 
2151  /* arbitrarily default to 48 kHz PAL audio frame size */
2152  /* TODO: We could compute this from the ratio between the audio
2153  * and video edit rates for 48 kHz NTSC we could use the
2154  * 1802-1802-1802-1802-1801 pattern. */
2155  mxf->edit_units_per_packet = 1920;
2156 }
2157 
2159 {
2160  MXFContext *mxf = s->priv_data;
2161  uint32_t length;
2162  int64_t file_size;
2163  KLVPacket klv;
2164 
2165  if (!s->pb->seekable)
2166  return;
2167 
2168  file_size = avio_size(s->pb);
2169  avio_seek(s->pb, file_size - 4, SEEK_SET);
2170  length = avio_rb32(s->pb);
2171  if (length <= 32 || length >= FFMIN(file_size, INT_MAX))
2172  goto end;
2173  avio_seek(s->pb, file_size - length, SEEK_SET);
2174  if (klv_read_packet(&klv, s->pb) < 0 ||
2176  klv.length != length - 20)
2177  goto end;
2178 
2179  avio_skip(s->pb, klv.length - 12);
2180  mxf->last_partition = avio_rb64(s->pb);
2181 
2182 end:
2183  avio_seek(s->pb, mxf->run_in, SEEK_SET);
2184 }
2185 
2187 {
2188  MXFContext *mxf = s->priv_data;
2189  KLVPacket klv;
2190  int64_t essence_offset = 0;
2191  int64_t last_pos = -1;
2192  uint64_t last_pos_index = 1;
2193  int ret;
2194 
2195  mxf->last_forward_tell = INT64_MAX;
2196  mxf->edit_units_per_packet = 1;
2197 
2199  av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
2200  return AVERROR_INVALIDDATA;
2201  }
2202  avio_seek(s->pb, -14, SEEK_CUR);
2203  mxf->fc = s;
2204  mxf->run_in = avio_tell(s->pb);
2205 
2207 
2208  while (!avio_feof(s->pb)) {
2209  const MXFMetadataReadTableEntry *metadata;
2210  if (avio_tell(s->pb) == last_pos) {
2211  av_log(mxf->fc, AV_LOG_ERROR, "MXF structure loop detected\n");
2212  return AVERROR_INVALIDDATA;
2213  }
2214  if ((1ULL<<61) % last_pos_index++ == 0)
2215  last_pos = avio_tell(s->pb);
2216  if (klv_read_packet(&klv, s->pb) < 0) {
2217  /* EOF - seek to previous partition or stop */
2218  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
2219  break;
2220  else
2221  continue;
2222  }
2223 
2224  PRINT_KEY(s, "read header", klv.key);
2225  av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
2230 
2231  if (!mxf->current_partition) {
2232  av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
2233  return AVERROR_INVALIDDATA;
2234  }
2235 
2236  if (!mxf->current_partition->essence_offset) {
2237  /* for OP1a we compute essence_offset
2238  * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
2239  * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
2240  * for OPAtom we still need the actual essence_offset though (the KL's length can vary)
2241  */
2242  int64_t op1a_essence_offset =
2247 
2248  if (mxf->op == OPAtom) {
2249  /* point essence_offset to the actual data
2250  * OPAtom has all the essence in one big KLV
2251  */
2254  } else {
2255  /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */
2256  mxf->current_partition->essence_offset = op1a_essence_offset;
2257  }
2258  }
2259 
2260  if (!essence_offset)
2261  essence_offset = klv.offset;
2262 
2263  /* seek to footer, previous partition or stop */
2264  if (mxf_parse_handle_essence(mxf) <= 0)
2265  break;
2266  continue;
2267  } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
2268  klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
2269  /* next partition pack - keep going, seek to previous partition or stop */
2270  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
2271  break;
2272  else if (mxf->parsing_backward)
2273  continue;
2274  /* we're still parsing forward. proceed to parsing this partition pack */
2275  }
2276 
2277  for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
2278  if (IS_KLV_KEY(klv.key, metadata->key)) {
2279  int res;
2280  if (klv.key[5] == 0x53) {
2281  res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
2282  } else {
2283  uint64_t next = avio_tell(s->pb) + klv.length;
2284  res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
2285 
2286  /* only seek forward, else this can loop for a long time */
2287  if (avio_tell(s->pb) > next) {
2288  av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
2289  klv.offset);
2290  return AVERROR_INVALIDDATA;
2291  }
2292 
2293  avio_seek(s->pb, next, SEEK_SET);
2294  }
2295  if (res < 0) {
2296  av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
2297  ret = res;
2298  goto fail;
2299  }
2300  break;
2301  } else {
2302  av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n",
2303  UID_ARG(klv.key));
2304  }
2305  }
2306  if (!metadata->read)
2307  avio_skip(s->pb, klv.length);
2308  }
2309  /* FIXME avoid seek */
2310  if (!essence_offset) {
2311  av_log(s, AV_LOG_ERROR, "no essence\n");
2312  return AVERROR_INVALIDDATA;
2313  }
2314  avio_seek(s->pb, essence_offset, SEEK_SET);
2315 
2317 
2318  /* we need to do this before computing the index tables
2319  * to be able to fill in zero IndexDurations with st->duration */
2320  if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
2321  goto fail;
2322 
2323  if ((ret = mxf_compute_index_tables(mxf)) < 0)
2324  goto fail;
2325 
2326  if (mxf->nb_index_tables > 1) {
2327  /* TODO: look up which IndexSID to use via EssenceContainerData */
2328  av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
2329  mxf->nb_index_tables, mxf->index_tables[0].index_sid);
2330  } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
2331  av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
2332  ret = AVERROR_INVALIDDATA;
2333  goto fail;
2334  }
2335 
2337 
2338  return 0;
2339 fail:
2340  mxf_read_close(s);
2341 
2342  return ret;
2343 }
2344 
2345 /**
2346  * Sets mxf->current_edit_unit based on what offset we're currently at.
2347  * @return next_ofs if OK, <0 on error
2348  */
2349 static int64_t mxf_set_current_edit_unit(MXFContext *mxf, int64_t current_offset)
2350 {
2351  int64_t last_ofs = -1, next_ofs = -1;
2352  MXFIndexTable *t = &mxf->index_tables[0];
2353 
2354  /* this is called from the OP1a demuxing logic, which means there
2355  * may be no index tables */
2356  if (mxf->nb_index_tables <= 0)
2357  return -1;
2358 
2359  /* find mxf->current_edit_unit so that the next edit unit starts ahead of current_offset */
2360  while (mxf->current_edit_unit >= 0) {
2361  if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0)
2362  return -1;
2363 
2364  if (next_ofs <= last_ofs) {
2365  /* large next_ofs didn't change or current_edit_unit wrapped
2366  * around this fixes the infinite loop on zzuf3.mxf */
2367  av_log(mxf->fc, AV_LOG_ERROR,
2368  "next_ofs didn't change. not deriving packet timestamps\n");
2369  return -1;
2370  }
2371 
2372  if (next_ofs > current_offset)
2373  break;
2374 
2375  last_ofs = next_ofs;
2376  mxf->current_edit_unit++;
2377  }
2378 
2379  /* not checking mxf->current_edit_unit >= t->nb_ptses here since CBR files may lack IndexEntryArrays */
2380  if (mxf->current_edit_unit < 0)
2381  return -1;
2382 
2383  return next_ofs;
2384 }
2385 
2386 static int mxf_compute_sample_count(MXFContext *mxf, int stream_index,
2387  uint64_t *sample_count)
2388 {
2389  int i, total = 0, size = 0;
2390  AVStream *st = mxf->fc->streams[stream_index];
2391  MXFTrack *track = st->priv_data;
2392  AVRational time_base = av_inv_q(track->edit_rate);
2394  const MXFSamplesPerFrame *spf = NULL;
2395 
2396  if ((sample_rate.num / sample_rate.den) == 48000)
2397  spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base);
2398  if (!spf) {
2399  int remainder = (sample_rate.num * time_base.num) %
2400  (time_base.den * sample_rate.den);
2401  *sample_count = av_q2d(av_mul_q((AVRational){mxf->current_edit_unit, 1},
2402  av_mul_q(sample_rate, time_base)));
2403  if (remainder)
2404  av_log(mxf->fc, AV_LOG_WARNING,
2405  "seeking detected on stream #%d with time base (%d/%d) and "
2406  "sample rate (%d/%d), audio pts won't be accurate.\n",
2407  stream_index, time_base.num, time_base.den,
2408  sample_rate.num, sample_rate.den);
2409  return 0;
2410  }
2411 
2412  while (spf->samples_per_frame[size]) {
2413  total += spf->samples_per_frame[size];
2414  size++;
2415  }
2416 
2417  av_assert2(size);
2418 
2419  *sample_count = (mxf->current_edit_unit / size) * (uint64_t)total;
2420  for (i = 0; i < mxf->current_edit_unit % size; i++) {
2421  *sample_count += spf->samples_per_frame[i];
2422  }
2423 
2424  return 0;
2425 }
2426 
2428  AVPacket *pkt)
2429 {
2430  MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data;
2431  int64_t bits_per_sample = codec->bits_per_coded_sample;
2432 
2433  if (!bits_per_sample)
2434  bits_per_sample = av_get_bits_per_sample(codec->codec_id);
2435 
2436  pkt->pts = track->sample_count;
2437 
2438  if ( codec->channels <= 0
2439  || bits_per_sample <= 0
2440  || codec->channels * (int64_t)bits_per_sample < 8)
2441  return AVERROR(EINVAL);
2442  track->sample_count += pkt->size / (codec->channels * (int64_t)bits_per_sample / 8);
2443  return 0;
2444 }
2445 
2447 {
2448  KLVPacket klv;
2449  MXFContext *mxf = s->priv_data;
2450  int ret;
2451 
2452  while ((ret = klv_read_packet(&klv, s->pb)) == 0) {
2453  PRINT_KEY(s, "read packet", klv.key);
2454  av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
2456  ret = mxf_decrypt_triplet(s, pkt, &klv);
2457  if (ret < 0) {
2458  av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
2459  return ret;
2460  }
2461  return 0;
2462  }
2465  int index = mxf_get_stream_index(s, &klv);
2466  int64_t next_ofs, next_klv;
2467  AVStream *st;
2468  MXFTrack *track;
2469  AVCodecContext *codec;
2470 
2471  if (index < 0) {
2472  av_log(s, AV_LOG_ERROR,
2473  "error getting stream index %"PRIu32"\n",
2474  AV_RB32(klv.key + 12));
2475  goto skip;
2476  }
2477 
2478  st = s->streams[index];
2479  track = st->priv_data;
2480 
2481  if (s->streams[index]->discard == AVDISCARD_ALL)
2482  goto skip;
2483 
2484  next_klv = avio_tell(s->pb) + klv.length;
2485  next_ofs = mxf_set_current_edit_unit(mxf, klv.offset);
2486 
2487  if (next_ofs >= 0 && next_klv > next_ofs) {
2488  /* if this check is hit then it's possible OPAtom was treated as OP1a
2489  * truncate the packet since it's probably very large (>2 GiB is common) */
2491  "OPAtom misinterpreted as OP1a?"
2492  "KLV for edit unit %i extending into "
2493  "next edit unit",
2494  mxf->current_edit_unit);
2495  klv.length = next_ofs - avio_tell(s->pb);
2496  }
2497 
2498  /* check for 8 channels AES3 element */
2499  if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
2500  ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
2501  pkt, klv.length);
2502  if (ret < 0) {
2503  av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
2504  return ret;
2505  }
2506  } else {
2507  ret = av_get_packet(s->pb, pkt, klv.length);
2508  if (ret < 0)
2509  return ret;
2510  }
2511  pkt->stream_index = index;
2512  pkt->pos = klv.offset;
2513 
2514  codec = s->streams[index]->codec;
2515 
2516  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
2517  /* mxf->current_edit_unit good - see if we have an
2518  * index table to derive timestamps from */
2519  MXFIndexTable *t = &mxf->index_tables[0];
2520 
2521  if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) {
2522  pkt->dts = mxf->current_edit_unit + t->first_dts;
2523  pkt->pts = t->ptses[mxf->current_edit_unit];
2524  } else if (track->intra_only) {
2525  /* intra-only -> PTS = EditUnit.
2526  * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
2527  pkt->pts = mxf->current_edit_unit;
2528  }
2529  } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2530  ret = mxf_set_audio_pts(mxf, codec, pkt);
2531  if (ret < 0)
2532  return ret;
2533  }
2534 
2535  /* seek for truncated packets */
2536  avio_seek(s->pb, next_klv, SEEK_SET);
2537 
2538  return 0;
2539  } else
2540  skip:
2541  avio_skip(s->pb, klv.length);
2542  }
2543  return avio_feof(s->pb) ? AVERROR_EOF : ret;
2544 }
2545 
2547 {
2548  MXFContext *mxf = s->priv_data;
2549  int ret, size;
2550  int64_t ret64, pos, next_pos;
2551  AVStream *st;
2552  MXFIndexTable *t;
2553  int edit_units;
2554 
2555  if (mxf->op != OPAtom)
2556  return mxf_read_packet_old(s, pkt);
2557 
2558  /* OPAtom - clip wrapped demuxing */
2559  /* NOTE: mxf_read_header() makes sure nb_index_tables > 0 for OPAtom */
2560  st = s->streams[0];
2561  t = &mxf->index_tables[0];
2562 
2563  if (mxf->current_edit_unit >= st->duration)
2564  return AVERROR_EOF;
2565 
2566  edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit);
2567 
2568  if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0)
2569  return ret;
2570 
2571  /* compute size by finding the next edit unit or the end of the essence container
2572  * not pretty, but it works */
2573  if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 &&
2574  (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
2575  av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
2576  return AVERROR_INVALIDDATA;
2577  }
2578 
2579  if ((size = next_pos - pos) <= 0) {
2580  av_log(s, AV_LOG_ERROR, "bad size: %i\n", size);
2581  return AVERROR_INVALIDDATA;
2582  }
2583 
2584  if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0)
2585  return ret64;
2586 
2587  if ((size = av_get_packet(s->pb, pkt, size)) < 0)
2588  return size;
2589 
2590  pkt->stream_index = 0;
2591 
2592  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
2593  mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
2594  pkt->dts = mxf->current_edit_unit + t->first_dts;
2595  pkt->pts = t->ptses[mxf->current_edit_unit];
2596  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2597  int ret = mxf_set_audio_pts(mxf, st->codec, pkt);
2598  if (ret < 0)
2599  return ret;
2600  }
2601 
2602  mxf->current_edit_unit += edit_units;
2603 
2604  return 0;
2605 }
2606 
2608 {
2609  MXFContext *mxf = s->priv_data;
2610  MXFIndexTableSegment *seg;
2611  int i;
2612 
2613  av_freep(&mxf->packages_refs);
2614 
2615  for (i = 0; i < s->nb_streams; i++)
2616  s->streams[i]->priv_data = NULL;
2617 
2618  for (i = 0; i < mxf->metadata_sets_count; i++) {
2619  switch (mxf->metadata_sets[i]->type) {
2620  case Descriptor:
2621  av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->extradata);
2622  break;
2623  case MultipleDescriptor:
2624  av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
2625  break;
2626  case Sequence:
2627  av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
2628  break;
2629  case SourcePackage:
2630  case MaterialPackage:
2631  av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
2632  av_freep(&((MXFPackage *)mxf->metadata_sets[i])->name);
2633  break;
2634  case IndexTableSegment:
2635  seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
2637  av_freep(&seg->flag_entries);
2639  break;
2640  default:
2641  break;
2642  }
2643  av_freep(&mxf->metadata_sets[i]);
2644  }
2645  av_freep(&mxf->partitions);
2646  av_freep(&mxf->metadata_sets);
2647  av_freep(&mxf->aesc);
2648  av_freep(&mxf->local_tags);
2649 
2650  if (mxf->index_tables) {
2651  for (i = 0; i < mxf->nb_index_tables; i++) {
2652  av_freep(&mxf->index_tables[i].segments);
2653  av_freep(&mxf->index_tables[i].ptses);
2654  av_freep(&mxf->index_tables[i].fake_index);
2655  }
2656  }
2657  av_freep(&mxf->index_tables);
2658 
2659  return 0;
2660 }
2661 
2662 static int mxf_probe(AVProbeData *p) {
2663  const uint8_t *bufp = p->buf;
2664  const uint8_t *end = p->buf + p->buf_size;
2665 
2666  if (p->buf_size < sizeof(mxf_header_partition_pack_key))
2667  return 0;
2668 
2669  /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
2670  end -= sizeof(mxf_header_partition_pack_key);
2671 
2672  for (; bufp < end;) {
2673  if (!((bufp[13] - 1) & 0xF2)){
2674  if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) &&
2675  AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) &&
2676  AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) &&
2678  return AVPROBE_SCORE_MAX;
2679  bufp ++;
2680  } else
2681  bufp += 10;
2682  }
2683 
2684  return 0;
2685 }
2686 
2687 /* rudimentary byte seek */
2688 /* XXX: use MXF Index */
2689 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2690 {
2691  AVStream *st = s->streams[stream_index];
2692  int64_t seconds;
2693  MXFContext* mxf = s->priv_data;
2694  int64_t seekpos;
2695  int i, ret;
2696  MXFIndexTable *t;
2697  MXFTrack *source_track = st->priv_data;
2698 
2699  /* if audio then truncate sample_time to EditRate */
2700  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2701  sample_time = av_rescale_q(sample_time, st->time_base,
2702  av_inv_q(source_track->edit_rate));
2703 
2704  if (mxf->nb_index_tables <= 0) {
2705  if (!s->bit_rate)
2706  return AVERROR_INVALIDDATA;
2707  if (sample_time < 0)
2708  sample_time = 0;
2709  seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
2710 
2711  seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
2712  if (seekpos < 0)
2713  return seekpos;
2714 
2715  ff_update_cur_dts(s, st, sample_time);
2716  mxf->current_edit_unit = sample_time;
2717  } else {
2718  t = &mxf->index_tables[0];
2719 
2720  /* clamp above zero, else ff_index_search_timestamp() returns negative
2721  * this also means we allow seeking before the start */
2722  sample_time = FFMAX(sample_time, 0);
2723 
2724  if (t->fake_index) {
2725  /* behave as if we have a proper index */
2726  if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
2727  return sample_time;
2728  } else {
2729  /* no IndexEntryArray (one or more CBR segments)
2730  * make sure we don't seek past the end */
2731  sample_time = FFMIN(sample_time, source_track->original_duration - 1);
2732  }
2733 
2734  if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) < 0)
2735  return ret;
2736 
2737  ff_update_cur_dts(s, st, sample_time);
2738  mxf->current_edit_unit = sample_time;
2739  avio_seek(s->pb, seekpos, SEEK_SET);
2740  }
2741 
2742  // Update all tracks sample count
2743  for (i = 0; i < s->nb_streams; i++) {
2744  AVStream *cur_st = s->streams[i];
2745  MXFTrack *cur_track = cur_st->priv_data;
2746  uint64_t current_sample_count = 0;
2747  if (cur_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2748  ret = mxf_compute_sample_count(mxf, i, &current_sample_count);
2749  if (ret < 0)
2750  return ret;
2751 
2752  cur_track->sample_count = current_sample_count;
2753  }
2754  }
2755  return 0;
2756 }
2757 
2759  .name = "mxf",
2760  .long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
2761  .priv_data_size = sizeof(MXFContext),
2762  .read_probe = mxf_probe,
2767 };