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.

2257 lines
84KB

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