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.

1441 lines
55KB

  1. /*
  2. * MXF demuxer.
  3. * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /*
  22. * References
  23. * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
  24. * SMPTE 377M MXF File Format Specifications
  25. * SMPTE 378M Operational Pattern 1a
  26. * SMPTE 379M MXF Generic Container
  27. * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
  28. * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
  29. * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
  30. *
  31. * Principle
  32. * Search for Track numbers which will identify essence element KLV packets.
  33. * Search for SourcePackage which define tracks which contains Track numbers.
  34. * Material Package contains tracks with reference to SourcePackage tracks.
  35. * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
  36. * Assign Descriptors to correct Tracks.
  37. *
  38. * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
  39. * Metadata parsing resolves Strong References to objects.
  40. *
  41. * Simple demuxer, only OP1A supported and some files might not work at all.
  42. * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
  43. */
  44. //#define DEBUG
  45. #include "libavutil/aes.h"
  46. #include "libavutil/mathematics.h"
  47. #include "libavcodec/bytestream.h"
  48. #include "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,
  58. OP1b,
  59. OP1c,
  60. OP2a,
  61. OP2b,
  62. OP2c,
  63. OP3a,
  64. OP3b,
  65. OP3c,
  66. OPAtom,
  67. } MXFOP;
  68. typedef struct {
  69. int closed;
  70. int complete;
  71. MXFPartitionType type;
  72. uint64_t previous_partition;
  73. int index_sid;
  74. int body_sid;
  75. } MXFPartition;
  76. typedef struct {
  77. UID uid;
  78. enum MXFMetadataSetType type;
  79. UID source_container_ul;
  80. } MXFCryptoContext;
  81. typedef struct {
  82. UID uid;
  83. enum MXFMetadataSetType type;
  84. UID source_package_uid;
  85. UID data_definition_ul;
  86. int64_t duration;
  87. int64_t start_position;
  88. int source_track_id;
  89. } MXFStructuralComponent;
  90. typedef struct {
  91. UID uid;
  92. enum MXFMetadataSetType type;
  93. UID data_definition_ul;
  94. UID *structural_components_refs;
  95. int structural_components_count;
  96. int64_t duration;
  97. } MXFSequence;
  98. typedef struct {
  99. UID uid;
  100. enum MXFMetadataSetType type;
  101. MXFSequence *sequence; /* mandatory, and only one */
  102. UID sequence_ref;
  103. int track_id;
  104. uint8_t track_number[4];
  105. AVRational edit_rate;
  106. } MXFTrack;
  107. typedef struct {
  108. UID uid;
  109. enum MXFMetadataSetType type;
  110. UID essence_container_ul;
  111. UID essence_codec_ul;
  112. AVRational sample_rate;
  113. AVRational aspect_ratio;
  114. int width;
  115. int height;
  116. int channels;
  117. int bits_per_sample;
  118. UID *sub_descriptors_refs;
  119. int sub_descriptors_count;
  120. int linked_track_id;
  121. uint8_t *extradata;
  122. int extradata_size;
  123. enum PixelFormat pix_fmt;
  124. } MXFDescriptor;
  125. typedef struct {
  126. UID uid;
  127. enum MXFMetadataSetType type;
  128. int edit_unit_byte_count;
  129. int index_sid;
  130. int body_sid;
  131. int slice_count;
  132. AVRational index_edit_rate;
  133. uint64_t index_start_position;
  134. uint64_t index_duration;
  135. int *slice;
  136. int *element_delta;
  137. int nb_delta_entries;
  138. int *flag_entries;
  139. uint64_t *stream_offset_entries;
  140. uint32_t **slice_offset_entries;
  141. int nb_index_entries;
  142. } MXFIndexTableSegment;
  143. typedef struct {
  144. UID uid;
  145. enum MXFMetadataSetType type;
  146. UID package_uid;
  147. UID *tracks_refs;
  148. int tracks_count;
  149. MXFDescriptor *descriptor; /* only one */
  150. UID descriptor_ref;
  151. } MXFPackage;
  152. typedef struct {
  153. UID uid;
  154. enum MXFMetadataSetType type;
  155. } MXFMetadataSet;
  156. typedef struct {
  157. MXFPartition *partitions;
  158. unsigned partitions_count;
  159. MXFOP op;
  160. UID *packages_refs;
  161. int packages_count;
  162. MXFMetadataSet **metadata_sets;
  163. int metadata_sets_count;
  164. AVFormatContext *fc;
  165. struct AVAES *aesc;
  166. uint8_t *local_tags;
  167. int local_tags_count;
  168. uint64_t footer_partition;
  169. int system_item;
  170. int64_t essence_offset;
  171. int first_essence_kl_length;
  172. int64_t first_essence_length;
  173. KLVPacket current_klv_data;
  174. int current_klv_index;
  175. } MXFContext;
  176. enum MXFWrappingScheme {
  177. Frame,
  178. Clip,
  179. };
  180. typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid);
  181. typedef struct {
  182. const UID key;
  183. MXFMetadataReadFunc *read;
  184. int ctx_size;
  185. enum MXFMetadataSetType type;
  186. } MXFMetadataReadTableEntry;
  187. /* partial keys to match */
  188. static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
  189. static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
  190. static const uint8_t mxf_system_item_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
  191. static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
  192. /* complete keys to match */
  193. 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 };
  194. static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
  195. static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
  196. static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
  197. #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
  198. static int64_t klv_decode_ber_length(AVIOContext *pb)
  199. {
  200. uint64_t size = avio_r8(pb);
  201. if (size & 0x80) { /* long form */
  202. int bytes_num = size & 0x7f;
  203. /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
  204. if (bytes_num > 8)
  205. return -1;
  206. size = 0;
  207. while (bytes_num--)
  208. size = size << 8 | avio_r8(pb);
  209. }
  210. return size;
  211. }
  212. static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
  213. {
  214. int i, b;
  215. for (i = 0; i < size && !url_feof(pb); i++) {
  216. b = avio_r8(pb);
  217. if (b == key[0])
  218. i = 0;
  219. else if (b != key[i])
  220. i = -1;
  221. }
  222. return i == size;
  223. }
  224. static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
  225. {
  226. if (!mxf_read_sync(pb, mxf_klv_key, 4))
  227. return -1;
  228. klv->offset = avio_tell(pb) - 4;
  229. memcpy(klv->key, mxf_klv_key, 4);
  230. avio_read(pb, klv->key + 4, 12);
  231. klv->length = klv_decode_ber_length(pb);
  232. return klv->length == -1 ? -1 : 0;
  233. }
  234. static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
  235. {
  236. int i;
  237. for (i = 0; i < s->nb_streams; i++) {
  238. MXFTrack *track = s->streams[i]->priv_data;
  239. /* SMPTE 379M 7.3 */
  240. if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
  241. return i;
  242. }
  243. /* return 0 if only one stream, for OP Atom files with 0 as track number */
  244. return s->nb_streams == 1 ? 0 : -1;
  245. }
  246. /* XXX: use AVBitStreamFilter */
  247. static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
  248. {
  249. const uint8_t *buf_ptr, *end_ptr;
  250. uint8_t *data_ptr;
  251. int i;
  252. if (length > 61444) /* worst case PAL 1920 samples 8 channels */
  253. return -1;
  254. length = av_get_packet(pb, pkt, length);
  255. if (length < 0)
  256. return length;
  257. data_ptr = pkt->data;
  258. end_ptr = pkt->data + length;
  259. buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
  260. for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
  261. for (i = 0; i < st->codec->channels; i++) {
  262. uint32_t sample = bytestream_get_le32(&buf_ptr);
  263. if (st->codec->bits_per_coded_sample == 24)
  264. bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
  265. else
  266. bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
  267. }
  268. buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
  269. }
  270. av_shrink_packet(pkt, data_ptr - pkt->data);
  271. return 0;
  272. }
  273. static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
  274. {
  275. static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
  276. MXFContext *mxf = s->priv_data;
  277. AVIOContext *pb = s->pb;
  278. int64_t end = avio_tell(pb) + klv->length;
  279. int64_t size;
  280. uint64_t orig_size;
  281. uint64_t plaintext_size;
  282. uint8_t ivec[16];
  283. uint8_t tmpbuf[16];
  284. int index;
  285. if (!mxf->aesc && s->key && s->keylen == 16) {
  286. mxf->aesc = av_malloc(av_aes_size);
  287. if (!mxf->aesc)
  288. return -1;
  289. av_aes_init(mxf->aesc, s->key, 128, 1);
  290. }
  291. // crypto context
  292. avio_skip(pb, klv_decode_ber_length(pb));
  293. // plaintext offset
  294. klv_decode_ber_length(pb);
  295. plaintext_size = avio_rb64(pb);
  296. // source klv key
  297. klv_decode_ber_length(pb);
  298. avio_read(pb, klv->key, 16);
  299. if (!IS_KLV_KEY(klv, mxf_essence_element_key))
  300. return -1;
  301. index = mxf_get_stream_index(s, klv);
  302. if (index < 0)
  303. return -1;
  304. // source size
  305. klv_decode_ber_length(pb);
  306. orig_size = avio_rb64(pb);
  307. if (orig_size < plaintext_size)
  308. return -1;
  309. // enc. code
  310. size = klv_decode_ber_length(pb);
  311. if (size < 32 || size - 32 < orig_size)
  312. return -1;
  313. avio_read(pb, ivec, 16);
  314. avio_read(pb, tmpbuf, 16);
  315. if (mxf->aesc)
  316. av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
  317. if (memcmp(tmpbuf, checkv, 16))
  318. av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
  319. size -= 32;
  320. size = av_get_packet(pb, pkt, size);
  321. if (size < 0)
  322. return size;
  323. else if (size < plaintext_size)
  324. return AVERROR_INVALIDDATA;
  325. size -= plaintext_size;
  326. if (mxf->aesc)
  327. av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
  328. &pkt->data[plaintext_size], size >> 4, ivec, 1);
  329. av_shrink_packet(pkt, orig_size);
  330. pkt->stream_index = index;
  331. avio_skip(pb, end - avio_tell(pb));
  332. return 0;
  333. }
  334. static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
  335. {
  336. KLVPacket klv;
  337. while (!url_feof(s->pb)) {
  338. if (klv_read_packet(&klv, s->pb) < 0)
  339. return -1;
  340. PRINT_KEY(s, "read packet", klv.key);
  341. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  342. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
  343. int res = mxf_decrypt_triplet(s, pkt, &klv);
  344. if (res < 0) {
  345. av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
  346. return -1;
  347. }
  348. return 0;
  349. }
  350. if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
  351. int index = mxf_get_stream_index(s, &klv);
  352. if (index < 0) {
  353. av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
  354. goto skip;
  355. }
  356. if (s->streams[index]->discard == AVDISCARD_ALL)
  357. goto skip;
  358. /* check for 8 channels AES3 element */
  359. if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
  360. if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
  361. av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
  362. return -1;
  363. }
  364. } else {
  365. int ret = av_get_packet(s->pb, pkt, klv.length);
  366. if (ret < 0)
  367. return ret;
  368. }
  369. pkt->stream_index = index;
  370. pkt->pos = klv.offset;
  371. return 0;
  372. } else
  373. skip:
  374. avio_skip(s->pb, klv.length);
  375. }
  376. return AVERROR_EOF;
  377. }
  378. static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  379. {
  380. MXFContext *mxf = arg;
  381. int item_num = avio_rb32(pb);
  382. int item_len = avio_rb32(pb);
  383. if (item_len != 18) {
  384. av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
  385. return -1;
  386. }
  387. if (item_num > UINT_MAX / item_len)
  388. return -1;
  389. mxf->local_tags_count = item_num;
  390. mxf->local_tags = av_malloc(item_num*item_len);
  391. if (!mxf->local_tags)
  392. return -1;
  393. avio_read(pb, mxf->local_tags, item_num*item_len);
  394. return 0;
  395. }
  396. static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  397. {
  398. MXFContext *mxf = arg;
  399. MXFPartition *partition;
  400. UID op;
  401. uint64_t footer_partition;
  402. if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
  403. return AVERROR(ENOMEM);
  404. mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
  405. if (!mxf->partitions)
  406. return AVERROR(ENOMEM);
  407. partition = &mxf->partitions[mxf->partitions_count++];
  408. switch(uid[13]) {
  409. case 2:
  410. partition->type = Header;
  411. break;
  412. case 3:
  413. partition->type = BodyPartition;
  414. break;
  415. case 4:
  416. partition->type = Footer;
  417. break;
  418. default:
  419. av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
  420. return AVERROR_INVALIDDATA;
  421. }
  422. /* consider both footers to be closed (there is only Footer and CompleteFooter) */
  423. partition->closed = partition->type == Footer || !(uid[14] & 1);
  424. partition->complete = uid[14] > 2;
  425. avio_skip(pb, 16);
  426. partition->previous_partition = avio_rb64(pb);
  427. footer_partition = avio_rb64(pb);
  428. avio_skip(pb, 16);
  429. partition->index_sid = avio_rb32(pb);
  430. avio_skip(pb, 8);
  431. partition->body_sid = avio_rb32(pb);
  432. avio_read(pb, op, sizeof(UID));
  433. /* some files don'thave FooterPartition set in every partition */
  434. if (footer_partition) {
  435. if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
  436. av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",
  437. mxf->footer_partition, footer_partition);
  438. } else {
  439. mxf->footer_partition = footer_partition;
  440. }
  441. }
  442. av_dlog(mxf->fc, "PartitionPack: PreviousPartition = 0x%lx, "
  443. "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
  444. partition->previous_partition, footer_partition,
  445. partition->index_sid, partition->body_sid);
  446. if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
  447. else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
  448. else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
  449. else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
  450. else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
  451. else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
  452. else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
  453. else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
  454. else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
  455. else if (op[12] == 0x10) mxf->op = OPAtom;
  456. else
  457. av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh\n", op[12], op[13]);
  458. return 0;
  459. }
  460. static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
  461. {
  462. if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
  463. return AVERROR(ENOMEM);
  464. mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
  465. if (!mxf->metadata_sets)
  466. return -1;
  467. mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
  468. mxf->metadata_sets_count++;
  469. return 0;
  470. }
  471. static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  472. {
  473. MXFCryptoContext *cryptocontext = arg;
  474. if (size != 16)
  475. return -1;
  476. if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
  477. avio_read(pb, cryptocontext->source_container_ul, 16);
  478. return 0;
  479. }
  480. static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  481. {
  482. MXFContext *mxf = arg;
  483. switch (tag) {
  484. case 0x1901:
  485. mxf->packages_count = avio_rb32(pb);
  486. if (mxf->packages_count >= UINT_MAX / sizeof(UID))
  487. return -1;
  488. mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
  489. if (!mxf->packages_refs)
  490. return -1;
  491. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  492. avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
  493. break;
  494. }
  495. return 0;
  496. }
  497. static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  498. {
  499. MXFStructuralComponent *source_clip = arg;
  500. switch(tag) {
  501. case 0x0202:
  502. source_clip->duration = avio_rb64(pb);
  503. break;
  504. case 0x1201:
  505. source_clip->start_position = avio_rb64(pb);
  506. break;
  507. case 0x1101:
  508. /* UMID, only get last 16 bytes */
  509. avio_skip(pb, 16);
  510. avio_read(pb, source_clip->source_package_uid, 16);
  511. break;
  512. case 0x1102:
  513. source_clip->source_track_id = avio_rb32(pb);
  514. break;
  515. }
  516. return 0;
  517. }
  518. static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  519. {
  520. MXFPackage *package = arg;
  521. switch(tag) {
  522. case 0x4403:
  523. package->tracks_count = avio_rb32(pb);
  524. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  525. return -1;
  526. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  527. if (!package->tracks_refs)
  528. return -1;
  529. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  530. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  531. break;
  532. }
  533. return 0;
  534. }
  535. static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  536. {
  537. MXFTrack *track = arg;
  538. switch(tag) {
  539. case 0x4801:
  540. track->track_id = avio_rb32(pb);
  541. break;
  542. case 0x4804:
  543. avio_read(pb, track->track_number, 4);
  544. break;
  545. case 0x4B01:
  546. track->edit_rate.den = avio_rb32(pb);
  547. track->edit_rate.num = avio_rb32(pb);
  548. break;
  549. case 0x4803:
  550. avio_read(pb, track->sequence_ref, 16);
  551. break;
  552. }
  553. return 0;
  554. }
  555. static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  556. {
  557. MXFSequence *sequence = arg;
  558. switch(tag) {
  559. case 0x0202:
  560. sequence->duration = avio_rb64(pb);
  561. break;
  562. case 0x0201:
  563. avio_read(pb, sequence->data_definition_ul, 16);
  564. break;
  565. case 0x1001:
  566. sequence->structural_components_count = avio_rb32(pb);
  567. if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
  568. return -1;
  569. sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
  570. if (!sequence->structural_components_refs)
  571. return -1;
  572. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  573. avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
  574. break;
  575. }
  576. return 0;
  577. }
  578. static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  579. {
  580. MXFPackage *package = arg;
  581. switch(tag) {
  582. case 0x4403:
  583. package->tracks_count = avio_rb32(pb);
  584. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  585. return -1;
  586. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  587. if (!package->tracks_refs)
  588. return -1;
  589. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  590. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  591. break;
  592. case 0x4401:
  593. /* UMID, only get last 16 bytes */
  594. avio_skip(pb, 16);
  595. avio_read(pb, package->package_uid, 16);
  596. break;
  597. case 0x4701:
  598. avio_read(pb, package->descriptor_ref, 16);
  599. break;
  600. }
  601. return 0;
  602. }
  603. static int mxf_read_delta_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
  604. {
  605. int i, length;
  606. segment->nb_delta_entries = avio_rb32(pb);
  607. length = avio_rb32(pb);
  608. if (!(segment->slice = av_calloc(segment->nb_delta_entries, sizeof(*segment->slice))) ||
  609. !(segment->element_delta = av_calloc(segment->nb_delta_entries, sizeof(*segment->element_delta))))
  610. return AVERROR(ENOMEM);
  611. for (i = 0; i < segment->nb_delta_entries; i++) {
  612. avio_r8(pb); /* PosTableIndex */
  613. segment->slice[i] = avio_r8(pb);
  614. segment->element_delta[i] = avio_rb32(pb);
  615. }
  616. return 0;
  617. }
  618. static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
  619. {
  620. int i, j, length;
  621. segment->nb_index_entries = avio_rb32(pb);
  622. length = avio_rb32(pb);
  623. if (!(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
  624. !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
  625. return AVERROR(ENOMEM);
  626. if (segment->slice_count &&
  627. !(segment->slice_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->slice_offset_entries))))
  628. return AVERROR(ENOMEM);
  629. for (i = 0; i < segment->nb_index_entries; i++) {
  630. avio_rb16(pb); /* TemporalOffset and KeyFrameOffset */
  631. segment->flag_entries[i] = avio_r8(pb);
  632. segment->stream_offset_entries[i] = avio_rb64(pb);
  633. if (segment->slice_count) {
  634. if (!(segment->slice_offset_entries[i] = av_calloc(segment->slice_count, sizeof(**segment->slice_offset_entries))))
  635. return AVERROR(ENOMEM);
  636. for (j = 0; j < segment->slice_count; j++)
  637. segment->slice_offset_entries[i][j] = avio_rb32(pb);
  638. }
  639. avio_skip(pb, length - 11 - 4 * segment->slice_count);
  640. }
  641. return 0;
  642. }
  643. static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  644. {
  645. MXFIndexTableSegment *segment = arg;
  646. switch(tag) {
  647. case 0x3F05:
  648. segment->edit_unit_byte_count = avio_rb32(pb);
  649. av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
  650. break;
  651. case 0x3F06:
  652. segment->index_sid = avio_rb32(pb);
  653. av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
  654. break;
  655. case 0x3F07:
  656. segment->body_sid = avio_rb32(pb);
  657. av_dlog(NULL, "BodySID %d\n", segment->body_sid);
  658. break;
  659. case 0x3F08:
  660. segment->slice_count = avio_r8(pb);
  661. av_dlog(NULL, "SliceCount %d\n", segment->slice_count);
  662. break;
  663. case 0x3F09:
  664. av_dlog(NULL, "DeltaEntryArray found\n");
  665. return mxf_read_delta_entry_array(pb, segment);
  666. case 0x3F0A:
  667. av_dlog(NULL, "IndexEntryArray found\n");
  668. return mxf_read_index_entry_array(pb, segment);
  669. case 0x3F0B:
  670. segment->index_edit_rate.num = avio_rb32(pb);
  671. segment->index_edit_rate.den = avio_rb32(pb);
  672. av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
  673. segment->index_edit_rate.den);
  674. break;
  675. case 0x3F0C:
  676. segment->index_start_position = avio_rb64(pb);
  677. av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
  678. break;
  679. case 0x3F0D:
  680. segment->index_duration = avio_rb64(pb);
  681. av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
  682. break;
  683. }
  684. return 0;
  685. }
  686. static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
  687. {
  688. int code, value, ofs = 0;
  689. char layout[16] = {0};
  690. do {
  691. code = avio_r8(pb);
  692. value = avio_r8(pb);
  693. av_dlog(NULL, "pixel layout: code %#x\n", code);
  694. if (ofs < 16) {
  695. layout[ofs++] = code;
  696. layout[ofs++] = value;
  697. }
  698. } while (code != 0); /* SMPTE 377M E.2.46 */
  699. ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
  700. }
  701. static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid)
  702. {
  703. MXFDescriptor *descriptor = arg;
  704. switch(tag) {
  705. case 0x3F01:
  706. descriptor->sub_descriptors_count = avio_rb32(pb);
  707. if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
  708. return -1;
  709. descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
  710. if (!descriptor->sub_descriptors_refs)
  711. return -1;
  712. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  713. avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
  714. break;
  715. case 0x3004:
  716. avio_read(pb, descriptor->essence_container_ul, 16);
  717. break;
  718. case 0x3006:
  719. descriptor->linked_track_id = avio_rb32(pb);
  720. break;
  721. case 0x3201: /* PictureEssenceCoding */
  722. avio_read(pb, descriptor->essence_codec_ul, 16);
  723. break;
  724. case 0x3203:
  725. descriptor->width = avio_rb32(pb);
  726. break;
  727. case 0x3202:
  728. descriptor->height = avio_rb32(pb);
  729. break;
  730. case 0x320E:
  731. descriptor->aspect_ratio.num = avio_rb32(pb);
  732. descriptor->aspect_ratio.den = avio_rb32(pb);
  733. break;
  734. case 0x3D03:
  735. descriptor->sample_rate.num = avio_rb32(pb);
  736. descriptor->sample_rate.den = avio_rb32(pb);
  737. break;
  738. case 0x3D06: /* SoundEssenceCompression */
  739. avio_read(pb, descriptor->essence_codec_ul, 16);
  740. break;
  741. case 0x3D07:
  742. descriptor->channels = avio_rb32(pb);
  743. break;
  744. case 0x3D01:
  745. descriptor->bits_per_sample = avio_rb32(pb);
  746. break;
  747. case 0x3401:
  748. mxf_read_pixel_layout(pb, descriptor);
  749. break;
  750. default:
  751. /* Private uid used by SONY C0023S01.mxf */
  752. if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
  753. descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
  754. if (!descriptor->extradata)
  755. return -1;
  756. descriptor->extradata_size = size;
  757. avio_read(pb, descriptor->extradata, size);
  758. }
  759. break;
  760. }
  761. return 0;
  762. }
  763. /*
  764. * Match an uid independently of the version byte and up to len common bytes
  765. * Returns: boolean
  766. */
  767. static int mxf_match_uid(const UID key, const UID uid, int len)
  768. {
  769. int i;
  770. for (i = 0; i < len; i++) {
  771. if (i != 7 && key[i] != uid[i])
  772. return 0;
  773. }
  774. return 1;
  775. }
  776. static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
  777. {
  778. while (uls->uid[0]) {
  779. if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
  780. break;
  781. uls++;
  782. }
  783. return uls;
  784. }
  785. static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
  786. {
  787. int i;
  788. if (!strong_ref)
  789. return NULL;
  790. for (i = 0; i < mxf->metadata_sets_count; i++) {
  791. if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
  792. (type == AnyType || mxf->metadata_sets[i]->type == type)) {
  793. return mxf->metadata_sets[i];
  794. }
  795. }
  796. return NULL;
  797. }
  798. static const MXFCodecUL mxf_essence_container_uls[] = {
  799. // video essence container uls
  800. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
  801. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
  802. // sound essence container uls
  803. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
  804. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
  805. { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
  806. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
  807. };
  808. static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
  809. {
  810. int i, j, nb_segments = 0;
  811. MXFIndexTableSegment **unsorted_segments;
  812. int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
  813. /* count number of segments, allocate arrays and copy unsorted segments */
  814. for (i = 0; i < mxf->metadata_sets_count; i++)
  815. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  816. nb_segments++;
  817. if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
  818. !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
  819. av_free(unsorted_segments);
  820. return AVERROR(ENOMEM);
  821. }
  822. for (i = j = 0; i < mxf->metadata_sets_count; i++)
  823. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  824. unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
  825. *nb_sorted_segments = 0;
  826. /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
  827. for (i = 0; i < nb_segments; i++) {
  828. int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
  829. for (j = 0; j < nb_segments; j++) {
  830. MXFIndexTableSegment *s = unsorted_segments[j];
  831. /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
  832. * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
  833. */
  834. if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
  835. (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
  836. best = j;
  837. best_body_sid = s->body_sid;
  838. best_index_sid = s->index_sid;
  839. best_index_start = s->index_start_position;
  840. }
  841. }
  842. /* no suitable entry found -> we're done */
  843. if (best == -1)
  844. break;
  845. (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
  846. last_body_sid = best_body_sid;
  847. last_index_sid = best_index_sid;
  848. last_index_start = best_index_start;
  849. }
  850. av_free(unsorted_segments);
  851. return 0;
  852. }
  853. static int mxf_parse_index(MXFContext *mxf, int i, AVStream *st)
  854. {
  855. int64_t accumulated_offset = 0;
  856. int j, k, ret, nb_sorted_segments;
  857. MXFIndexTableSegment **sorted_segments;
  858. if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)))
  859. return ret;
  860. for (j = 0; j < nb_sorted_segments; j++) {
  861. int n_delta = i;
  862. int duration, sample_duration = 1, last_sample_size = 0;
  863. int64_t segment_size;
  864. MXFIndexTableSegment *tableseg = sorted_segments[j];
  865. /* reset accumulated_offset on BodySID change */
  866. if (j > 0 && tableseg->body_sid != sorted_segments[j-1]->body_sid)
  867. accumulated_offset = 0;
  868. /* HACK: How to correctly link between streams and slices? */
  869. if (i < mxf->system_item + st->index)
  870. n_delta++;
  871. if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
  872. continue;
  873. duration = tableseg->index_duration > 0 ? tableseg->index_duration :
  874. st->duration - st->nb_index_entries;
  875. segment_size = tableseg->edit_unit_byte_count * duration;
  876. /* check small EditUnitByteCount for audio */
  877. if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
  878. && !tableseg->index_duration) {
  879. /* duration might be prime relative to the new sample_duration,
  880. * which means we need to handle the last frame differently */
  881. sample_duration = 8192;
  882. last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
  883. tableseg->edit_unit_byte_count *= sample_duration;
  884. duration /= sample_duration;
  885. if (last_sample_size) duration++;
  886. }
  887. for (k = 0; k < duration; k++) {
  888. int64_t pos;
  889. int size, flags = 0;
  890. if (k < tableseg->nb_index_entries) {
  891. pos = tableseg->stream_offset_entries[k];
  892. if (n_delta < tableseg->nb_delta_entries) {
  893. if (n_delta < tableseg->nb_delta_entries - 1) {
  894. size =
  895. tableseg->slice_offset_entries[k][tableseg->slice[n_delta+1]-1] +
  896. tableseg->element_delta[n_delta+1] -
  897. tableseg->element_delta[n_delta];
  898. if (tableseg->slice[n_delta] > 0)
  899. size -= tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
  900. } else if (k < duration - 1) {
  901. size = tableseg->stream_offset_entries[k+1] -
  902. tableseg->stream_offset_entries[k] -
  903. tableseg->slice_offset_entries[k][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
  904. tableseg->element_delta[tableseg->nb_delta_entries-1];
  905. } else
  906. size = 0;
  907. if (tableseg->slice[n_delta] > 0)
  908. pos += tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
  909. pos += tableseg->element_delta[n_delta];
  910. } else
  911. size = 0;
  912. flags = !(tableseg->flag_entries[k] & 0x30) ? AVINDEX_KEYFRAME : 0;
  913. } else {
  914. pos = (int64_t)k * tableseg->edit_unit_byte_count + accumulated_offset;
  915. if (n_delta < tableseg->nb_delta_entries - 1)
  916. size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
  917. else {
  918. /* use smaller size for last sample if we should */
  919. if (last_sample_size && k == duration - 1)
  920. size = last_sample_size;
  921. else
  922. size = tableseg->edit_unit_byte_count;
  923. if (tableseg->nb_delta_entries)
  924. size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
  925. }
  926. if (n_delta < tableseg->nb_delta_entries)
  927. pos += tableseg->element_delta[n_delta];
  928. flags = AVINDEX_KEYFRAME;
  929. }
  930. if (k > 0 && pos < mxf->first_essence_length && accumulated_offset == 0)
  931. pos += mxf->first_essence_kl_length;
  932. pos += mxf->essence_offset;
  933. av_dlog(mxf->fc, "Stream %d IndexEntry %d n_Delta %d Offset %"PRIx64" Timestamp %"PRId64"\n",
  934. st->index, st->nb_index_entries, n_delta, pos, sample_duration * st->nb_index_entries);
  935. if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
  936. return ret;
  937. }
  938. accumulated_offset += segment_size;
  939. }
  940. av_free(sorted_segments);
  941. return 0;
  942. }
  943. static int mxf_parse_structural_metadata(MXFContext *mxf)
  944. {
  945. MXFPackage *material_package = NULL;
  946. MXFPackage *temp_package = NULL;
  947. int i, j, k, ret;
  948. av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
  949. /* TODO: handle multiple material packages (OP3x) */
  950. for (i = 0; i < mxf->packages_count; i++) {
  951. material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
  952. if (material_package) break;
  953. }
  954. if (!material_package) {
  955. av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
  956. return -1;
  957. }
  958. for (i = 0; i < material_package->tracks_count; i++) {
  959. MXFPackage *source_package = NULL;
  960. MXFTrack *material_track = NULL;
  961. MXFTrack *source_track = NULL;
  962. MXFTrack *temp_track = NULL;
  963. MXFDescriptor *descriptor = NULL;
  964. MXFStructuralComponent *component = NULL;
  965. UID *essence_container_ul = NULL;
  966. const MXFCodecUL *codec_ul = NULL;
  967. const MXFCodecUL *container_ul = NULL;
  968. AVStream *st;
  969. if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
  970. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
  971. continue;
  972. }
  973. if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
  974. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
  975. continue;
  976. }
  977. /* TODO: handle multiple source clips */
  978. for (j = 0; j < material_track->sequence->structural_components_count; j++) {
  979. /* TODO: handle timecode component */
  980. component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
  981. if (!component)
  982. continue;
  983. for (k = 0; k < mxf->packages_count; k++) {
  984. temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
  985. if (!temp_package)
  986. continue;
  987. if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
  988. source_package = temp_package;
  989. break;
  990. }
  991. }
  992. if (!source_package) {
  993. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id);
  994. break;
  995. }
  996. for (k = 0; k < source_package->tracks_count; k++) {
  997. if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
  998. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
  999. return -1;
  1000. }
  1001. if (temp_track->track_id == component->source_track_id) {
  1002. source_track = temp_track;
  1003. break;
  1004. }
  1005. }
  1006. if (!source_track) {
  1007. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
  1008. break;
  1009. }
  1010. }
  1011. if (!source_track)
  1012. continue;
  1013. st = avformat_new_stream(mxf->fc, NULL);
  1014. if (!st) {
  1015. av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
  1016. return -1;
  1017. }
  1018. st->id = source_track->track_id;
  1019. st->priv_data = source_track;
  1020. st->duration = component->duration;
  1021. if (st->duration == -1)
  1022. st->duration = AV_NOPTS_VALUE;
  1023. st->start_time = component->start_position;
  1024. av_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
  1025. if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
  1026. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
  1027. return -1;
  1028. }
  1029. PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
  1030. codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
  1031. st->codec->codec_type = codec_ul->id;
  1032. source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
  1033. if (source_package->descriptor) {
  1034. if (source_package->descriptor->type == MultipleDescriptor) {
  1035. for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
  1036. MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
  1037. if (!sub_descriptor) {
  1038. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
  1039. continue;
  1040. }
  1041. if (sub_descriptor->linked_track_id == source_track->track_id) {
  1042. descriptor = sub_descriptor;
  1043. break;
  1044. }
  1045. }
  1046. } else if (source_package->descriptor->type == Descriptor)
  1047. descriptor = source_package->descriptor;
  1048. }
  1049. if (!descriptor) {
  1050. av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
  1051. continue;
  1052. }
  1053. PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
  1054. PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
  1055. essence_container_ul = &descriptor->essence_container_ul;
  1056. /* HACK: replacing the original key with mxf_encrypted_essence_container
  1057. * is not allowed according to s429-6, try to find correct information anyway */
  1058. if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
  1059. av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
  1060. for (k = 0; k < mxf->metadata_sets_count; k++) {
  1061. MXFMetadataSet *metadata = mxf->metadata_sets[k];
  1062. if (metadata->type == CryptoContext) {
  1063. essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
  1069. codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
  1070. st->codec->codec_id = codec_ul->id;
  1071. if (descriptor->extradata) {
  1072. st->codec->extradata = descriptor->extradata;
  1073. st->codec->extradata_size = descriptor->extradata_size;
  1074. }
  1075. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1076. container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
  1077. if (st->codec->codec_id == CODEC_ID_NONE)
  1078. st->codec->codec_id = container_ul->id;
  1079. st->codec->width = descriptor->width;
  1080. st->codec->height = descriptor->height;
  1081. if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
  1082. st->codec->pix_fmt = descriptor->pix_fmt;
  1083. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1084. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  1085. container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
  1086. if (st->codec->codec_id == CODEC_ID_NONE)
  1087. st->codec->codec_id = container_ul->id;
  1088. st->codec->channels = descriptor->channels;
  1089. st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
  1090. st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
  1091. /* TODO: implement CODEC_ID_RAWAUDIO */
  1092. if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
  1093. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1094. st->codec->codec_id = CODEC_ID_PCM_S24LE;
  1095. else if (descriptor->bits_per_sample == 32)
  1096. st->codec->codec_id = CODEC_ID_PCM_S32LE;
  1097. } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
  1098. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1099. st->codec->codec_id = CODEC_ID_PCM_S24BE;
  1100. else if (descriptor->bits_per_sample == 32)
  1101. st->codec->codec_id = CODEC_ID_PCM_S32BE;
  1102. } else if (st->codec->codec_id == CODEC_ID_MP2) {
  1103. st->need_parsing = AVSTREAM_PARSE_FULL;
  1104. }
  1105. }
  1106. if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
  1107. av_log(mxf->fc, AV_LOG_WARNING, "only frame wrapped mappings are correctly supported\n");
  1108. st->need_parsing = AVSTREAM_PARSE_FULL;
  1109. }
  1110. if ((ret = mxf_parse_index(mxf, i, st)))
  1111. return ret;
  1112. }
  1113. return 0;
  1114. }
  1115. static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
  1116. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
  1117. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
  1118. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
  1119. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
  1120. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
  1121. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
  1122. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
  1123. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
  1124. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
  1125. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
  1126. { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
  1127. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
  1128. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
  1129. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
  1130. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
  1131. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
  1132. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
  1133. { { 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 */
  1134. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
  1135. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
  1136. { { 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 */
  1137. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
  1138. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
  1139. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
  1140. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
  1141. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
  1142. { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
  1143. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
  1144. };
  1145. static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
  1146. {
  1147. AVIOContext *pb = mxf->fc->pb;
  1148. MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
  1149. uint64_t klv_end = avio_tell(pb) + klv->length;
  1150. if (!ctx)
  1151. return -1;
  1152. while (avio_tell(pb) + 4 < klv_end) {
  1153. int tag = avio_rb16(pb);
  1154. int size = avio_rb16(pb); /* KLV specified by 0x53 */
  1155. uint64_t next = avio_tell(pb) + size;
  1156. UID uid = {0};
  1157. av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
  1158. if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
  1159. av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
  1160. continue;
  1161. }
  1162. if (tag > 0x7FFF) { /* dynamic tag */
  1163. int i;
  1164. for (i = 0; i < mxf->local_tags_count; i++) {
  1165. int local_tag = AV_RB16(mxf->local_tags+i*18);
  1166. if (local_tag == tag) {
  1167. memcpy(uid, mxf->local_tags+i*18+2, 16);
  1168. av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
  1169. PRINT_KEY(mxf->fc, "uid", uid);
  1170. }
  1171. }
  1172. }
  1173. if (ctx_size && tag == 0x3C0A)
  1174. avio_read(pb, ctx->uid, 16);
  1175. else if (read_child(ctx, pb, tag, size, uid) < 0)
  1176. return -1;
  1177. avio_seek(pb, next, SEEK_SET);
  1178. }
  1179. if (ctx_size) ctx->type = type;
  1180. return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
  1181. }
  1182. static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1183. {
  1184. MXFContext *mxf = s->priv_data;
  1185. KLVPacket klv;
  1186. if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
  1187. av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
  1188. return -1;
  1189. }
  1190. avio_seek(s->pb, -14, SEEK_CUR);
  1191. mxf->fc = s;
  1192. while (!url_feof(s->pb)) {
  1193. const MXFMetadataReadTableEntry *metadata;
  1194. if (klv_read_packet(&klv, s->pb) < 0)
  1195. return -1;
  1196. PRINT_KEY(s, "read header", klv.key);
  1197. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  1198. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
  1199. IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
  1200. /* FIXME avoid seek */
  1201. avio_seek(s->pb, klv.offset, SEEK_SET);
  1202. break;
  1203. }
  1204. if (IS_KLV_KEY(klv.key, mxf_system_item_key)) {
  1205. mxf->system_item = 1;
  1206. avio_skip(s->pb, klv.length);
  1207. continue;
  1208. }
  1209. for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
  1210. if (IS_KLV_KEY(klv.key, metadata->key)) {
  1211. int res;
  1212. if (klv.key[5] == 0x53) {
  1213. res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
  1214. } else {
  1215. uint64_t next = avio_tell(s->pb) + klv.length;
  1216. res = metadata->read(mxf, s->pb, 0, 0, klv.key);
  1217. avio_seek(s->pb, next, SEEK_SET);
  1218. }
  1219. if (res < 0) {
  1220. av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
  1221. return -1;
  1222. }
  1223. break;
  1224. }
  1225. }
  1226. if (!metadata->read)
  1227. avio_skip(s->pb, klv.length);
  1228. }
  1229. return mxf_parse_structural_metadata(mxf);
  1230. }
  1231. static int mxf_read_close(AVFormatContext *s)
  1232. {
  1233. MXFContext *mxf = s->priv_data;
  1234. MXFIndexTableSegment *seg;
  1235. int i, j;
  1236. av_freep(&mxf->packages_refs);
  1237. for (i = 0; i < s->nb_streams; i++)
  1238. s->streams[i]->priv_data = NULL;
  1239. for (i = 0; i < mxf->metadata_sets_count; i++) {
  1240. switch (mxf->metadata_sets[i]->type) {
  1241. case MultipleDescriptor:
  1242. av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
  1243. break;
  1244. case Sequence:
  1245. av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
  1246. break;
  1247. case SourcePackage:
  1248. case MaterialPackage:
  1249. av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
  1250. break;
  1251. case IndexTableSegment:
  1252. seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
  1253. for (j = 0; j < seg->nb_index_entries; j++)
  1254. av_freep(&seg->slice_offset_entries[j]);
  1255. av_freep(&seg->slice);
  1256. av_freep(&seg->element_delta);
  1257. av_freep(&seg->flag_entries);
  1258. av_freep(&seg->stream_offset_entries);
  1259. av_freep(&seg->slice_offset_entries);
  1260. break;
  1261. default:
  1262. break;
  1263. }
  1264. av_freep(&mxf->metadata_sets[i]);
  1265. }
  1266. av_freep(&mxf->partitions);
  1267. av_freep(&mxf->metadata_sets);
  1268. av_freep(&mxf->aesc);
  1269. av_freep(&mxf->local_tags);
  1270. return 0;
  1271. }
  1272. static int mxf_probe(AVProbeData *p) {
  1273. uint8_t *bufp = p->buf;
  1274. uint8_t *end = p->buf + p->buf_size;
  1275. if (p->buf_size < sizeof(mxf_header_partition_pack_key))
  1276. return 0;
  1277. /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
  1278. end -= sizeof(mxf_header_partition_pack_key);
  1279. for (; bufp < end; bufp++) {
  1280. if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
  1281. return AVPROBE_SCORE_MAX;
  1282. }
  1283. return 0;
  1284. }
  1285. /* rudimentary byte seek */
  1286. /* XXX: use MXF Index */
  1287. static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  1288. {
  1289. AVStream *st = s->streams[stream_index];
  1290. int64_t seconds;
  1291. if (!s->bit_rate)
  1292. return -1;
  1293. if (sample_time < 0)
  1294. sample_time = 0;
  1295. seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
  1296. if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
  1297. return -1;
  1298. ff_update_cur_dts(s, st, sample_time);
  1299. return 0;
  1300. }
  1301. AVInputFormat ff_mxf_demuxer = {
  1302. .name = "mxf",
  1303. .long_name = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
  1304. .priv_data_size = sizeof(MXFContext),
  1305. .read_probe = mxf_probe,
  1306. .read_header = mxf_read_header,
  1307. .read_packet = mxf_read_packet,
  1308. .read_close = mxf_read_close,
  1309. .read_seek = mxf_read_seek,
  1310. };