FFmpeg
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  * SMPTE 2067-21 Interoperable Master Format — Application #2E
32  *
33  * Principle
34  * Search for Track numbers which will identify essence element KLV packets.
35  * Search for SourcePackage which define tracks which contains Track numbers.
36  * Material Package contains tracks with reference to SourcePackage tracks.
37  * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
38  * Assign Descriptors to correct Tracks.
39  *
40  * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
41  * Metadata parsing resolves Strong References to objects.
42  *
43  * Simple demuxer, only OP1A supported and some files might not work at all.
44  * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
45  */
46 
47 #include <inttypes.h>
48 
49 #include "libavutil/aes.h"
50 #include "libavutil/avstring.h"
52 #include "libavutil/mathematics.h"
53 #include "libavcodec/bytestream.h"
54 #include "libavutil/intreadwrite.h"
55 #include "libavutil/parseutils.h"
56 #include "libavutil/timecode.h"
57 #include "libavutil/opt.h"
58 #include "avformat.h"
59 #include "internal.h"
60 #include "mxf.h"
61 
62 #define MXF_MAX_CHUNK_SIZE (32 << 20)
63 
64 typedef enum {
69 
70 typedef enum {
71  OP1a = 1,
81  OPSONYOpt, /* FATE sample, violates the spec in places */
82 } MXFOP;
83 
84 typedef enum {
89 
90 typedef struct MXFPartition {
91  int closed;
92  int complete;
95  int index_sid;
96  int body_sid;
97  int64_t this_partition;
98  int64_t essence_offset; ///< absolute offset of essence
99  int64_t essence_length;
104  int64_t pack_ofs; ///< absolute offset of pack in file, including run-in
105  int64_t body_offset;
107 } MXFPartition;
108 
109 typedef struct MXFMetadataSet {
111  uint64_t partition_score;
114 
115 typedef struct MXFCryptoContext {
119 
120 typedef struct MXFStructuralComponent {
125  int64_t duration;
126  int64_t start_position;
129 
130 typedef struct MXFSequence {
135  int64_t duration;
136  uint8_t origin;
137 } MXFSequence;
138 
139 typedef struct MXFTimecodeComponent {
143  struct AVRational rate;
146 
147 typedef struct {
151 
152 typedef struct {
156  int64_t duration;
158 
159 typedef struct {
161  char *name;
162  char *value;
164 
165 typedef struct {
167  MXFSequence *sequence; /* mandatory, and only one */
169  int track_id;
170  char *name;
171  uint8_t track_number[4];
174  uint64_t sample_count;
175  int64_t original_duration; /* st->duration in SampleRate/EditRate units */
177  int body_sid;
179  int edit_units_per_packet; /* how many edit units to read at a time (PCM, ClipWrapped) */
180 } MXFTrack;
181 
182 typedef struct MXFDescriptor {
189  int width;
190  int height; /* Field height, not frame height */
191  int frame_layout; /* See MXFFrameLayout enum */
193 #define MXF_FIELD_DOMINANCE_DEFAULT 0
194 #define MXF_FIELD_DOMINANCE_FF 1 /* coded first, displayed first */
195 #define MXF_FIELD_DOMINANCE_FL 2 /* coded first, displayed last */
197  int channels;
199  int64_t duration; /* ContainerDuration optional property */
200  unsigned int component_depth;
201  unsigned int black_ref_level;
202  unsigned int white_ref_level;
203  unsigned int color_range;
204  unsigned int horiz_subsampling;
205  unsigned int vert_subsampling;
209  uint8_t *extradata;
217  size_t coll_size;
218 } MXFDescriptor;
219 
220 typedef struct MXFIndexTableSegment {
224  int body_sid;
227  uint64_t index_duration;
233 
234 typedef struct MXFPackage {
240  MXFDescriptor *descriptor; /* only one */
242  char *name;
245 } MXFPackage;
246 
247 typedef struct MXFEssenceContainerData {
252  int body_sid;
254 
255 /* decoded index table */
256 typedef struct MXFIndexTable {
258  int body_sid;
259  int nb_ptses; /* number of PTSes or total duration of index */
260  int64_t first_dts; /* DTS = EditUnit + first_dts */
261  int64_t *ptses; /* maps EditUnit -> PTS */
263  MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
264  AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
265  int8_t *offsets; /* temporal offsets for display order to stored order conversion */
266 } MXFIndexTable;
267 
268 typedef struct MXFContext {
269  const AVClass *class; /**< Class for private options. */
280  struct AVAES *aesc;
281  uint8_t *local_tags;
285  int run_in;
293 } MXFContext;
294 
295 /* NOTE: klv_offset is not set (-1) for local keys */
296 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
297 
299  const UID key;
301  int ctx_size;
304 
305 /* partial keys to match */
306 static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
307 static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
308 static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
309 static const uint8_t mxf_canopus_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x0a,0x0e,0x0f,0x03,0x01 };
310 static const uint8_t mxf_system_item_key_cp[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 };
311 static const uint8_t mxf_system_item_key_gc[] = { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x03,0x01,0x14 };
312 static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
313 static const uint8_t mxf_apple_coll_prefix[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x0e,0x20,0x04,0x01,0x05,0x03,0x01 };
314 /* complete keys to match */
315 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 };
316 static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
317 static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
318 static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
319 static const uint8_t mxf_avid_project_name[] = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf };
320 static const uint8_t mxf_jp2k_rsiz[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0a,0x04,0x01,0x06,0x03,0x01,0x00,0x00,0x00 };
321 static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
322 static const uint8_t mxf_indirect_value_utf16be[] = { 0x42,0x01,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
323 static const uint8_t mxf_apple_coll_max_cll[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x0e,0x20,0x04,0x01,0x05,0x03,0x01,0x01 };
324 static const uint8_t mxf_apple_coll_max_fall[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x0e,0x20,0x04,0x01,0x05,0x03,0x01,0x02 };
325 
327 static const uint8_t mxf_mastering_display_uls[4][16] = {
332 };
333 
334 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
335 
336 static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx)
337 {
339  switch ((*ctx)->type) {
340  case Descriptor:
341  case MultipleDescriptor:
342  av_freep(&((MXFDescriptor *)*ctx)->extradata);
343  av_freep(&((MXFDescriptor *)*ctx)->mastering);
344  av_freep(&((MXFDescriptor *)*ctx)->coll);
345  av_freep(&((MXFDescriptor *)*ctx)->sub_descriptors_refs);
346  break;
347  case Sequence:
348  av_freep(&((MXFSequence *)*ctx)->structural_components_refs);
349  break;
350  case EssenceGroup:
351  av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs);
352  break;
353  case SourcePackage:
354  case MaterialPackage:
355  av_freep(&((MXFPackage *)*ctx)->tracks_refs);
356  av_freep(&((MXFPackage *)*ctx)->name);
357  av_freep(&((MXFPackage *)*ctx)->comment_refs);
358  break;
359  case TaggedValue:
360  av_freep(&((MXFTaggedValue *)*ctx)->name);
361  av_freep(&((MXFTaggedValue *)*ctx)->value);
362  break;
363  case Track:
364  av_freep(&((MXFTrack *)*ctx)->name);
365  break;
366  case IndexTableSegment:
367  seg = (MXFIndexTableSegment *)*ctx;
369  av_freep(&seg->flag_entries);
371  default:
372  break;
373  }
374  if (freectx) {
375  av_freep(ctx);
376  }
377 }
378 
380 {
381  uint64_t size = avio_r8(pb);
382  if (size & 0x80) { /* long form */
383  int bytes_num = size & 0x7f;
384  /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
385  if (bytes_num > 8)
386  return AVERROR_INVALIDDATA;
387  size = 0;
388  while (bytes_num--)
389  size = size << 8 | avio_r8(pb);
390  }
391  if (size > INT64_MAX)
392  return AVERROR_INVALIDDATA;
393  return size;
394 }
395 
396 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
397 {
398  int i, b;
399  for (i = 0; i < size && !avio_feof(pb); i++) {
400  b = avio_r8(pb);
401  if (b == key[0])
402  i = 0;
403  else if (b != key[i])
404  i = -1;
405  }
406  return i == size;
407 }
408 
409 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
410 {
411  int64_t length, pos;
412  if (!mxf_read_sync(pb, mxf_klv_key, 4))
413  return AVERROR_INVALIDDATA;
414  klv->offset = avio_tell(pb) - 4;
415  memcpy(klv->key, mxf_klv_key, 4);
416  avio_read(pb, klv->key + 4, 12);
417  length = klv_decode_ber_length(pb);
418  if (length < 0)
419  return length;
420  klv->length = length;
421  pos = avio_tell(pb);
422  if (pos > INT64_MAX - length)
423  return AVERROR_INVALIDDATA;
424  klv->next_klv = pos + length;
425  return 0;
426 }
427 
428 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv, int body_sid)
429 {
430  int i;
431 
432  for (i = 0; i < s->nb_streams; i++) {
433  MXFTrack *track = s->streams[i]->priv_data;
434  /* SMPTE 379M 7.3 */
435  if (track && (!body_sid || !track->body_sid || track->body_sid == body_sid) && !memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
436  return i;
437  }
438  /* return 0 if only one stream, for OP Atom files with 0 as track number */
439  return s->nb_streams == 1 && s->streams[0]->priv_data ? 0 : -1;
440 }
441 
443 {
444  // we look for partition where the offset is placed
445  int a, b, m;
446  int64_t pack_ofs;
447 
448  a = -1;
449  b = mxf->partitions_count;
450 
451  while (b - a > 1) {
452  m = (a + b) >> 1;
453  pack_ofs = mxf->partitions[m].pack_ofs;
454  if (pack_ofs <= offset)
455  a = m;
456  else
457  b = m;
458  }
459 
460  if (a == -1)
461  return 0;
462  return mxf->partitions[a].body_sid;
463 }
464 
465 static int mxf_get_eia608_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt, int64_t length)
466 {
467  int count = avio_rb16(s->pb);
468  int cdp_identifier, cdp_length, cdp_footer_id, ccdata_id, cc_count;
469  int line_num, sample_coding, sample_count;
470  int did, sdid, data_length;
471  int i, ret;
472 
473  if (count != 1)
474  av_log(s, AV_LOG_WARNING, "unsupported multiple ANC packets (%d) per KLV packet\n", count);
475 
476  for (i = 0; i < count; i++) {
477  if (length < 6) {
478  av_log(s, AV_LOG_ERROR, "error reading s436m packet %"PRId64"\n", length);
479  return AVERROR_INVALIDDATA;
480  }
481  line_num = avio_rb16(s->pb);
482  avio_r8(s->pb); // wrapping type
483  sample_coding = avio_r8(s->pb);
484  sample_count = avio_rb16(s->pb);
485  length -= 6 + 8 + sample_count;
486  if (line_num != 9 && line_num != 11)
487  continue;
488  if (sample_coding == 7 || sample_coding == 8 || sample_coding == 9) {
489  av_log(s, AV_LOG_WARNING, "unsupported s436m 10 bit sample coding\n");
490  continue;
491  }
492  if (length < 0)
493  return AVERROR_INVALIDDATA;
494 
495  avio_rb32(s->pb); // array count
496  avio_rb32(s->pb); // array elem size
497  did = avio_r8(s->pb);
498  sdid = avio_r8(s->pb);
499  data_length = avio_r8(s->pb);
500  if (did != 0x61 || sdid != 1) {
501  av_log(s, AV_LOG_WARNING, "unsupported did or sdid: %x %x\n", did, sdid);
502  continue;
503  }
504  cdp_identifier = avio_rb16(s->pb); // cdp id
505  if (cdp_identifier != 0x9669) {
506  av_log(s, AV_LOG_ERROR, "wrong cdp identifier %x\n", cdp_identifier);
507  return AVERROR_INVALIDDATA;
508  }
509  cdp_length = avio_r8(s->pb);
510  avio_r8(s->pb); // cdp_frame_rate
511  avio_r8(s->pb); // cdp_flags
512  avio_rb16(s->pb); // cdp_hdr_sequence_cntr
513  ccdata_id = avio_r8(s->pb); // ccdata_id
514  if (ccdata_id != 0x72) {
515  av_log(s, AV_LOG_ERROR, "wrong cdp data section %x\n", ccdata_id);
516  return AVERROR_INVALIDDATA;
517  }
518  cc_count = avio_r8(s->pb) & 0x1f;
519  ret = av_get_packet(s->pb, pkt, cc_count * 3);
520  if (ret < 0)
521  return ret;
522  if (cdp_length - 9 - 4 < cc_count * 3) {
523  av_log(s, AV_LOG_ERROR, "wrong cdp size %d cc count %d\n", cdp_length, cc_count);
524  return AVERROR_INVALIDDATA;
525  }
526  avio_skip(s->pb, data_length - 9 - 4 - cc_count * 3);
527  cdp_footer_id = avio_r8(s->pb);
528  if (cdp_footer_id != 0x74) {
529  av_log(s, AV_LOG_ERROR, "wrong cdp footer section %x\n", cdp_footer_id);
530  return AVERROR_INVALIDDATA;
531  }
532  avio_rb16(s->pb); // cdp_ftr_sequence_cntr
533  avio_r8(s->pb); // packet_checksum
534  break;
535  }
536 
537  return 0;
538 }
539 
540 /* XXX: use AVBitStreamFilter */
541 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
542 {
543  const uint8_t *buf_ptr, *end_ptr;
544  uint8_t *data_ptr;
545  int i;
546 
547  if (length > 61444) /* worst case PAL 1920 samples 8 channels */
548  return AVERROR_INVALIDDATA;
549  length = av_get_packet(pb, pkt, length);
550  if (length < 0)
551  return length;
552  data_ptr = pkt->data;
553  end_ptr = pkt->data + length;
554  buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
555 
556  if (st->codecpar->channels > 8)
557  return AVERROR_INVALIDDATA;
558 
559  for (; end_ptr - buf_ptr >= st->codecpar->channels * 4; ) {
560  for (i = 0; i < st->codecpar->channels; i++) {
561  uint32_t sample = bytestream_get_le32(&buf_ptr);
562  if (st->codecpar->bits_per_coded_sample == 24)
563  bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
564  else
565  bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
566  }
567  buf_ptr += 32 - st->codecpar->channels*4; // always 8 channels stored SMPTE 331M
568  }
569  av_shrink_packet(pkt, data_ptr - pkt->data);
570  return 0;
571 }
572 
574 {
575  static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
576  MXFContext *mxf = s->priv_data;
577  AVIOContext *pb = s->pb;
578  int64_t end = avio_tell(pb) + klv->length;
579  int64_t size;
580  uint64_t orig_size;
581  uint64_t plaintext_size;
582  uint8_t ivec[16];
583  uint8_t tmpbuf[16];
584  int index;
585  int body_sid;
586 
587  if (!mxf->aesc && s->key && s->keylen == 16) {
588  mxf->aesc = av_aes_alloc();
589  if (!mxf->aesc)
590  return AVERROR(ENOMEM);
591  av_aes_init(mxf->aesc, s->key, 128, 1);
592  }
593  // crypto context
595  if (size < 0)
596  return size;
597  avio_skip(pb, size);
598  // plaintext offset
600  plaintext_size = avio_rb64(pb);
601  // source klv key
603  avio_read(pb, klv->key, 16);
605  return AVERROR_INVALIDDATA;
606 
607  body_sid = find_body_sid_by_absolute_offset(mxf, klv->offset);
608  index = mxf_get_stream_index(s, klv, body_sid);
609  if (index < 0)
610  return AVERROR_INVALIDDATA;
611  // source size
613  orig_size = avio_rb64(pb);
614  if (orig_size < plaintext_size)
615  return AVERROR_INVALIDDATA;
616  // enc. code
618  if (size < 32 || size - 32 < orig_size || (int)orig_size != orig_size)
619  return AVERROR_INVALIDDATA;
620  avio_read(pb, ivec, 16);
621  avio_read(pb, tmpbuf, 16);
622  if (mxf->aesc)
623  av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
624  if (memcmp(tmpbuf, checkv, 16))
625  av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
626  size -= 32;
627  size = av_get_packet(pb, pkt, size);
628  if (size < 0)
629  return size;
630  else if (size < plaintext_size)
631  return AVERROR_INVALIDDATA;
632  size -= plaintext_size;
633  if (mxf->aesc)
634  av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
635  &pkt->data[plaintext_size], size >> 4, ivec, 1);
636  av_shrink_packet(pkt, orig_size);
638  avio_skip(pb, end - avio_tell(pb));
639  return 0;
640 }
641 
642 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
643 {
644  MXFContext *mxf = arg;
645  int item_num = avio_rb32(pb);
646  int item_len = avio_rb32(pb);
647 
648  if (item_len != 18) {
649  avpriv_request_sample(pb, "Primer pack item length %d", item_len);
650  return AVERROR_PATCHWELCOME;
651  }
652  if (item_num > 65536 || item_num < 0) {
653  av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num);
654  return AVERROR_INVALIDDATA;
655  }
656  if (mxf->local_tags)
657  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n");
658  av_free(mxf->local_tags);
659  mxf->local_tags_count = 0;
660  mxf->local_tags = av_calloc(item_num, item_len);
661  if (!mxf->local_tags)
662  return AVERROR(ENOMEM);
663  mxf->local_tags_count = item_num;
664  avio_read(pb, mxf->local_tags, item_num*item_len);
665  return 0;
666 }
667 
668 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
669 {
670  MXFContext *mxf = arg;
671  AVFormatContext *s = mxf->fc;
672  MXFPartition *partition, *tmp_part;
673  UID op;
674  uint64_t footer_partition;
675  uint32_t nb_essence_containers;
676 
677  if (mxf->partitions_count >= INT_MAX / 2)
678  return AVERROR_INVALIDDATA;
679 
680  tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions));
681  if (!tmp_part)
682  return AVERROR(ENOMEM);
683  mxf->partitions = tmp_part;
684 
685  if (mxf->parsing_backward) {
686  /* insert the new partition pack in the middle
687  * this makes the entries in mxf->partitions sorted by offset */
688  memmove(&mxf->partitions[mxf->last_forward_partition+1],
690  (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
691  partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
692  } else {
693  mxf->last_forward_partition++;
694  partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
695  }
696 
697  memset(partition, 0, sizeof(*partition));
698  mxf->partitions_count++;
699  partition->pack_length = avio_tell(pb) - klv_offset + size;
700  partition->pack_ofs = klv_offset;
701 
702  switch(uid[13]) {
703  case 2:
704  partition->type = Header;
705  break;
706  case 3:
707  partition->type = BodyPartition;
708  break;
709  case 4:
710  partition->type = Footer;
711  break;
712  default:
713  av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
714  return AVERROR_INVALIDDATA;
715  }
716 
717  /* consider both footers to be closed (there is only Footer and CompleteFooter) */
718  partition->closed = partition->type == Footer || !(uid[14] & 1);
719  partition->complete = uid[14] > 2;
720  avio_skip(pb, 4);
721  partition->kag_size = avio_rb32(pb);
722  partition->this_partition = avio_rb64(pb);
723  partition->previous_partition = avio_rb64(pb);
724  footer_partition = avio_rb64(pb);
725  partition->header_byte_count = avio_rb64(pb);
726  partition->index_byte_count = avio_rb64(pb);
727  partition->index_sid = avio_rb32(pb);
728  partition->body_offset = avio_rb64(pb);
729  partition->body_sid = avio_rb32(pb);
730  if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) {
731  av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n");
732  return AVERROR_INVALIDDATA;
733  }
734  nb_essence_containers = avio_rb32(pb);
735 
736  if (partition->type == Header) {
737  char str[36];
738  snprintf(str, sizeof(str), "%08x.%08x.%08x.%08x", AV_RB32(&op[0]), AV_RB32(&op[4]), AV_RB32(&op[8]), AV_RB32(&op[12]));
739  av_dict_set(&s->metadata, "operational_pattern_ul", str, 0);
740  }
741 
742  if (partition->this_partition &&
743  partition->previous_partition == partition->this_partition) {
744  av_log(mxf->fc, AV_LOG_ERROR,
745  "PreviousPartition equal to ThisPartition %"PRIx64"\n",
746  partition->previous_partition);
747  /* override with the actual previous partition offset */
748  if (!mxf->parsing_backward && mxf->last_forward_partition > 1) {
749  MXFPartition *prev =
750  mxf->partitions + mxf->last_forward_partition - 2;
751  partition->previous_partition = prev->this_partition;
752  }
753  /* if no previous body partition are found point to the header
754  * partition */
755  if (partition->previous_partition == partition->this_partition)
756  partition->previous_partition = 0;
757  av_log(mxf->fc, AV_LOG_ERROR,
758  "Overriding PreviousPartition with %"PRIx64"\n",
759  partition->previous_partition);
760  }
761 
762  /* some files don't have FooterPartition set in every partition */
763  if (footer_partition) {
764  if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
765  av_log(mxf->fc, AV_LOG_ERROR,
766  "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
767  mxf->footer_partition, footer_partition);
768  } else {
769  mxf->footer_partition = footer_partition;
770  }
771  }
772 
773  av_log(mxf->fc, AV_LOG_TRACE,
774  "PartitionPack: ThisPartition = 0x%"PRIX64
775  ", PreviousPartition = 0x%"PRIX64", "
776  "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
777  partition->this_partition,
778  partition->previous_partition, footer_partition,
779  partition->index_sid, partition->body_sid);
780 
781  /* sanity check PreviousPartition if set */
782  //NOTE: this isn't actually enough, see mxf_seek_to_previous_partition()
783  if (partition->previous_partition &&
784  mxf->run_in + partition->previous_partition >= klv_offset) {
785  av_log(mxf->fc, AV_LOG_ERROR,
786  "PreviousPartition points to this partition or forward\n");
787  return AVERROR_INVALIDDATA;
788  }
789 
790  if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
791  else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
792  else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
793  else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
794  else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
795  else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
796  else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
797  else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
798  else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
799  else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
800  else if (op[12] == 0x10) {
801  /* SMPTE 390m: "There shall be exactly one essence container"
802  * The following block deals with files that violate this, namely:
803  * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
804  * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
805  if (nb_essence_containers != 1) {
806  MXFOP op = nb_essence_containers ? OP1a : OPAtom;
807 
808  /* only nag once */
809  if (!mxf->op)
810  av_log(mxf->fc, AV_LOG_WARNING,
811  "\"OPAtom\" with %"PRIu32" ECs - assuming %s\n",
812  nb_essence_containers,
813  op == OP1a ? "OP1a" : "OPAtom");
814 
815  mxf->op = op;
816  } else
817  mxf->op = OPAtom;
818  } else {
819  av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
820  mxf->op = OP1a;
821  }
822 
823  if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
824  av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ",
825  partition->kag_size);
826 
827  if (mxf->op == OPSONYOpt)
828  partition->kag_size = 512;
829  else
830  partition->kag_size = 1;
831 
832  av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size);
833  }
834 
835  return 0;
836 }
837 
838 static uint64_t partition_score(MXFPartition *p)
839 {
840  uint64_t score;
841  if (!p)
842  return 0;
843  if (p->type == Footer)
844  score = 5;
845  else if (p->complete)
846  score = 4;
847  else if (p->closed)
848  score = 3;
849  else
850  score = 1;
851  return (score << 60) | ((uint64_t)p->this_partition >> 4);
852 }
853 
854 static int mxf_add_metadata_set(MXFContext *mxf, MXFMetadataSet **metadata_set)
855 {
857  enum MXFMetadataSetType type = (*metadata_set)->type;
858 
859  // Index Table is special because it might be added manually without
860  // partition and we iterate thorugh all instances of them. Also some files
861  // use the same Instance UID for different index tables...
862  if (type != IndexTableSegment) {
863  for (int i = 0; i < mxf->metadata_sets_count; i++) {
864  if (!memcmp((*metadata_set)->uid, mxf->metadata_sets[i]->uid, 16) && type == mxf->metadata_sets[i]->type) {
865  uint64_t old_s = mxf->metadata_sets[i]->partition_score;
866  uint64_t new_s = (*metadata_set)->partition_score;
867  if (old_s > new_s) {
868  mxf_free_metadataset(metadata_set, 1);
869  return 0;
870  }
871  }
872  }
873  }
874  tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets));
875  if (!tmp) {
876  mxf_free_metadataset(metadata_set, 1);
877  return AVERROR(ENOMEM);
878  }
879  mxf->metadata_sets = tmp;
880  mxf->metadata_sets[mxf->metadata_sets_count] = *metadata_set;
881  mxf->metadata_sets_count++;
882  return 0;
883 }
884 
885 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
886 {
887  MXFCryptoContext *cryptocontext = arg;
888  if (size != 16)
889  return AVERROR_INVALIDDATA;
891  avio_read(pb, cryptocontext->source_container_ul, 16);
892  return 0;
893 }
894 
895 static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count)
896 {
897  *count = avio_rb32(pb);
898  av_free(*refs);
899  *refs = av_calloc(*count, sizeof(UID));
900  if (!*refs) {
901  *count = 0;
902  return AVERROR(ENOMEM);
903  }
904  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
905  avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID));
906  return 0;
907 }
908 
909 static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be)
910 {
911  int ret;
912  size_t buf_size;
913 
914  if (size < 0 || size > INT_MAX/2)
915  return AVERROR(EINVAL);
916 
917  buf_size = size + size / 2 + 1;
918  av_free(*str);
919  *str = av_malloc(buf_size);
920  if (!*str)
921  return AVERROR(ENOMEM);
922 
923  if (be)
924  ret = avio_get_str16be(pb, size, *str, buf_size);
925  else
926  ret = avio_get_str16le(pb, size, *str, buf_size);
927 
928  if (ret < 0) {
929  av_freep(str);
930  return ret;
931  }
932 
933  return ret;
934 }
935 
936 #define READ_STR16(type, big_endian) \
937 static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \
938 { \
939 return mxf_read_utf16_string(pb, size, str, big_endian); \
940 }
941 READ_STR16(be, 1)
942 READ_STR16(le, 0)
943 #undef READ_STR16
944 
945 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
946 {
947  MXFContext *mxf = arg;
948  switch (tag) {
949  case 0x1901:
950  if (mxf->packages_refs)
951  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n");
952  return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count);
953  case 0x1902:
955  }
956  return 0;
957 }
958 
959 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
960 {
961  MXFStructuralComponent *source_clip = arg;
962  switch(tag) {
963  case 0x0202:
964  source_clip->duration = avio_rb64(pb);
965  break;
966  case 0x1201:
967  source_clip->start_position = avio_rb64(pb);
968  break;
969  case 0x1101:
970  /* UMID, only get last 16 bytes */
971  avio_read(pb, source_clip->source_package_ul, 16);
972  avio_read(pb, source_clip->source_package_uid, 16);
973  break;
974  case 0x1102:
975  source_clip->source_track_id = avio_rb32(pb);
976  break;
977  }
978  return 0;
979 }
980 
981 static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
982 {
983  MXFTimecodeComponent *mxf_timecode = arg;
984  switch(tag) {
985  case 0x1501:
986  mxf_timecode->start_frame = avio_rb64(pb);
987  break;
988  case 0x1502:
989  mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
990  break;
991  case 0x1503:
992  mxf_timecode->drop_frame = avio_r8(pb);
993  break;
994  }
995  return 0;
996 }
997 
998 static int mxf_read_pulldown_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
999 {
1000  MXFPulldownComponent *mxf_pulldown = arg;
1001  switch(tag) {
1002  case 0x0d01:
1003  avio_read(pb, mxf_pulldown->input_segment_ref, 16);
1004  break;
1005  }
1006  return 0;
1007 }
1008 
1009 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1010 {
1011  MXFTrack *track = arg;
1012  switch(tag) {
1013  case 0x4801:
1014  track->track_id = avio_rb32(pb);
1015  break;
1016  case 0x4804:
1017  avio_read(pb, track->track_number, 4);
1018  break;
1019  case 0x4802:
1020  mxf_read_utf16be_string(pb, size, &track->name);
1021  break;
1022  case 0x4b01:
1023  track->edit_rate.num = avio_rb32(pb);
1024  track->edit_rate.den = avio_rb32(pb);
1025  break;
1026  case 0x4803:
1027  avio_read(pb, track->sequence_ref, 16);
1028  break;
1029  }
1030  return 0;
1031 }
1032 
1033 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1034 {
1035  MXFSequence *sequence = arg;
1036  switch(tag) {
1037  case 0x0202:
1038  sequence->duration = avio_rb64(pb);
1039  break;
1040  case 0x0201:
1041  avio_read(pb, sequence->data_definition_ul, 16);
1042  break;
1043  case 0x4b02:
1044  sequence->origin = avio_r8(pb);
1045  break;
1046  case 0x1001:
1048  &sequence->structural_components_count);
1049  }
1050  return 0;
1051 }
1052 
1053 static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1054 {
1055  MXFEssenceGroup *essence_group = arg;
1056  switch (tag) {
1057  case 0x0202:
1058  essence_group->duration = avio_rb64(pb);
1059  break;
1060  case 0x0501:
1061  return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs,
1062  &essence_group->structural_components_count);
1063  }
1064  return 0;
1065 }
1066 
1067 static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1068 {
1069  MXFPackage *package = arg;
1070  switch(tag) {
1071  case 0x4403:
1072  return mxf_read_strong_ref_array(pb, &package->tracks_refs,
1073  &package->tracks_count);
1074  case 0x4401:
1075  /* UMID */
1076  avio_read(pb, package->package_ul, 16);
1077  avio_read(pb, package->package_uid, 16);
1078  break;
1079  case 0x4701:
1080  avio_read(pb, package->descriptor_ref, 16);
1081  break;
1082  case 0x4402:
1083  return mxf_read_utf16be_string(pb, size, &package->name);
1084  case 0x4406:
1085  return mxf_read_strong_ref_array(pb, &package->comment_refs,
1086  &package->comment_count);
1087  }
1088  return 0;
1089 }
1090 
1091 static int mxf_read_essence_container_data(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1092 {
1093  MXFEssenceContainerData *essence_data = arg;
1094  switch(tag) {
1095  case 0x2701:
1096  /* linked package umid UMID */
1097  avio_read(pb, essence_data->package_ul, 16);
1098  avio_read(pb, essence_data->package_uid, 16);
1099  break;
1100  case 0x3f06:
1101  essence_data->index_sid = avio_rb32(pb);
1102  break;
1103  case 0x3f07:
1104  essence_data->body_sid = avio_rb32(pb);
1105  break;
1106  }
1107  return 0;
1108 }
1109 
1111 {
1112  int i, length;
1113 
1114  segment->nb_index_entries = avio_rb32(pb);
1115 
1116  length = avio_rb32(pb);
1117  if(segment->nb_index_entries && length < 11)
1118  return AVERROR_INVALIDDATA;
1119 
1120  if (!FF_ALLOC_TYPED_ARRAY(segment->temporal_offset_entries, segment->nb_index_entries) ||
1121  !FF_ALLOC_TYPED_ARRAY(segment->flag_entries , segment->nb_index_entries) ||
1122  !FF_ALLOC_TYPED_ARRAY(segment->stream_offset_entries , segment->nb_index_entries)) {
1123  av_freep(&segment->temporal_offset_entries);
1124  av_freep(&segment->flag_entries);
1125  return AVERROR(ENOMEM);
1126  }
1127 
1128  for (i = 0; i < segment->nb_index_entries; i++) {
1129  if(avio_feof(pb))
1130  return AVERROR_INVALIDDATA;
1131  segment->temporal_offset_entries[i] = avio_r8(pb);
1132  avio_r8(pb); /* KeyFrameOffset */
1133  segment->flag_entries[i] = avio_r8(pb);
1134  segment->stream_offset_entries[i] = avio_rb64(pb);
1135  avio_skip(pb, length - 11);
1136  }
1137  return 0;
1138 }
1139 
1140 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1141 {
1143  switch(tag) {
1144  case 0x3F05:
1145  segment->edit_unit_byte_count = avio_rb32(pb);
1146  av_log(NULL, AV_LOG_TRACE, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
1147  break;
1148  case 0x3F06:
1149  segment->index_sid = avio_rb32(pb);
1150  av_log(NULL, AV_LOG_TRACE, "IndexSID %d\n", segment->index_sid);
1151  break;
1152  case 0x3F07:
1153  segment->body_sid = avio_rb32(pb);
1154  av_log(NULL, AV_LOG_TRACE, "BodySID %d\n", segment->body_sid);
1155  break;
1156  case 0x3F0A:
1157  av_log(NULL, AV_LOG_TRACE, "IndexEntryArray found\n");
1158  return mxf_read_index_entry_array(pb, segment);
1159  case 0x3F0B:
1160  segment->index_edit_rate.num = avio_rb32(pb);
1161  segment->index_edit_rate.den = avio_rb32(pb);
1162  av_log(NULL, AV_LOG_TRACE, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
1163  segment->index_edit_rate.den);
1164  break;
1165  case 0x3F0C:
1166  segment->index_start_position = avio_rb64(pb);
1167  av_log(NULL, AV_LOG_TRACE, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
1168  break;
1169  case 0x3F0D:
1170  segment->index_duration = avio_rb64(pb);
1171  av_log(NULL, AV_LOG_TRACE, "IndexDuration %"PRId64"\n", segment->index_duration);
1172  break;
1173  }
1174  return 0;
1175 }
1176 
1177 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
1178 {
1179  int code, value, ofs = 0;
1180  char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */
1181 
1182  do {
1183  code = avio_r8(pb);
1184  value = avio_r8(pb);
1185  av_log(NULL, AV_LOG_TRACE, "pixel layout: code %#x\n", code);
1186 
1187  if (ofs <= 14) {
1188  layout[ofs++] = code;
1189  layout[ofs++] = value;
1190  } else
1191  break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */
1192  } while (code != 0); /* SMPTE 377M E.2.46 */
1193 
1194  ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
1195 }
1196 
1197 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1198 {
1199  MXFDescriptor *descriptor = arg;
1200  int entry_count, entry_size;
1201 
1202  switch(tag) {
1203  case 0x3F01:
1204  return mxf_read_strong_ref_array(pb, &descriptor->sub_descriptors_refs,
1205  &descriptor->sub_descriptors_count);
1206  case 0x3002: /* ContainerDuration */
1207  descriptor->duration = avio_rb64(pb);
1208  break;
1209  case 0x3004:
1210  avio_read(pb, descriptor->essence_container_ul, 16);
1211  break;
1212  case 0x3005:
1213  avio_read(pb, descriptor->codec_ul, 16);
1214  break;
1215  case 0x3006:
1216  descriptor->linked_track_id = avio_rb32(pb);
1217  break;
1218  case 0x3201: /* PictureEssenceCoding */
1219  avio_read(pb, descriptor->essence_codec_ul, 16);
1220  break;
1221  case 0x3203:
1222  descriptor->width = avio_rb32(pb);
1223  break;
1224  case 0x3202:
1225  descriptor->height = avio_rb32(pb);
1226  break;
1227  case 0x320C:
1228  descriptor->frame_layout = avio_r8(pb);
1229  break;
1230  case 0x320D:
1231  entry_count = avio_rb32(pb);
1232  entry_size = avio_rb32(pb);
1233  if (entry_size == 4) {
1234  if (entry_count > 0)
1235  descriptor->video_line_map[0] = avio_rb32(pb);
1236  else
1237  descriptor->video_line_map[0] = 0;
1238  if (entry_count > 1)
1239  descriptor->video_line_map[1] = avio_rb32(pb);
1240  else
1241  descriptor->video_line_map[1] = 0;
1242  } else
1243  av_log(NULL, AV_LOG_WARNING, "VideoLineMap element size %d currently not supported\n", entry_size);
1244  break;
1245  case 0x320E:
1246  descriptor->aspect_ratio.num = avio_rb32(pb);
1247  descriptor->aspect_ratio.den = avio_rb32(pb);
1248  break;
1249  case 0x3210:
1250  avio_read(pb, descriptor->color_trc_ul, 16);
1251  break;
1252  case 0x3212:
1253  descriptor->field_dominance = avio_r8(pb);
1254  break;
1255  case 0x3219:
1256  avio_read(pb, descriptor->color_primaries_ul, 16);
1257  break;
1258  case 0x321A:
1259  avio_read(pb, descriptor->color_space_ul, 16);
1260  break;
1261  case 0x3301:
1262  descriptor->component_depth = avio_rb32(pb);
1263  break;
1264  case 0x3302:
1265  descriptor->horiz_subsampling = avio_rb32(pb);
1266  break;
1267  case 0x3304:
1268  descriptor->black_ref_level = avio_rb32(pb);
1269  break;
1270  case 0x3305:
1271  descriptor->white_ref_level = avio_rb32(pb);
1272  break;
1273  case 0x3306:
1274  descriptor->color_range = avio_rb32(pb);
1275  break;
1276  case 0x3308:
1277  descriptor->vert_subsampling = avio_rb32(pb);
1278  break;
1279  case 0x3D03:
1280  descriptor->sample_rate.num = avio_rb32(pb);
1281  descriptor->sample_rate.den = avio_rb32(pb);
1282  break;
1283  case 0x3D06: /* SoundEssenceCompression */
1284  avio_read(pb, descriptor->essence_codec_ul, 16);
1285  break;
1286  case 0x3D07:
1287  descriptor->channels = avio_rb32(pb);
1288  break;
1289  case 0x3D01:
1290  descriptor->bits_per_sample = avio_rb32(pb);
1291  break;
1292  case 0x3401:
1293  mxf_read_pixel_layout(pb, descriptor);
1294  break;
1295  default:
1296  /* Private uid used by SONY C0023S01.mxf */
1298  if (descriptor->extradata)
1299  av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n");
1300  av_free(descriptor->extradata);
1301  descriptor->extradata_size = 0;
1302  descriptor->extradata = av_malloc(size);
1303  if (!descriptor->extradata)
1304  return AVERROR(ENOMEM);
1305  descriptor->extradata_size = size;
1306  avio_read(pb, descriptor->extradata, size);
1307  }
1308  if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) {
1309  uint32_t rsiz = avio_rb16(pb);
1310  if (rsiz == FF_PROFILE_JPEG2000_DCINEMA_2K ||
1312  descriptor->pix_fmt = AV_PIX_FMT_XYZ12;
1313  }
1315  if (!descriptor->mastering) {
1317  if (!descriptor->mastering)
1318  return AVERROR(ENOMEM);
1319  }
1321  for (int i = 0; i < 3; i++) {
1322  /* Order: large x, large y, other (i.e. RGB) */
1325  }
1326  /* Check we have seen mxf_mastering_display_white_point_chromaticity */
1327  if (descriptor->mastering->white_point[0].den != 0)
1328  descriptor->mastering->has_primaries = 1;
1329  }
1333  /* Check we have seen mxf_mastering_display_primaries */
1334  if (descriptor->mastering->display_primaries[0][0].den != 0)
1335  descriptor->mastering->has_primaries = 1;
1336  }
1339  /* Check we have seen mxf_mastering_display_minimum_luminance */
1340  if (descriptor->mastering->min_luminance.den != 0)
1341  descriptor->mastering->has_luminance = 1;
1342  }
1345  /* Check we have seen mxf_mastering_display_maximum_luminance */
1346  if (descriptor->mastering->max_luminance.den != 0)
1347  descriptor->mastering->has_luminance = 1;
1348  }
1349  }
1351  if (!descriptor->coll) {
1352  descriptor->coll = av_content_light_metadata_alloc(&descriptor->coll_size);
1353  if (!descriptor->coll)
1354  return AVERROR(ENOMEM);
1355  }
1357  descriptor->coll->MaxCLL = avio_rb16(pb);
1358  }
1360  descriptor->coll->MaxFALL = avio_rb16(pb);
1361  }
1362  }
1363  break;
1364  }
1365  return 0;
1366 }
1367 
1368 static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size)
1369 {
1370  MXFTaggedValue *tagged_value = arg;
1371  uint8_t key[17];
1372 
1373  if (size <= 17)
1374  return 0;
1375 
1376  avio_read(pb, key, 17);
1377  /* TODO: handle other types of of indirect values */
1378  if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) {
1379  return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value);
1380  } else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) {
1381  return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value);
1382  }
1383  return 0;
1384 }
1385 
1386 static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1387 {
1388  MXFTaggedValue *tagged_value = arg;
1389  switch (tag){
1390  case 0x5001:
1391  return mxf_read_utf16be_string(pb, size, &tagged_value->name);
1392  case 0x5003:
1393  return mxf_read_indirect_value(tagged_value, pb, size);
1394  }
1395  return 0;
1396 }
1397 
1398 /*
1399  * Match an uid independently of the version byte and up to len common bytes
1400  * Returns: boolean
1401  */
1402 static int mxf_match_uid(const UID key, const UID uid, int len)
1403 {
1404  int i;
1405  for (i = 0; i < len; i++) {
1406  if (i != 7 && key[i] != uid[i])
1407  return 0;
1408  }
1409  return 1;
1410 }
1411 
1412 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
1413 {
1414  while (uls->uid[0]) {
1415  if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
1416  break;
1417  uls++;
1418  }
1419  return uls;
1420 }
1421 
1422 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
1423 {
1424  int i;
1425 
1426  if (!strong_ref)
1427  return NULL;
1428  for (i = mxf->metadata_sets_count - 1; i >= 0; i--) {
1429  if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
1430  (type == AnyType || mxf->metadata_sets[i]->type == type)) {
1431  return mxf->metadata_sets[i];
1432  }
1433  }
1434  return NULL;
1435 }
1436 
1438  // video essence container uls
1439  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000, NULL, 14, J2KWrap },
1440  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x10,0x60,0x01 }, 14, AV_CODEC_ID_H264, NULL, 15 }, /* H.264 */
1441  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x11,0x01,0x00 }, 14, AV_CODEC_ID_DNXHD, NULL, 14 }, /* VC-3 */
1442  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x12,0x01,0x00 }, 14, AV_CODEC_ID_VC1, NULL, 14 }, /* VC-1 */
1443  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x14,0x01,0x00 }, 14, AV_CODEC_ID_TIFF, NULL, 14 }, /* TIFF */
1444  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x15,0x01,0x00 }, 14, AV_CODEC_ID_DIRAC, NULL, 14 }, /* VC-2 */
1445  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x1b,0x01,0x00 }, 14, AV_CODEC_ID_CFHD, NULL, 14 }, /* VC-5 */
1446  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 }, 14, AV_CODEC_ID_PRORES, NULL, 14 }, /* ProRes */
1447  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO, NULL, 15 }, /* MPEG-ES */
1448  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO, NULL, 15, D10D11Wrap }, /* SMPTE D-10 mapping */
1449  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO, NULL, 15 }, /* DV 625 25mbps */
1450  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO, NULL, 15, RawVWrap }, /* uncompressed picture */
1451  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x01,0x01 }, 15, AV_CODEC_ID_HQ_HQA },
1452  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x02,0x01 }, 15, AV_CODEC_ID_HQX },
1453  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x15,0x00,0x04,0x02,0x10,0x00,0x01 }, 16, AV_CODEC_ID_HEVC, NULL, 15 }, /* Canon XF-HEVC */
1454  { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4f }, 14, AV_CODEC_ID_RAWVIDEO }, /* Legacy ?? Uncompressed Picture */
1455  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1456 };
1457 
1458 /* EC ULs for intra-only formats */
1460  { { 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 */
1461  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1462 };
1463 
1464 /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
1466  { { 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 */
1467  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG 2000 code stream */
1468  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1469 };
1470 
1471 /* actual coded width for AVC-Intra to allow selecting correct SPS/PPS */
1473  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 16, 1440 },
1474  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 16, 1440 },
1475  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 16, 1440 },
1476  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 16, 1440 },
1477  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, 0 },
1478 };
1479 
1481  // sound essence container uls
1482  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE, NULL, 14, RawAWrap }, /* BWF */
1483  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2, NULL, 15 }, /* MPEG-ES */
1484  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE, NULL, 13 }, /* D-10 Mapping 50Mbps PAL Extended Template */
1485  { { 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 */
1486  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14, AV_CODEC_ID_AAC }, /* MPEG-2 AAC ADTS (legacy) */
1487  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1488 };
1489 
1491  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0d,0x00,0x00 }, 16, AV_CODEC_ID_NONE, "vbi_smpte_436M", 11 },
1492  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 }, 16, AV_CODEC_ID_NONE, "vbi_vanc_smpte_436M", 11 },
1493  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x13,0x01,0x01 }, 16, AV_CODEC_ID_TTML },
1494  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1495 };
1496 
1497 static MXFWrappingScheme mxf_get_wrapping_kind(UID *essence_container_ul)
1498 {
1499  int val;
1500  const MXFCodecUL *codec_ul;
1501 
1503  if (!codec_ul->uid[0])
1505  if (!codec_ul->uid[0])
1506  codec_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul);
1507  if (!codec_ul->uid[0] || !codec_ul->wrapping_indicator_pos)
1508  return UnknownWrapped;
1509 
1510  val = (*essence_container_ul)[codec_ul->wrapping_indicator_pos];
1511  switch (codec_ul->wrapping_indicator_type) {
1512  case RawVWrap:
1513  val = val % 4;
1514  break;
1515  case RawAWrap:
1516  if (val == 0x03 || val == 0x04)
1517  val -= 0x02;
1518  break;
1519  case D10D11Wrap:
1520  if (val == 0x02)
1521  val = 0x01;
1522  break;
1523  case J2KWrap:
1524  if (val != 0x02)
1525  val = 0x01;
1526  break;
1527  }
1528  if (val == 0x01)
1529  return FrameWrapped;
1530  if (val == 0x02)
1531  return ClipWrapped;
1532  return UnknownWrapped;
1533 }
1534 
1535 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
1536 {
1537  int i, j, nb_segments = 0;
1538  MXFIndexTableSegment **unsorted_segments;
1539  int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
1540 
1541  /* count number of segments, allocate arrays and copy unsorted segments */
1542  for (i = 0; i < mxf->metadata_sets_count; i++)
1543  if (mxf->metadata_sets[i]->type == IndexTableSegment)
1544  nb_segments++;
1545 
1546  if (!nb_segments)
1547  return AVERROR_INVALIDDATA;
1548 
1549  if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
1550  !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
1551  av_freep(sorted_segments);
1552  av_free(unsorted_segments);
1553  return AVERROR(ENOMEM);
1554  }
1555 
1556  for (i = nb_segments = 0; i < mxf->metadata_sets_count; i++) {
1557  if (mxf->metadata_sets[i]->type == IndexTableSegment) {
1559  if (s->edit_unit_byte_count || s->nb_index_entries)
1560  unsorted_segments[nb_segments++] = s;
1561  else
1562  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
1563  s->index_sid, s->index_start_position);
1564  }
1565  }
1566 
1567  if (!nb_segments) {
1568  av_freep(sorted_segments);
1569  av_free(unsorted_segments);
1570  return AVERROR_INVALIDDATA;
1571  }
1572 
1573  *nb_sorted_segments = 0;
1574 
1575  /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
1576  for (i = 0; i < nb_segments; i++) {
1577  int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
1578  uint64_t best_index_duration = 0;
1579 
1580  for (j = 0; j < nb_segments; j++) {
1581  MXFIndexTableSegment *s = unsorted_segments[j];
1582 
1583  /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
1584  * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
1585  * If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have.
1586  */
1587  if ((i == 0 ||
1588  s->body_sid > last_body_sid ||
1589  s->body_sid == last_body_sid && s->index_sid > last_index_sid ||
1590  s->body_sid == last_body_sid && s->index_sid == last_index_sid && s->index_start_position > last_index_start) &&
1591  (best == -1 ||
1592  s->body_sid < best_body_sid ||
1593  s->body_sid == best_body_sid && s->index_sid < best_index_sid ||
1594  s->body_sid == best_body_sid && s->index_sid == best_index_sid && s->index_start_position < best_index_start ||
1595  s->body_sid == best_body_sid && s->index_sid == best_index_sid && s->index_start_position == best_index_start && s->index_duration > best_index_duration)) {
1596  best = j;
1597  best_body_sid = s->body_sid;
1598  best_index_sid = s->index_sid;
1599  best_index_start = s->index_start_position;
1600  best_index_duration = s->index_duration;
1601  }
1602  }
1603 
1604  /* no suitable entry found -> we're done */
1605  if (best == -1)
1606  break;
1607 
1608  (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
1609  last_body_sid = best_body_sid;
1610  last_index_sid = best_index_sid;
1611  last_index_start = best_index_start;
1612  }
1613 
1614  av_free(unsorted_segments);
1615 
1616  return 0;
1617 }
1618 
1619 /**
1620  * Computes the absolute file offset of the given essence container offset
1621  */
1622 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out, MXFPartition **partition_out)
1623 {
1624  MXFPartition *last_p = NULL;
1625  int a, b, m, m0;
1626 
1627  if (offset < 0)
1628  return AVERROR(EINVAL);
1629 
1630  a = -1;
1631  b = mxf->partitions_count;
1632 
1633  while (b - a > 1) {
1634  m0 = m = (a + b) >> 1;
1635 
1636  while (m < b && mxf->partitions[m].body_sid != body_sid)
1637  m++;
1638 
1639  if (m < b && mxf->partitions[m].body_offset <= offset)
1640  a = m;
1641  else
1642  b = m0;
1643  }
1644 
1645  if (a >= 0)
1646  last_p = &mxf->partitions[a];
1647 
1648  if (last_p && (!last_p->essence_length || last_p->essence_length > (offset - last_p->body_offset))) {
1649  *offset_out = last_p->essence_offset + (offset - last_p->body_offset);
1650  if (partition_out)
1651  *partition_out = last_p;
1652  return 0;
1653  }
1654 
1655  av_log(mxf->fc, AV_LOG_ERROR,
1656  "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
1657  offset, body_sid);
1658 
1659  return AVERROR_INVALIDDATA;
1660 }
1661 
1662 /**
1663  * Returns the end position of the essence container with given BodySID, or zero if unknown
1664  */
1665 static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
1666 {
1667  for (int x = mxf->partitions_count - 1; x >= 0; x--) {
1668  MXFPartition *p = &mxf->partitions[x];
1669 
1670  if (p->body_sid != body_sid)
1671  continue;
1672 
1673  if (!p->essence_length)
1674  return 0;
1675 
1676  return p->essence_offset + p->essence_length;
1677  }
1678 
1679  return 0;
1680 }
1681 
1682 /* EditUnit -> absolute offset */
1683 static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, AVRational edit_rate, int64_t *edit_unit_out, int64_t *offset_out, MXFPartition **partition_out, int nag)
1684 {
1685  int i;
1686  int64_t offset_temp = 0;
1687 
1688  edit_unit = av_rescale_q(edit_unit, index_table->segments[0]->index_edit_rate, edit_rate);
1689 
1690  for (i = 0; i < index_table->nb_segments; i++) {
1691  MXFIndexTableSegment *s = index_table->segments[i];
1692 
1693  edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
1694 
1695  if (edit_unit < s->index_start_position + s->index_duration) {
1696  int64_t index = edit_unit - s->index_start_position;
1697 
1698  if (s->edit_unit_byte_count)
1699  offset_temp += s->edit_unit_byte_count * index;
1700  else {
1701  if (s->nb_index_entries == 2 * s->index_duration + 1)
1702  index *= 2; /* Avid index */
1703 
1704  if (index < 0 || index >= s->nb_index_entries) {
1705  av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
1706  index_table->index_sid, s->index_start_position);
1707  return AVERROR_INVALIDDATA;
1708  }
1709 
1710  offset_temp = s->stream_offset_entries[index];
1711  }
1712 
1713  if (edit_unit_out)
1714  *edit_unit_out = av_rescale_q(edit_unit, edit_rate, s->index_edit_rate);
1715 
1716  return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out, partition_out);
1717  } else {
1718  /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
1719  offset_temp += s->edit_unit_byte_count * s->index_duration;
1720  }
1721  }
1722 
1723  if (nag)
1724  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);
1725 
1726  return AVERROR_INVALIDDATA;
1727 }
1728 
1730 {
1731  int i, j, x;
1732  int8_t max_temporal_offset = -128;
1733  uint8_t *flags;
1734 
1735  /* first compute how many entries we have */
1736  for (i = 0; i < index_table->nb_segments; i++) {
1737  MXFIndexTableSegment *s = index_table->segments[i];
1738 
1739  if (!s->nb_index_entries) {
1740  index_table->nb_ptses = 0;
1741  return 0; /* no TemporalOffsets */
1742  }
1743 
1744  if (s->index_duration > INT_MAX - index_table->nb_ptses) {
1745  index_table->nb_ptses = 0;
1746  av_log(mxf->fc, AV_LOG_ERROR, "ignoring IndexSID %d, duration is too large\n", s->index_sid);
1747  return 0;
1748  }
1749 
1750  index_table->nb_ptses += s->index_duration;
1751  }
1752 
1753  /* paranoid check */
1754  if (index_table->nb_ptses <= 0)
1755  return 0;
1756 
1757  if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
1758  !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry))) ||
1759  !(index_table->offsets = av_calloc(index_table->nb_ptses, sizeof(int8_t))) ||
1760  !(flags = av_calloc(index_table->nb_ptses, sizeof(uint8_t)))) {
1761  av_freep(&index_table->ptses);
1762  av_freep(&index_table->fake_index);
1763  av_freep(&index_table->offsets);
1764  return AVERROR(ENOMEM);
1765  }
1766 
1767  /* we may have a few bad TemporalOffsets
1768  * make sure the corresponding PTSes don't have the bogus value 0 */
1769  for (x = 0; x < index_table->nb_ptses; x++)
1770  index_table->ptses[x] = AV_NOPTS_VALUE;
1771 
1772  /**
1773  * We have this:
1774  *
1775  * x TemporalOffset
1776  * 0: 0
1777  * 1: 1
1778  * 2: 1
1779  * 3: -2
1780  * 4: 1
1781  * 5: 1
1782  * 6: -2
1783  *
1784  * We want to transform it into this:
1785  *
1786  * x DTS PTS
1787  * 0: -1 0
1788  * 1: 0 3
1789  * 2: 1 1
1790  * 3: 2 2
1791  * 4: 3 6
1792  * 5: 4 4
1793  * 6: 5 5
1794  *
1795  * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
1796  * then settings ffstream(mxf)->first_dts = -max(TemporalOffset[x]).
1797  * The latter makes DTS <= PTS.
1798  */
1799  for (i = x = 0; i < index_table->nb_segments; i++) {
1800  MXFIndexTableSegment *s = index_table->segments[i];
1801  int index_delta = 1;
1802  int n = s->nb_index_entries;
1803 
1804  if (s->nb_index_entries == 2 * s->index_duration + 1) {
1805  index_delta = 2; /* Avid index */
1806  /* ignore the last entry - it's the size of the essence container */
1807  n--;
1808  }
1809 
1810  for (j = 0; j < n; j += index_delta, x++) {
1811  int offset = s->temporal_offset_entries[j] / index_delta;
1812  int index = x + offset;
1813 
1814  if (x >= index_table->nb_ptses) {
1815  av_log(mxf->fc, AV_LOG_ERROR,
1816  "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
1817  s->nb_index_entries, s->index_duration);
1818  break;
1819  }
1820 
1821  flags[x] = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
1822 
1823  if (index < 0 || index >= index_table->nb_ptses) {
1824  av_log(mxf->fc, AV_LOG_ERROR,
1825  "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
1826  x, offset, index);
1827  continue;
1828  }
1829 
1830  index_table->offsets[x] = offset;
1831  index_table->ptses[index] = x;
1832  max_temporal_offset = FFMAX(max_temporal_offset, offset);
1833  }
1834  }
1835 
1836  /* calculate the fake index table in display order */
1837  for (x = 0; x < index_table->nb_ptses; x++) {
1838  index_table->fake_index[x].timestamp = x;
1839  if (index_table->ptses[x] != AV_NOPTS_VALUE)
1840  index_table->fake_index[index_table->ptses[x]].flags = flags[x];
1841  }
1842  av_freep(&flags);
1843 
1844  index_table->first_dts = -max_temporal_offset;
1845 
1846  return 0;
1847 }
1848 
1849 /**
1850  * Sorts and collects index table segments into index tables.
1851  * Also computes PTSes if possible.
1852  */
1854 {
1855  int i, j, k, ret, nb_sorted_segments;
1856  MXFIndexTableSegment **sorted_segments = NULL;
1857 
1858  if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
1859  nb_sorted_segments <= 0) {
1860  av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
1861  return 0;
1862  }
1863 
1864  /* sanity check and count unique BodySIDs/IndexSIDs */
1865  for (i = 0; i < nb_sorted_segments; i++) {
1866  if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
1867  mxf->nb_index_tables++;
1868  else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
1869  av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
1871  goto finish_decoding_index;
1872  }
1873  }
1874 
1876  sizeof(*mxf->index_tables));
1877  if (!mxf->index_tables) {
1878  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
1879  ret = AVERROR(ENOMEM);
1880  goto finish_decoding_index;
1881  }
1882 
1883  /* distribute sorted segments to index tables */
1884  for (i = j = 0; i < nb_sorted_segments; i++) {
1885  if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
1886  /* next IndexSID */
1887  j++;
1888  }
1889 
1890  mxf->index_tables[j].nb_segments++;
1891  }
1892 
1893  for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
1894  MXFIndexTable *t = &mxf->index_tables[j];
1895  MXFTrack *mxf_track = NULL;
1896 
1898  sizeof(*t->segments));
1899 
1900  if (!t->segments) {
1901  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment"
1902  " pointer array\n");
1903  ret = AVERROR(ENOMEM);
1904  goto finish_decoding_index;
1905  }
1906 
1907  if (sorted_segments[i]->index_start_position)
1908  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
1909  sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
1910 
1911  memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
1912  t->index_sid = sorted_segments[i]->index_sid;
1913  t->body_sid = sorted_segments[i]->body_sid;
1914 
1915  if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
1916  goto finish_decoding_index;
1917 
1918  for (k = 0; k < mxf->fc->nb_streams; k++) {
1919  MXFTrack *track = mxf->fc->streams[k]->priv_data;
1920  if (track && track->index_sid == t->index_sid) {
1921  mxf_track = track;
1922  break;
1923  }
1924  }
1925 
1926  /* fix zero IndexDurations */
1927  for (k = 0; k < t->nb_segments; k++) {
1928  if (!t->segments[k]->index_edit_rate.num || !t->segments[k]->index_edit_rate.den) {
1929  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has invalid IndexEditRate\n",
1930  t->index_sid, k);
1931  if (mxf_track)
1932  t->segments[k]->index_edit_rate = mxf_track->edit_rate;
1933  }
1934 
1935  if (t->segments[k]->index_duration)
1936  continue;
1937 
1938  if (t->nb_segments > 1)
1939  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
1940  t->index_sid, k);
1941 
1942  if (!mxf_track) {
1943  av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
1944  break;
1945  }
1946 
1947  /* assume the first stream's duration is reasonable
1948  * leave index_duration = 0 on further segments in case we have any (unlikely)
1949  */
1950  t->segments[k]->index_duration = mxf_track->original_duration;
1951  break;
1952  }
1953  }
1954 
1955  ret = 0;
1956 finish_decoding_index:
1957  av_free(sorted_segments);
1958  return ret;
1959 }
1960 
1961 static int mxf_is_intra_only(MXFDescriptor *descriptor)
1962 {
1964  &descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE ||
1966  &descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE;
1967 }
1968 
1969 static int mxf_uid_to_str(UID uid, char **str)
1970 {
1971  int i;
1972  char *p;
1973  p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1);
1974  if (!p)
1975  return AVERROR(ENOMEM);
1976  for (i = 0; i < sizeof(UID); i++) {
1977  snprintf(p, 2 + 1, "%.2x", uid[i]);
1978  p += 2;
1979  if (i == 3 || i == 5 || i == 7 || i == 9) {
1980  snprintf(p, 1 + 1, "-");
1981  p++;
1982  }
1983  }
1984  return 0;
1985 }
1986 
1987 static int mxf_umid_to_str(UID ul, UID uid, char **str)
1988 {
1989  int i;
1990  char *p;
1991  p = *str = av_mallocz(sizeof(UID) * 4 + 2 + 1);
1992  if (!p)
1993  return AVERROR(ENOMEM);
1994  snprintf(p, 2 + 1, "0x");
1995  p += 2;
1996  for (i = 0; i < sizeof(UID); i++) {
1997  snprintf(p, 2 + 1, "%.2X", ul[i]);
1998  p += 2;
1999 
2000  }
2001  for (i = 0; i < sizeof(UID); i++) {
2002  snprintf(p, 2 + 1, "%.2X", uid[i]);
2003  p += 2;
2004  }
2005  return 0;
2006 }
2007 
2008 static int mxf_version_to_str(uint16_t major, uint16_t minor, uint16_t tertiary,
2009  uint16_t patch, uint16_t release, char **str)
2010 {
2011  *str = av_asprintf("%d.%d.%d.%d.%d", major, minor, tertiary, patch, release);
2012  if (!*str)
2013  return AVERROR(ENOMEM);
2014  return 0;
2015 }
2016 
2017 static int mxf_add_umid_metadata(AVDictionary **pm, const char *key, MXFPackage* package)
2018 {
2019  char *str;
2020  int ret;
2021  if (!package)
2022  return 0;
2023  if ((ret = mxf_umid_to_str(package->package_ul, package->package_uid, &str)) < 0)
2024  return ret;
2026  return 0;
2027 }
2028 
2029 static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
2030 {
2031  char buf[AV_TIMECODE_STR_SIZE];
2032  av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
2033 
2034  return 0;
2035 }
2036 
2038 {
2039  MXFStructuralComponent *component = NULL;
2040  MXFPulldownComponent *pulldown = NULL;
2041 
2042  component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
2043  if (!component)
2044  return NULL;
2045 
2046  switch (component->meta.type) {
2047  case TimecodeComponent:
2048  return (MXFTimecodeComponent*)component;
2049  case PulldownComponent: /* timcode component may be located on a pulldown component */
2050  pulldown = (MXFPulldownComponent*)component;
2052  default:
2053  break;
2054  }
2055  return NULL;
2056 }
2057 
2058 static MXFPackage* mxf_resolve_source_package(MXFContext *mxf, UID package_ul, UID package_uid)
2059 {
2060  MXFPackage *package = NULL;
2061  int i;
2062 
2063  for (i = 0; i < mxf->packages_count; i++) {
2064  package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], SourcePackage);
2065  if (!package)
2066  continue;
2067 
2068  if (!memcmp(package->package_ul, package_ul, 16) && !memcmp(package->package_uid, package_uid, 16))
2069  return package;
2070  }
2071  return NULL;
2072 }
2073 
2074 static MXFDescriptor* mxf_resolve_multidescriptor(MXFContext *mxf, MXFDescriptor *descriptor, int track_id)
2075 {
2076  MXFDescriptor *sub_descriptor = NULL;
2077  int i;
2078 
2079  if (!descriptor)
2080  return NULL;
2081 
2082  if (descriptor->meta.type == MultipleDescriptor) {
2083  for (i = 0; i < descriptor->sub_descriptors_count; i++) {
2084  sub_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->sub_descriptors_refs[i], Descriptor);
2085 
2086  if (!sub_descriptor) {
2087  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
2088  continue;
2089  }
2090  if (sub_descriptor->linked_track_id == track_id) {
2091  return sub_descriptor;
2092  }
2093  }
2094  } else if (descriptor->meta.type == Descriptor)
2095  return descriptor;
2096 
2097  return NULL;
2098 }
2099 
2101 {
2102  MXFStructuralComponent *component = NULL;
2103  MXFPackage *package = NULL;
2104  MXFDescriptor *descriptor = NULL;
2105  int i;
2106 
2107  if (!essence_group || !essence_group->structural_components_count)
2108  return NULL;
2109 
2110  /* essence groups contains multiple representations of the same media,
2111  this return the first components with a valid Descriptor typically index 0 */
2112  for (i =0; i < essence_group->structural_components_count; i++){
2113  component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip);
2114  if (!component)
2115  continue;
2116 
2117  if (!(package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid)))
2118  continue;
2119 
2120  descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor);
2121  if (descriptor)
2122  return component;
2123  }
2124  return NULL;
2125 }
2126 
2128 {
2129  MXFStructuralComponent *component = NULL;
2130 
2131  component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
2132  if (!component)
2133  return NULL;
2134  switch (component->meta.type) {
2135  case SourceClip:
2136  return component;
2137  case EssenceGroup:
2138  return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component);
2139  default:
2140  break;
2141  }
2142  return NULL;
2143 }
2144 
2146 {
2148  int i;
2149  char *key = NULL;
2150 
2151  for (i = 0; i < package->comment_count; i++) {
2152  tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue);
2153  if (!tag || !tag->name || !tag->value)
2154  continue;
2155 
2156  key = av_asprintf("comment_%s", tag->name);
2157  if (!key)
2158  return AVERROR(ENOMEM);
2159 
2161  }
2162  return 0;
2163 }
2164 
2166 {
2167  MXFPackage *physical_package = NULL;
2168  MXFTrack *physical_track = NULL;
2169  MXFStructuralComponent *sourceclip = NULL;
2170  MXFTimecodeComponent *mxf_tc = NULL;
2171  int i, j, k;
2172  AVTimecode tc;
2173  int flags;
2174  int64_t start_position;
2175 
2176  for (i = 0; i < source_track->sequence->structural_components_count; i++) {
2177  sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip);
2178  if (!sourceclip)
2179  continue;
2180 
2181  if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_ul, sourceclip->source_package_uid)))
2182  break;
2183 
2184  mxf_add_umid_metadata(&st->metadata, "reel_umid", physical_package);
2185 
2186  /* the name of physical source package is name of the reel or tape */
2187  if (physical_package->name && physical_package->name[0])
2188  av_dict_set(&st->metadata, "reel_name", physical_package->name, 0);
2189 
2190  /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track
2191  * to the start_frame of the timecode component located on one of the tracks of the physical source package.
2192  */
2193  for (j = 0; j < physical_package->tracks_count; j++) {
2194  if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) {
2195  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
2196  continue;
2197  }
2198 
2199  if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) {
2200  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
2201  continue;
2202  }
2203 
2204  if (physical_track->edit_rate.num <= 0 ||
2205  physical_track->edit_rate.den <= 0) {
2206  av_log(mxf->fc, AV_LOG_WARNING,
2207  "Invalid edit rate (%d/%d) found on structural"
2208  " component #%d, defaulting to 25/1\n",
2209  physical_track->edit_rate.num,
2210  physical_track->edit_rate.den, i);
2211  physical_track->edit_rate = (AVRational){25, 1};
2212  }
2213 
2214  for (k = 0; k < physical_track->sequence->structural_components_count; k++) {
2215  if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k])))
2216  continue;
2217 
2218  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2219  /* scale sourceclip start_position to match physical track edit rate */
2220  start_position = av_rescale_q(sourceclip->start_position,
2221  physical_track->edit_rate,
2222  source_track->edit_rate);
2223 
2224  if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) {
2225  mxf_add_timecode_metadata(&st->metadata, "timecode", &tc);
2226  return 0;
2227  }
2228  }
2229  }
2230  }
2231 
2232  return 0;
2233 }
2234 
2236 {
2237  MXFStructuralComponent *component = NULL;
2238  const MXFCodecUL *codec_ul = NULL;
2239  MXFPackage tmp_package;
2240  AVStream *st;
2241  int j;
2242 
2243  for (j = 0; j < track->sequence->structural_components_count; j++) {
2244  component = mxf_resolve_sourceclip(mxf, &track->sequence->structural_components_refs[j]);
2245  if (!component)
2246  continue;
2247  break;
2248  }
2249  if (!component)
2250  return 0;
2251 
2252  st = avformat_new_stream(mxf->fc, NULL);
2253  if (!st) {
2254  av_log(mxf->fc, AV_LOG_ERROR, "could not allocate metadata stream\n");
2255  return AVERROR(ENOMEM);
2256  }
2257 
2260  st->id = track->track_id;
2261 
2262  memcpy(&tmp_package.package_ul, component->source_package_ul, 16);
2263  memcpy(&tmp_package.package_uid, component->source_package_uid, 16);
2264  mxf_add_umid_metadata(&st->metadata, "file_package_umid", &tmp_package);
2265  if (track->name && track->name[0])
2266  av_dict_set(&st->metadata, "track_name", track->name, 0);
2267 
2269  av_dict_set(&st->metadata, "data_type", av_get_media_type_string(codec_ul->id), 0);
2270  return 0;
2271 }
2272 
2274 {
2275  if (descriptor->black_ref_level || descriptor->white_ref_level || descriptor->color_range) {
2276  /* CDCI range metadata */
2277  if (!descriptor->component_depth)
2278  return AVCOL_RANGE_UNSPECIFIED;
2279  if (descriptor->black_ref_level == 0 &&
2280  descriptor->white_ref_level == ((1<<descriptor->component_depth) - 1) &&
2281  (descriptor->color_range == (1<<descriptor->component_depth) ||
2282  descriptor->color_range == ((1<<descriptor->component_depth) - 1)))
2283  return AVCOL_RANGE_JPEG;
2284  if (descriptor->component_depth >= 8 &&
2285  descriptor->black_ref_level == (1 <<(descriptor->component_depth - 4)) &&
2286  descriptor->white_ref_level == (235<<(descriptor->component_depth - 8)) &&
2287  descriptor->color_range == ((14<<(descriptor->component_depth - 4)) + 1))
2288  return AVCOL_RANGE_MPEG;
2289  avpriv_request_sample(mxf->fc, "Unrecognized CDCI color range (color diff range %d, b %d, w %d, depth %d)",
2290  descriptor->color_range, descriptor->black_ref_level,
2291  descriptor->white_ref_level, descriptor->component_depth);
2292  }
2293 
2294  return AVCOL_RANGE_UNSPECIFIED;
2295 }
2296 
2298 {
2299  MXFPackage *material_package = NULL;
2300  int i, j, k, ret;
2301 
2302  av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count);
2303  /* TODO: handle multiple material packages (OP3x) */
2304  for (i = 0; i < mxf->packages_count; i++) {
2305  material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
2306  if (material_package) break;
2307  }
2308  if (!material_package) {
2309  av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
2310  return AVERROR_INVALIDDATA;
2311  }
2312 
2313  mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
2314  if (material_package->name && material_package->name[0])
2315  av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
2316  mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
2317 
2318  for (i = 0; i < material_package->tracks_count; i++) {
2319  MXFPackage *source_package = NULL;
2320  MXFTrack *material_track = NULL;
2321  MXFTrack *source_track = NULL;
2322  MXFTrack *temp_track = NULL;
2323  MXFDescriptor *descriptor = NULL;
2324  MXFStructuralComponent *component = NULL;
2325  MXFTimecodeComponent *mxf_tc = NULL;
2326  UID *essence_container_ul = NULL;
2327  const MXFCodecUL *codec_ul = NULL;
2328  const MXFCodecUL *container_ul = NULL;
2329  const MXFCodecUL *pix_fmt_ul = NULL;
2330  AVStream *st;
2331  FFStream *sti;
2332  AVTimecode tc;
2333  int flags;
2334 
2335  if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
2336  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
2337  continue;
2338  }
2339 
2340  if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
2341  mxf_tc = (MXFTimecodeComponent*)component;
2342  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2343  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
2344  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
2345  }
2346  }
2347 
2348  if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
2349  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
2350  continue;
2351  }
2352 
2353  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
2354  component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
2355  if (!component)
2356  continue;
2357 
2358  mxf_tc = (MXFTimecodeComponent*)component;
2359  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2360  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
2361  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
2362  break;
2363  }
2364  }
2365 
2366  /* TODO: handle multiple source clips, only finds first valid source clip */
2367  if(material_track->sequence->structural_components_count > 1)
2368  av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n",
2369  material_track->track_id, material_track->sequence->structural_components_count);
2370 
2371  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
2372  component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]);
2373  if (!component)
2374  continue;
2375 
2376  source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid);
2377  if (!source_package) {
2378  av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id);
2379  continue;
2380  }
2381  for (k = 0; k < source_package->tracks_count; k++) {
2382  if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
2383  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
2385  goto fail_and_free;
2386  }
2387  if (temp_track->track_id == component->source_track_id) {
2388  source_track = temp_track;
2389  break;
2390  }
2391  }
2392  if (!source_track) {
2393  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
2394  break;
2395  }
2396 
2397  for (k = 0; k < mxf->essence_container_data_count; k++) {
2398  MXFEssenceContainerData *essence_data;
2399 
2400  if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) {
2401  av_log(mxf->fc, AV_LOG_TRACE, "could not resolve essence container data strong ref\n");
2402  continue;
2403  }
2404  if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) {
2405  source_track->body_sid = essence_data->body_sid;
2406  source_track->index_sid = essence_data->index_sid;
2407  break;
2408  }
2409  }
2410 
2411  if(source_track && component)
2412  break;
2413  }
2414  if (!source_track || !component || !source_package) {
2415  if((ret = mxf_add_metadata_stream(mxf, material_track)))
2416  goto fail_and_free;
2417  continue;
2418  }
2419 
2420  if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
2421  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
2423  goto fail_and_free;
2424  }
2425 
2426  /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
2427  * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
2428  if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
2429  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
2430  continue;
2431  }
2432 
2433  st = avformat_new_stream(mxf->fc, NULL);
2434  if (!st) {
2435  av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
2436  ret = AVERROR(ENOMEM);
2437  goto fail_and_free;
2438  }
2439  sti = ffstream(st);
2440  st->id = material_track->track_id;
2441  st->priv_data = source_track;
2442 
2443  source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
2444  descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id);
2445 
2446  /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many
2447  * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */
2448  if (descriptor && descriptor->duration != AV_NOPTS_VALUE)
2449  source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration);
2450  else
2451  source_track->original_duration = st->duration = component->duration;
2452 
2453  if (st->duration == -1)
2454  st->duration = AV_NOPTS_VALUE;
2455  st->start_time = component->start_position;
2456  if (material_track->edit_rate.num <= 0 ||
2457  material_track->edit_rate.den <= 0) {
2458  av_log(mxf->fc, AV_LOG_WARNING,
2459  "Invalid edit rate (%d/%d) found on stream #%d, "
2460  "defaulting to 25/1\n",
2461  material_track->edit_rate.num,
2462  material_track->edit_rate.den, st->index);
2463  material_track->edit_rate = (AVRational){25, 1};
2464  }
2465  avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
2466 
2467  /* ensure SourceTrack EditRate == MaterialTrack EditRate since only
2468  * the former is accessible via st->priv_data */
2469  source_track->edit_rate = material_track->edit_rate;
2470 
2471  PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
2473  st->codecpar->codec_type = codec_ul->id;
2474 
2475  if (!descriptor) {
2476  av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
2477  continue;
2478  }
2479  PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
2480  PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
2481  essence_container_ul = &descriptor->essence_container_ul;
2482  source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul);
2483  if (source_track->wrapping == UnknownWrapped)
2484  av_log(mxf->fc, AV_LOG_INFO, "wrapping of stream %d is unknown\n", st->index);
2485  /* HACK: replacing the original key with mxf_encrypted_essence_container
2486  * is not allowed according to s429-6, try to find correct information anyway */
2487  if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
2488  av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
2489  for (k = 0; k < mxf->metadata_sets_count; k++) {
2490  MXFMetadataSet *metadata = mxf->metadata_sets[k];
2491  if (metadata->type == CryptoContext) {
2492  essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
2493  break;
2494  }
2495  }
2496  }
2497 
2498  /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
2500  st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
2501  if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
2503  st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
2504  }
2505 
2506  av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
2508  for (k = 0; k < 16; k++) {
2509  av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
2510  descriptor->essence_codec_ul[k]);
2511  if (!(k+1 & 19) || k == 5)
2512  av_log(mxf->fc, AV_LOG_VERBOSE, ".");
2513  }
2514  av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
2515 
2516  mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package);
2517  if (source_package->name && source_package->name[0])
2518  av_dict_set(&st->metadata, "file_package_name", source_package->name, 0);
2519  if (material_track->name && material_track->name[0])
2520  av_dict_set(&st->metadata, "track_name", material_track->name, 0);
2521 
2522  mxf_parse_physical_source_package(mxf, source_track, st);
2523 
2524  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2525  source_track->intra_only = mxf_is_intra_only(descriptor);
2527  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2528  st->codecpar->codec_id = container_ul->id;
2529  st->codecpar->width = descriptor->width;
2530  st->codecpar->height = descriptor->height; /* Field height, not frame height */
2531  switch (descriptor->frame_layout) {
2532  case FullFrame:
2534  break;
2535  case OneField:
2536  /* Every other line is stored and needs to be duplicated. */
2537  av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
2538  break; /* The correct thing to do here is fall through, but by breaking we might be
2539  able to decode some streams at half the vertical resolution, rather than not al all.
2540  It's also for compatibility with the old behavior. */
2541  case MixedFields:
2542  break;
2543  case SegmentedFrame:
2545  case SeparateFields:
2546  av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n",
2547  descriptor->video_line_map[0], descriptor->video_line_map[1],
2548  descriptor->field_dominance);
2549  if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) {
2550  /* Detect coded field order from VideoLineMap:
2551  * (even, even) => bottom field coded first
2552  * (even, odd) => top field coded first
2553  * (odd, even) => top field coded first
2554  * (odd, odd) => bottom field coded first
2555  */
2556  if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) {
2557  switch (descriptor->field_dominance) {
2561  break;
2564  break;
2565  default:
2567  "Field dominance %d support",
2568  descriptor->field_dominance);
2569  }
2570  } else {
2571  switch (descriptor->field_dominance) {
2575  break;
2578  break;
2579  default:
2581  "Field dominance %d support",
2582  descriptor->field_dominance);
2583  }
2584  }
2585  }
2586  /* Turn field height into frame height. */
2587  st->codecpar->height *= 2;
2588  break;
2589  default:
2590  av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
2591  }
2592 
2593  if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2594  switch (descriptor->essence_codec_ul[14]) {
2595  case 1: st->codecpar->codec_tag = MKTAG('a','p','c','o'); break;
2596  case 2: st->codecpar->codec_tag = MKTAG('a','p','c','s'); break;
2597  case 3: st->codecpar->codec_tag = MKTAG('a','p','c','n'); break;
2598  case 4: st->codecpar->codec_tag = MKTAG('a','p','c','h'); break;
2599  case 5: st->codecpar->codec_tag = MKTAG('a','p','4','h'); break;
2600  case 6: st->codecpar->codec_tag = MKTAG('a','p','4','x'); break;
2601  }
2602  }
2603 
2604  if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
2605  st->codecpar->format = descriptor->pix_fmt;
2606  if (st->codecpar->format == AV_PIX_FMT_NONE) {
2608  &descriptor->essence_codec_ul);
2609  st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id;
2610  if (st->codecpar->format== AV_PIX_FMT_NONE) {
2612  &descriptor->essence_codec_ul)->id;
2613  if (!st->codecpar->codec_tag) {
2614  /* support files created before RP224v10 by defaulting to UYVY422
2615  if subsampling is 4:2:2 and component depth is 8-bit */
2616  if (descriptor->horiz_subsampling == 2 &&
2617  descriptor->vert_subsampling == 1 &&
2618  descriptor->component_depth == 8) {
2620  }
2621  }
2622  }
2623  }
2624  }
2626  if (material_track->sequence->origin) {
2627  av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
2628  }
2629  if (source_track->sequence->origin) {
2630  av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
2631  }
2632  if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den)
2633  sti->display_aspect_ratio = descriptor->aspect_ratio;
2634  st->codecpar->color_range = mxf_get_color_range(mxf, descriptor);
2638  if (descriptor->mastering) {
2640  (uint8_t *)descriptor->mastering,
2641  sizeof(*descriptor->mastering));
2642  if (ret < 0)
2643  goto fail_and_free;
2644  descriptor->mastering = NULL;
2645  }
2646  if (descriptor->coll) {
2648  (uint8_t *)descriptor->coll,
2649  descriptor->coll_size);
2650  if (ret < 0)
2651  goto fail_and_free;
2652  descriptor->coll = NULL;
2653  }
2654  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2656  /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
2658  st->codecpar->codec_id = (enum AVCodecID)container_ul->id;
2659  st->codecpar->channels = descriptor->channels;
2660 
2661  if (descriptor->sample_rate.den > 0) {
2662  st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
2663  avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
2664  } else {
2665  av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
2666  "found for stream #%d, time base forced to 1/48000\n",
2667  descriptor->sample_rate.num, descriptor->sample_rate.den,
2668  st->index);
2669  avpriv_set_pts_info(st, 64, 1, 48000);
2670  }
2671 
2672  /* if duration is set, rescale it from EditRate to SampleRate */
2673  if (st->duration != AV_NOPTS_VALUE)
2674  st->duration = av_rescale_q(st->duration,
2675  av_inv_q(material_track->edit_rate),
2676  st->time_base);
2677 
2678  /* TODO: implement AV_CODEC_ID_RAWAUDIO */
2679  if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
2680  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
2682  else if (descriptor->bits_per_sample == 32)
2684  } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
2685  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
2687  else if (descriptor->bits_per_sample == 32)
2689  } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
2691  }
2693  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
2694  enum AVMediaType type;
2696  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2697  st->codecpar->codec_id = container_ul->id;
2699  if (type == AVMEDIA_TYPE_SUBTITLE)
2700  st->codecpar->codec_type = type;
2701  if (container_ul->desc)
2702  av_dict_set(&st->metadata, "data_type", container_ul->desc, 0);
2703  if (mxf->eia608_extract &&
2704  !strcmp(container_ul->desc, "vbi_vanc_smpte_436M")) {
2707  }
2708  }
2709  if (descriptor->extradata) {
2710  if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) {
2711  memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size);
2712  }
2713  } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
2715  &descriptor->essence_codec_ul)->id;
2716  if (coded_width)
2717  st->codecpar->width = coded_width;
2719  if (ret < 0)
2720  return ret;
2721  }
2722  if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) {
2723  /* TODO: decode timestamps */
2725  }
2726  }
2727 
2728  for (int i = 0; i < mxf->fc->nb_streams; i++) {
2729  MXFTrack *track1 = mxf->fc->streams[i]->priv_data;
2730  if (track1 && track1->body_sid) {
2731  for (int j = i + 1; j < mxf->fc->nb_streams; j++) {
2732  MXFTrack *track2 = mxf->fc->streams[j]->priv_data;
2733  if (track2 && track1->body_sid == track2->body_sid && track1->wrapping != track2->wrapping) {
2734  if (track1->wrapping == UnknownWrapped)
2735  track1->wrapping = track2->wrapping;
2736  else if (track2->wrapping == UnknownWrapped)
2737  track2->wrapping = track1->wrapping;
2738  else
2739  av_log(mxf->fc, AV_LOG_ERROR, "stream %d and stream %d have the same BodySID (%d) "
2740  "with different wrapping\n", i, j, track1->body_sid);
2741  }
2742  }
2743  }
2744  }
2745 
2746  ret = 0;
2747 fail_and_free:
2748  return ret;
2749 }
2750 
2751 static int64_t mxf_timestamp_to_int64(uint64_t timestamp)
2752 {
2753  struct tm time = { 0 };
2754  int msecs;
2755  time.tm_year = (timestamp >> 48) - 1900;
2756  time.tm_mon = (timestamp >> 40 & 0xFF) - 1;
2757  time.tm_mday = (timestamp >> 32 & 0xFF);
2758  time.tm_hour = (timestamp >> 24 & 0xFF);
2759  time.tm_min = (timestamp >> 16 & 0xFF);
2760  time.tm_sec = (timestamp >> 8 & 0xFF);
2761  msecs = (timestamp & 0xFF) * 4;
2762 
2763  /* Clip values for legacy reasons. Maybe we should return error instead? */
2764  time.tm_mon = av_clip(time.tm_mon, 0, 11);
2765  time.tm_mday = av_clip(time.tm_mday, 1, 31);
2766  time.tm_hour = av_clip(time.tm_hour, 0, 23);
2767  time.tm_min = av_clip(time.tm_min, 0, 59);
2768  time.tm_sec = av_clip(time.tm_sec, 0, 59);
2769  msecs = av_clip(msecs, 0, 999);
2770 
2771  return (int64_t)av_timegm(&time) * 1000000 + msecs * 1000;
2772 }
2773 
2774 #define SET_STR_METADATA(pb, name, str) do { \
2775  if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \
2776  return ret; \
2777  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
2778 } while (0)
2779 
2780 #define SET_VERSION_METADATA(pb, name, major, minor, tertiary, patch, release, str) do { \
2781  major = avio_rb16(pb); \
2782  minor = avio_rb16(pb); \
2783  tertiary = avio_rb16(pb); \
2784  patch = avio_rb16(pb); \
2785  release = avio_rb16(pb); \
2786  if ((ret = mxf_version_to_str(major, minor, tertiary, patch, release, &str)) < 0) \
2787  return ret; \
2788  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
2789 } while (0)
2790 
2791 #define SET_UID_METADATA(pb, name, var, str) do { \
2792  avio_read(pb, var, 16); \
2793  if ((ret = mxf_uid_to_str(var, &str)) < 0) \
2794  return ret; \
2795  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
2796 } while (0)
2797 
2798 #define SET_TS_METADATA(pb, name, var, str) do { \
2799  var = avio_rb64(pb); \
2800  if (var && (ret = avpriv_dict_set_timestamp(&s->metadata, name, mxf_timestamp_to_int64(var))) < 0) \
2801  return ret; \
2802 } while (0)
2803 
2804 static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
2805 {
2806  MXFContext *mxf = arg;
2807  AVFormatContext *s = mxf->fc;
2808  int ret;
2809  UID uid = { 0 };
2810  char *str = NULL;
2811  uint64_t ts;
2812  uint16_t major, minor, tertiary, patch, release;
2813  switch (tag) {
2814  case 0x3C01:
2815  SET_STR_METADATA(pb, "company_name", str);
2816  break;
2817  case 0x3C02:
2818  SET_STR_METADATA(pb, "product_name", str);
2819  break;
2820  case 0x3C03:
2821  SET_VERSION_METADATA(pb, "product_version_num", major, minor, tertiary, patch, release, str);
2822  break;
2823  case 0x3C04:
2824  SET_STR_METADATA(pb, "product_version", str);
2825  break;
2826  case 0x3C05:
2827  SET_UID_METADATA(pb, "product_uid", uid, str);
2828  break;
2829  case 0x3C06:
2830  SET_TS_METADATA(pb, "modification_date", ts, str);
2831  break;
2832  case 0x3C07:
2833  SET_VERSION_METADATA(pb, "toolkit_version_num", major, minor, tertiary, patch, release, str);
2834  break;
2835  case 0x3C08:
2836  SET_STR_METADATA(pb, "application_platform", str);
2837  break;
2838  case 0x3C09:
2839  SET_UID_METADATA(pb, "generation_uid", uid, str);
2840  break;
2841  case 0x3C0A:
2842  SET_UID_METADATA(pb, "uid", uid, str);
2843  break;
2844  }
2845  return 0;
2846 }
2847 
2848 static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
2849 {
2850  MXFContext *mxf = arg;
2851  AVFormatContext *s = mxf->fc;
2852  int ret;
2853  char *str = NULL;
2854 
2855  if (tag >= 0x8000 && (IS_KLV_KEY(uid, mxf_avid_project_name))) {
2856  SET_STR_METADATA(pb, "project_name", str);
2857  }
2858  return 0;
2859 }
2860 
2862  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
2863  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
2864  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
2865  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
2866  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
2867  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
2868  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
2869  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
2870  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
2871  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
2872  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
2873  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_metadata },
2874  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata },
2875  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
2876  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_package, sizeof(MXFPackage), SourcePackage },
2877  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_package, sizeof(MXFPackage), MaterialPackage },
2878  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
2879  { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup},
2880  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
2881  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue },
2882  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
2883  { { 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 */
2884  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
2885  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
2886  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
2887  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
2888  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */
2889  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5b,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VBI - SMPTE 436M */
2890  { { 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 */
2891  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */
2892  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x64,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* DC Timed Text Descriptor */
2893  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
2894  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
2895  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
2896  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0c,0x00 }, mxf_read_pulldown_component, sizeof(MXFPulldownComponent), PulldownComponent },
2897  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
2898  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
2899  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x23,0x00 }, mxf_read_essence_container_data, sizeof(MXFEssenceContainerData), EssenceContainerData },
2900  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
2901 };
2902 
2904 {
2905  ctx->type = type;
2906  ctx->partition_score = partition_score(partition);
2907  switch (type){
2908  case MultipleDescriptor:
2909  case Descriptor:
2910  ((MXFDescriptor*)ctx)->pix_fmt = AV_PIX_FMT_NONE;
2911  ((MXFDescriptor*)ctx)->duration = AV_NOPTS_VALUE;
2912  break;
2913  default:
2914  break;
2915  }
2916  return 0;
2917 }
2918 
2919 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
2920 {
2921  AVIOContext *pb = mxf->fc->pb;
2922  uint64_t klv_end = avio_tell(pb) + klv->length;
2923  MXFMetadataSet *meta;
2924  void *ctx;
2925 
2926  if (ctx_size) {
2927  meta = av_mallocz(ctx_size);
2928  if (!meta)
2929  return AVERROR(ENOMEM);
2930  ctx = meta;
2932  } else {
2933  meta = NULL;
2934  ctx = mxf;
2935  }
2936  while (avio_tell(pb) + 4ULL < klv_end && !avio_feof(pb)) {
2937  int ret;
2938  int tag = avio_rb16(pb);
2939  int size = avio_rb16(pb); /* KLV specified by 0x53 */
2940  int64_t next = avio_tell(pb);
2941  UID uid = {0};
2942  if (next < 0 || next > INT64_MAX - size) {
2943  if (meta) {
2944  mxf_free_metadataset(&meta, 1);
2945  }
2946  return next < 0 ? next : AVERROR_INVALIDDATA;
2947  }
2948  next += size;
2949 
2950  av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x size %d\n", tag, size);
2951  if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
2952  av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
2953  continue;
2954  }
2955  if (tag > 0x7FFF) { /* dynamic tag */
2956  int i;
2957  for (i = 0; i < mxf->local_tags_count; i++) {
2958  int local_tag = AV_RB16(mxf->local_tags+i*18);
2959  if (local_tag == tag) {
2960  memcpy(uid, mxf->local_tags+i*18+2, 16);
2961  av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x\n", local_tag);
2962  PRINT_KEY(mxf->fc, "uid", uid);
2963  }
2964  }
2965  }
2966  if (meta && tag == 0x3C0A) {
2967  avio_read(pb, meta->uid, 16);
2968  } else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0) {
2969  if (meta) {
2970  mxf_free_metadataset(&meta, 1);
2971  }
2972  return ret;
2973  }
2974 
2975  /* Accept the 64k local set limit being exceeded (Avid). Don't accept
2976  * it extending past the end of the KLV though (zzuf5.mxf). */
2977  if (avio_tell(pb) > klv_end) {
2978  if (meta) {
2979  mxf_free_metadataset(&meta, 1);
2980  }
2981 
2982  av_log(mxf->fc, AV_LOG_ERROR,
2983  "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
2984  tag, klv->offset);
2985  return AVERROR_INVALIDDATA;
2986  } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
2987  avio_seek(pb, next, SEEK_SET);
2988  }
2989  return meta ? mxf_add_metadata_set(mxf, &meta) : 0;
2990 }
2991 
2992 /**
2993  * Matches any partition pack key, in other words:
2994  * - HeaderPartition
2995  * - BodyPartition
2996  * - FooterPartition
2997  * @return non-zero if the key is a partition pack key, zero otherwise
2998  */
3000 {
3001  //NOTE: this is a little lax since it doesn't constraint key[14]
3002  return !memcmp(key, mxf_header_partition_pack_key, 13) &&
3003  key[13] >= 2 && key[13] <= 4;
3004 }
3005 
3006 /**
3007  * Parses a metadata KLV
3008  * @return <0 on error, 0 otherwise
3009  */
3011  int ctx_size, enum MXFMetadataSetType type)
3012 {
3013  AVFormatContext *s = mxf->fc;
3014  int res;
3015  if (klv.key[5] == 0x53) {
3016  res = mxf_read_local_tags(mxf, &klv, read, ctx_size, type);
3017  } else {
3018  uint64_t next = avio_tell(s->pb) + klv.length;
3019  res = read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
3020 
3021  /* only seek forward, else this can loop for a long time */
3022  if (avio_tell(s->pb) > next) {
3023  av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
3024  klv.offset);
3025  return AVERROR_INVALIDDATA;
3026  }
3027 
3028  avio_seek(s->pb, next, SEEK_SET);
3029  }
3030  if (res < 0) {
3031  av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
3032  return res;
3033  }
3034  return 0;
3035 }
3036 
3037 /**
3038  * Seeks to the previous partition and parses it, if possible
3039  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3040  */
3042 {
3043  AVIOContext *pb = mxf->fc->pb;
3044  KLVPacket klv;
3045  int64_t current_partition_ofs;
3046  int ret;
3047 
3048  if (!mxf->current_partition ||
3050  return 0; /* we've parsed all partitions */
3051 
3052  /* seek to previous partition */
3053  current_partition_ofs = mxf->current_partition->pack_ofs; //includes run-in
3054  avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
3055  mxf->current_partition = NULL;
3056 
3057  av_log(mxf->fc, AV_LOG_TRACE, "seeking to previous partition\n");
3058 
3059  /* Make sure this is actually a PartitionPack, and if so parse it.
3060  * See deadlock2.mxf
3061  */
3062  if ((ret = klv_read_packet(&klv, pb)) < 0) {
3063  av_log(mxf->fc, AV_LOG_ERROR, "failed to read PartitionPack KLV\n");
3064  return ret;
3065  }
3066 
3067  if (!mxf_is_partition_pack_key(klv.key)) {
3068  av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition @ %" PRIx64 " isn't a PartitionPack\n", klv.offset);
3069  return AVERROR_INVALIDDATA;
3070  }
3071 
3072  /* We can't just check ofs >= current_partition_ofs because PreviousPartition
3073  * can point to just before the current partition, causing klv_read_packet()
3074  * to sync back up to it. See deadlock3.mxf
3075  */
3076  if (klv.offset >= current_partition_ofs) {
3077  av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition for PartitionPack @ %"
3078  PRIx64 " indirectly points to itself\n", current_partition_ofs);
3079  return AVERROR_INVALIDDATA;
3080  }
3081 
3082  if ((ret = mxf_parse_klv(mxf, klv, mxf_read_partition_pack, 0, 0)) < 0)
3083  return ret;
3084 
3085  return 1;
3086 }
3087 
3088 /**
3089  * Called when essence is encountered
3090  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3091  */
3093 {
3094  AVIOContext *pb = mxf->fc->pb;
3095  int64_t ret;
3096 
3097  if (mxf->parsing_backward) {
3098  return mxf_seek_to_previous_partition(mxf);
3099  } else {
3100  if (!mxf->footer_partition) {
3101  av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n");
3102  return 0;
3103  }
3104 
3105  av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n");
3106 
3107  /* remember where we were so we don't end up seeking further back than this */
3108  mxf->last_forward_tell = avio_tell(pb);
3109 
3110  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) {
3111  av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n");
3112  return -1;
3113  }
3114 
3115  /* seek to FooterPartition and parse backward */
3116  if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
3117  av_log(mxf->fc, AV_LOG_ERROR,
3118  "failed to seek to FooterPartition @ 0x%" PRIx64
3119  " (%"PRId64") - partial file?\n",
3120  mxf->run_in + mxf->footer_partition, ret);
3121  return ret;
3122  }
3123 
3124  mxf->current_partition = NULL;
3125  mxf->parsing_backward = 1;
3126  }
3127 
3128  return 1;
3129 }
3130 
3131 /**
3132  * Called when the next partition or EOF is encountered
3133  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3134  */
3136 {
3137  return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
3138 }
3139 
3141 {
3142  for (int i = 0; i < s->nb_streams; i++) {
3143  MXFTrack *track = s->streams[i]->priv_data;
3144  if (track && track->body_sid == body_sid && track->wrapping != UnknownWrapped)
3145  return track->wrapping;
3146  }
3147  return UnknownWrapped;
3148 }
3149 
3150 /**
3151  * Figures out the proper offset and length of the essence container in each partition
3152  */
3154 {
3155  MXFContext *mxf = s->priv_data;
3156  int x;
3157 
3158  for (x = 0; x < mxf->partitions_count; x++) {
3159  MXFPartition *p = &mxf->partitions[x];
3160  MXFWrappingScheme wrapping;
3161 
3162  if (!p->body_sid)
3163  continue; /* BodySID == 0 -> no essence */
3164 
3165  /* for clip wrapped essences we point essence_offset after the KL (usually klv.offset + 20 or 25)
3166  * otherwise we point essence_offset at the key of the first essence KLV.
3167  */
3168 
3169  wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_by_body_sid(s, p->body_sid);
3170 
3171  if (wrapping == ClipWrapped) {
3174  } else {
3176 
3177  /* essence container spans to the next partition */
3178  if (x < mxf->partitions_count - 1)
3180 
3181  if (p->essence_length < 0) {
3182  /* next ThisPartition < essence_offset */
3183  p->essence_length = 0;
3184  av_log(mxf->fc, AV_LOG_ERROR,
3185  "partition %i: bad ThisPartition = %"PRIX64"\n",
3186  x+1, mxf->partitions[x+1].this_partition);
3187  }
3188  }
3189  }
3190 }
3191 
3192 static int is_pcm(enum AVCodecID codec_id)
3193 {
3194  /* we only care about "normal" PCM codecs until we get samples */
3196 }
3197 
3198 static MXFIndexTable *mxf_find_index_table(MXFContext *mxf, int index_sid)
3199 {
3200  int i;
3201  for (i = 0; i < mxf->nb_index_tables; i++)
3202  if (mxf->index_tables[i].index_sid == index_sid)
3203  return &mxf->index_tables[i];
3204  return NULL;
3205 }
3206 
3207 /**
3208  * Deal with the case where for some audio atoms EditUnitByteCount is
3209  * very small (2, 4..). In those cases we should read more than one
3210  * sample per call to mxf_read_packet().
3211  */
3213 {
3214  MXFTrack *track = st->priv_data;
3215  MXFIndexTable *t;
3216 
3217  if (!track)
3218  return;
3219  track->edit_units_per_packet = 1;
3220  if (track->wrapping != ClipWrapped)
3221  return;
3222 
3223  t = mxf_find_index_table(mxf, track->index_sid);
3224 
3225  /* expect PCM with exactly one index table segment and a small (< 32) EUBC */
3226  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
3227  !is_pcm(st->codecpar->codec_id) ||
3228  !t ||
3229  t->nb_segments != 1 ||
3230  t->segments[0]->edit_unit_byte_count >= 32)
3231  return;
3232 
3233  /* arbitrarily default to 48 kHz PAL audio frame size */
3234  /* TODO: We could compute this from the ratio between the audio
3235  * and video edit rates for 48 kHz NTSC we could use the
3236  * 1802-1802-1802-1802-1801 pattern. */
3237  track->edit_units_per_packet = FFMAX(1, track->edit_rate.num / track->edit_rate.den / 25);
3238 }
3239 
3240 /**
3241  * Deal with the case where ClipWrapped essences does not have any IndexTableSegments.
3242  */
3244 {
3245  MXFTrack *track = st->priv_data;
3247  MXFPartition *p = NULL;
3248  int essence_partition_count = 0;
3249  int edit_unit_byte_count = 0;
3250  int i, ret;
3251 
3252  if (!track || track->wrapping != ClipWrapped)
3253  return 0;
3254 
3255  /* check if track already has an IndexTableSegment */
3256  for (i = 0; i < mxf->metadata_sets_count; i++) {
3257  if (mxf->metadata_sets[i]->type == IndexTableSegment) {
3259  if (s->body_sid == track->body_sid)
3260  return 0;
3261  }
3262  }
3263 
3264  /* find the essence partition */
3265  for (i = 0; i < mxf->partitions_count; i++) {
3266  /* BodySID == 0 -> no essence */
3267  if (mxf->partitions[i].body_sid != track->body_sid)
3268  continue;
3269 
3270  p = &mxf->partitions[i];
3271  essence_partition_count++;
3272  }
3273 
3274  /* only handle files with a single essence partition */
3275  if (essence_partition_count != 1)
3276  return 0;
3277 
3279  edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3;
3280  } else if (st->duration > 0 && p->first_essence_klv.length > 0 && p->first_essence_klv.length % st->duration == 0) {
3281  edit_unit_byte_count = p->first_essence_klv.length / st->duration;
3282  }
3283 
3284  if (edit_unit_byte_count <= 0)
3285  return 0;
3286 
3287  av_log(mxf->fc, AV_LOG_WARNING, "guessing index for stream %d using edit unit byte count %d\n", st->index, edit_unit_byte_count);
3288 
3289  if (!(segment = av_mallocz(sizeof(*segment))))
3290  return AVERROR(ENOMEM);
3291 
3292  if ((ret = mxf_add_metadata_set(mxf, (MXFMetadataSet**)&segment)))
3293  return ret;
3294 
3295  /* Make sure we have nonzero unique index_sid, body_sid will be ok, because
3296  * using the same SID for index is forbidden in MXF. */
3297  if (!track->index_sid)
3298  track->index_sid = track->body_sid;
3299 
3300  segment->meta.type = IndexTableSegment;
3301  /* stream will be treated as small EditUnitByteCount */
3302  segment->edit_unit_byte_count = edit_unit_byte_count;
3303  segment->index_start_position = 0;
3304  segment->index_duration = st->duration;
3305  segment->index_edit_rate = av_inv_q(st->time_base);
3306  segment->index_sid = track->index_sid;
3307  segment->body_sid = p->body_sid;
3308  return 0;
3309 }
3310 
3312 {
3313  MXFContext *mxf = s->priv_data;
3314  uint32_t length;
3315  int64_t file_size, max_rip_length, min_rip_length;
3316  KLVPacket klv;
3317 
3318  if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
3319  return;
3320 
3321  file_size = avio_size(s->pb);
3322 
3323  /* S377m says to check the RIP length for "silly" values, without defining "silly".
3324  * The limit below assumes a file with nothing but partition packs and a RIP.
3325  * Before changing this, consider that a muxer may place each sample in its own partition.
3326  *
3327  * 105 is the size of the smallest possible PartitionPack
3328  * 12 is the size of each RIP entry
3329  * 28 is the size of the RIP header and footer, assuming an 8-byte BER
3330  */
3331  max_rip_length = ((file_size - mxf->run_in) / 105) * 12 + 28;
3332  max_rip_length = FFMIN(max_rip_length, INT_MAX); //2 GiB and up is also silly
3333 
3334  /* We're only interested in RIPs with at least two entries.. */
3335  min_rip_length = 16+1+24+4;
3336 
3337  /* See S377m section 11 */
3338  avio_seek(s->pb, file_size - 4, SEEK_SET);
3339  length = avio_rb32(s->pb);
3340 
3341  if (length < min_rip_length || length > max_rip_length)
3342  goto end;
3343  avio_seek(s->pb, file_size - length, SEEK_SET);
3344  if (klv_read_packet(&klv, s->pb) < 0 ||
3346  goto end;
3347  if (klv.next_klv != file_size || klv.length <= 4 || (klv.length - 4) % 12) {
3348  av_log(s, AV_LOG_WARNING, "Invalid RIP KLV length\n");
3349  goto end;
3350  }
3351 
3352  avio_skip(s->pb, klv.length - 12);
3353  mxf->footer_partition = avio_rb64(s->pb);
3354 
3355  /* sanity check */
3356  if (mxf->run_in + mxf->footer_partition >= file_size) {
3357  av_log(s, AV_LOG_WARNING, "bad FooterPartition in RIP - ignoring\n");
3358  mxf->footer_partition = 0;
3359  }
3360 
3361 end:
3362  avio_seek(s->pb, mxf->run_in, SEEK_SET);
3363 }
3364 
3366 {
3367  MXFContext *mxf = s->priv_data;
3368  KLVPacket klv;
3369  int64_t essence_offset = 0;
3370  int ret;
3371 
3372  mxf->last_forward_tell = INT64_MAX;
3373 
3375  av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
3376  return AVERROR_INVALIDDATA;
3377  }
3378  avio_seek(s->pb, -14, SEEK_CUR);
3379  mxf->fc = s;
3380  mxf->run_in = avio_tell(s->pb);
3381 
3383 
3384  while (!avio_feof(s->pb)) {
3385  const MXFMetadataReadTableEntry *metadata;
3386 
3387  if (klv_read_packet(&klv, s->pb) < 0) {
3388  /* EOF - seek to previous partition or stop */
3389  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
3390  break;
3391  else
3392  continue;
3393  }
3394 
3395  PRINT_KEY(s, "read header", klv.key);
3396  av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
3403 
3404  if (!mxf->current_partition) {
3405  av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
3406  return AVERROR_INVALIDDATA;
3407  }
3408 
3411 
3412  if (!essence_offset)
3413  essence_offset = klv.offset;
3414 
3415  /* seek to footer, previous partition or stop */
3416  if (mxf_parse_handle_essence(mxf) <= 0)
3417  break;
3418  continue;
3419  } else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) {
3420  /* next partition pack - keep going, seek to previous partition or stop */
3421  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
3422  break;
3423  else if (mxf->parsing_backward)
3424  continue;
3425  /* we're still parsing forward. proceed to parsing this partition pack */
3426  }
3427 
3428  for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
3429  if (IS_KLV_KEY(klv.key, metadata->key)) {
3430  if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0)
3431  return ret;
3432  break;
3433  }
3434  }
3435  if (!metadata->read) {
3436  av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n",
3437  UID_ARG(klv.key));
3438  avio_skip(s->pb, klv.length);
3439  }
3440  }
3441  /* FIXME avoid seek */
3442  if (!essence_offset) {
3443  av_log(s, AV_LOG_ERROR, "no essence\n");
3444  return AVERROR_INVALIDDATA;
3445  }
3446  avio_seek(s->pb, essence_offset, SEEK_SET);
3447 
3448  /* we need to do this before computing the index tables
3449  * to be able to fill in zero IndexDurations with st->duration */
3450  if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
3451  return ret;
3452 
3453  for (int i = 0; i < s->nb_streams; i++)
3454  mxf_handle_missing_index_segment(mxf, s->streams[i]);
3455 
3456  if ((ret = mxf_compute_index_tables(mxf)) < 0)
3457  return ret;
3458 
3459  if (mxf->nb_index_tables > 1) {
3460  /* TODO: look up which IndexSID to use via EssenceContainerData */
3461  av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
3462  mxf->nb_index_tables, mxf->index_tables[0].index_sid);
3463  } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom && (s->error_recognition & AV_EF_EXPLODE)) {
3464  av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
3465  return AVERROR_INVALIDDATA;
3466  }
3467 
3469 
3470  for (int i = 0; i < s->nb_streams; i++)
3471  mxf_compute_edit_units_per_packet(mxf, s->streams[i]);
3472 
3473  return 0;
3474 }
3475 
3476 /* Get the edit unit of the next packet from current_offset in a track. The returned edit unit can be original_duration as well! */
3477 static int mxf_get_next_track_edit_unit(MXFContext *mxf, MXFTrack *track, int64_t current_offset, int64_t *edit_unit_out)
3478 {
3479  int64_t a, b, m, offset;
3480  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3481 
3482  if (!t || track->original_duration <= 0)
3483  return -1;
3484 
3485  a = -1;
3486  b = track->original_duration;
3487 
3488  while (b - a > 1) {
3489  m = (a + b) >> 1;
3490  if (mxf_edit_unit_absolute_offset(mxf, t, m, track->edit_rate, NULL, &offset, NULL, 0) < 0)
3491  return -1;
3492  if (offset < current_offset)
3493  a = m;
3494  else
3495  b = m;
3496  }
3497 
3498  *edit_unit_out = b;
3499 
3500  return 0;
3501 }
3502 
3504  int64_t edit_unit)
3505 {
3506  MXFTrack *track = st->priv_data;
3507  AVRational time_base = av_inv_q(track->edit_rate);
3509 
3510  // For non-audio sample_count equals current edit unit
3512  return edit_unit;
3513 
3514  if ((sample_rate.num / sample_rate.den) == 48000) {
3515  return av_rescale_q(edit_unit, sample_rate, track->edit_rate);
3516  } else {
3517  int remainder = (sample_rate.num * time_base.num) %
3518  (time_base.den * sample_rate.den);
3519  if (remainder)
3520  av_log(mxf->fc, AV_LOG_WARNING,
3521  "seeking detected on stream #%d with time base (%d/%d) and "
3522  "sample rate (%d/%d), audio pts won't be accurate.\n",
3523  st->index, time_base.num, time_base.den,
3524  sample_rate.num, sample_rate.den);
3525  return av_rescale_q(edit_unit, sample_rate, track->edit_rate);
3526  }
3527 }
3528 
3529 /**
3530  * Make sure track->sample_count is correct based on what offset we're currently at.
3531  * Also determine the next edit unit (or packet) offset.
3532  * @return next_ofs if OK, <0 on error
3533  */
3534 static int64_t mxf_set_current_edit_unit(MXFContext *mxf, AVStream *st, int64_t current_offset, int resync)
3535 {
3536  int64_t next_ofs = -1;
3537  MXFTrack *track = st->priv_data;
3538  int64_t edit_unit = av_rescale_q(track->sample_count, st->time_base, av_inv_q(track->edit_rate));
3539  int64_t new_edit_unit;
3540  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3541 
3542  if (!t || track->wrapping == UnknownWrapped)
3543  return -1;
3544 
3545  if (mxf_edit_unit_absolute_offset(mxf, t, edit_unit + track->edit_units_per_packet, track->edit_rate, NULL, &next_ofs, NULL, 0) < 0 &&
3546  (next_ofs = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
3547  av_log(mxf->fc, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
3548  return -1;
3549  }
3550 
3551  /* check if the next edit unit offset (next_ofs) starts ahead of current_offset */
3552  if (next_ofs > current_offset)
3553  return next_ofs;
3554 
3555  if (!resync) {
3556  av_log(mxf->fc, AV_LOG_ERROR, "cannot find current edit unit for stream %d, invalid index?\n", st->index);
3557  return -1;
3558  }
3559 
3560  if (mxf_get_next_track_edit_unit(mxf, track, current_offset + 1, &new_edit_unit) < 0 || new_edit_unit <= 0) {
3561  av_log(mxf->fc, AV_LOG_ERROR, "failed to find next track edit unit in stream %d\n", st->index);
3562  return -1;
3563  }
3564 
3565  new_edit_unit--;
3566  track->sample_count = mxf_compute_sample_count(mxf, st, new_edit_unit);
3567  av_log(mxf->fc, AV_LOG_WARNING, "edit unit sync lost on stream %d, jumping from %"PRId64" to %"PRId64"\n", st->index, edit_unit, new_edit_unit);
3568 
3569  return mxf_set_current_edit_unit(mxf, st, current_offset, 0);
3570 }
3571 
3573  AVPacket *pkt)
3574 {
3575  AVStream *st = mxf->fc->streams[pkt->stream_index];
3576  MXFTrack *track = st->priv_data;
3577  int64_t bits_per_sample = par->bits_per_coded_sample;
3578 
3579  if (!bits_per_sample)
3580  bits_per_sample = av_get_bits_per_sample(par->codec_id);
3581 
3582  pkt->pts = track->sample_count;
3583 
3584  if ( par->channels <= 0
3585  || bits_per_sample <= 0
3586  || par->channels * (int64_t)bits_per_sample < 8)
3587  track->sample_count = mxf_compute_sample_count(mxf, st, av_rescale_q(track->sample_count, st->time_base, av_inv_q(track->edit_rate)) + 1);
3588  else
3589  track->sample_count += pkt->size / (par->channels * (int64_t)bits_per_sample / 8);
3590 
3591  return 0;
3592 }
3593 
3594 static int mxf_set_pts(MXFContext *mxf, AVStream *st, AVPacket *pkt)
3595 {
3596  AVCodecParameters *par = st->codecpar;
3597  MXFTrack *track = st->priv_data;
3598 
3599  if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
3600  /* see if we have an index table to derive timestamps from */
3601  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3602 
3603  if (t && track->sample_count < t->nb_ptses) {
3604  pkt->dts = track->sample_count + t->first_dts;
3605  pkt->pts = t->ptses[track->sample_count];
3606  } else if (track->intra_only) {
3607  /* intra-only -> PTS = EditUnit.
3608  * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
3609  pkt->pts = track->sample_count;
3610  }
3611  track->sample_count++;
3612  } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
3613  int ret = mxf_set_audio_pts(mxf, par, pkt);
3614  if (ret < 0)
3615  return ret;
3616  } else if (track) {
3617  pkt->dts = pkt->pts = track->sample_count;
3618  pkt->duration = 1;
3619  track->sample_count++;
3620  }
3621  return 0;
3622 }
3623 
3625 {
3626  KLVPacket klv;
3627  MXFContext *mxf = s->priv_data;
3628  int ret;
3629 
3630  while (1) {
3631  int64_t max_data_size;
3632  int64_t pos = avio_tell(s->pb);
3633 
3634  if (pos < mxf->current_klv_data.next_klv - mxf->current_klv_data.length || pos >= mxf->current_klv_data.next_klv) {
3635  mxf->current_klv_data = (KLVPacket){{0}};
3636  ret = klv_read_packet(&klv, s->pb);
3637  if (ret < 0)
3638  break;
3639  max_data_size = klv.length;
3640  pos = klv.next_klv - klv.length;
3641  PRINT_KEY(s, "read packet", klv.key);
3642  av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
3644  ret = mxf_decrypt_triplet(s, pkt, &klv);
3645  if (ret < 0) {
3646  av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
3647  return ret;
3648  }
3649  return 0;
3650  }
3651  } else {
3652  klv = mxf->current_klv_data;
3653  max_data_size = klv.next_klv - pos;
3654  }
3658  int body_sid = find_body_sid_by_absolute_offset(mxf, klv.offset);
3659  int index = mxf_get_stream_index(s, &klv, body_sid);
3660  int64_t next_ofs;
3661  AVStream *st;
3662  MXFTrack *track;
3663 
3664  if (index < 0) {
3666  "error getting stream index %"PRIu32"\n",
3667  AV_RB32(klv.key + 12));
3668  goto skip;
3669  }
3670 
3671  st = s->streams[index];
3672  track = st->priv_data;
3673 
3674  if (s->streams[index]->discard == AVDISCARD_ALL)
3675  goto skip;
3676 
3677  next_ofs = mxf_set_current_edit_unit(mxf, st, pos, 1);
3678 
3679  if (track->wrapping != FrameWrapped) {
3680  int64_t size;
3681 
3682  if (next_ofs <= 0) {
3683  // If we have no way to packetize the data, then return it in chunks...
3684  if (klv.next_klv - klv.length == pos && max_data_size > MXF_MAX_CHUNK_SIZE) {
3686  avpriv_request_sample(s, "Huge KLV without proper index in non-frame wrapped essence");
3687  }
3688  size = FFMIN(max_data_size, MXF_MAX_CHUNK_SIZE);
3689  } else {
3690  if ((size = next_ofs - pos) <= 0) {
3691  av_log(s, AV_LOG_ERROR, "bad size: %"PRId64"\n", size);
3692  mxf->current_klv_data = (KLVPacket){{0}};
3693  return AVERROR_INVALIDDATA;
3694  }
3695  // We must not overread, because the next edit unit might be in another KLV
3696  if (size > max_data_size)
3697  size = max_data_size;
3698  }
3699 
3700  mxf->current_klv_data = klv;
3701  klv.offset = pos;
3702  klv.length = size;
3703  klv.next_klv = klv.offset + klv.length;
3704  }
3705 
3706  /* check for 8 channels AES3 element */
3707  if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
3708  ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
3709  pkt, klv.length);
3710  if (ret < 0) {
3711  av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
3712  mxf->current_klv_data = (KLVPacket){{0}};
3713  return ret;
3714  }
3715  } else if (mxf->eia608_extract &&
3716  s->streams[index]->codecpar->codec_id == AV_CODEC_ID_EIA_608) {
3717  ret = mxf_get_eia608_packet(s, s->streams[index], pkt, klv.length);
3718  if (ret < 0) {
3719  mxf->current_klv_data = (KLVPacket){{0}};
3720  return ret;
3721  }
3722  } else {
3723  ret = av_get_packet(s->pb, pkt, klv.length);
3724  if (ret < 0) {
3725  mxf->current_klv_data = (KLVPacket){{0}};
3726  return ret;
3727  }
3728  }
3729  pkt->stream_index = index;
3730  pkt->pos = klv.offset;
3731 
3732  ret = mxf_set_pts(mxf, st, pkt);
3733  if (ret < 0) {
3734  mxf->current_klv_data = (KLVPacket){{0}};
3735  return ret;
3736  }
3737 
3738  /* seek for truncated packets */
3739  avio_seek(s->pb, klv.next_klv, SEEK_SET);
3740 
3741  return 0;
3742  } else {
3743  skip:
3744  avio_skip(s->pb, max_data_size);
3745  mxf->current_klv_data = (KLVPacket){{0}};
3746  }
3747  }
3748  return avio_feof(s->pb) ? AVERROR_EOF : ret;
3749 }
3750 
3752 {
3753  MXFContext *mxf = s->priv_data;
3754  int i;
3755 
3756  av_freep(&mxf->packages_refs);
3758 
3759  for (i = 0; i < s->nb_streams; i++)
3760  s->streams[i]->priv_data = NULL;
3761 
3762  for (i = 0; i < mxf->metadata_sets_count; i++) {
3764  }
3765  mxf->metadata_sets_count = 0;
3766  av_freep(&mxf->partitions);
3767  av_freep(&mxf->metadata_sets);
3768  av_freep(&mxf->aesc);
3769  av_freep(&mxf->local_tags);
3770 
3771  if (mxf->index_tables) {
3772  for (i = 0; i < mxf->nb_index_tables; i++) {
3773  av_freep(&mxf->index_tables[i].segments);
3774  av_freep(&mxf->index_tables[i].ptses);
3776  av_freep(&mxf->index_tables[i].offsets);
3777  }
3778  }
3779  av_freep(&mxf->index_tables);
3780 
3781  return 0;
3782 }
3783 
3784 static int mxf_probe(const AVProbeData *p) {
3785  const uint8_t *bufp = p->buf;
3786  const uint8_t *end = p->buf + p->buf_size;
3787 
3788  if (p->buf_size < sizeof(mxf_header_partition_pack_key))
3789  return 0;
3790 
3791  /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
3792  end -= sizeof(mxf_header_partition_pack_key);
3793 
3794  for (; bufp < end;) {
3795  if (!((bufp[13] - 1) & 0xF2)){
3796  if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) &&
3797  AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) &&
3798  AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) &&
3800  return bufp == p->buf ? AVPROBE_SCORE_MAX : AVPROBE_SCORE_MAX - 1;
3801  bufp ++;
3802  } else
3803  bufp += 10;
3804  }
3805 
3806  return 0;
3807 }
3808 
3809 /* rudimentary byte seek */
3810 /* XXX: use MXF Index */
3811 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3812 {
3813  AVStream *st = s->streams[stream_index];
3814  int64_t seconds;
3815  MXFContext* mxf = s->priv_data;
3816  int64_t seekpos;
3817  int i, ret;
3818  MXFIndexTable *t;
3819  MXFTrack *source_track = st->priv_data;
3820 
3821  if (!source_track)
3822  return 0;
3823 
3824  /* if audio then truncate sample_time to EditRate */
3826  sample_time = av_rescale_q(sample_time, st->time_base,
3827  av_inv_q(source_track->edit_rate));
3828 
3829  if (mxf->nb_index_tables <= 0) {
3830  if (!s->bit_rate)
3831  return AVERROR_INVALIDDATA;
3832  if (sample_time < 0)
3833  sample_time = 0;
3834  seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
3835 
3836  seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
3837  if (seekpos < 0)
3838  return seekpos;
3839 
3840  avpriv_update_cur_dts(s, st, sample_time);
3841  mxf->current_klv_data = (KLVPacket){{0}};
3842  } else {
3843  MXFPartition *partition;
3844 
3845  t = &mxf->index_tables[0];
3846  if (t->index_sid != source_track->index_sid) {
3847  /* If the first index table does not belong to the stream, then find a stream which does belong to the index table */
3848  for (i = 0; i < s->nb_streams; i++) {
3849  MXFTrack *new_source_track = s->streams[i]->priv_data;
3850  if (new_source_track && new_source_track->index_sid == t->index_sid) {
3851  sample_time = av_rescale_q(sample_time, new_source_track->edit_rate, source_track->edit_rate);
3852  source_track = new_source_track;
3853  st = s->streams[i];
3854  break;
3855  }
3856  }
3857  if (i == s->nb_streams)
3858  return AVERROR_INVALIDDATA;
3859  }
3860 
3861  /* clamp above zero, else ff_index_search_timestamp() returns negative
3862  * this also means we allow seeking before the start */
3863  sample_time = FFMAX(sample_time, 0);
3864 
3865  if (t->fake_index) {
3866  /* The first frames may not be keyframes in presentation order, so
3867  * we have to advance the target to be able to find the first
3868  * keyframe backwards... */
3869  if (!(flags & AVSEEK_FLAG_ANY) &&
3871  t->ptses[0] != AV_NOPTS_VALUE &&
3872  sample_time < t->ptses[0] &&
3873  (t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME))
3874  sample_time = t->ptses[0];
3875 
3876  /* behave as if we have a proper index */
3877  if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
3878  return sample_time;
3879  /* get the stored order index from the display order index */
3880  sample_time += t->offsets[sample_time];
3881  } else {
3882  /* no IndexEntryArray (one or more CBR segments)
3883  * make sure we don't seek past the end */
3884  sample_time = FFMIN(sample_time, source_track->original_duration - 1);
3885  }
3886 
3887  if (source_track->wrapping == UnknownWrapped)
3888  av_log(mxf->fc, AV_LOG_WARNING, "attempted seek in an UnknownWrapped essence\n");
3889 
3890  if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, source_track->edit_rate, &sample_time, &seekpos, &partition, 1)) < 0)
3891  return ret;
3892 
3893  avpriv_update_cur_dts(s, st, sample_time);
3894  if (source_track->wrapping == ClipWrapped) {
3895  KLVPacket klv = partition->first_essence_klv;
3896  if (seekpos < klv.next_klv - klv.length || seekpos >= klv.next_klv) {
3897  av_log(mxf->fc, AV_LOG_ERROR, "attempted seek out of clip wrapped KLV\n");
3898  return AVERROR_INVALIDDATA;
3899  }
3900  mxf->current_klv_data = klv;
3901  } else {
3902  mxf->current_klv_data = (KLVPacket){{0}};
3903  }
3904  avio_seek(s->pb, seekpos, SEEK_SET);
3905  }
3906 
3907  // Update all tracks sample count
3908  for (i = 0; i < s->nb_streams; i++) {
3909  AVStream *cur_st = s->streams[i];
3910  MXFTrack *cur_track = cur_st->priv_data;
3911  if (cur_track) {
3912  int64_t track_edit_unit = sample_time;
3913  if (st != cur_st)
3914  mxf_get_next_track_edit_unit(mxf, cur_track, seekpos, &track_edit_unit);
3915  cur_track->sample_count = mxf_compute_sample_count(mxf, cur_st, track_edit_unit);
3916  }
3917  }
3918  return 0;
3919 }
3920 
3921 static const AVOption options[] = {
3922  { "eia608_extract", "extract eia 608 captions from s436m track",
3923  offsetof(MXFContext, eia608_extract), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1,
3925  { NULL },
3926 };
3927 
3928 static const AVClass demuxer_class = {
3929  .class_name = "mxf",
3930  .item_name = av_default_item_name,
3931  .option = options,
3932  .version = LIBAVUTIL_VERSION_INT,
3933  .category = AV_CLASS_CATEGORY_DEMUXER,
3934 };
3935 
3937  .name = "mxf",
3938  .long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
3939  .flags = AVFMT_SEEK_TO_PTS,
3940  .priv_data_size = sizeof(MXFContext),
3941  .flags_internal = FF_FMT_INIT_CLEANUP,
3942  .read_probe = mxf_probe,
3947  .priv_class = &demuxer_class,
3948 };
AV_CODEC_ID_PCM_S16LE
@ AV_CODEC_ID_PCM_S16LE
Definition: codec_id.h:313
mxf_read_generic_descriptor
static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1197
AVMasteringDisplayMetadata::has_primaries
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
Definition: mastering_display_metadata.h:62
mxf_read_header
static int mxf_read_header(AVFormatContext *s)
Definition: mxfdec.c:3365
AV_CODEC_ID_EIA_608
@ AV_CODEC_ID_EIA_608
Definition: codec_id.h:531
MXFMetadataSet::uid
UID uid
Definition: mxfdec.c:110
be
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it be(in the first position) for now. Options ------- Then comes the options array. This is what will define the user accessible options. For example
OPSONYOpt
@ OPSONYOpt
Definition: mxfdec.c:81
MXFContext::op
MXFOP op
Definition: mxfdec.c:272
MXFIndexTable::offsets
int8_t * offsets
Definition: mxfdec.c:265
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AV_TIMECODE_STR_SIZE
#define AV_TIMECODE_STR_SIZE
Definition: timecode.h:33
av_aes_init
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)
Initialize an AVAES context.
Definition: aes.c:195
AVMasteringDisplayMetadata::max_luminance
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
Definition: mastering_display_metadata.h:57
AVCodecParameters::extradata
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
mxf_read_cryptographic_context
static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:885
mxf_read_timecode_component
static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:981
av_clip
#define av_clip
Definition: common.h:96
mxf_compute_essence_containers
static void mxf_compute_essence_containers(AVFormatContext *s)
Figures out the proper offset and length of the essence container in each partition.
Definition: mxfdec.c:3153
FF_FMT_INIT_CLEANUP
#define FF_FMT_INIT_CLEANUP
For an AVInputFormat with this flag set read_close() needs to be called by the caller upon read_heade...
Definition: internal.h:48
ff_mxf_color_primaries_uls
const MXFCodecUL ff_mxf_color_primaries_uls[]
Definition: mxf.c:92
mxf_set_audio_pts
static int mxf_set_audio_pts(MXFContext *mxf, AVCodecParameters *par, AVPacket *pkt)
Definition: mxfdec.c:3572
mxf_add_timecode_metadata
static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
Definition: mxfdec.c:2029
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
uid
UID uid
Definition: mxfenc.c:2206
opt.h
avformat_new_stream
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:724
OPAtom
@ OPAtom
Definition: mxfdec.c:80
Track
Definition: ismindex.c:69
mxf_read_sequence
static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1033
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
MXFTrack::edit_rate
AVRational edit_rate
Definition: mxfdec.c:172
mxf_resolve_essence_group_choice
static MXFStructuralComponent * mxf_resolve_essence_group_choice(MXFContext *mxf, MXFEssenceGroup *essence_group)
Definition: mxfdec.c:2100
OP2b
@ OP2b
Definition: mxfdec.c:75
FF_MXF_MasteringDisplayMinimumLuminance
#define FF_MXF_MasteringDisplayMinimumLuminance
Definition: mxf.h:94
AVCodecParameters
This struct describes the properties of an encoded stream.
Definition: codec_par.h:52
MXFContext::index_tables
MXFIndexTable * index_tables
Definition: mxfdec.c:291
mxf_parse_package_comments
static int mxf_parse_package_comments(MXFContext *mxf, AVDictionary **pm, MXFPackage *package)
Definition: mxfdec.c:2145
MXFPartition::complete
int complete
Definition: mxfdec.c:92
AVCodecParameters::color_space
enum AVColorSpace color_space
Definition: codec_par.h:149
AVStream::priv_data
void * priv_data
Definition: avformat.h:854
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
avcodec_get_type
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: codec_desc.c:3539
RawVWrap
@ RawVWrap
Definition: mxf.h:79
AVMasteringDisplayMetadata::display_primaries
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
Definition: mastering_display_metadata.h:42
TaggedValue
@ TaggedValue
Definition: mxf.h:50
AVMasteringDisplayMetadata::has_luminance
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
Definition: mastering_display_metadata.h:67
AV_CODEC_ID_DIRAC
@ AV_CODEC_ID_DIRAC
Definition: codec_id.h:166
mxf_read_primer_pack
static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:642
av_asprintf
char * av_asprintf(const char *fmt,...)
Definition: avstring.c:113
mxf_intra_only_picture_coded_width
static const MXFCodecUL mxf_intra_only_picture_coded_width[]
Definition: mxfdec.c:1472
AV_CODEC_ID_RAWVIDEO
@ AV_CODEC_ID_RAWVIDEO
Definition: codec_id.h:63
MXFPartition::kag_size
int32_t kag_size
Definition: mxfdec.c:100
MXFPartition::type
MXFPartitionType type
Definition: mxfdec.c:93
OP3b
@ OP3b
Definition: mxfdec.c:78
FF_MXF_MasteringDisplayPrimaries
#define FF_MXF_MasteringDisplayPrimaries
Definition: mxf.h:91
KLVPacket::offset
int64_t offset
Definition: mxf.h:70
AV_RN16
#define AV_RN16(p)
Definition: intreadwrite.h:360
AVContentLightMetadata::MaxCLL
unsigned MaxCLL
Max content light level (cd/m^2).
Definition: mastering_display_metadata.h:102
avio_get_str16be
int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen)
KLVPacket::key
UID key
Definition: mxf.h:69
tmp
static uint8_t tmp[11]
Definition: aes_ctr.c:26
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1165
index
fg index
Definition: ffmpeg_filter.c:168
mxf_indirect_value_utf16be
static const uint8_t mxf_indirect_value_utf16be[]
Definition: mxfdec.c:322
AVCOL_RANGE_JPEG
@ AVCOL_RANGE_JPEG
Full range content.
Definition: pixfmt.h:576
MXFStructuralComponent::source_track_id
int source_track_id
Definition: mxfdec.c:127
MXFEssenceContainerData::package_ul
UID package_ul
Definition: mxfdec.c:250
AVPacket::data
uint8_t * data
Definition: packet.h:373
SourceClip
@ SourceClip
Definition: mxf.h:35
MXFWrappingScheme
MXFWrappingScheme
Definition: mxfdec.c:84
mxf_read_pixel_layout
static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
Definition: mxfdec.c:1177
AVOption
AVOption.
Definition: opt.h:247
b
#define b
Definition: input.c:40
mxf_resolve_strong_ref
static void * mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
Definition: mxfdec.c:1422
MXFTrack::index_sid
int index_sid
Definition: mxfdec.c:176
mxf_data_essence_container_uls
static const MXFCodecUL mxf_data_essence_container_uls[]
Definition: mxfdec.c:1490
MXFDescriptor::video_line_map
int video_line_map[2]
Definition: mxfdec.c:192
MXFDescriptor::field_dominance
int field_dominance
Definition: mxfdec.c:196
mxf_set_pts
static int mxf_set_pts(MXFContext *mxf, AVStream *st, AVPacket *pkt)
Definition: mxfdec.c:3594
av_mallocz_array
void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.c:214
MXFContext::packages_refs
UID * packages_refs
Definition: mxfdec.c:273
MXFStructuralComponent::source_package_uid
UID source_package_uid
Definition: mxfdec.c:123
MXFPartition
Definition: mxfdec.c:90
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
OP1a
@ OP1a
Definition: mxfdec.c:71
mxf_read_content_storage
static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:945
AVPacket::duration
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:391
MXFMetadataSet
Definition: mxfdec.c:109
AVCodecParameters::codec_tag
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:64
mxf_read_track
static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1009
mxf_intra_only_essence_container_uls
static const MXFCodecUL mxf_intra_only_essence_container_uls[]
Definition: mxfdec.c:1459
MXFPartition::pack_length
int pack_length
Definition: mxfdec.c:103
mathematics.h
AVDictionary
Definition: dict.c:30
AVProbeData::buf_size
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:449
MXFIndexTableSegment::flag_entries
int * flag_entries
Definition: mxfdec.c:229
MXFContext::current_klv_data
KLVPacket current_klv_data
Definition: mxfdec.c:284
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
mxf_parse_handle_essence
static int mxf_parse_handle_essence(MXFContext *mxf)
Called when essence is encountered.
Definition: mxfdec.c:3092
MXFEssenceContainerData::package_uid
UID package_uid
Definition: mxfdec.c:249
MXFDescriptor::black_ref_level
unsigned int black_ref_level
Definition: mxfdec.c:201
MXFDescriptor::essence_container_ul
UID essence_container_ul
Definition: mxfdec.c:184
MXFPulldownComponent
Definition: mxfdec.c:147
MXFIndexTableSegment::index_edit_rate
AVRational index_edit_rate
Definition: mxfdec.c:225
MXFDescriptor::essence_codec_ul
UID essence_codec_ul
Definition: mxfdec.c:185
MXFIndexTableSegment::index_duration
uint64_t index_duration
Definition: mxfdec.c:227
mxf_header_partition_pack_key
static const uint8_t mxf_header_partition_pack_key[]
Definition: mxfdec.c:306
Footer
@ Footer
Definition: mxfdec.c:67
MXFPackage::comment_refs
UID * comment_refs
Definition: mxfdec.c:243
MXFContext
Definition: mxfdec.c:268
MXFTrack::sequence_ref
UID sequence_ref
Definition: mxfdec.c:168
ff_mxf_color_trc_uls
const MXFCodecUL ff_mxf_color_trc_uls[]
Definition: mxf.c:107
mxf_parse_structural_metadata
static int mxf_parse_structural_metadata(MXFContext *mxf)
Definition: mxfdec.c:2297
avio_size
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:338
TimecodeComponent
@ TimecodeComponent
Definition: mxf.h:36
MXFDescriptor::color_range
unsigned int color_range
Definition: mxfdec.c:203
sample_rate
sample_rate
Definition: ffmpeg_filter.c:156
FF_MXF_MasteringDisplay_PREFIX
#define FF_MXF_MasteringDisplay_PREFIX
Definition: mxf.h:90
SeparateFields
@ SeparateFields
Definition: mxf.h:57
AVIndexEntry
Definition: avformat.h:777
MXFCryptoContext::source_container_ul
UID source_container_ul
Definition: mxfdec.c:117
MXFDescriptor::width
int width
Definition: mxfdec.c:189
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:31
AVINDEX_KEYFRAME
#define AVINDEX_KEYFRAME
Definition: avformat.h:785
ff_mxf_codec_tag_uls
const MXFCodecUL ff_mxf_codec_tag_uls[]
Definition: mxf.c:87
MXFEssenceGroup
Definition: mxfdec.c:152
AVContentLightMetadata
Content light level needed by to transmit HDR over HDMI (CTA-861.3).
Definition: mastering_display_metadata.h:98
READ_STR16
#define READ_STR16(type, big_endian)
Definition: mxfdec.c:936
AVCodecParameters::color_primaries
enum AVColorPrimaries color_primaries
Definition: codec_par.h:147
AVPROBE_SCORE_MAX
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:458
MXFPackage::descriptor
MXFDescriptor * descriptor
Definition: mxfdec.c:240
mxf_find_index_table
static MXFIndexTable * mxf_find_index_table(MXFContext *mxf, int index_sid)
Definition: mxfdec.c:3198
MXFPartitionType
MXFPartitionType
Definition: mxfdec.c:64
mxf_read_essence_group
static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1053
MXFEssenceContainerData::meta
MXFMetadataSet meta
Definition: mxfdec.c:248
MXFIndexTableSegment::nb_index_entries
int nb_index_entries
Definition: mxfdec.c:231
MXFTrack::edit_units_per_packet
int edit_units_per_packet
Definition: mxfdec.c:179
mxf.h
AVCodecParameters::channels
int channels
Audio only.
Definition: codec_par.h:166
mxf_set_current_edit_unit
static int64_t mxf_set_current_edit_unit(MXFContext *mxf, AVStream *st, int64_t current_offset, int resync)
Make sure track->sample_count is correct based on what offset we're currently at.
Definition: mxfdec.c:3534
AV_FIELD_TT
@ AV_FIELD_TT
Definition: codec_par.h:39
mxf_apple_coll_max_fall
static const uint8_t mxf_apple_coll_max_fall[]
Definition: mxfdec.c:324
MXFPartition::closed
int closed
Definition: mxfdec.c:91
ffstream
static av_always_inline FFStream * ffstream(AVStream *st)
Definition: internal.h:426
AVFMT_SEEK_TO_PTS
#define AVFMT_SEEK_TO_PTS
Seeking is based on PTS.
Definition: avformat.h:489
AV_CODEC_ID_PCM_S16BE
@ AV_CODEC_ID_PCM_S16BE
Definition: codec_id.h:314
AVSEEK_FLAG_ANY
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:2153
read_seek
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:149
av_shrink_packet
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition: avpacket.c:114
MXFDescriptor::channels
int channels
Definition: mxfdec.c:197
timecode.h
mxf_get_next_track_edit_unit
static int mxf_get_next_track_edit_unit(MXFContext *mxf, MXFTrack *track, int64_t current_offset, int64_t *edit_unit_out)
Definition: mxfdec.c:3477
MXFDescriptor::coll_size
size_t coll_size
Definition: mxfdec.c:217
mxf_read_random_index_pack
static void mxf_read_random_index_pack(AVFormatContext *s)
Definition: mxfdec.c:3311
MXFCodecUL::id
int id
Definition: mxf.h:102
av_timecode_make_string
char * av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum)
Load timecode string in buf.
Definition: timecode.c:102
MXFMetadataReadTableEntry::key
const UID key
Definition: mxfdec.c:299
read_close
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:141
MXFTrack::original_duration
int64_t original_duration
Definition: mxfdec.c:175
avio_tell
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:486
mxf_handle_missing_index_segment
static int mxf_handle_missing_index_segment(MXFContext *mxf, AVStream *st)
Deal with the case where ClipWrapped essences does not have any IndexTableSegments.
Definition: mxfdec.c:3243
MXFSequence::structural_components_refs
UID * structural_components_refs
Definition: mxfdec.c:133
val
static double val(void *priv, double ch)
Definition: aeval.c:76
FF_ALLOC_TYPED_ARRAY
#define FF_ALLOC_TYPED_ARRAY(p, nelem)
Definition: internal.h:97
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
av_timegm
time_t av_timegm(struct tm *tm)
Convert the decomposed UTC time in tm to a time_t value.
Definition: parseutils.c:568
MXFDescriptor::mastering
AVMasteringDisplayMetadata * mastering
Definition: mxfdec.c:215
MXFIndexTable::first_dts
int64_t first_dts
Definition: mxfdec.c:260
AVStream::duration
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:888
MXFDescriptor::horiz_subsampling
unsigned int horiz_subsampling
Definition: mxfdec.c:204
AV_FIELD_TB
@ AV_FIELD_TB
Definition: codec_par.h:41
MXFPackage::meta
MXFMetadataSet meta
Definition: mxfdec.c:235
AVRational::num
int num
Numerator.
Definition: rational.h:59
mxf_absolute_bodysid_offset
static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out, MXFPartition **partition_out)
Computes the absolute file offset of the given essence container offset.
Definition: mxfdec.c:1622
MXFTrack::meta
MXFMetadataSet meta
Definition: mxfdec.c:166
MXFContext::last_forward_partition
int last_forward_partition
Definition: mxfdec.c:289
AV_DICT_DONT_STRDUP_VAL
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition: dict.h:72
av_get_bits_per_sample
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:585
AVCodecParameters::color_trc
enum AVColorTransferCharacteristic color_trc
Definition: codec_par.h:148
mxf_version_to_str
static int mxf_version_to_str(uint16_t major, uint16_t minor, uint16_t tertiary, uint16_t patch, uint16_t release, char **str)
Definition: mxfdec.c:2008
MXFDescriptor::frame_layout
int frame_layout
Definition: mxfdec.c:191
mxf_timestamp_to_int64
static int64_t mxf_timestamp_to_int64(uint64_t timestamp)
Definition: mxfdec.c:2751
OneField
@ OneField
Definition: mxf.h:58
MXFDescriptor::linked_track_id
int linked_track_id
Definition: mxfdec.c:208
mxf_read_identification_metadata
static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
Definition: mxfdec.c:2804
mxf_add_metadata_set
static int mxf_add_metadata_set(MXFContext *mxf, MXFMetadataSet **metadata_set)
Definition: mxfdec.c:854
MXFPackage::tracks_refs
UID * tracks_refs
Definition: mxfdec.c:238
mxf_probe
static int mxf_probe(const AVProbeData *p)
Definition: mxfdec.c:3784
MXFMetadataReadTableEntry
Definition: mxfdec.c:298
avio_rb32
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:773
AV_LOG_TRACE
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:206
pkt
AVPacket * pkt
Definition: movenc.c:59
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
AVFormatContext::metadata
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1326
MXFEssenceGroup::structural_components_count
int structural_components_count
Definition: mxfdec.c:155
mxf_metadata_read_table
static const MXFMetadataReadTableEntry mxf_metadata_read_table[]
Definition: mxfdec.c:2861
AVInputFormat
Definition: avformat.h:626
mxf_compute_ptses_fake_index
static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
Definition: mxfdec.c:1729
MXFIndexTableSegment
Definition: mxfdec.c:220
MXFIndexTable::nb_segments
int nb_segments
Definition: mxfdec.c:262
PRINT_KEY
#define PRINT_KEY(pc, s, x)
Definition: mxf.h:149
MXFDescriptor::duration
int64_t duration
Definition: mxfdec.c:199
MXFPartition::index_byte_count
int64_t index_byte_count
Definition: mxfdec.c:102
mxf_read_preface_metadata
static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:2848