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.

2576 lines
95KB

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