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.

2650 lines
99KB

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