You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2216 lines
83KB

  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. * References
  23. * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
  24. * SMPTE 377M MXF File Format Specifications
  25. * SMPTE 378M Operational Pattern 1a
  26. * SMPTE 379M MXF Generic Container
  27. * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
  28. * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
  29. * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
  30. *
  31. * Principle
  32. * Search for Track numbers which will identify essence element KLV packets.
  33. * Search for SourcePackage which define tracks which contains Track numbers.
  34. * Material Package contains tracks with reference to SourcePackage tracks.
  35. * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
  36. * Assign Descriptors to correct Tracks.
  37. *
  38. * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
  39. * Metadata parsing resolves Strong References to objects.
  40. *
  41. * Simple demuxer, only OP1A supported and some files might not work at all.
  42. * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
  43. */
  44. //#define DEBUG
  45. #include "libavutil/aes.h"
  46. #include "libavutil/mathematics.h"
  47. #include "libavcodec/bytestream.h"
  48. #include "libavutil/timecode.h"
  49. #include "avformat.h"
  50. #include "internal.h"
  51. #include "mxf.h"
  52. typedef enum {
  53. Header,
  54. BodyPartition,
  55. Footer
  56. } MXFPartitionType;
  57. typedef enum {
  58. OP1a = 1,
  59. OP1b,
  60. OP1c,
  61. OP2a,
  62. OP2b,
  63. OP2c,
  64. OP3a,
  65. OP3b,
  66. OP3c,
  67. OPAtom,
  68. OPSONYOpt, /* FATE sample, violates the spec in places */
  69. } MXFOP;
  70. typedef struct {
  71. int closed;
  72. int complete;
  73. MXFPartitionType type;
  74. uint64_t previous_partition;
  75. int index_sid;
  76. int body_sid;
  77. int64_t this_partition;
  78. int64_t essence_offset; ///< absolute offset of essence
  79. int64_t essence_length;
  80. int32_t kag_size;
  81. int64_t header_byte_count;
  82. int64_t index_byte_count;
  83. int pack_length;
  84. } MXFPartition;
  85. typedef struct {
  86. UID uid;
  87. enum MXFMetadataSetType type;
  88. UID source_container_ul;
  89. } MXFCryptoContext;
  90. typedef struct {
  91. UID uid;
  92. enum MXFMetadataSetType type;
  93. UID source_package_uid;
  94. UID data_definition_ul;
  95. int64_t duration;
  96. int64_t start_position;
  97. int source_track_id;
  98. } MXFStructuralComponent;
  99. typedef struct {
  100. UID uid;
  101. enum MXFMetadataSetType type;
  102. UID data_definition_ul;
  103. UID *structural_components_refs;
  104. int structural_components_count;
  105. int64_t duration;
  106. } MXFSequence;
  107. typedef struct {
  108. UID uid;
  109. enum MXFMetadataSetType type;
  110. int drop_frame;
  111. int start_frame;
  112. struct AVRational rate;
  113. AVTimecode tc;
  114. } MXFTimecodeComponent;
  115. typedef struct {
  116. UID uid;
  117. enum MXFMetadataSetType type;
  118. MXFSequence *sequence; /* mandatory, and only one */
  119. UID sequence_ref;
  120. int track_id;
  121. uint8_t track_number[4];
  122. AVRational edit_rate;
  123. int intra_only;
  124. } MXFTrack;
  125. typedef struct {
  126. UID uid;
  127. enum MXFMetadataSetType type;
  128. UID essence_container_ul;
  129. UID essence_codec_ul;
  130. AVRational sample_rate;
  131. AVRational aspect_ratio;
  132. int width;
  133. int height;
  134. int channels;
  135. int bits_per_sample;
  136. unsigned int component_depth;
  137. unsigned int horiz_subsampling;
  138. unsigned int vert_subsampling;
  139. UID *sub_descriptors_refs;
  140. int sub_descriptors_count;
  141. int linked_track_id;
  142. uint8_t *extradata;
  143. int extradata_size;
  144. enum PixelFormat pix_fmt;
  145. } MXFDescriptor;
  146. typedef struct {
  147. UID uid;
  148. enum MXFMetadataSetType type;
  149. int edit_unit_byte_count;
  150. int index_sid;
  151. int body_sid;
  152. AVRational index_edit_rate;
  153. uint64_t index_start_position;
  154. uint64_t index_duration;
  155. int8_t *temporal_offset_entries;
  156. int *flag_entries;
  157. uint64_t *stream_offset_entries;
  158. int nb_index_entries;
  159. } MXFIndexTableSegment;
  160. typedef struct {
  161. UID uid;
  162. enum MXFMetadataSetType type;
  163. UID package_uid;
  164. UID *tracks_refs;
  165. int tracks_count;
  166. MXFDescriptor *descriptor; /* only one */
  167. UID descriptor_ref;
  168. } MXFPackage;
  169. typedef struct {
  170. UID uid;
  171. enum MXFMetadataSetType type;
  172. } MXFMetadataSet;
  173. /* decoded index table */
  174. typedef struct {
  175. int index_sid;
  176. int body_sid;
  177. int nb_ptses; /* number of PTSes or total duration of index */
  178. int64_t first_dts; /* DTS = EditUnit + first_dts */
  179. int64_t *ptses; /* maps EditUnit -> PTS */
  180. int nb_segments;
  181. MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
  182. AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
  183. } MXFIndexTable;
  184. typedef struct {
  185. MXFPartition *partitions;
  186. unsigned partitions_count;
  187. MXFOP op;
  188. UID *packages_refs;
  189. int packages_count;
  190. MXFMetadataSet **metadata_sets;
  191. int metadata_sets_count;
  192. AVFormatContext *fc;
  193. struct AVAES *aesc;
  194. uint8_t *local_tags;
  195. int local_tags_count;
  196. uint64_t footer_partition;
  197. KLVPacket current_klv_data;
  198. int current_klv_index;
  199. int run_in;
  200. MXFPartition *current_partition;
  201. int parsing_backward;
  202. int64_t last_forward_tell;
  203. int last_forward_partition;
  204. int current_edit_unit;
  205. int nb_index_tables;
  206. MXFIndexTable *index_tables;
  207. int edit_units_per_packet; ///< how many edit units to read at a time (PCM, OPAtom)
  208. } MXFContext;
  209. enum MXFWrappingScheme {
  210. Frame,
  211. Clip,
  212. };
  213. /* NOTE: klv_offset is not set (-1) for local keys */
  214. typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
  215. typedef struct {
  216. const UID key;
  217. MXFMetadataReadFunc *read;
  218. int ctx_size;
  219. enum MXFMetadataSetType type;
  220. } MXFMetadataReadTableEntry;
  221. /* partial keys to match */
  222. static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
  223. static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
  224. static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
  225. static const uint8_t mxf_system_item_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
  226. static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
  227. /* complete keys to match */
  228. 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 };
  229. static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
  230. static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
  231. static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
  232. #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
  233. static int64_t klv_decode_ber_length(AVIOContext *pb)
  234. {
  235. uint64_t size = avio_r8(pb);
  236. if (size & 0x80) { /* long form */
  237. int bytes_num = size & 0x7f;
  238. /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
  239. if (bytes_num > 8)
  240. return AVERROR_INVALIDDATA;
  241. size = 0;
  242. while (bytes_num--)
  243. size = size << 8 | avio_r8(pb);
  244. }
  245. return size;
  246. }
  247. static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
  248. {
  249. int i, b;
  250. for (i = 0; i < size && !url_feof(pb); i++) {
  251. b = avio_r8(pb);
  252. if (b == key[0])
  253. i = 0;
  254. else if (b != key[i])
  255. i = -1;
  256. }
  257. return i == size;
  258. }
  259. static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
  260. {
  261. if (!mxf_read_sync(pb, mxf_klv_key, 4))
  262. return AVERROR_INVALIDDATA;
  263. klv->offset = avio_tell(pb) - 4;
  264. memcpy(klv->key, mxf_klv_key, 4);
  265. avio_read(pb, klv->key + 4, 12);
  266. klv->length = klv_decode_ber_length(pb);
  267. return klv->length == -1 ? -1 : 0;
  268. }
  269. static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
  270. {
  271. int i;
  272. for (i = 0; i < s->nb_streams; i++) {
  273. MXFTrack *track = s->streams[i]->priv_data;
  274. /* SMPTE 379M 7.3 */
  275. if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
  276. return i;
  277. }
  278. /* return 0 if only one stream, for OP Atom files with 0 as track number */
  279. return s->nb_streams == 1 ? 0 : -1;
  280. }
  281. /* XXX: use AVBitStreamFilter */
  282. static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
  283. {
  284. const uint8_t *buf_ptr, *end_ptr;
  285. uint8_t *data_ptr;
  286. int i;
  287. if (length > 61444) /* worst case PAL 1920 samples 8 channels */
  288. return AVERROR_INVALIDDATA;
  289. length = av_get_packet(pb, pkt, length);
  290. if (length < 0)
  291. return length;
  292. data_ptr = pkt->data;
  293. end_ptr = pkt->data + length;
  294. buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
  295. for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
  296. for (i = 0; i < st->codec->channels; i++) {
  297. uint32_t sample = bytestream_get_le32(&buf_ptr);
  298. if (st->codec->bits_per_coded_sample == 24)
  299. bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
  300. else
  301. bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
  302. }
  303. buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
  304. }
  305. av_shrink_packet(pkt, data_ptr - pkt->data);
  306. return 0;
  307. }
  308. static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
  309. {
  310. static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
  311. MXFContext *mxf = s->priv_data;
  312. AVIOContext *pb = s->pb;
  313. int64_t end = avio_tell(pb) + klv->length;
  314. int64_t size;
  315. uint64_t orig_size;
  316. uint64_t plaintext_size;
  317. uint8_t ivec[16];
  318. uint8_t tmpbuf[16];
  319. int index;
  320. if (!mxf->aesc && s->key && s->keylen == 16) {
  321. mxf->aesc = av_malloc(av_aes_size);
  322. if (!mxf->aesc)
  323. return AVERROR(ENOMEM);
  324. av_aes_init(mxf->aesc, s->key, 128, 1);
  325. }
  326. // crypto context
  327. avio_skip(pb, klv_decode_ber_length(pb));
  328. // plaintext offset
  329. klv_decode_ber_length(pb);
  330. plaintext_size = avio_rb64(pb);
  331. // source klv key
  332. klv_decode_ber_length(pb);
  333. avio_read(pb, klv->key, 16);
  334. if (!IS_KLV_KEY(klv, mxf_essence_element_key))
  335. return AVERROR_INVALIDDATA;
  336. index = mxf_get_stream_index(s, klv);
  337. if (index < 0)
  338. return AVERROR_INVALIDDATA;
  339. // source size
  340. klv_decode_ber_length(pb);
  341. orig_size = avio_rb64(pb);
  342. if (orig_size < plaintext_size)
  343. return AVERROR_INVALIDDATA;
  344. // enc. code
  345. size = klv_decode_ber_length(pb);
  346. if (size < 32 || size - 32 < orig_size)
  347. return AVERROR_INVALIDDATA;
  348. avio_read(pb, ivec, 16);
  349. avio_read(pb, tmpbuf, 16);
  350. if (mxf->aesc)
  351. av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
  352. if (memcmp(tmpbuf, checkv, 16))
  353. av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
  354. size -= 32;
  355. size = av_get_packet(pb, pkt, size);
  356. if (size < 0)
  357. return size;
  358. else if (size < plaintext_size)
  359. return AVERROR_INVALIDDATA;
  360. size -= plaintext_size;
  361. if (mxf->aesc)
  362. av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
  363. &pkt->data[plaintext_size], size >> 4, ivec, 1);
  364. av_shrink_packet(pkt, orig_size);
  365. pkt->stream_index = index;
  366. avio_skip(pb, end - avio_tell(pb));
  367. return 0;
  368. }
  369. static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  370. {
  371. MXFContext *mxf = arg;
  372. int item_num = avio_rb32(pb);
  373. int item_len = avio_rb32(pb);
  374. if (item_len != 18) {
  375. av_log_ask_for_sample(pb, "unsupported primer pack item length %d\n",
  376. item_len);
  377. return AVERROR_PATCHWELCOME;
  378. }
  379. if (item_num > UINT_MAX / item_len)
  380. return AVERROR_INVALIDDATA;
  381. mxf->local_tags_count = item_num;
  382. mxf->local_tags = av_malloc(item_num*item_len);
  383. if (!mxf->local_tags)
  384. return AVERROR(ENOMEM);
  385. avio_read(pb, mxf->local_tags, item_num*item_len);
  386. return 0;
  387. }
  388. static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  389. {
  390. MXFContext *mxf = arg;
  391. MXFPartition *partition, *tmp_part;
  392. UID op;
  393. uint64_t footer_partition;
  394. uint32_t nb_essence_containers;
  395. if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
  396. return AVERROR(ENOMEM);
  397. tmp_part = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
  398. if (!tmp_part)
  399. return AVERROR(ENOMEM);
  400. mxf->partitions = tmp_part;
  401. if (mxf->parsing_backward) {
  402. /* insert the new partition pack in the middle
  403. * this makes the entries in mxf->partitions sorted by offset */
  404. memmove(&mxf->partitions[mxf->last_forward_partition+1],
  405. &mxf->partitions[mxf->last_forward_partition],
  406. (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
  407. partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
  408. } else {
  409. mxf->last_forward_partition++;
  410. partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
  411. }
  412. memset(partition, 0, sizeof(*partition));
  413. mxf->partitions_count++;
  414. partition->pack_length = avio_tell(pb) - klv_offset + size;
  415. switch(uid[13]) {
  416. case 2:
  417. partition->type = Header;
  418. break;
  419. case 3:
  420. partition->type = BodyPartition;
  421. break;
  422. case 4:
  423. partition->type = Footer;
  424. break;
  425. default:
  426. av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
  427. return AVERROR_INVALIDDATA;
  428. }
  429. /* consider both footers to be closed (there is only Footer and CompleteFooter) */
  430. partition->closed = partition->type == Footer || !(uid[14] & 1);
  431. partition->complete = uid[14] > 2;
  432. avio_skip(pb, 4);
  433. partition->kag_size = avio_rb32(pb);
  434. partition->this_partition = avio_rb64(pb);
  435. partition->previous_partition = avio_rb64(pb);
  436. footer_partition = avio_rb64(pb);
  437. partition->header_byte_count = avio_rb64(pb);
  438. partition->index_byte_count = avio_rb64(pb);
  439. partition->index_sid = avio_rb32(pb);
  440. avio_skip(pb, 8);
  441. partition->body_sid = avio_rb32(pb);
  442. avio_read(pb, op, sizeof(UID));
  443. nb_essence_containers = avio_rb32(pb);
  444. /* some files don'thave FooterPartition set in every partition */
  445. if (footer_partition) {
  446. if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
  447. av_log(mxf->fc, AV_LOG_ERROR,
  448. "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
  449. mxf->footer_partition, footer_partition);
  450. } else {
  451. mxf->footer_partition = footer_partition;
  452. }
  453. }
  454. av_dlog(mxf->fc,
  455. "PartitionPack: ThisPartition = 0x%"PRIX64
  456. ", PreviousPartition = 0x%"PRIX64", "
  457. "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
  458. partition->this_partition,
  459. partition->previous_partition, footer_partition,
  460. partition->index_sid, partition->body_sid);
  461. /* sanity check PreviousPartition if set */
  462. if (partition->previous_partition &&
  463. mxf->run_in + partition->previous_partition >= klv_offset) {
  464. av_log(mxf->fc, AV_LOG_ERROR,
  465. "PreviousPartition points to this partition or forward\n");
  466. return AVERROR_INVALIDDATA;
  467. }
  468. if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
  469. else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
  470. else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
  471. else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
  472. else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
  473. else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
  474. else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
  475. else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
  476. else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
  477. else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
  478. else if (op[12] == 0x10) {
  479. /* SMPTE 390m: "There shall be exactly one essence container"
  480. * The following block deals with files that violate this, namely:
  481. * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
  482. * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
  483. if (nb_essence_containers != 1) {
  484. MXFOP op = nb_essence_containers ? OP1a : OPAtom;
  485. /* only nag once */
  486. if (!mxf->op)
  487. av_log(mxf->fc, AV_LOG_WARNING, "\"OPAtom\" with %u ECs - assuming %s\n",
  488. nb_essence_containers, op == OP1a ? "OP1a" : "OPAtom");
  489. mxf->op = op;
  490. } else
  491. mxf->op = OPAtom;
  492. } else {
  493. av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
  494. mxf->op = OP1a;
  495. }
  496. if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
  497. av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
  498. if (mxf->op == OPSONYOpt)
  499. partition->kag_size = 512;
  500. else
  501. partition->kag_size = 1;
  502. av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
  503. }
  504. return 0;
  505. }
  506. static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
  507. {
  508. MXFMetadataSet **tmp;
  509. if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
  510. return AVERROR(ENOMEM);
  511. tmp = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
  512. if (!tmp)
  513. return AVERROR(ENOMEM);
  514. mxf->metadata_sets = tmp;
  515. mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
  516. mxf->metadata_sets_count++;
  517. return 0;
  518. }
  519. static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  520. {
  521. MXFCryptoContext *cryptocontext = arg;
  522. if (size != 16)
  523. return AVERROR_INVALIDDATA;
  524. if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
  525. avio_read(pb, cryptocontext->source_container_ul, 16);
  526. return 0;
  527. }
  528. static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  529. {
  530. MXFContext *mxf = arg;
  531. switch (tag) {
  532. case 0x1901:
  533. mxf->packages_count = avio_rb32(pb);
  534. if (mxf->packages_count >= UINT_MAX / sizeof(UID))
  535. return AVERROR_INVALIDDATA;
  536. mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
  537. if (!mxf->packages_refs)
  538. return AVERROR(ENOMEM);
  539. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  540. avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
  541. break;
  542. }
  543. return 0;
  544. }
  545. static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  546. {
  547. MXFStructuralComponent *source_clip = arg;
  548. switch(tag) {
  549. case 0x0202:
  550. source_clip->duration = avio_rb64(pb);
  551. break;
  552. case 0x1201:
  553. source_clip->start_position = avio_rb64(pb);
  554. break;
  555. case 0x1101:
  556. /* UMID, only get last 16 bytes */
  557. avio_skip(pb, 16);
  558. avio_read(pb, source_clip->source_package_uid, 16);
  559. break;
  560. case 0x1102:
  561. source_clip->source_track_id = avio_rb32(pb);
  562. break;
  563. }
  564. return 0;
  565. }
  566. static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  567. {
  568. MXFPackage *package = arg;
  569. switch(tag) {
  570. case 0x4403:
  571. package->tracks_count = avio_rb32(pb);
  572. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  573. return AVERROR_INVALIDDATA;
  574. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  575. if (!package->tracks_refs)
  576. return AVERROR(ENOMEM);
  577. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  578. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  579. break;
  580. }
  581. return 0;
  582. }
  583. static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  584. {
  585. MXFTimecodeComponent *mxf_timecode = arg;
  586. switch(tag) {
  587. case 0x1501:
  588. mxf_timecode->start_frame = avio_rb64(pb);
  589. break;
  590. case 0x1502:
  591. mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
  592. break;
  593. case 0x1503:
  594. mxf_timecode->drop_frame = avio_r8(pb);
  595. break;
  596. }
  597. return 0;
  598. }
  599. static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  600. {
  601. MXFTrack *track = arg;
  602. switch(tag) {
  603. case 0x4801:
  604. track->track_id = avio_rb32(pb);
  605. break;
  606. case 0x4804:
  607. avio_read(pb, track->track_number, 4);
  608. break;
  609. case 0x4B01:
  610. track->edit_rate.num = avio_rb32(pb);
  611. track->edit_rate.den = avio_rb32(pb);
  612. break;
  613. case 0x4803:
  614. avio_read(pb, track->sequence_ref, 16);
  615. break;
  616. }
  617. return 0;
  618. }
  619. static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  620. {
  621. MXFSequence *sequence = arg;
  622. switch(tag) {
  623. case 0x0202:
  624. sequence->duration = avio_rb64(pb);
  625. break;
  626. case 0x0201:
  627. avio_read(pb, sequence->data_definition_ul, 16);
  628. break;
  629. case 0x1001:
  630. sequence->structural_components_count = avio_rb32(pb);
  631. if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
  632. return AVERROR_INVALIDDATA;
  633. sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
  634. if (!sequence->structural_components_refs)
  635. return AVERROR(ENOMEM);
  636. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  637. avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
  638. break;
  639. }
  640. return 0;
  641. }
  642. static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  643. {
  644. MXFPackage *package = arg;
  645. switch(tag) {
  646. case 0x4403:
  647. package->tracks_count = avio_rb32(pb);
  648. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  649. return AVERROR_INVALIDDATA;
  650. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  651. if (!package->tracks_refs)
  652. return AVERROR(ENOMEM);
  653. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  654. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  655. break;
  656. case 0x4401:
  657. /* UMID, only get last 16 bytes */
  658. avio_skip(pb, 16);
  659. avio_read(pb, package->package_uid, 16);
  660. break;
  661. case 0x4701:
  662. avio_read(pb, package->descriptor_ref, 16);
  663. break;
  664. }
  665. return 0;
  666. }
  667. static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
  668. {
  669. int i, length;
  670. segment->nb_index_entries = avio_rb32(pb);
  671. length = avio_rb32(pb);
  672. if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
  673. !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
  674. !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
  675. return AVERROR(ENOMEM);
  676. for (i = 0; i < segment->nb_index_entries; i++) {
  677. segment->temporal_offset_entries[i] = avio_r8(pb);
  678. avio_r8(pb); /* KeyFrameOffset */
  679. segment->flag_entries[i] = avio_r8(pb);
  680. segment->stream_offset_entries[i] = avio_rb64(pb);
  681. avio_skip(pb, length - 11);
  682. }
  683. return 0;
  684. }
  685. static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  686. {
  687. MXFIndexTableSegment *segment = arg;
  688. switch(tag) {
  689. case 0x3F05:
  690. segment->edit_unit_byte_count = avio_rb32(pb);
  691. av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
  692. break;
  693. case 0x3F06:
  694. segment->index_sid = avio_rb32(pb);
  695. av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
  696. break;
  697. case 0x3F07:
  698. segment->body_sid = avio_rb32(pb);
  699. av_dlog(NULL, "BodySID %d\n", segment->body_sid);
  700. break;
  701. case 0x3F0A:
  702. av_dlog(NULL, "IndexEntryArray found\n");
  703. return mxf_read_index_entry_array(pb, segment);
  704. case 0x3F0B:
  705. segment->index_edit_rate.num = avio_rb32(pb);
  706. segment->index_edit_rate.den = avio_rb32(pb);
  707. av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
  708. segment->index_edit_rate.den);
  709. break;
  710. case 0x3F0C:
  711. segment->index_start_position = avio_rb64(pb);
  712. av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
  713. break;
  714. case 0x3F0D:
  715. segment->index_duration = avio_rb64(pb);
  716. av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
  717. break;
  718. }
  719. return 0;
  720. }
  721. static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
  722. {
  723. int code, value, ofs = 0;
  724. char layout[16] = {0};
  725. do {
  726. code = avio_r8(pb);
  727. value = avio_r8(pb);
  728. av_dlog(NULL, "pixel layout: code %#x\n", code);
  729. if (ofs < 16) {
  730. layout[ofs++] = code;
  731. layout[ofs++] = value;
  732. }
  733. } while (code != 0); /* SMPTE 377M E.2.46 */
  734. ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
  735. }
  736. static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  737. {
  738. MXFDescriptor *descriptor = arg;
  739. descriptor->pix_fmt = PIX_FMT_NONE;
  740. switch(tag) {
  741. case 0x3F01:
  742. descriptor->sub_descriptors_count = avio_rb32(pb);
  743. if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
  744. return AVERROR_INVALIDDATA;
  745. descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
  746. if (!descriptor->sub_descriptors_refs)
  747. return AVERROR(ENOMEM);
  748. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  749. avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
  750. break;
  751. case 0x3004:
  752. avio_read(pb, descriptor->essence_container_ul, 16);
  753. break;
  754. case 0x3006:
  755. descriptor->linked_track_id = avio_rb32(pb);
  756. break;
  757. case 0x3201: /* PictureEssenceCoding */
  758. avio_read(pb, descriptor->essence_codec_ul, 16);
  759. break;
  760. case 0x3203:
  761. descriptor->width = avio_rb32(pb);
  762. break;
  763. case 0x3202:
  764. descriptor->height = avio_rb32(pb);
  765. break;
  766. case 0x320E:
  767. descriptor->aspect_ratio.num = avio_rb32(pb);
  768. descriptor->aspect_ratio.den = avio_rb32(pb);
  769. break;
  770. case 0x3301:
  771. descriptor->component_depth = avio_rb32(pb);
  772. break;
  773. case 0x3302:
  774. descriptor->horiz_subsampling = avio_rb32(pb);
  775. break;
  776. case 0x3308:
  777. descriptor->vert_subsampling = avio_rb32(pb);
  778. break;
  779. case 0x3D03:
  780. descriptor->sample_rate.num = avio_rb32(pb);
  781. descriptor->sample_rate.den = avio_rb32(pb);
  782. break;
  783. case 0x3D06: /* SoundEssenceCompression */
  784. avio_read(pb, descriptor->essence_codec_ul, 16);
  785. break;
  786. case 0x3D07:
  787. descriptor->channels = avio_rb32(pb);
  788. break;
  789. case 0x3D01:
  790. descriptor->bits_per_sample = avio_rb32(pb);
  791. break;
  792. case 0x3401:
  793. mxf_read_pixel_layout(pb, descriptor);
  794. break;
  795. default:
  796. /* Private uid used by SONY C0023S01.mxf */
  797. if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
  798. descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
  799. if (!descriptor->extradata)
  800. return AVERROR(ENOMEM);
  801. descriptor->extradata_size = size;
  802. avio_read(pb, descriptor->extradata, size);
  803. }
  804. break;
  805. }
  806. return 0;
  807. }
  808. /*
  809. * Match an uid independently of the version byte and up to len common bytes
  810. * Returns: boolean
  811. */
  812. static int mxf_match_uid(const UID key, const UID uid, int len)
  813. {
  814. int i;
  815. for (i = 0; i < len; i++) {
  816. if (i != 7 && key[i] != uid[i])
  817. return 0;
  818. }
  819. return 1;
  820. }
  821. static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
  822. {
  823. while (uls->uid[0]) {
  824. if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
  825. break;
  826. uls++;
  827. }
  828. return uls;
  829. }
  830. static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
  831. {
  832. int i;
  833. if (!strong_ref)
  834. return NULL;
  835. for (i = 0; i < mxf->metadata_sets_count; i++) {
  836. if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
  837. (type == AnyType || mxf->metadata_sets[i]->type == type)) {
  838. return mxf->metadata_sets[i];
  839. }
  840. }
  841. return NULL;
  842. }
  843. static const MXFCodecUL mxf_picture_essence_container_uls[] = {
  844. // video essence container uls
  845. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
  846. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
  847. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, CODEC_ID_RAWVIDEO }, /* Uncompressed Picture */
  848. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
  849. };
  850. /* EC ULs for intra-only formats */
  851. static const MXFCodecUL mxf_intra_only_essence_container_uls[] = {
  852. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, CODEC_ID_MPEG2VIDEO }, /* MXF-GC SMPTE D-10 Mappings */
  853. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
  854. };
  855. /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
  856. static const MXFCodecUL mxf_intra_only_picture_essence_coding_uls[] = {
  857. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14, CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra Profiles */
  858. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
  859. };
  860. static const MXFCodecUL mxf_sound_essence_container_uls[] = {
  861. // sound essence container uls
  862. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
  863. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
  864. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
  865. { { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0xFF,0x4B,0x46,0x41,0x41,0x00,0x0D,0x4D,0x4F }, 14, CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
  866. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
  867. };
  868. static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
  869. {
  870. int i, j, nb_segments = 0;
  871. MXFIndexTableSegment **unsorted_segments;
  872. int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
  873. /* count number of segments, allocate arrays and copy unsorted segments */
  874. for (i = 0; i < mxf->metadata_sets_count; i++)
  875. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  876. nb_segments++;
  877. if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
  878. !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
  879. av_freep(sorted_segments);
  880. av_free(unsorted_segments);
  881. return AVERROR(ENOMEM);
  882. }
  883. for (i = j = 0; i < mxf->metadata_sets_count; i++)
  884. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  885. unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
  886. *nb_sorted_segments = 0;
  887. /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
  888. for (i = 0; i < nb_segments; i++) {
  889. int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
  890. for (j = 0; j < nb_segments; j++) {
  891. MXFIndexTableSegment *s = unsorted_segments[j];
  892. /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
  893. * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
  894. */
  895. if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
  896. (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
  897. best = j;
  898. best_body_sid = s->body_sid;
  899. best_index_sid = s->index_sid;
  900. best_index_start = s->index_start_position;
  901. }
  902. }
  903. /* no suitable entry found -> we're done */
  904. if (best == -1)
  905. break;
  906. (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
  907. last_body_sid = best_body_sid;
  908. last_index_sid = best_index_sid;
  909. last_index_start = best_index_start;
  910. }
  911. av_free(unsorted_segments);
  912. return 0;
  913. }
  914. /**
  915. * Computes the absolute file offset of the given essence container offset
  916. */
  917. static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
  918. {
  919. int x;
  920. int64_t offset_in = offset; /* for logging */
  921. for (x = 0; x < mxf->partitions_count; x++) {
  922. MXFPartition *p = &mxf->partitions[x];
  923. if (p->body_sid != body_sid)
  924. continue;
  925. if (offset < p->essence_length || !p->essence_length) {
  926. *offset_out = p->essence_offset + offset;
  927. return 0;
  928. }
  929. offset -= p->essence_length;
  930. }
  931. av_log(mxf->fc, AV_LOG_ERROR,
  932. "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
  933. offset_in, body_sid);
  934. return AVERROR_INVALIDDATA;
  935. }
  936. /**
  937. * Returns the end position of the essence container with given BodySID, or zero if unknown
  938. */
  939. static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
  940. {
  941. int x;
  942. int64_t ret = 0;
  943. for (x = 0; x < mxf->partitions_count; x++) {
  944. MXFPartition *p = &mxf->partitions[x];
  945. if (p->body_sid != body_sid)
  946. continue;
  947. if (!p->essence_length)
  948. return 0;
  949. ret = p->essence_offset + p->essence_length;
  950. }
  951. return ret;
  952. }
  953. /* EditUnit -> absolute offset */
  954. static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, int64_t *edit_unit_out, int64_t *offset_out, int nag)
  955. {
  956. int i;
  957. int64_t offset_temp = 0;
  958. for (i = 0; i < index_table->nb_segments; i++) {
  959. MXFIndexTableSegment *s = index_table->segments[i];
  960. edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
  961. if (edit_unit < s->index_start_position + s->index_duration) {
  962. int64_t index = edit_unit - s->index_start_position;
  963. if (s->edit_unit_byte_count)
  964. offset_temp += s->edit_unit_byte_count * index;
  965. else if (s->nb_index_entries) {
  966. if (s->nb_index_entries == 2 * s->index_duration + 1)
  967. index *= 2; /* Avid index */
  968. if (index < 0 || index > s->nb_index_entries) {
  969. av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
  970. index_table->index_sid, s->index_start_position);
  971. return AVERROR_INVALIDDATA;
  972. }
  973. offset_temp = s->stream_offset_entries[index];
  974. } else {
  975. av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
  976. index_table->index_sid, s->index_start_position);
  977. return AVERROR_INVALIDDATA;
  978. }
  979. if (edit_unit_out)
  980. *edit_unit_out = edit_unit;
  981. return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out);
  982. } else {
  983. /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
  984. offset_temp += s->edit_unit_byte_count * s->index_duration;
  985. }
  986. }
  987. if (nag)
  988. 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);
  989. return AVERROR_INVALIDDATA;
  990. }
  991. static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
  992. {
  993. int i, j, x;
  994. int8_t max_temporal_offset = -128;
  995. /* first compute how many entries we have */
  996. for (i = 0; i < index_table->nb_segments; i++) {
  997. MXFIndexTableSegment *s = index_table->segments[i];
  998. if (!s->nb_index_entries) {
  999. index_table->nb_ptses = 0;
  1000. return 0; /* no TemporalOffsets */
  1001. }
  1002. index_table->nb_ptses += s->index_duration;
  1003. }
  1004. /* paranoid check */
  1005. if (index_table->nb_ptses <= 0)
  1006. return 0;
  1007. if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
  1008. !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry)))) {
  1009. av_freep(&index_table->ptses);
  1010. return AVERROR(ENOMEM);
  1011. }
  1012. /* we may have a few bad TemporalOffsets
  1013. * make sure the corresponding PTSes don't have the bogus value 0 */
  1014. for (x = 0; x < index_table->nb_ptses; x++)
  1015. index_table->ptses[x] = AV_NOPTS_VALUE;
  1016. /**
  1017. * We have this:
  1018. *
  1019. * x TemporalOffset
  1020. * 0: 0
  1021. * 1: 1
  1022. * 2: 1
  1023. * 3: -2
  1024. * 4: 1
  1025. * 5: 1
  1026. * 6: -2
  1027. *
  1028. * We want to transform it into this:
  1029. *
  1030. * x DTS PTS
  1031. * 0: -1 0
  1032. * 1: 0 3
  1033. * 2: 1 1
  1034. * 3: 2 2
  1035. * 4: 3 6
  1036. * 5: 4 4
  1037. * 6: 5 5
  1038. *
  1039. * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
  1040. * then settings mxf->first_dts = -max(TemporalOffset[x]).
  1041. * The latter makes DTS <= PTS.
  1042. */
  1043. for (i = x = 0; i < index_table->nb_segments; i++) {
  1044. MXFIndexTableSegment *s = index_table->segments[i];
  1045. int index_delta = 1;
  1046. int n = s->nb_index_entries;
  1047. if (s->nb_index_entries == 2 * s->index_duration + 1) {
  1048. index_delta = 2; /* Avid index */
  1049. /* ignore the last entry - it's the size of the essence container */
  1050. n--;
  1051. }
  1052. for (j = 0; j < n; j += index_delta, x++) {
  1053. int offset = s->temporal_offset_entries[j] / index_delta;
  1054. int index = x + offset;
  1055. if (x >= index_table->nb_ptses) {
  1056. av_log(mxf->fc, AV_LOG_ERROR,
  1057. "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
  1058. s->nb_index_entries, s->index_duration);
  1059. break;
  1060. }
  1061. index_table->fake_index[x].timestamp = x;
  1062. index_table->fake_index[x].flags = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
  1063. if (index < 0 || index >= index_table->nb_ptses) {
  1064. av_log(mxf->fc, AV_LOG_ERROR,
  1065. "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
  1066. x, offset, index);
  1067. continue;
  1068. }
  1069. index_table->ptses[index] = x;
  1070. max_temporal_offset = FFMAX(max_temporal_offset, offset);
  1071. }
  1072. }
  1073. index_table->first_dts = -max_temporal_offset;
  1074. return 0;
  1075. }
  1076. /**
  1077. * Sorts and collects index table segments into index tables.
  1078. * Also computes PTSes if possible.
  1079. */
  1080. static int mxf_compute_index_tables(MXFContext *mxf)
  1081. {
  1082. int i, j, k, ret, nb_sorted_segments;
  1083. MXFIndexTableSegment **sorted_segments = NULL;
  1084. if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
  1085. nb_sorted_segments <= 0) {
  1086. av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
  1087. return 0;
  1088. }
  1089. /* sanity check and count unique BodySIDs/IndexSIDs */
  1090. for (i = 0; i < nb_sorted_segments; i++) {
  1091. if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
  1092. mxf->nb_index_tables++;
  1093. else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
  1094. av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
  1095. ret = AVERROR_INVALIDDATA;
  1096. goto finish_decoding_index;
  1097. }
  1098. }
  1099. if (!(mxf->index_tables = av_calloc(mxf->nb_index_tables, sizeof(MXFIndexTable)))) {
  1100. av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
  1101. ret = AVERROR(ENOMEM);
  1102. goto finish_decoding_index;
  1103. }
  1104. /* distribute sorted segments to index tables */
  1105. for (i = j = 0; i < nb_sorted_segments; i++) {
  1106. if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
  1107. /* next IndexSID */
  1108. j++;
  1109. }
  1110. mxf->index_tables[j].nb_segments++;
  1111. }
  1112. for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
  1113. MXFIndexTable *t = &mxf->index_tables[j];
  1114. if (!(t->segments = av_calloc(t->nb_segments, sizeof(MXFIndexTableSegment*)))) {
  1115. av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment pointer array\n");
  1116. ret = AVERROR(ENOMEM);
  1117. goto finish_decoding_index;
  1118. }
  1119. if (sorted_segments[i]->index_start_position)
  1120. av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
  1121. sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
  1122. memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
  1123. t->index_sid = sorted_segments[i]->index_sid;
  1124. t->body_sid = sorted_segments[i]->body_sid;
  1125. if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
  1126. goto finish_decoding_index;
  1127. /* fix zero IndexDurations */
  1128. for (k = 0; k < t->nb_segments; k++) {
  1129. if (t->segments[k]->index_duration)
  1130. continue;
  1131. if (t->nb_segments > 1)
  1132. av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
  1133. t->index_sid, k);
  1134. if (mxf->fc->nb_streams <= 0) {
  1135. av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
  1136. break;
  1137. }
  1138. /* assume the first stream's duration is reasonable
  1139. * leave index_duration = 0 on further segments in case we have any (unlikely)
  1140. */
  1141. t->segments[k]->index_duration = mxf->fc->streams[0]->duration;
  1142. break;
  1143. }
  1144. }
  1145. ret = 0;
  1146. finish_decoding_index:
  1147. av_free(sorted_segments);
  1148. return ret;
  1149. }
  1150. static int mxf_is_intra_only(MXFDescriptor *descriptor)
  1151. {
  1152. return mxf_get_codec_ul(mxf_intra_only_essence_container_uls,
  1153. &descriptor->essence_container_ul)->id != CODEC_ID_NONE ||
  1154. mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls,
  1155. &descriptor->essence_codec_ul)->id != CODEC_ID_NONE;
  1156. }
  1157. static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
  1158. {
  1159. char buf[AV_TIMECODE_STR_SIZE];
  1160. av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
  1161. return 0;
  1162. }
  1163. static int mxf_parse_structural_metadata(MXFContext *mxf)
  1164. {
  1165. MXFPackage *material_package = NULL;
  1166. MXFPackage *temp_package = NULL;
  1167. int i, j, k, ret;
  1168. av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
  1169. /* TODO: handle multiple material packages (OP3x) */
  1170. for (i = 0; i < mxf->packages_count; i++) {
  1171. material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
  1172. if (material_package) break;
  1173. }
  1174. if (!material_package) {
  1175. av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
  1176. return AVERROR_INVALIDDATA;
  1177. }
  1178. for (i = 0; i < material_package->tracks_count; i++) {
  1179. MXFPackage *source_package = NULL;
  1180. MXFTrack *material_track = NULL;
  1181. MXFTrack *source_track = NULL;
  1182. MXFTrack *temp_track = NULL;
  1183. MXFDescriptor *descriptor = NULL;
  1184. MXFStructuralComponent *component = NULL;
  1185. MXFTimecodeComponent *mxf_tc = NULL;
  1186. UID *essence_container_ul = NULL;
  1187. const MXFCodecUL *codec_ul = NULL;
  1188. const MXFCodecUL *container_ul = NULL;
  1189. const MXFCodecUL *pix_fmt_ul = NULL;
  1190. AVStream *st;
  1191. AVTimecode tc;
  1192. int flags;
  1193. if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
  1194. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
  1195. continue;
  1196. }
  1197. if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
  1198. mxf_tc = (MXFTimecodeComponent*)component;
  1199. flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
  1200. if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf) == 0) {
  1201. mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
  1202. }
  1203. }
  1204. if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
  1205. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
  1206. continue;
  1207. }
  1208. for (j = 0; j < material_track->sequence->structural_components_count; j++) {
  1209. component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
  1210. if (!component)
  1211. continue;
  1212. mxf_tc = (MXFTimecodeComponent*)component;
  1213. flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
  1214. if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf) == 0) {
  1215. mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
  1216. break;
  1217. }
  1218. }
  1219. /* TODO: handle multiple source clips */
  1220. for (j = 0; j < material_track->sequence->structural_components_count; j++) {
  1221. component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
  1222. if (!component)
  1223. continue;
  1224. for (k = 0; k < mxf->packages_count; k++) {
  1225. temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
  1226. if (!temp_package)
  1227. continue;
  1228. if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
  1229. source_package = temp_package;
  1230. break;
  1231. }
  1232. }
  1233. if (!source_package) {
  1234. av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
  1235. break;
  1236. }
  1237. for (k = 0; k < source_package->tracks_count; k++) {
  1238. if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
  1239. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
  1240. ret = AVERROR_INVALIDDATA;
  1241. goto fail_and_free;
  1242. }
  1243. if (temp_track->track_id == component->source_track_id) {
  1244. source_track = temp_track;
  1245. break;
  1246. }
  1247. }
  1248. if (!source_track) {
  1249. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
  1250. break;
  1251. }
  1252. }
  1253. if (!source_track || !component)
  1254. continue;
  1255. if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
  1256. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
  1257. ret = AVERROR_INVALIDDATA;
  1258. goto fail_and_free;
  1259. }
  1260. /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
  1261. * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
  1262. if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
  1263. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
  1264. continue;
  1265. }
  1266. st = avformat_new_stream(mxf->fc, NULL);
  1267. if (!st) {
  1268. av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
  1269. ret = AVERROR(ENOMEM);
  1270. goto fail_and_free;
  1271. }
  1272. st->id = source_track->track_id;
  1273. st->priv_data = source_track;
  1274. st->duration = component->duration;
  1275. if (st->duration == -1)
  1276. st->duration = AV_NOPTS_VALUE;
  1277. st->start_time = component->start_position;
  1278. avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
  1279. PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
  1280. codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
  1281. st->codec->codec_type = codec_ul->id;
  1282. source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
  1283. if (source_package->descriptor) {
  1284. if (source_package->descriptor->type == MultipleDescriptor) {
  1285. for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
  1286. MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
  1287. if (!sub_descriptor) {
  1288. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
  1289. continue;
  1290. }
  1291. if (sub_descriptor->linked_track_id == source_track->track_id) {
  1292. descriptor = sub_descriptor;
  1293. break;
  1294. }
  1295. }
  1296. } else if (source_package->descriptor->type == Descriptor)
  1297. descriptor = source_package->descriptor;
  1298. }
  1299. if (!descriptor) {
  1300. av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
  1301. continue;
  1302. }
  1303. PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
  1304. PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
  1305. essence_container_ul = &descriptor->essence_container_ul;
  1306. /* HACK: replacing the original key with mxf_encrypted_essence_container
  1307. * is not allowed according to s429-6, try to find correct information anyway */
  1308. if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
  1309. av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
  1310. for (k = 0; k < mxf->metadata_sets_count; k++) {
  1311. MXFMetadataSet *metadata = mxf->metadata_sets[k];
  1312. if (metadata->type == CryptoContext) {
  1313. essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
  1314. break;
  1315. }
  1316. }
  1317. }
  1318. /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
  1319. codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
  1320. st->codec->codec_id = codec_ul->id;
  1321. if (descriptor->extradata) {
  1322. st->codec->extradata = descriptor->extradata;
  1323. st->codec->extradata_size = descriptor->extradata_size;
  1324. }
  1325. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1326. source_track->intra_only = mxf_is_intra_only(descriptor);
  1327. container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
  1328. if (st->codec->codec_id == CODEC_ID_NONE)
  1329. st->codec->codec_id = container_ul->id;
  1330. st->codec->width = descriptor->width;
  1331. st->codec->height = descriptor->height;
  1332. if (st->codec->codec_id == CODEC_ID_RAWVIDEO) {
  1333. st->codec->pix_fmt = descriptor->pix_fmt;
  1334. if (st->codec->pix_fmt == PIX_FMT_NONE) {
  1335. pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, &descriptor->essence_codec_ul);
  1336. st->codec->pix_fmt = pix_fmt_ul->id;
  1337. if (st->codec->pix_fmt == PIX_FMT_NONE) {
  1338. /* support files created before RP224v10 by defaulting to UYVY422
  1339. if subsampling is 4:2:2 and component depth is 8-bit */
  1340. if (descriptor->horiz_subsampling == 2 &&
  1341. descriptor->vert_subsampling == 1 &&
  1342. descriptor->component_depth == 8) {
  1343. st->codec->pix_fmt = PIX_FMT_UYVY422;
  1344. }
  1345. }
  1346. }
  1347. }
  1348. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1349. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  1350. container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
  1351. if (st->codec->codec_id == CODEC_ID_NONE)
  1352. st->codec->codec_id = container_ul->id;
  1353. st->codec->channels = descriptor->channels;
  1354. st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
  1355. if (descriptor->sample_rate.den > 0)
  1356. st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
  1357. /* TODO: implement CODEC_ID_RAWAUDIO */
  1358. if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
  1359. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1360. st->codec->codec_id = CODEC_ID_PCM_S24LE;
  1361. else if (descriptor->bits_per_sample == 32)
  1362. st->codec->codec_id = CODEC_ID_PCM_S32LE;
  1363. } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
  1364. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1365. st->codec->codec_id = CODEC_ID_PCM_S24BE;
  1366. else if (descriptor->bits_per_sample == 32)
  1367. st->codec->codec_id = CODEC_ID_PCM_S32BE;
  1368. } else if (st->codec->codec_id == CODEC_ID_MP2) {
  1369. st->need_parsing = AVSTREAM_PARSE_FULL;
  1370. }
  1371. }
  1372. if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
  1373. /* TODO: decode timestamps */
  1374. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  1375. }
  1376. }
  1377. ret = 0;
  1378. fail_and_free:
  1379. return ret;
  1380. }
  1381. static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
  1382. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
  1383. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
  1384. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
  1385. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
  1386. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
  1387. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
  1388. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
  1389. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
  1390. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
  1391. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
  1392. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
  1393. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
  1394. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
  1395. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
  1396. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
  1397. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
  1398. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
  1399. { { 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 */
  1400. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
  1401. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
  1402. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG 2 Video */
  1403. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
  1404. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
  1405. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
  1406. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
  1407. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
  1408. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
  1409. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
  1410. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
  1411. };
  1412. static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
  1413. {
  1414. AVIOContext *pb = mxf->fc->pb;
  1415. MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
  1416. uint64_t klv_end = avio_tell(pb) + klv->length;
  1417. if (!ctx)
  1418. return AVERROR(ENOMEM);
  1419. while (avio_tell(pb) + 4 < klv_end && !url_feof(pb)) {
  1420. int ret;
  1421. int tag = avio_rb16(pb);
  1422. int size = avio_rb16(pb); /* KLV specified by 0x53 */
  1423. uint64_t next = avio_tell(pb) + size;
  1424. UID uid = {0};
  1425. av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
  1426. if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
  1427. av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
  1428. continue;
  1429. }
  1430. if (tag > 0x7FFF) { /* dynamic tag */
  1431. int i;
  1432. for (i = 0; i < mxf->local_tags_count; i++) {
  1433. int local_tag = AV_RB16(mxf->local_tags+i*18);
  1434. if (local_tag == tag) {
  1435. memcpy(uid, mxf->local_tags+i*18+2, 16);
  1436. av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
  1437. PRINT_KEY(mxf->fc, "uid", uid);
  1438. }
  1439. }
  1440. }
  1441. if (ctx_size && tag == 0x3C0A)
  1442. avio_read(pb, ctx->uid, 16);
  1443. else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0)
  1444. return ret;
  1445. /* Accept the 64k local set limit being exceeded (Avid). Don't accept
  1446. * it extending past the end of the KLV though (zzuf5.mxf). */
  1447. if (avio_tell(pb) > klv_end) {
  1448. av_log(mxf->fc, AV_LOG_ERROR,
  1449. "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
  1450. tag, klv->offset);
  1451. return AVERROR_INVALIDDATA;
  1452. } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
  1453. avio_seek(pb, next, SEEK_SET);
  1454. }
  1455. if (ctx_size) ctx->type = type;
  1456. return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
  1457. }
  1458. /**
  1459. * Seeks to the previous partition, if possible
  1460. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1461. */
  1462. static int mxf_seek_to_previous_partition(MXFContext *mxf)
  1463. {
  1464. AVIOContext *pb = mxf->fc->pb;
  1465. if (!mxf->current_partition ||
  1466. mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
  1467. return 0; /* we've parsed all partitions */
  1468. /* seek to previous partition */
  1469. avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
  1470. mxf->current_partition = NULL;
  1471. av_dlog(mxf->fc, "seeking to previous partition\n");
  1472. return 1;
  1473. }
  1474. /**
  1475. * Called when essence is encountered
  1476. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1477. */
  1478. static int mxf_parse_handle_essence(MXFContext *mxf)
  1479. {
  1480. AVIOContext *pb = mxf->fc->pb;
  1481. int64_t ret;
  1482. if (mxf->parsing_backward) {
  1483. return mxf_seek_to_previous_partition(mxf);
  1484. } else {
  1485. if (!mxf->footer_partition) {
  1486. av_dlog(mxf->fc, "no footer\n");
  1487. return 0;
  1488. }
  1489. av_dlog(mxf->fc, "seeking to footer\n");
  1490. /* remember where we were so we don't end up seeking further back than this */
  1491. mxf->last_forward_tell = avio_tell(pb);
  1492. if (!pb->seekable) {
  1493. av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
  1494. return -1;
  1495. }
  1496. /* seek to footer partition and parse backward */
  1497. if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
  1498. av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
  1499. mxf->run_in + mxf->footer_partition, ret);
  1500. return ret;
  1501. }
  1502. mxf->current_partition = NULL;
  1503. mxf->parsing_backward = 1;
  1504. }
  1505. return 1;
  1506. }
  1507. /**
  1508. * Called when the next partition or EOF is encountered
  1509. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1510. */
  1511. static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
  1512. {
  1513. return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
  1514. }
  1515. /**
  1516. * Figures out the proper offset and length of the essence container in each partition
  1517. */
  1518. static void mxf_compute_essence_containers(MXFContext *mxf)
  1519. {
  1520. int x;
  1521. /* everything is already correct */
  1522. if (mxf->op == OPAtom)
  1523. return;
  1524. for (x = 0; x < mxf->partitions_count; x++) {
  1525. MXFPartition *p = &mxf->partitions[x];
  1526. if (!p->body_sid)
  1527. continue; /* BodySID == 0 -> no essence */
  1528. if (x >= mxf->partitions_count - 1)
  1529. break; /* last partition - can't compute length (and we don't need to) */
  1530. /* essence container spans to the next partition */
  1531. p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
  1532. if (p->essence_length < 0) {
  1533. /* next ThisPartition < essence_offset */
  1534. p->essence_length = 0;
  1535. av_log(mxf->fc, AV_LOG_ERROR,
  1536. "partition %i: bad ThisPartition = %"PRIX64"\n",
  1537. x+1, mxf->partitions[x+1].this_partition);
  1538. }
  1539. }
  1540. }
  1541. static int64_t round_to_kag(int64_t position, int kag_size)
  1542. {
  1543. /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
  1544. /* NOTE: kag_size may be any integer between 1 - 2^10 */
  1545. int64_t ret = (position / kag_size) * kag_size;
  1546. return ret == position ? ret : ret + kag_size;
  1547. }
  1548. static int is_pcm(enum CodecID codec_id)
  1549. {
  1550. /* we only care about "normal" PCM codecs until we get samples */
  1551. return codec_id >= CODEC_ID_PCM_S16LE && codec_id < CODEC_ID_PCM_S24DAUD;
  1552. }
  1553. /**
  1554. * Deal with the case where for some audio atoms EditUnitByteCount is
  1555. * very small (2, 4..). In those cases we should read more than one
  1556. * sample per call to mxf_read_packet().
  1557. */
  1558. static void mxf_handle_small_eubc(AVFormatContext *s)
  1559. {
  1560. MXFContext *mxf = s->priv_data;
  1561. /* assuming non-OPAtom == frame wrapped
  1562. * no sane writer would wrap 2 byte PCM packets with 20 byte headers.. */
  1563. if (mxf->op != OPAtom)
  1564. return;
  1565. /* expect PCM with exactly one index table segment and a small (< 32) EUBC */
  1566. if (s->nb_streams != 1 ||
  1567. s->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
  1568. !is_pcm(s->streams[0]->codec->codec_id) ||
  1569. mxf->nb_index_tables != 1 ||
  1570. mxf->index_tables[0].nb_segments != 1 ||
  1571. mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32)
  1572. return;
  1573. /* arbitrarily default to 48 kHz PAL audio frame size */
  1574. /* TODO: We could compute this from the ratio between the audio
  1575. * and video edit rates for 48 kHz NTSC we could use the
  1576. * 1802-1802-1802-1802-1801 pattern. */
  1577. mxf->edit_units_per_packet = 1920;
  1578. }
  1579. static int mxf_read_header(AVFormatContext *s)
  1580. {
  1581. MXFContext *mxf = s->priv_data;
  1582. KLVPacket klv;
  1583. int64_t essence_offset = 0;
  1584. int ret;
  1585. mxf->last_forward_tell = INT64_MAX;
  1586. mxf->edit_units_per_packet = 1;
  1587. if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
  1588. av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
  1589. return AVERROR_INVALIDDATA;
  1590. }
  1591. avio_seek(s->pb, -14, SEEK_CUR);
  1592. mxf->fc = s;
  1593. mxf->run_in = avio_tell(s->pb);
  1594. while (!url_feof(s->pb)) {
  1595. const MXFMetadataReadTableEntry *metadata;
  1596. if (klv_read_packet(&klv, s->pb) < 0) {
  1597. /* EOF - seek to previous partition or stop */
  1598. if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
  1599. break;
  1600. else
  1601. continue;
  1602. }
  1603. PRINT_KEY(s, "read header", klv.key);
  1604. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  1605. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
  1606. IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
  1607. IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
  1608. IS_KLV_KEY(klv.key, mxf_system_item_key)) {
  1609. if (!mxf->current_partition) {
  1610. av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
  1611. return AVERROR_INVALIDDATA;
  1612. }
  1613. if (!mxf->current_partition->essence_offset) {
  1614. /* for OP1a we compute essence_offset
  1615. * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
  1616. * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
  1617. * for OPAtom we still need the actual essence_offset though (the KL's length can vary)
  1618. */
  1619. int64_t op1a_essence_offset =
  1620. round_to_kag(mxf->current_partition->this_partition +
  1621. mxf->current_partition->pack_length, mxf->current_partition->kag_size) +
  1622. round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
  1623. round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size);
  1624. if (mxf->op == OPAtom) {
  1625. /* point essence_offset to the actual data
  1626. * OPAtom has all the essence in one big KLV
  1627. */
  1628. mxf->current_partition->essence_offset = avio_tell(s->pb);
  1629. mxf->current_partition->essence_length = klv.length;
  1630. } else {
  1631. /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */
  1632. mxf->current_partition->essence_offset = op1a_essence_offset;
  1633. }
  1634. }
  1635. if (!essence_offset)
  1636. essence_offset = klv.offset;
  1637. /* seek to footer, previous partition or stop */
  1638. if (mxf_parse_handle_essence(mxf) <= 0)
  1639. break;
  1640. continue;
  1641. } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
  1642. klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
  1643. /* next partition pack - keep going, seek to previous partition or stop */
  1644. if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
  1645. break;
  1646. }
  1647. for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
  1648. if (IS_KLV_KEY(klv.key, metadata->key)) {
  1649. int res;
  1650. if (klv.key[5] == 0x53) {
  1651. res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
  1652. } else {
  1653. uint64_t next = avio_tell(s->pb) + klv.length;
  1654. res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
  1655. /* only seek forward, else this can loop for a long time */
  1656. if (avio_tell(s->pb) > next) {
  1657. av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
  1658. klv.offset);
  1659. return AVERROR_INVALIDDATA;
  1660. }
  1661. avio_seek(s->pb, next, SEEK_SET);
  1662. }
  1663. if (res < 0) {
  1664. av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
  1665. return res;
  1666. }
  1667. break;
  1668. }
  1669. }
  1670. if (!metadata->read)
  1671. avio_skip(s->pb, klv.length);
  1672. }
  1673. /* FIXME avoid seek */
  1674. if (!essence_offset) {
  1675. av_log(s, AV_LOG_ERROR, "no essence\n");
  1676. return AVERROR_INVALIDDATA;
  1677. }
  1678. avio_seek(s->pb, essence_offset, SEEK_SET);
  1679. mxf_compute_essence_containers(mxf);
  1680. /* we need to do this before computing the index tables
  1681. * to be able to fill in zero IndexDurations with st->duration */
  1682. if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
  1683. return ret;
  1684. if ((ret = mxf_compute_index_tables(mxf)) < 0)
  1685. return ret;
  1686. if (mxf->nb_index_tables > 1) {
  1687. /* TODO: look up which IndexSID to use via EssenceContainerData */
  1688. av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
  1689. mxf->nb_index_tables, mxf->index_tables[0].index_sid);
  1690. } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
  1691. av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
  1692. return AVERROR_INVALIDDATA;
  1693. }
  1694. mxf_handle_small_eubc(s);
  1695. return 0;
  1696. }
  1697. /**
  1698. * Sets mxf->current_edit_unit based on what offset we're currently at.
  1699. * @return next_ofs if OK, <0 on error
  1700. */
  1701. static int64_t mxf_set_current_edit_unit(MXFContext *mxf, int64_t current_offset)
  1702. {
  1703. int64_t last_ofs = -1, next_ofs = -1;
  1704. MXFIndexTable *t = &mxf->index_tables[0];
  1705. /* this is called from the OP1a demuxing logic, which means there
  1706. * may be no index tables */
  1707. if (mxf->nb_index_tables <= 0)
  1708. return -1;
  1709. /* find mxf->current_edit_unit so that the next edit unit starts ahead of current_offset */
  1710. while (mxf->current_edit_unit >= 0) {
  1711. if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0)
  1712. return -1;
  1713. if (next_ofs <= last_ofs) {
  1714. /* large next_ofs didn't change or current_edit_unit wrapped
  1715. * around this fixes the infinite loop on zzuf3.mxf */
  1716. av_log(mxf->fc, AV_LOG_ERROR,
  1717. "next_ofs didn't change. not deriving packet timestamps\n");
  1718. return - 1;
  1719. }
  1720. if (next_ofs > current_offset)
  1721. break;
  1722. last_ofs = next_ofs;
  1723. mxf->current_edit_unit++;
  1724. }
  1725. /* not checking mxf->current_edit_unit >= t->nb_ptses here since CBR files may lack IndexEntryArrays */
  1726. if (mxf->current_edit_unit < 0)
  1727. return -1;
  1728. return next_ofs;
  1729. }
  1730. static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
  1731. {
  1732. KLVPacket klv;
  1733. MXFContext *mxf = s->priv_data;
  1734. while (!url_feof(s->pb)) {
  1735. int ret;
  1736. if (klv_read_packet(&klv, s->pb) < 0)
  1737. return -1;
  1738. PRINT_KEY(s, "read packet", klv.key);
  1739. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  1740. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
  1741. ret = mxf_decrypt_triplet(s, pkt, &klv);
  1742. if (ret < 0) {
  1743. av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
  1744. return AVERROR_INVALIDDATA;
  1745. }
  1746. return 0;
  1747. }
  1748. if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
  1749. IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
  1750. int index = mxf_get_stream_index(s, &klv);
  1751. int64_t next_ofs, next_klv;
  1752. if (index < 0) {
  1753. av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
  1754. goto skip;
  1755. }
  1756. if (s->streams[index]->discard == AVDISCARD_ALL)
  1757. goto skip;
  1758. next_klv = avio_tell(s->pb) + klv.length;
  1759. next_ofs = mxf_set_current_edit_unit(mxf, klv.offset);
  1760. if (next_ofs >= 0 && next_klv > next_ofs) {
  1761. /* if this check is hit then it's possible OPAtom was treated as OP1a
  1762. * truncate the packet since it's probably very large (>2 GiB is common) */
  1763. av_log_ask_for_sample(s,
  1764. "KLV for edit unit %i extends into next edit unit - OPAtom misinterpreted as OP1a?\n",
  1765. mxf->current_edit_unit);
  1766. klv.length = next_ofs - avio_tell(s->pb);
  1767. }
  1768. /* check for 8 channels AES3 element */
  1769. if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
  1770. if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
  1771. av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
  1772. return AVERROR_INVALIDDATA;
  1773. }
  1774. } else {
  1775. ret = av_get_packet(s->pb, pkt, klv.length);
  1776. if (ret < 0)
  1777. return ret;
  1778. }
  1779. pkt->stream_index = index;
  1780. pkt->pos = klv.offset;
  1781. if (s->streams[index]->codec->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
  1782. /* mxf->current_edit_unit good - see if we have an index table to derive timestamps from */
  1783. MXFIndexTable *t = &mxf->index_tables[0];
  1784. if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) {
  1785. pkt->dts = mxf->current_edit_unit + t->first_dts;
  1786. pkt->pts = t->ptses[mxf->current_edit_unit];
  1787. }
  1788. }
  1789. /* seek for truncated packets */
  1790. avio_seek(s->pb, next_klv, SEEK_SET);
  1791. return 0;
  1792. } else
  1793. skip:
  1794. avio_skip(s->pb, klv.length);
  1795. }
  1796. return AVERROR_EOF;
  1797. }
  1798. static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
  1799. {
  1800. MXFContext *mxf = s->priv_data;
  1801. int ret, size;
  1802. int64_t ret64, pos, next_pos;
  1803. AVStream *st;
  1804. MXFIndexTable *t;
  1805. int edit_units;
  1806. if (mxf->op != OPAtom)
  1807. return mxf_read_packet_old(s, pkt);
  1808. /* OPAtom - clip wrapped demuxing */
  1809. /* NOTE: mxf_read_header() makes sure nb_index_tables > 0 for OPAtom */
  1810. st = s->streams[0];
  1811. t = &mxf->index_tables[0];
  1812. if (mxf->current_edit_unit >= st->duration)
  1813. return AVERROR_EOF;
  1814. edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit);
  1815. if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0)
  1816. return ret;
  1817. /* compute size by finding the next edit unit or the end of the essence container
  1818. * not pretty, but it works */
  1819. if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 &&
  1820. (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
  1821. av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
  1822. return AVERROR_INVALIDDATA;
  1823. }
  1824. if ((size = next_pos - pos) <= 0) {
  1825. av_log(s, AV_LOG_ERROR, "bad size: %i\n", size);
  1826. return AVERROR_INVALIDDATA;
  1827. }
  1828. if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0)
  1829. return ret64;
  1830. if ((ret = av_get_packet(s->pb, pkt, size)) != size)
  1831. return ret < 0 ? ret : AVERROR_EOF;
  1832. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
  1833. mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
  1834. pkt->dts = mxf->current_edit_unit + t->first_dts;
  1835. pkt->pts = t->ptses[mxf->current_edit_unit];
  1836. }
  1837. pkt->stream_index = 0;
  1838. mxf->current_edit_unit += edit_units;
  1839. return 0;
  1840. }
  1841. static int mxf_read_close(AVFormatContext *s)
  1842. {
  1843. MXFContext *mxf = s->priv_data;
  1844. MXFIndexTableSegment *seg;
  1845. int i;
  1846. av_freep(&mxf->packages_refs);
  1847. for (i = 0; i < s->nb_streams; i++)
  1848. s->streams[i]->priv_data = NULL;
  1849. for (i = 0; i < mxf->metadata_sets_count; i++) {
  1850. switch (mxf->metadata_sets[i]->type) {
  1851. case MultipleDescriptor:
  1852. av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
  1853. break;
  1854. case Sequence:
  1855. av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
  1856. break;
  1857. case SourcePackage:
  1858. case MaterialPackage:
  1859. av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
  1860. break;
  1861. case IndexTableSegment:
  1862. seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
  1863. av_freep(&seg->temporal_offset_entries);
  1864. av_freep(&seg->flag_entries);
  1865. av_freep(&seg->stream_offset_entries);
  1866. break;
  1867. default:
  1868. break;
  1869. }
  1870. av_freep(&mxf->metadata_sets[i]);
  1871. }
  1872. av_freep(&mxf->partitions);
  1873. av_freep(&mxf->metadata_sets);
  1874. av_freep(&mxf->aesc);
  1875. av_freep(&mxf->local_tags);
  1876. for (i = 0; i < mxf->nb_index_tables; i++) {
  1877. av_freep(&mxf->index_tables[i].segments);
  1878. av_freep(&mxf->index_tables[i].ptses);
  1879. av_freep(&mxf->index_tables[i].fake_index);
  1880. }
  1881. av_freep(&mxf->index_tables);
  1882. return 0;
  1883. }
  1884. static int mxf_probe(AVProbeData *p) {
  1885. uint8_t *bufp = p->buf;
  1886. uint8_t *end = p->buf + p->buf_size;
  1887. if (p->buf_size < sizeof(mxf_header_partition_pack_key))
  1888. return 0;
  1889. /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
  1890. end -= sizeof(mxf_header_partition_pack_key);
  1891. for (; bufp < end; bufp++) {
  1892. if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
  1893. return AVPROBE_SCORE_MAX;
  1894. }
  1895. return 0;
  1896. }
  1897. /* rudimentary byte seek */
  1898. /* XXX: use MXF Index */
  1899. static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  1900. {
  1901. AVStream *st = s->streams[stream_index];
  1902. int64_t seconds;
  1903. MXFContext* mxf = s->priv_data;
  1904. int64_t seekpos;
  1905. int ret;
  1906. MXFIndexTable *t;
  1907. if (mxf->index_tables <= 0) {
  1908. if (!s->bit_rate)
  1909. return AVERROR_INVALIDDATA;
  1910. if (sample_time < 0)
  1911. sample_time = 0;
  1912. seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
  1913. if ((ret = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET)) < 0)
  1914. return ret;
  1915. ff_update_cur_dts(s, st, sample_time);
  1916. } else {
  1917. t = &mxf->index_tables[0];
  1918. /* clamp above zero, else ff_index_search_timestamp() returns negative
  1919. * this also means we allow seeking before the start */
  1920. sample_time = FFMAX(sample_time, 0);
  1921. if (t->fake_index) {
  1922. /* behave as if we have a proper index */
  1923. if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
  1924. return sample_time;
  1925. } else {
  1926. /* no IndexEntryArray (one or more CBR segments)
  1927. * make sure we don't seek past the end */
  1928. sample_time = FFMIN(sample_time, st->duration - 1);
  1929. }
  1930. if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) << 0)
  1931. return ret;
  1932. ff_update_cur_dts(s, st, sample_time);
  1933. mxf->current_edit_unit = sample_time;
  1934. avio_seek(s->pb, seekpos, SEEK_SET);
  1935. }
  1936. return 0;
  1937. }
  1938. AVInputFormat ff_mxf_demuxer = {
  1939. .name = "mxf",
  1940. .long_name = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
  1941. .priv_data_size = sizeof(MXFContext),
  1942. .read_probe = mxf_probe,
  1943. .read_header = mxf_read_header,
  1944. .read_packet = mxf_read_packet,
  1945. .read_close = mxf_read_close,
  1946. .read_seek = mxf_read_seek,
  1947. };