Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * MXF muxer
  3.  * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
  4.  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  5.  *
  6.  * This file is part of FFmpeg.
  7.  *
  8.  * FFmpeg is free software; you can redistribute it and/or
  9.  * modify it under the terms of the GNU Lesser General Public
  10.  * License as published by the Free Software Foundation; either
  11.  * version 2.1 of the License, or (at your option) any later version.
  12.  *
  13.  * FFmpeg is distributed in the hope that it will be useful,
  14.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16.  * Lesser General Public License for more details.
  17.  *
  18.  * You should have received a copy of the GNU Lesser General Public
  19.  * License along with FFmpeg; if not, write to the Free Software
  20.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21.  *
  22.  * signal_standard, color_siting, store_user_comments and klv_fill_key version
  23.  * fixes sponsored by NOA GmbH
  24.  */
  25.  
  26. /*
  27.  * References
  28.  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
  29.  * SMPTE 377M MXF File Format Specifications
  30.  * SMPTE 379M MXF Generic Container
  31.  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
  32.  * SMPTE 422M Mapping JPEG 2000 Codestreams into the MXF Generic Container
  33.  * SMPTE RP210: SMPTE Metadata Dictionary
  34.  * SMPTE RP224: Registry of SMPTE Universal Labels
  35.  */
  36.  
  37. #include <inttypes.h>
  38. #include <math.h>
  39. #include <time.h>
  40.  
  41. #include "libavutil/opt.h"
  42. #include "libavutil/random_seed.h"
  43. #include "libavutil/timecode.h"
  44. #include "libavutil/avassert.h"
  45. #include "libavutil/pixdesc.h"
  46. #include "libavutil/time_internal.h"
  47. #include "libavcodec/bytestream.h"
  48. #include "libavcodec/dnxhddata.h"
  49. #include "libavcodec/h264.h"
  50. #include "libavcodec/internal.h"
  51. #include "audiointerleave.h"
  52. #include "avformat.h"
  53. #include "avio_internal.h"
  54. #include "internal.h"
  55. #include "mxf.h"
  56. #include "config.h"
  57.  
  58. extern AVOutputFormat ff_mxf_d10_muxer;
  59. extern AVOutputFormat ff_mxf_opatom_muxer;
  60.  
  61. #define EDIT_UNITS_PER_BODY 250
  62. #define KAG_SIZE 512
  63.  
  64. typedef struct MXFLocalTagPair {
  65.     int local_tag;
  66.     UID uid;
  67. } MXFLocalTagPair;
  68.  
  69. typedef struct MXFIndexEntry {
  70.     uint8_t flags;
  71.     uint64_t offset;
  72.     unsigned slice_offset; ///< offset of audio slice
  73.     uint16_t temporal_ref;
  74. } MXFIndexEntry;
  75.  
  76. typedef struct MXFStreamContext {
  77.     AudioInterleaveContext aic;
  78.     UID track_essence_element_key;
  79.     int index;               ///< index in mxf_essence_container_uls table
  80.     const UID *codec_ul;
  81.     int order;               ///< interleaving order if dts are equal
  82.     int interlaced;          ///< whether picture is interlaced
  83.     int field_dominance;     ///< tff=1, bff=2
  84.     int component_depth;
  85.     int color_siting;
  86.     int signal_standard;
  87.     int h_chroma_sub_sample;
  88.     int temporal_reordering;
  89.     AVRational aspect_ratio; ///< display aspect ratio
  90.     int closed_gop;          ///< gop is closed, used in mpeg-2 frame parsing
  91.     int video_bit_rate;
  92. } MXFStreamContext;
  93.  
  94. typedef struct MXFContainerEssenceEntry {
  95.     UID container_ul;
  96.     UID element_ul;
  97.     UID codec_ul;
  98.     void (*write_desc)(AVFormatContext *, AVStream *);
  99. } MXFContainerEssenceEntry;
  100.  
  101. static const struct {
  102.     enum AVCodecID id;
  103.     int index;
  104. } mxf_essence_mappings[] = {
  105.     { AV_CODEC_ID_MPEG2VIDEO, 0 },
  106.     { AV_CODEC_ID_PCM_S24LE,  1 },
  107.     { AV_CODEC_ID_PCM_S16LE,  1 },
  108.     { AV_CODEC_ID_DVVIDEO,   15 },
  109.     { AV_CODEC_ID_DNXHD,     24 },
  110.     { AV_CODEC_ID_JPEG2000,  34 },
  111.     { AV_CODEC_ID_H264,      35 },
  112.     { AV_CODEC_ID_NONE }
  113. };
  114.  
  115. static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
  116. static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
  117. static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
  118. static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st);
  119. static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st);
  120.  
  121. static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
  122.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
  123.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  124.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
  125.       mxf_write_mpegvideo_desc },
  126.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
  127.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
  128.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  129.       mxf_write_aes3_desc },
  130.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
  131.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
  132.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  133.       mxf_write_wav_desc },
  134.     // D-10 625/50 PAL 50mb/s
  135.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
  136.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
  137.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 },
  138.       mxf_write_cdci_desc },
  139.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
  140.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
  141.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  142.       mxf_write_generic_sound_desc },
  143.     // D-10 525/60 NTSC 50mb/s
  144.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 },
  145.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
  146.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x02 },
  147.       mxf_write_cdci_desc },
  148.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 },
  149.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
  150.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  151.       mxf_write_generic_sound_desc },
  152.     // D-10 625/50 PAL 40mb/s
  153.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 },
  154.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
  155.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x03 },
  156.       mxf_write_cdci_desc },
  157.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 },
  158.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
  159.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  160.       mxf_write_generic_sound_desc },
  161.     // D-10 525/60 NTSC 40mb/s
  162.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 },
  163.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
  164.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x04 },
  165.       mxf_write_cdci_desc },
  166.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 },
  167.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
  168.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  169.       mxf_write_generic_sound_desc },
  170.     // D-10 625/50 PAL 30mb/s
  171.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 },
  172.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
  173.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 },
  174.       mxf_write_cdci_desc },
  175.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 },
  176.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
  177.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  178.       mxf_write_generic_sound_desc },
  179.     // D-10 525/60 NTSC 30mb/s
  180.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 },
  181.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
  182.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x06 },
  183.       mxf_write_cdci_desc },
  184.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 },
  185.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
  186.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
  187.       mxf_write_generic_sound_desc },
  188.     // DV Unknown
  189.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x7F,0x01 },
  190.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  191.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x00,0x00,0x00 },
  192.       mxf_write_cdci_desc },
  193.     // DV25 525/60
  194.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x40,0x01 },
  195.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  196.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x01,0x00 },
  197.       mxf_write_cdci_desc },
  198.     // DV25 625/50
  199.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 },
  200.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  201.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x02,0x00 },
  202.       mxf_write_cdci_desc },
  203.     // DV50 525/60
  204.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x50,0x01 },
  205.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  206.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x03,0x00 },
  207.       mxf_write_cdci_desc },
  208.     // DV50 625/50
  209.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x51,0x01 },
  210.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  211.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x04,0x00 },
  212.       mxf_write_cdci_desc },
  213.     // DV100 1080/60
  214.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x60,0x01 },
  215.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  216.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x05,0x00 },
  217.       mxf_write_cdci_desc },
  218.     // DV100 1080/50
  219.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x61,0x01 },
  220.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  221.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x06,0x00 },
  222.       mxf_write_cdci_desc },
  223.     // DV100 720/60
  224.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x62,0x01 },
  225.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  226.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x07,0x00 },
  227.       mxf_write_cdci_desc },
  228.     // DV100 720/50
  229.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x63,0x01 },
  230.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
  231.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x08,0x00 },
  232.       mxf_write_cdci_desc },
  233.     // DNxHD 1080p 10bit high
  234.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  235.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  236.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 },
  237.       mxf_write_cdci_desc },
  238.     // DNxHD 1080p 8bit medium
  239.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  240.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  241.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x03,0x00,0x00 },
  242.       mxf_write_cdci_desc },
  243.     // DNxHD 1080p 8bit high
  244.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  245.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  246.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x04,0x00,0x00 },
  247.       mxf_write_cdci_desc },
  248.     // DNxHD 1080i 10bit high
  249.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  250.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  251.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x07,0x00,0x00 },
  252.       mxf_write_cdci_desc },
  253.     // DNxHD 1080i 8bit medium
  254.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  255.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  256.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x08,0x00,0x00 },
  257.       mxf_write_cdci_desc },
  258.     // DNxHD 1080i 8bit high
  259.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  260.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  261.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x09,0x00,0x00 },
  262.       mxf_write_cdci_desc },
  263.     // DNxHD 720p 10bit
  264.     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  265.       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  266.       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x10,0x00,0x00 },
  267.       mxf_write_cdci_desc },
  268.     // DNxHD 720p 8bit high
  269.     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  270.       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  271.       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x11,0x00,0x00 },
  272.       mxf_write_cdci_desc },
  273.     // DNxHD 720p 8bit medium
  274.     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  275.       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  276.       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x12,0x00,0x00 },
  277.       mxf_write_cdci_desc },
  278.     // DNxHD 720p 8bit low
  279.     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
  280.       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  281.       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x13,0x00,0x00 },
  282.       mxf_write_cdci_desc },
  283.     // JPEG2000
  284.     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 },
  285.       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x08,0x00 },
  286.       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 },
  287.       mxf_write_cdci_desc },
  288.     // H.264
  289.     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x10,0x60,0x01 },
  290.       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
  291.       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
  292.       mxf_write_mpegvideo_desc },
  293.     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
  294.       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
  295.       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
  296.       NULL },
  297. };
  298.  
  299. typedef struct MXFContext {
  300.     AVClass *av_class;
  301.     int64_t footer_partition_offset;
  302.     int essence_container_count;
  303.     AVRational time_base;
  304.     int header_written;
  305.     MXFIndexEntry *index_entries;
  306.     unsigned edit_units_count;
  307.     uint64_t timestamp;   ///< timestamp, as year(16),month(8),day(8),hour(8),minutes(8),msec/4(8)
  308.     uint8_t slice_count;  ///< index slice count minus 1 (1 if no audio, 0 otherwise)
  309.     int last_indexed_edit_unit;
  310.     uint64_t *body_partition_offset;
  311.     unsigned body_partitions_count;
  312.     int last_key_index;  ///< index of last key frame
  313.     uint64_t duration;
  314.     AVTimecode tc;       ///< timecode context
  315.     AVStream *timecode_track;
  316.     int timecode_base;       ///< rounded time code base (25 or 30)
  317.     int edit_unit_byte_count; ///< fixed edit unit byte count
  318.     uint64_t body_offset;
  319.     uint32_t instance_number;
  320.     uint8_t umid[16];        ///< unique material identifier
  321.     int channel_count;
  322.     int signal_standard;
  323.     uint32_t tagged_value_count;
  324.     AVRational audio_edit_rate;
  325.     int store_user_comments;
  326. } MXFContext;
  327.  
  328. static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
  329. static const uint8_t umid_ul[]              = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13 };
  330.  
  331. /**
  332.  * complete key for operation pattern, partitions, and primer pack
  333.  */
  334. static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x09,0x00 };
  335. static const uint8_t opatom_ul[]                   = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x02,0x01,0x10,0x03,0x00,0x00 };
  336. static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
  337. static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
  338. static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
  339. static const uint8_t random_index_pack_key[]       = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
  340. static const uint8_t header_open_partition_key[]   = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }; // OpenIncomplete
  341. static const uint8_t header_closed_partition_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }; // ClosedComplete
  342. static const uint8_t klv_fill_key[]                = { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x10,0x01,0x00,0x00,0x00 };
  343. static const uint8_t body_partition_key[]          = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }; // ClosedComplete
  344.  
  345. /**
  346.  * partial key for header metadata
  347.  */
  348. static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
  349. static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
  350.  
  351. /**
  352.  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
  353.  */
  354. static const MXFLocalTagPair mxf_local_tag_batch[] = {
  355.     // preface set
  356.     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
  357.     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
  358.     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
  359.     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
  360.     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
  361.     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
  362.     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
  363.     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
  364.     // Identification
  365.     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
  366.     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
  367.     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
  368.     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
  369.     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
  370.     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
  371.     // Content Storage
  372.     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
  373.     { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
  374.     // Essence Container Data
  375.     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
  376.     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
  377.     // Package
  378.     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
  379.     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
  380.     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
  381.     { 0x4402, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x03,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Package Name */
  382.     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
  383.     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
  384.     // Track
  385.     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
  386.     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
  387.     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
  388.     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
  389.     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
  390.     // Sequence
  391.     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
  392.     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
  393.     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
  394.     // Source Clip
  395.     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
  396.     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
  397.     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
  398.     // Timecode Component
  399.     { 0x1501, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x05,0x00,0x00}}, /* Start Time Code */
  400.     { 0x1502, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x04,0x01,0x01,0x02,0x06,0x00,0x00}}, /* Rounded Time Code Base */
  401.     { 0x1503, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x04,0x01,0x01,0x05,0x00,0x00,0x00}}, /* Drop Frame */
  402.     // File Descriptor
  403.     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
  404.     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
  405.     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
  406.     { 0x3002, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x02,0x00,0x00,0x00,0x00}}, /* ContainerDuration */
  407.     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
  408.     // Generic Picture Essence Descriptor
  409.     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
  410.     { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
  411.     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
  412.     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
  413.     { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
  414.     { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
  415.     { 0x320B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0E,0x00,0x00,0x00}}, /* Presentation Y offset */
  416.     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
  417.     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
  418.     { 0x3212, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x01,0x06,0x00,0x00,0x00}}, /* Field Dominance (Opt) */
  419.     { 0x3215, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x05,0x01,0x13,0x00,0x00,0x00,0x00}}, /* Signal Standard */
  420.     // CDCI Picture Essence Descriptor
  421.     { 0x3301, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x0A,0x00,0x00,0x00}}, /* Component Depth */
  422.     { 0x3302, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x05,0x00,0x00,0x00}}, /* Horizontal Subsampling */
  423.     { 0x3303, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x06,0x00,0x00,0x00}}, /* Color Siting */
  424.     // Generic Sound Essence Descriptor
  425.     { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
  426.     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
  427.     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
  428.     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
  429.     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
  430.     // Index Table Segment
  431.     { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
  432.     { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
  433.     { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
  434.     { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
  435.     { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
  436.     { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
  437.     { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
  438.     { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
  439.     // MPEG video Descriptor
  440.     { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
  441.     { 0x8007, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0A,0x00,0x00}}, /* ProfileAndLevel */
  442.     // Wave Audio Essence Descriptor
  443.     { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
  444.     { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
  445. };
  446.  
  447. static const MXFLocalTagPair mxf_user_comments_local_tag[] = {
  448.     { 0x4406, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0C,0x00,0x00,0x00}}, /* User Comments */
  449.     { 0x5001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x09,0x01,0x00,0x00}}, /* Name */
  450.     { 0x5003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0A,0x01,0x00,0x00}}, /* Value */
  451. };
  452.  
  453. static void mxf_write_uuid(AVIOContext *pb, enum MXFMetadataSetType type, int value)
  454. {
  455.     avio_write(pb, uuid_base, 12);
  456.     avio_wb16(pb, type);
  457.     avio_wb16(pb, value);
  458. }
  459.  
  460. static void mxf_write_umid(AVFormatContext *s, int type)
  461. {
  462.     MXFContext *mxf = s->priv_data;
  463.     avio_write(s->pb, umid_ul, 13);
  464.     avio_wb24(s->pb, mxf->instance_number);
  465.     avio_write(s->pb, mxf->umid, 15);
  466.     avio_w8(s->pb, type);
  467. }
  468.  
  469. static void mxf_write_refs_count(AVIOContext *pb, int ref_count)
  470. {
  471.     avio_wb32(pb, ref_count);
  472.     avio_wb32(pb, 16);
  473. }
  474.  
  475. static int klv_ber_length(uint64_t len)
  476. {
  477.     if (len < 128)
  478.         return 1;
  479.     else
  480.         return (av_log2(len) >> 3) + 2;
  481. }
  482.  
  483. static int klv_encode_ber_length(AVIOContext *pb, uint64_t len)
  484. {
  485.     // Determine the best BER size
  486.     int size;
  487.     if (len < 128) {
  488.         //short form
  489.         avio_w8(pb, len);
  490.         return 1;
  491.     }
  492.  
  493.     size = (av_log2(len) >> 3) + 1;
  494.  
  495.     // long form
  496.     avio_w8(pb, 0x80 + size);
  497.     while(size) {
  498.         size--;
  499.         avio_w8(pb, len >> 8 * size & 0xff);
  500.     }
  501.     return 0;
  502. }
  503.  
  504. static void klv_encode_ber4_length(AVIOContext *pb, int len)
  505. {
  506.     avio_w8(pb, 0x80 + 3);
  507.     avio_wb24(pb, len);
  508. }
  509.  
  510. static void klv_encode_ber9_length(AVIOContext *pb, uint64_t len)
  511. {
  512.     avio_w8(pb, 0x80 + 8);
  513.     avio_wb64(pb, len);
  514. }
  515.  
  516. /*
  517.  * Get essence container ul index
  518.  */
  519. static int mxf_get_essence_container_ul_index(enum AVCodecID id)
  520. {
  521.     int i;
  522.     for (i = 0; mxf_essence_mappings[i].id; i++)
  523.         if (mxf_essence_mappings[i].id == id)
  524.             return mxf_essence_mappings[i].index;
  525.     return -1;
  526. }
  527.  
  528. static void mxf_write_primer_pack(AVFormatContext *s)
  529. {
  530.     MXFContext *mxf = s->priv_data;
  531.     AVIOContext *pb = s->pb;
  532.     int local_tag_number, i = 0;
  533.  
  534.     local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
  535.     local_tag_number += mxf->store_user_comments * FF_ARRAY_ELEMS(mxf_user_comments_local_tag);
  536.  
  537.     avio_write(pb, primer_pack_key, 16);
  538.     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
  539.  
  540.     avio_wb32(pb, local_tag_number); // local_tag num
  541.     avio_wb32(pb, 18); // item size, always 18 according to the specs
  542.  
  543.     for (i = 0; i < FF_ARRAY_ELEMS(mxf_local_tag_batch); i++) {
  544.         avio_wb16(pb, mxf_local_tag_batch[i].local_tag);
  545.         avio_write(pb, mxf_local_tag_batch[i].uid, 16);
  546.     }
  547.     if (mxf->store_user_comments)
  548.         for (i = 0; i < FF_ARRAY_ELEMS(mxf_user_comments_local_tag); i++) {
  549.             avio_wb16(pb, mxf_user_comments_local_tag[i].local_tag);
  550.             avio_write(pb, mxf_user_comments_local_tag[i].uid, 16);
  551.         }
  552. }
  553.  
  554. static void mxf_write_local_tag(AVIOContext *pb, int size, int tag)
  555. {
  556.     avio_wb16(pb, tag);
  557.     avio_wb16(pb, size);
  558. }
  559.  
  560. static void mxf_write_metadata_key(AVIOContext *pb, unsigned int value)
  561. {
  562.     avio_write(pb, header_metadata_key, 13);
  563.     avio_wb24(pb, value);
  564. }
  565.  
  566. static void mxf_free(AVFormatContext *s)
  567. {
  568.     int i;
  569.  
  570.     for (i = 0; i < s->nb_streams; i++) {
  571.         AVStream *st = s->streams[i];
  572.         av_freep(&st->priv_data);
  573.     }
  574. }
  575.  
  576. static const MXFCodecUL *mxf_get_data_definition_ul(int type)
  577. {
  578.     const MXFCodecUL *uls = ff_mxf_data_definition_uls;
  579.     while (uls->uid[0]) {
  580.         if (type == uls->id)
  581.             break;
  582.         uls++;
  583.     }
  584.     return uls;
  585. }
  586.  
  587. //one EC -> one descriptor. N ECs -> MultipleDescriptor + N descriptors
  588. #define DESCRIPTOR_COUNT(essence_container_count) \
  589.     (essence_container_count > 1 ? essence_container_count + 1 : essence_container_count)
  590.  
  591. static void mxf_write_essence_container_refs(AVFormatContext *s)
  592. {
  593.     MXFContext *c = s->priv_data;
  594.     AVIOContext *pb = s->pb;
  595.     int i;
  596.  
  597.     mxf_write_refs_count(pb, DESCRIPTOR_COUNT(c->essence_container_count));
  598.     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
  599.     for (i = 0; i < c->essence_container_count; i++) {
  600.         MXFStreamContext *sc = s->streams[i]->priv_data;
  601.         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
  602.     }
  603.  
  604.     if (c->essence_container_count > 1)
  605.         avio_write(pb, multiple_desc_ul, 16);
  606. }
  607.  
  608. static void mxf_write_preface(AVFormatContext *s)
  609. {
  610.     MXFContext *mxf = s->priv_data;
  611.     AVIOContext *pb = s->pb;
  612.  
  613.     mxf_write_metadata_key(pb, 0x012f00);
  614.     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
  615.     klv_encode_ber_length(pb, 130 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
  616.  
  617.     // write preface set uid
  618.     mxf_write_local_tag(pb, 16, 0x3C0A);
  619.     mxf_write_uuid(pb, Preface, 0);
  620.     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
  621.  
  622.     // last modified date
  623.     mxf_write_local_tag(pb, 8, 0x3B02);
  624.     avio_wb64(pb, mxf->timestamp);
  625.  
  626.     // write version
  627.     mxf_write_local_tag(pb, 2, 0x3B05);
  628.     avio_wb16(pb, 258); // v1.2
  629.  
  630.     // write identification_refs
  631.     mxf_write_local_tag(pb, 16 + 8, 0x3B06);
  632.     mxf_write_refs_count(pb, 1);
  633.     mxf_write_uuid(pb, Identification, 0);
  634.  
  635.     // write content_storage_refs
  636.     mxf_write_local_tag(pb, 16, 0x3B03);
  637.     mxf_write_uuid(pb, ContentStorage, 0);
  638.  
  639.     // operational pattern
  640.     mxf_write_local_tag(pb, 16, 0x3B09);
  641.     if (s->oformat == &ff_mxf_opatom_muxer)
  642.         avio_write(pb, opatom_ul, 16);
  643.     else
  644.         avio_write(pb, op1a_ul, 16);
  645.  
  646.     // write essence_container_refs
  647.     mxf_write_local_tag(pb, 8 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count), 0x3B0A);
  648.     mxf_write_essence_container_refs(s);
  649.  
  650.     // write dm_scheme_refs
  651.     mxf_write_local_tag(pb, 8, 0x3B0B);
  652.     avio_wb64(pb, 0);
  653. }
  654.  
  655. /*
  656.  * Returns the length of the UTF-16 string, in 16-bit characters, that would result
  657.  * from decoding the utf-8 string.
  658.  */
  659. static uint64_t mxf_utf16len(const char *utf8_str)
  660. {
  661.     const uint8_t *q = utf8_str;
  662.     uint64_t size = 0;
  663.     while (*q) {
  664.         uint32_t ch;
  665.         GET_UTF8(ch, *q++, goto invalid;)
  666.         if (ch < 0x10000)
  667.             size++;
  668.         else
  669.             size += 2;
  670.         continue;
  671. invalid:
  672.         av_log(NULL, AV_LOG_ERROR, "Invaid UTF8 sequence in mxf_utf16len\n\n");
  673.     }
  674.     size += 1;
  675.     return size;
  676. }
  677.  
  678. /*
  679.  * Returns the calculated length a local tag containing an utf-8 string as utf-16
  680.  */
  681. static int mxf_utf16_local_tag_length(const char *utf8_str)
  682. {
  683.     uint64_t size;
  684.  
  685.     if (!utf8_str)
  686.         return 0;
  687.  
  688.     size = mxf_utf16len(utf8_str);
  689.     if (size >= UINT16_MAX/2) {
  690.         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
  691.         return 0;
  692.     }
  693.  
  694.     return 4 + size * 2;
  695. }
  696.  
  697. /*
  698.  * Write a local tag containing an utf-8 string as utf-16
  699.  */
  700. static void mxf_write_local_tag_utf16(AVIOContext *pb, int tag, const char *value)
  701. {
  702.     uint64_t size = mxf_utf16len(value);
  703.  
  704.     if (size >= UINT16_MAX/2) {
  705.         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
  706.         return;
  707.     }
  708.  
  709.     mxf_write_local_tag(pb, size*2, tag);
  710.     avio_put_str16be(pb, value);
  711. }
  712.  
  713. static void mxf_write_identification(AVFormatContext *s)
  714. {
  715.     MXFContext *mxf = s->priv_data;
  716.     AVIOContext *pb = s->pb;
  717.     const char *company = "FFmpeg";
  718.     const char *product = s->oformat != &ff_mxf_opatom_muxer ? "OP1a Muxer" : "OPAtom Muxer";
  719.     const char *version;
  720.     int length;
  721.  
  722.     mxf_write_metadata_key(pb, 0x013000);
  723.     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
  724.  
  725.     version = s->flags & AVFMT_FLAG_BITEXACT ?
  726.         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
  727.     length = 72 + mxf_utf16_local_tag_length(company) +
  728.                   mxf_utf16_local_tag_length(product) +
  729.                   mxf_utf16_local_tag_length(version);
  730.     klv_encode_ber_length(pb, length);
  731.  
  732.     // write uid
  733.     mxf_write_local_tag(pb, 16, 0x3C0A);
  734.     mxf_write_uuid(pb, Identification, 0);
  735.     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
  736.  
  737.     // write generation uid
  738.     mxf_write_local_tag(pb, 16, 0x3C09);
  739.     mxf_write_uuid(pb, Identification, 1);
  740.     mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
  741.     mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
  742.     mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
  743.  
  744.     // write product uid
  745.     mxf_write_local_tag(pb, 16, 0x3C05);
  746.     mxf_write_uuid(pb, Identification, 2);
  747.  
  748.     // modification date
  749.     mxf_write_local_tag(pb, 8, 0x3C06);
  750.     avio_wb64(pb, mxf->timestamp);
  751. }
  752.  
  753. static void mxf_write_content_storage(AVFormatContext *s)
  754. {
  755.     AVIOContext *pb = s->pb;
  756.  
  757.     mxf_write_metadata_key(pb, 0x011800);
  758.     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
  759.     klv_encode_ber_length(pb, 92);
  760.  
  761.     // write uid
  762.     mxf_write_local_tag(pb, 16, 0x3C0A);
  763.     mxf_write_uuid(pb, ContentStorage, 0);
  764.     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
  765.  
  766.     // write package reference
  767.     mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
  768.     mxf_write_refs_count(pb, 2);
  769.     mxf_write_uuid(pb, MaterialPackage, 0);
  770.     mxf_write_uuid(pb, SourcePackage, 0);
  771.  
  772.     // write essence container data
  773.     mxf_write_local_tag(pb, 8 + 16, 0x1902);
  774.     mxf_write_refs_count(pb, 1);
  775.     mxf_write_uuid(pb, EssenceContainerData, 0);
  776. }
  777.  
  778. static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
  779. {
  780.     MXFContext *mxf = s->priv_data;
  781.     AVIOContext *pb = s->pb;
  782.     MXFStreamContext *sc = st->priv_data;
  783.  
  784.     mxf_write_metadata_key(pb, 0x013b00);
  785.     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
  786.     klv_encode_ber_length(pb, 80);
  787.  
  788.     // write track uid
  789.     mxf_write_local_tag(pb, 16, 0x3C0A);
  790.     mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
  791.     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
  792.  
  793.     // write track id
  794.     mxf_write_local_tag(pb, 4, 0x4801);
  795.     avio_wb32(pb, st->index+2);
  796.  
  797.     // write track number
  798.     mxf_write_local_tag(pb, 4, 0x4804);
  799.     if (type == MaterialPackage)
  800.         avio_wb32(pb, 0); // track number of material package is 0
  801.     else
  802.         avio_write(pb, sc->track_essence_element_key + 12, 4);
  803.  
  804.     mxf_write_local_tag(pb, 8, 0x4B01);
  805.  
  806.     if (st == mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer){
  807.         avio_wb32(pb, mxf->tc.rate.num);
  808.         avio_wb32(pb, mxf->tc.rate.den);
  809.     } else {
  810.         avio_wb32(pb, mxf->time_base.den);
  811.         avio_wb32(pb, mxf->time_base.num);
  812.     }
  813.  
  814.     // write origin
  815.     mxf_write_local_tag(pb, 8, 0x4B02);
  816.     avio_wb64(pb, 0);
  817.  
  818.     // write sequence refs
  819.     mxf_write_local_tag(pb, 16, 0x4803);
  820.     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
  821. }
  822.  
  823. static const uint8_t smpte_12m_timecode_track_data_ul[] = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x01,0x01,0x00,0x00,0x00 };
  824.  
  825. static void mxf_write_common_fields(AVFormatContext *s, AVStream *st)
  826. {
  827.     MXFContext *mxf = s->priv_data;
  828.     AVIOContext *pb = s->pb;
  829.  
  830.     // find data define uls
  831.     mxf_write_local_tag(pb, 16, 0x0201);
  832.     if (st == mxf->timecode_track)
  833.         avio_write(pb, smpte_12m_timecode_track_data_ul, 16);
  834.     else {
  835.         const MXFCodecUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
  836.         avio_write(pb, data_def_ul->uid, 16);
  837.     }
  838.  
  839.     // write duration
  840.     mxf_write_local_tag(pb, 8, 0x0202);
  841.  
  842.     if (st != mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer && st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
  843.         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
  844.     } else {
  845.         avio_wb64(pb, mxf->duration);
  846.     }
  847. }
  848.  
  849. static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
  850. {
  851.     MXFContext *mxf = s->priv_data;
  852.     AVIOContext *pb = s->pb;
  853.     enum MXFMetadataSetType component;
  854.  
  855.     mxf_write_metadata_key(pb, 0x010f00);
  856.     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
  857.     klv_encode_ber_length(pb, 80);
  858.  
  859.     mxf_write_local_tag(pb, 16, 0x3C0A);
  860.     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
  861.  
  862.     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
  863.     mxf_write_common_fields(s, st);
  864.  
  865.     // write structural component
  866.     mxf_write_local_tag(pb, 16 + 8, 0x1001);
  867.     mxf_write_refs_count(pb, 1);
  868.     if (st == mxf->timecode_track)
  869.         component = TimecodeComponent;
  870.     else
  871.         component = SourceClip;
  872.     if (type == SourcePackage)
  873.         component += TypeBottom;
  874.     mxf_write_uuid(pb, component, st->index);
  875. }
  876.  
  877. static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
  878. {
  879.     MXFContext *mxf = s->priv_data;
  880.     AVIOContext *pb = s->pb;
  881.  
  882.     mxf_write_metadata_key(pb, 0x011400);
  883.     klv_encode_ber_length(pb, 75);
  884.  
  885.     // UID
  886.     mxf_write_local_tag(pb, 16, 0x3C0A);
  887.     mxf_write_uuid(pb, type == MaterialPackage ? TimecodeComponent :
  888.                    TimecodeComponent + TypeBottom, st->index);
  889.  
  890.     mxf_write_common_fields(s, st);
  891.  
  892.     // Start Time Code
  893.     mxf_write_local_tag(pb, 8, 0x1501);
  894.     avio_wb64(pb, mxf->tc.start);
  895.  
  896.     // Rounded Time Code Base
  897.     mxf_write_local_tag(pb, 2, 0x1502);
  898.     avio_wb16(pb, mxf->timecode_base);
  899.  
  900.     // Drop Frame
  901.     mxf_write_local_tag(pb, 1, 0x1503);
  902.     avio_w8(pb, !!(mxf->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
  903. }
  904.  
  905. static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
  906. {
  907.     AVIOContext *pb = s->pb;
  908.     int i;
  909.  
  910.     mxf_write_metadata_key(pb, 0x011100);
  911.     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
  912.     klv_encode_ber_length(pb, 108);
  913.  
  914.     // write uid
  915.     mxf_write_local_tag(pb, 16, 0x3C0A);
  916.     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
  917.  
  918.     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
  919.     mxf_write_common_fields(s, st);
  920.  
  921.     // write start_position
  922.     mxf_write_local_tag(pb, 8, 0x1201);
  923.     avio_wb64(pb, 0);
  924.  
  925.     // write source package uid, end of the reference
  926.     mxf_write_local_tag(pb, 32, 0x1101);
  927.     if (type == SourcePackage) {
  928.         for (i = 0; i < 4; i++)
  929.             avio_wb64(pb, 0);
  930.     } else
  931.         mxf_write_umid(s, 1);
  932.  
  933.     // write source track id
  934.     mxf_write_local_tag(pb, 4, 0x1102);
  935.     if (type == SourcePackage)
  936.         avio_wb32(pb, 0);
  937.     else
  938.         avio_wb32(pb, st->index+2);
  939. }
  940.  
  941. static void mxf_write_multi_descriptor(AVFormatContext *s)
  942. {
  943.     MXFContext *mxf = s->priv_data;
  944.     AVIOContext *pb = s->pb;
  945.     const uint8_t *ul;
  946.     int i;
  947.  
  948.     mxf_write_metadata_key(pb, 0x014400);
  949.     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
  950.     klv_encode_ber_length(pb, 64 + 16LL * s->nb_streams);
  951.  
  952.     mxf_write_local_tag(pb, 16, 0x3C0A);
  953.     mxf_write_uuid(pb, MultipleDescriptor, 0);
  954.     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
  955.  
  956.     // write sample rate
  957.     mxf_write_local_tag(pb, 8, 0x3001);
  958.     avio_wb32(pb, mxf->time_base.den);
  959.     avio_wb32(pb, mxf->time_base.num);
  960.  
  961.     // write essence container ul
  962.     mxf_write_local_tag(pb, 16, 0x3004);
  963.     if (mxf->essence_container_count > 1)
  964.         ul = multiple_desc_ul;
  965.     else {
  966.         MXFStreamContext *sc = s->streams[0]->priv_data;
  967.         ul = mxf_essence_container_uls[sc->index].container_ul;
  968.     }
  969.     avio_write(pb, ul, 16);
  970.  
  971.     // write sub descriptor refs
  972.     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
  973.     mxf_write_refs_count(pb, s->nb_streams);
  974.     for (i = 0; i < s->nb_streams; i++)
  975.         mxf_write_uuid(pb, SubDescriptor, i);
  976. }
  977.  
  978. static void mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
  979. {
  980.     MXFContext *mxf = s->priv_data;
  981.     MXFStreamContext *sc = st->priv_data;
  982.     AVIOContext *pb = s->pb;
  983.  
  984.     avio_write(pb, key, 16);
  985.     klv_encode_ber4_length(pb, size+20+8+12+20);
  986.  
  987.     mxf_write_local_tag(pb, 16, 0x3C0A);
  988.     mxf_write_uuid(pb, SubDescriptor, st->index);
  989.  
  990.     mxf_write_local_tag(pb, 4, 0x3006);
  991.     avio_wb32(pb, st->index+2);
  992.  
  993.     mxf_write_local_tag(pb, 8, 0x3001);
  994.     avio_wb32(pb, mxf->time_base.den);
  995.     avio_wb32(pb, mxf->time_base.num);
  996.  
  997.     mxf_write_local_tag(pb, 16, 0x3004);
  998.     avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
  999. }
  1000.  
  1001. static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
  1002. static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
  1003. static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
  1004. static const UID mxf_cdci_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x28,0x00 };
  1005. static const UID mxf_generic_sound_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x42,0x00 };
  1006.  
  1007. static void mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
  1008. {
  1009.     MXFStreamContext *sc = st->priv_data;
  1010.     AVIOContext *pb = s->pb;
  1011.     int stored_height = (st->codec->height+15)/16*16;
  1012.     int display_height;
  1013.     int f1, f2;
  1014.     unsigned desc_size = size+8+8+8+8+8+8+8+5+16+sc->interlaced*4+12+20+5;
  1015.     if (sc->interlaced && sc->field_dominance)
  1016.         desc_size += 5;
  1017.     if (sc->signal_standard)
  1018.         desc_size += 5;
  1019.  
  1020.     mxf_write_generic_desc(s, st, key, desc_size);
  1021.  
  1022.     mxf_write_local_tag(pb, 4, 0x3203);
  1023.     avio_wb32(pb, st->codec->width);
  1024.  
  1025.     mxf_write_local_tag(pb, 4, 0x3202);
  1026.     avio_wb32(pb, stored_height>>sc->interlaced);
  1027.  
  1028.     mxf_write_local_tag(pb, 4, 0x3209);
  1029.     avio_wb32(pb, st->codec->width);
  1030.  
  1031.     if (st->codec->height == 608) // PAL + VBI
  1032.         display_height = 576;
  1033.     else if (st->codec->height == 512)  // NTSC + VBI
  1034.         display_height = 486;
  1035.     else
  1036.         display_height = st->codec->height;
  1037.  
  1038.     mxf_write_local_tag(pb, 4, 0x3208);
  1039.     avio_wb32(pb, display_height>>sc->interlaced);
  1040.  
  1041.     // presentation Y offset
  1042.     mxf_write_local_tag(pb, 4, 0x320B);
  1043.     avio_wb32(pb, (st->codec->height - display_height)>>sc->interlaced);
  1044.  
  1045.     // component depth
  1046.     mxf_write_local_tag(pb, 4, 0x3301);
  1047.     avio_wb32(pb, sc->component_depth);
  1048.  
  1049.     // horizontal subsampling
  1050.     mxf_write_local_tag(pb, 4, 0x3302);
  1051.     avio_wb32(pb, sc->h_chroma_sub_sample);
  1052.  
  1053.     // color siting
  1054.     mxf_write_local_tag(pb, 1, 0x3303);
  1055.     avio_w8(pb, sc->color_siting);
  1056.  
  1057.     if (sc->signal_standard) {
  1058.         mxf_write_local_tag(pb, 1, 0x3215);
  1059.         avio_w8(pb, sc->signal_standard);
  1060.     }
  1061.  
  1062.     // frame layout
  1063.     mxf_write_local_tag(pb, 1, 0x320C);
  1064.     avio_w8(pb, sc->interlaced);
  1065.  
  1066.     // video line map
  1067.     switch (st->codec->height) {
  1068.     case  576: f1 = 23; f2 = st->codec->codec_id == AV_CODEC_ID_DVVIDEO ? 335 : 336; break;
  1069.     case  608: f1 =  7; f2 = 320; break;
  1070.     case  480: f1 = 20; f2 = st->codec->codec_id == AV_CODEC_ID_DVVIDEO ? 285 : 283; break;
  1071.     case  512: f1 =  7; f2 = 270; break;
  1072.     case  720: f1 = 26; f2 =   0; break; // progressive
  1073.     case 1080: f1 = 21; f2 = 584; break;
  1074.     default:   f1 =  0; f2 =   0; break;
  1075.     }
  1076.  
  1077.     if (!sc->interlaced) {
  1078.         f2  = 0;
  1079.         f1 *= 2;
  1080.     }
  1081.  
  1082.     mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
  1083.     avio_wb32(pb, sc->interlaced ? 2 : 1);
  1084.     avio_wb32(pb, 4);
  1085.     avio_wb32(pb, f1);
  1086.     if (sc->interlaced)
  1087.         avio_wb32(pb, f2);
  1088.  
  1089.     mxf_write_local_tag(pb, 8, 0x320E);
  1090.     avio_wb32(pb, sc->aspect_ratio.num);
  1091.     avio_wb32(pb, sc->aspect_ratio.den);
  1092.  
  1093.     mxf_write_local_tag(pb, 16, 0x3201);
  1094.     avio_write(pb, *sc->codec_ul, 16);
  1095.  
  1096.     if (sc->interlaced && sc->field_dominance) {
  1097.         mxf_write_local_tag(pb, 1, 0x3212);
  1098.         avio_w8(pb, sc->field_dominance);
  1099.     }
  1100.  
  1101. }
  1102.  
  1103. static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st)
  1104. {
  1105.     mxf_write_cdci_common(s, st, mxf_cdci_descriptor_key, 0);
  1106. }
  1107.  
  1108. static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
  1109. {
  1110.     AVIOContext *pb = s->pb;
  1111.     MXFStreamContext *sc = st->priv_data;
  1112.     int profile_and_level = (st->codec->profile<<4) | st->codec->level;
  1113.  
  1114.     if (st->codec->codec_id != AV_CODEC_ID_H264) {
  1115.         mxf_write_cdci_common(s, st, mxf_mpegvideo_descriptor_key, 8+5);
  1116.  
  1117.         // bit rate
  1118.         mxf_write_local_tag(pb, 4, 0x8000);
  1119.         avio_wb32(pb, sc->video_bit_rate);
  1120.  
  1121.         // profile and level
  1122.         mxf_write_local_tag(pb, 1, 0x8007);
  1123.         if (!st->codec->profile)
  1124.             profile_and_level |= 0x80; // escape bit
  1125.         avio_w8(pb, profile_and_level);
  1126.     } else {
  1127.         mxf_write_cdci_common(s, st, mxf_mpegvideo_descriptor_key, 0);
  1128.     }
  1129. }
  1130.  
  1131. static void mxf_write_generic_sound_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
  1132. {
  1133.     AVIOContext *pb = s->pb;
  1134.     MXFContext *mxf = s->priv_data;
  1135.     int show_warnings = !mxf->footer_partition_offset;
  1136.     int duration_size = 0;
  1137.  
  1138.     if (s->oformat == &ff_mxf_opatom_muxer)
  1139.         duration_size = 12;
  1140.  
  1141.     mxf_write_generic_desc(s, st, key, size+duration_size+5+12+8+8);
  1142.  
  1143.     if (duration_size > 0){
  1144.         mxf_write_local_tag(pb, 8, 0x3002);
  1145.         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
  1146.     }
  1147.  
  1148.     // audio locked
  1149.     mxf_write_local_tag(pb, 1, 0x3D02);
  1150.     avio_w8(pb, 1);
  1151.  
  1152.     // write audio sampling rate
  1153.     mxf_write_local_tag(pb, 8, 0x3D03);
  1154.     avio_wb32(pb, st->codec->sample_rate);
  1155.     avio_wb32(pb, 1);
  1156.  
  1157.     mxf_write_local_tag(pb, 4, 0x3D07);
  1158.     if (mxf->channel_count == -1) {
  1159.         if (show_warnings && (s->oformat == &ff_mxf_d10_muxer) && (st->codec->channels != 4) && (st->codec->channels != 8))
  1160.             av_log(s, AV_LOG_WARNING, "the number of audio channels shall be 4 or 8 : the output will not comply to MXF D-10 specs, use -d10_channelcount to fix this\n");
  1161.         avio_wb32(pb, st->codec->channels);
  1162.     } else if (s->oformat == &ff_mxf_d10_muxer) {
  1163.         if (show_warnings && (mxf->channel_count < st->codec->channels))
  1164.             av_log(s, AV_LOG_WARNING, "d10_channelcount < actual number of audio channels : some channels will be discarded\n");
  1165.         if (show_warnings && (mxf->channel_count != 4) && (mxf->channel_count != 8))
  1166.             av_log(s, AV_LOG_WARNING, "d10_channelcount shall be set to 4 or 8 : the output will not comply to MXF D-10 specs\n");
  1167.         avio_wb32(pb, mxf->channel_count);
  1168.     } else {
  1169.         if (show_warnings && mxf->channel_count != -1 && s->oformat != &ff_mxf_opatom_muxer)
  1170.             av_log(s, AV_LOG_ERROR, "-d10_channelcount requires MXF D-10 and will be ignored\n");
  1171.         avio_wb32(pb, st->codec->channels);
  1172.     }
  1173.  
  1174.     mxf_write_local_tag(pb, 4, 0x3D01);
  1175.     avio_wb32(pb, av_get_bits_per_sample(st->codec->codec_id));
  1176. }
  1177.  
  1178. static void mxf_write_wav_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
  1179. {
  1180.     AVIOContext *pb = s->pb;
  1181.  
  1182.     mxf_write_generic_sound_common(s, st, key, size+6+8);
  1183.  
  1184.     mxf_write_local_tag(pb, 2, 0x3D0A);
  1185.     avio_wb16(pb, st->codec->block_align);
  1186.  
  1187.     // avg bytes per sec
  1188.     mxf_write_local_tag(pb, 4, 0x3D09);
  1189.     avio_wb32(pb, st->codec->block_align*st->codec->sample_rate);
  1190. }
  1191.  
  1192. static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
  1193. {
  1194.     mxf_write_wav_common(s, st, mxf_wav_descriptor_key, 0);
  1195. }
  1196.  
  1197. static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
  1198. {
  1199.     mxf_write_wav_common(s, st, mxf_aes3_descriptor_key, 0);
  1200. }
  1201.  
  1202. static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st)
  1203. {
  1204.     mxf_write_generic_sound_common(s, st, mxf_generic_sound_descriptor_key, 0);
  1205. }
  1206.  
  1207. static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
  1208.  
  1209. static int mxf_write_tagged_value(AVFormatContext *s, const char* name, const char* value)
  1210. {
  1211.     MXFContext *mxf = s->priv_data;
  1212.     AVIOContext *pb = s->pb;
  1213.     int name_size = mxf_utf16_local_tag_length(name);
  1214.     int indirect_value_size = 13 + mxf_utf16_local_tag_length(value);
  1215.  
  1216.     if (!name_size || indirect_value_size == 13)
  1217.         return 1;
  1218.  
  1219.     mxf_write_metadata_key(pb, 0x013f00);
  1220.     klv_encode_ber_length(pb, 24 + name_size + indirect_value_size);
  1221.  
  1222.     // write instance UID
  1223.     mxf_write_local_tag(pb, 16, 0x3C0A);
  1224.     mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count);
  1225.  
  1226.     // write name
  1227.     mxf_write_local_tag_utf16(pb, 0x5001, name); // Name
  1228.  
  1229.     // write indirect value
  1230.     mxf_write_local_tag(pb, indirect_value_size, 0x5003);
  1231.     avio_write(pb, mxf_indirect_value_utf16le, 17);
  1232.     avio_put_str16le(pb, value);
  1233.  
  1234.     mxf->tagged_value_count++;
  1235.     return 0;
  1236. }
  1237.  
  1238. static int mxf_write_user_comments(AVFormatContext *s, const AVDictionary *m)
  1239. {
  1240.     MXFContext *mxf = s->priv_data;
  1241.     AVDictionaryEntry *t = NULL;
  1242.     int count = 0;
  1243.  
  1244.     while ((t = av_dict_get(m, "comment_", t, AV_DICT_IGNORE_SUFFIX))) {
  1245.         if (mxf->tagged_value_count >= UINT16_MAX) {
  1246.             av_log(s, AV_LOG_ERROR, "too many tagged values, ignoring remaining\n");
  1247.             return count;
  1248.         }
  1249.  
  1250.         if (mxf_write_tagged_value(s, t->key + 8, t->value) == 0)
  1251.             count++;
  1252.     }
  1253.     return count;
  1254. }
  1255.  
  1256. static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type, const char *package_name)
  1257. {
  1258.     MXFContext *mxf = s->priv_data;
  1259.     AVIOContext *pb = s->pb;
  1260.     int i, track_count = s->nb_streams+1;
  1261.     int name_size = mxf_utf16_local_tag_length(package_name);
  1262.     int user_comment_count = 0;
  1263.  
  1264.     if (type == MaterialPackage) {
  1265.         if (mxf->store_user_comments)
  1266.             user_comment_count = mxf_write_user_comments(s, s->metadata);
  1267.         mxf_write_metadata_key(pb, 0x013600);
  1268.         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
  1269.         klv_encode_ber_length(pb, 92 + name_size + (16*track_count) + (16*user_comment_count) + 12LL*mxf->store_user_comments);
  1270.     } else {
  1271.         mxf_write_metadata_key(pb, 0x013700);
  1272.         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
  1273.         klv_encode_ber_length(pb, 112 + name_size + (16*track_count) + 12LL*mxf->store_user_comments); // 20 bytes length for descriptor reference
  1274.     }
  1275.  
  1276.     // write uid
  1277.     mxf_write_local_tag(pb, 16, 0x3C0A);
  1278.     mxf_write_uuid(pb, type, 0);
  1279.     av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
  1280.     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
  1281.  
  1282.     // write package umid
  1283.     mxf_write_local_tag(pb, 32, 0x4401);
  1284.     mxf_write_umid(s, type == SourcePackage);
  1285.     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
  1286.  
  1287.     // package name
  1288.     if (name_size)
  1289.         mxf_write_local_tag_utf16(pb, 0x4402, package_name);
  1290.  
  1291.     // package creation date
  1292.     mxf_write_local_tag(pb, 8, 0x4405);
  1293.     avio_wb64(pb, mxf->timestamp);
  1294.  
  1295.     // package modified date
  1296.     mxf_write_local_tag(pb, 8, 0x4404);
  1297.     avio_wb64(pb, mxf->timestamp);
  1298.  
  1299.     // write track refs
  1300.     mxf_write_local_tag(pb, track_count*16 + 8, 0x4403);
  1301.     mxf_write_refs_count(pb, track_count);
  1302.     mxf_write_uuid(pb, type == MaterialPackage ? Track :
  1303.                    Track + TypeBottom, -1); // timecode track
  1304.     for (i = 0; i < s->nb_streams; i++)
  1305.         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
  1306.  
  1307.     // write user comment refs
  1308.     if (mxf->store_user_comments) {
  1309.         mxf_write_local_tag(pb, user_comment_count*16 + 8, 0x4406);
  1310.         mxf_write_refs_count(pb, user_comment_count);
  1311.         for (i = 0; i < user_comment_count; i++)
  1312.             mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count - user_comment_count + i);
  1313.     }
  1314.  
  1315.     // write multiple descriptor reference
  1316.     if (type == SourcePackage) {
  1317.         mxf_write_local_tag(pb, 16, 0x4701);
  1318.         if (s->nb_streams > 1) {
  1319.             mxf_write_uuid(pb, MultipleDescriptor, 0);
  1320.             mxf_write_multi_descriptor(s);
  1321.         } else
  1322.             mxf_write_uuid(pb, SubDescriptor, 0);
  1323.     }
  1324.  
  1325.     // write timecode track
  1326.     mxf_write_track(s, mxf->timecode_track, type);
  1327.     mxf_write_sequence(s, mxf->timecode_track, type);
  1328.     mxf_write_timecode_component(s, mxf->timecode_track, type);
  1329.  
  1330.     for (i = 0; i < s->nb_streams; i++) {
  1331.         AVStream *st = s->streams[i];
  1332.         mxf_write_track(s, st, type);
  1333.         mxf_write_sequence(s, st, type);
  1334.         mxf_write_structural_component(s, st, type);
  1335.  
  1336.         if (type == SourcePackage) {
  1337.             MXFStreamContext *sc = st->priv_data;
  1338.             mxf_essence_container_uls[sc->index].write_desc(s, st);
  1339.         }
  1340.     }
  1341. }
  1342.  
  1343. static int mxf_write_essence_container_data(AVFormatContext *s)
  1344. {
  1345.     AVIOContext *pb = s->pb;
  1346.  
  1347.     mxf_write_metadata_key(pb, 0x012300);
  1348.     klv_encode_ber_length(pb, 72);
  1349.  
  1350.     mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
  1351.     mxf_write_uuid(pb, EssenceContainerData, 0);
  1352.  
  1353.     mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
  1354.     mxf_write_umid(s, 1);
  1355.  
  1356.     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
  1357.     avio_wb32(pb, 1);
  1358.  
  1359.     mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
  1360.     avio_wb32(pb, 2);
  1361.  
  1362.     return 0;
  1363. }
  1364.  
  1365. static int mxf_write_header_metadata_sets(AVFormatContext *s)
  1366. {
  1367.     const char *material_package_name = NULL;
  1368.     const char *file_package_name = NULL;
  1369.     AVDictionaryEntry *entry = NULL;
  1370.     AVStream *st = NULL;
  1371.     int i;
  1372.  
  1373.     if (entry = av_dict_get(s->metadata, "material_package_name", NULL, 0))
  1374.        material_package_name = entry->value;
  1375.  
  1376.     if (entry = av_dict_get(s->metadata, "file_package_name", NULL, 0)) {
  1377.         file_package_name = entry->value;
  1378.     } else {
  1379.         /* check if any of the streams contain a file_package_name */
  1380.         for (i = 0; i < s->nb_streams; i++) {
  1381.             st = s->streams[i];
  1382.             if (entry = av_dict_get(st->metadata, "file_package_name", NULL, 0)) {
  1383.                 file_package_name = entry->value;
  1384.                 break;
  1385.             }
  1386.         }
  1387.     }
  1388.  
  1389.     mxf_write_preface(s);
  1390.     mxf_write_identification(s);
  1391.     mxf_write_content_storage(s);
  1392.     mxf_write_package(s, MaterialPackage, material_package_name);
  1393.     mxf_write_package(s, SourcePackage, file_package_name);
  1394.     mxf_write_essence_container_data(s);
  1395.     return 0;
  1396. }
  1397.  
  1398. static unsigned klv_fill_size(uint64_t size)
  1399. {
  1400.     unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
  1401.     if (pad < 20) // smallest fill item possible
  1402.         return pad + KAG_SIZE;
  1403.     else
  1404.         return pad & (KAG_SIZE-1);
  1405. }
  1406.  
  1407. static void mxf_write_index_table_segment(AVFormatContext *s)
  1408. {
  1409.     MXFContext *mxf = s->priv_data;
  1410.     AVIOContext *pb = s->pb;
  1411.     int i, j, temporal_reordering = 0;
  1412.     int key_index = mxf->last_key_index;
  1413.  
  1414.     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
  1415.  
  1416.     if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)
  1417.         return;
  1418.  
  1419.     avio_write(pb, index_table_segment_key, 16);
  1420.  
  1421.     if (mxf->edit_unit_byte_count) {
  1422.         klv_encode_ber_length(pb, 80);
  1423.     } else {
  1424.         klv_encode_ber_length(pb, 85 + 12+(s->nb_streams+1LL)*6 +
  1425.                               12+mxf->edit_units_count*(11+mxf->slice_count*4LL));
  1426.     }
  1427.  
  1428.     // instance id
  1429.     mxf_write_local_tag(pb, 16, 0x3C0A);
  1430.     mxf_write_uuid(pb, IndexTableSegment, 0);
  1431.  
  1432.     // index edit rate
  1433.     mxf_write_local_tag(pb, 8, 0x3F0B);
  1434.     avio_wb32(pb, mxf->time_base.den);
  1435.     avio_wb32(pb, mxf->time_base.num);
  1436.  
  1437.     // index start position
  1438.     mxf_write_local_tag(pb, 8, 0x3F0C);
  1439.     avio_wb64(pb, mxf->last_indexed_edit_unit);
  1440.  
  1441.     // index duration
  1442.     mxf_write_local_tag(pb, 8, 0x3F0D);
  1443.     if (mxf->edit_unit_byte_count)
  1444.         avio_wb64(pb, 0); // index table covers whole container
  1445.     else
  1446.         avio_wb64(pb, mxf->edit_units_count);
  1447.  
  1448.     // edit unit byte count
  1449.     mxf_write_local_tag(pb, 4, 0x3F05);
  1450.     avio_wb32(pb, mxf->edit_unit_byte_count);
  1451.  
  1452.     // index sid
  1453.     mxf_write_local_tag(pb, 4, 0x3F06);
  1454.     avio_wb32(pb, 2);
  1455.  
  1456.     // body sid
  1457.     mxf_write_local_tag(pb, 4, 0x3F07);
  1458.     avio_wb32(pb, 1);
  1459.  
  1460.     if (!mxf->edit_unit_byte_count) {
  1461.         // real slice count - 1
  1462.         mxf_write_local_tag(pb, 1, 0x3F08);
  1463.         avio_w8(pb, mxf->slice_count);
  1464.  
  1465.         // delta entry array
  1466.         mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);
  1467.         avio_wb32(pb, s->nb_streams+1); // num of entries
  1468.         avio_wb32(pb, 6);               // size of one entry
  1469.         // write system item delta entry
  1470.         avio_w8(pb, 0);
  1471.         avio_w8(pb, 0); // slice entry
  1472.         avio_wb32(pb, 0); // element delta
  1473.         for (i = 0; i < s->nb_streams; i++) {
  1474.             AVStream *st = s->streams[i];
  1475.             MXFStreamContext *sc = st->priv_data;
  1476.             avio_w8(pb, sc->temporal_reordering);
  1477.             if (sc->temporal_reordering)
  1478.                 temporal_reordering = 1;
  1479.             if (i == 0) { // video track
  1480.                 avio_w8(pb, 0); // slice number
  1481.                 avio_wb32(pb, KAG_SIZE); // system item size including klv fill
  1482.             } else { // audio track
  1483.                 unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;
  1484.                 audio_frame_size += klv_fill_size(audio_frame_size);
  1485.                 avio_w8(pb, 1);
  1486.                 avio_wb32(pb, (i-1)*audio_frame_size); // element delta
  1487.             }
  1488.         }
  1489.  
  1490.         mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A);
  1491.         avio_wb32(pb, mxf->edit_units_count);  // num of entries
  1492.         avio_wb32(pb, 11+mxf->slice_count*4);  // size of one entry
  1493.  
  1494.         for (i = 0; i < mxf->edit_units_count; i++) {
  1495.             int temporal_offset = 0;
  1496.  
  1497.             if (!(mxf->index_entries[i].flags & 0x33)) { // I frame
  1498.                 mxf->last_key_index = key_index;
  1499.                 key_index = i;
  1500.             }
  1501.  
  1502.             if (temporal_reordering) {
  1503.                 int pic_num_in_gop = i - key_index;
  1504.                 if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {
  1505.                     for (j = key_index; j < mxf->edit_units_count; j++) {
  1506.                         if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)
  1507.                             break;
  1508.                     }
  1509.                     if (j == mxf->edit_units_count)
  1510.                         av_log(s, AV_LOG_WARNING, "missing frames\n");
  1511.                     temporal_offset = j - key_index - pic_num_in_gop;
  1512.                 }
  1513.             }
  1514.             avio_w8(pb, temporal_offset);
  1515.  
  1516.             if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction
  1517.                 avio_w8(pb, mxf->last_key_index - i);
  1518.             } else {
  1519.                 avio_w8(pb, key_index - i); // key frame offset
  1520.                 if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
  1521.                     mxf->last_key_index = key_index;
  1522.             }
  1523.  
  1524.             if (!(mxf->index_entries[i].flags & 0x33) && // I frame
  1525.                 mxf->index_entries[i].flags & 0x40 && !temporal_offset)
  1526.                 mxf->index_entries[i].flags |= 0x80; // random access
  1527.             avio_w8(pb, mxf->index_entries[i].flags);
  1528.             // stream offset
  1529.             avio_wb64(pb, mxf->index_entries[i].offset);
  1530.             if (s->nb_streams > 1)
  1531.                 avio_wb32(pb, mxf->index_entries[i].slice_offset);
  1532.         }
  1533.  
  1534.         mxf->last_key_index = key_index - mxf->edit_units_count;
  1535.         mxf->last_indexed_edit_unit += mxf->edit_units_count;
  1536.         mxf->edit_units_count = 0;
  1537.     }
  1538. }
  1539.  
  1540. static void mxf_write_klv_fill(AVFormatContext *s)
  1541. {
  1542.     unsigned pad = klv_fill_size(avio_tell(s->pb));
  1543.     if (pad) {
  1544.         avio_write(s->pb, klv_fill_key, 16);
  1545.         pad -= 16 + 4;
  1546.         klv_encode_ber4_length(s->pb, pad);
  1547.         ffio_fill(s->pb, 0, pad);
  1548.         av_assert1(!(avio_tell(s->pb) & (KAG_SIZE-1)));
  1549.     }
  1550. }
  1551.  
  1552. static int mxf_write_partition(AVFormatContext *s, int bodysid,
  1553.                                 int indexsid,
  1554.                                 const uint8_t *key, int write_metadata)
  1555. {
  1556.     MXFContext *mxf = s->priv_data;
  1557.     AVIOContext *pb = s->pb;
  1558.     int64_t header_byte_count_offset;
  1559.     unsigned index_byte_count = 0;
  1560.     uint64_t partition_offset = avio_tell(pb);
  1561.     int err;
  1562.  
  1563.     if (!mxf->edit_unit_byte_count && mxf->edit_units_count)
  1564.         index_byte_count = 85 + 12+(s->nb_streams+1)*6 +
  1565.             12+mxf->edit_units_count*(11+mxf->slice_count*4);
  1566.     else if (mxf->edit_unit_byte_count && indexsid)
  1567.         index_byte_count = 80;
  1568.  
  1569.     if (index_byte_count) {
  1570.         // add encoded ber length
  1571.         index_byte_count += 16 + klv_ber_length(index_byte_count);
  1572.         index_byte_count += klv_fill_size(index_byte_count);
  1573.     }
  1574.  
  1575.     if (key && !memcmp(key, body_partition_key, 16)) {
  1576.         if ((err = av_reallocp_array(&mxf->body_partition_offset, mxf->body_partitions_count + 1,
  1577.                                      sizeof(*mxf->body_partition_offset))) < 0) {
  1578.             mxf->body_partitions_count = 0;
  1579.             return err;
  1580.         }
  1581.         mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;
  1582.     }
  1583.  
  1584.     // write klv
  1585.     if (key)
  1586.         avio_write(pb, key, 16);
  1587.     else
  1588.         avio_write(pb, body_partition_key, 16);
  1589.  
  1590.     klv_encode_ber_length(pb, 88 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
  1591.  
  1592.     // write partition value
  1593.     avio_wb16(pb, 1); // majorVersion
  1594.     avio_wb16(pb, 2); // minorVersion
  1595.     avio_wb32(pb, KAG_SIZE); // KAGSize
  1596.  
  1597.     avio_wb64(pb, partition_offset); // ThisPartition
  1598.  
  1599.     if (key && !memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
  1600.         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
  1601.     else if (key && !memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
  1602.         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
  1603.     else
  1604.         avio_wb64(pb, 0);
  1605.  
  1606.     avio_wb64(pb, mxf->footer_partition_offset); // footerPartition
  1607.  
  1608.     // set offset
  1609.     header_byte_count_offset = avio_tell(pb);
  1610.     avio_wb64(pb, 0); // headerByteCount, update later
  1611.  
  1612.     // indexTable
  1613.     avio_wb64(pb, index_byte_count); // indexByteCount
  1614.     avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
  1615.  
  1616.     // BodyOffset
  1617.     if (bodysid && mxf->edit_units_count && mxf->body_partitions_count && s->oformat != &ff_mxf_opatom_muxer)
  1618.         avio_wb64(pb, mxf->body_offset);
  1619.     else
  1620.         avio_wb64(pb, 0);
  1621.  
  1622.     avio_wb32(pb, bodysid); // bodySID
  1623.  
  1624.     // operational pattern
  1625.     if (s->oformat == &ff_mxf_opatom_muxer)
  1626.         avio_write(pb, opatom_ul, 16);
  1627.     else
  1628.         avio_write(pb, op1a_ul, 16);
  1629.  
  1630.     // essence container
  1631.     mxf_write_essence_container_refs(s);
  1632.  
  1633.     if (write_metadata) {
  1634.         // mark the start of the headermetadata and calculate metadata size
  1635.         int64_t pos, start;
  1636.         unsigned header_byte_count;
  1637.  
  1638.         mxf_write_klv_fill(s);
  1639.         start = avio_tell(s->pb);
  1640.         mxf_write_primer_pack(s);
  1641.         mxf_write_header_metadata_sets(s);
  1642.         pos = avio_tell(s->pb);
  1643.         header_byte_count = pos - start + klv_fill_size(pos);
  1644.  
  1645.         // update header_byte_count
  1646.         avio_seek(pb, header_byte_count_offset, SEEK_SET);
  1647.         avio_wb64(pb, header_byte_count);
  1648.         avio_seek(pb, pos, SEEK_SET);
  1649.     }
  1650.  
  1651.     if(key)
  1652.         avio_flush(pb);
  1653.  
  1654.     return 0;
  1655. }
  1656.  
  1657. static int mxf_parse_dnxhd_frame(AVFormatContext *s, AVStream *st,
  1658. AVPacket *pkt)
  1659. {
  1660.     MXFContext *mxf = s->priv_data;
  1661.     MXFStreamContext *sc = st->priv_data;
  1662.     int i, cid;
  1663.     uint8_t* header_cid;
  1664.     int frame_size = 0;
  1665.  
  1666.     if (mxf->header_written)
  1667.         return 1;
  1668.  
  1669.     if (pkt->size < 43)
  1670.         return -1;
  1671.  
  1672.     header_cid = pkt->data + 0x28;
  1673.     cid = header_cid[0] << 24 | header_cid[1] << 16 | header_cid[2] << 8 | header_cid[3];
  1674.  
  1675.     if ((frame_size = avpriv_dnxhd_get_frame_size(cid)) < 0)
  1676.         return -1;
  1677.     if ((sc->interlaced = avpriv_dnxhd_get_interlaced(cid)) < 0)
  1678.         return AVERROR_INVALIDDATA;
  1679.  
  1680.     switch (cid) {
  1681.     case 1235:
  1682.         sc->index = 24;
  1683.         sc->component_depth = 10;
  1684.         break;
  1685.     case 1237:
  1686.         sc->index = 25;
  1687.         break;
  1688.     case 1238:
  1689.         sc->index = 26;
  1690.         break;
  1691.     case 1241:
  1692.         sc->index = 27;
  1693.         sc->component_depth = 10;
  1694.         break;
  1695.     case 1242:
  1696.         sc->index = 28;
  1697.         break;
  1698.     case 1243:
  1699.         sc->index = 29;
  1700.         break;
  1701.     case 1250:
  1702.         sc->index = 30;
  1703.         sc->component_depth = 10;
  1704.         break;
  1705.     case 1251:
  1706.         sc->index = 31;
  1707.         break;
  1708.     case 1252:
  1709.         sc->index = 32;
  1710.         break;
  1711.     case 1253:
  1712.         sc->index = 33;
  1713.         break;
  1714.     default:
  1715.         return -1;
  1716.     }
  1717.  
  1718.     sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
  1719.     sc->aspect_ratio = (AVRational){ 16, 9 };
  1720.  
  1721.     if(s->oformat == &ff_mxf_opatom_muxer){
  1722.         mxf->edit_unit_byte_count = frame_size;
  1723.         return 1;
  1724.     }
  1725.  
  1726.     mxf->edit_unit_byte_count = KAG_SIZE;
  1727.     for (i = 0; i < s->nb_streams; i++) {
  1728.         AVStream *st = s->streams[i];
  1729.         MXFStreamContext *sc = st->priv_data;
  1730.         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  1731.             mxf->edit_unit_byte_count += 16 + 4 + sc->aic.samples[0]*sc->aic.sample_size;
  1732.             mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
  1733.         } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1734.             mxf->edit_unit_byte_count += 16 + 4 + frame_size;
  1735.             mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
  1736.         }
  1737.     }
  1738.  
  1739.     return 1;
  1740. }
  1741.  
  1742. static int mxf_parse_dv_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  1743. {
  1744.     MXFContext *mxf = s->priv_data;
  1745.     MXFStreamContext *sc = st->priv_data;
  1746.     uint8_t *vs_pack, *vsc_pack;
  1747.     int i, ul_index, frame_size, stype, pal;
  1748.  
  1749.     if (mxf->header_written)
  1750.         return 1;
  1751.  
  1752.     // Check for minimal frame size
  1753.     if (pkt->size < 120000)
  1754.         return -1;
  1755.  
  1756.     vs_pack  = pkt->data + 80*5 + 48;
  1757.     vsc_pack = pkt->data + 80*5 + 53;
  1758.     stype    = vs_pack[3] & 0x1f;
  1759.     pal      = (vs_pack[3] >> 5) & 0x1;
  1760.  
  1761.     if ((vs_pack[2] & 0x07) == 0x02)
  1762.         sc->aspect_ratio = (AVRational){ 16, 9 };
  1763.     else
  1764.         sc->aspect_ratio = (AVRational){ 4, 3 };
  1765.  
  1766.     sc->interlaced = (vsc_pack[3] >> 4) & 0x01;
  1767.     // TODO: fix dv encoder to set proper FF/FS value in VSC pack
  1768.     // and set field dominance accordingly
  1769.     // av_log(s, AV_LOG_DEBUG, "DV vsc pack ff/ss = %x\n", vsc_pack[2] >> 6);
  1770.  
  1771.     switch (stype) {
  1772.     case 0x18: // DV100 720p
  1773.         ul_index = 6 + pal;
  1774.         frame_size = pal ? 288000 : 240000;
  1775.         if (sc->interlaced) {
  1776.             av_log(s, AV_LOG_ERROR, "source marked as interlaced but codec profile is progressive\n");
  1777.             sc->interlaced = 0;
  1778.         }
  1779.         break;
  1780.     case 0x14: // DV100 1080i
  1781.         ul_index = 4 + pal;
  1782.         frame_size = pal ? 576000 : 480000;
  1783.         break;
  1784.     case 0x04: // DV50
  1785.         ul_index = 2 + pal;
  1786.         frame_size = pal ? 288000 : 240000;
  1787.         break;
  1788.     default: // DV25
  1789.         ul_index = 0 + pal;
  1790.         frame_size = pal ? 144000 : 120000;
  1791.     }
  1792.  
  1793.     sc->index = ul_index + 16;
  1794.     sc->codec_ul =  &mxf_essence_container_uls[sc->index].codec_ul;
  1795.  
  1796.     if(s->oformat == &ff_mxf_opatom_muxer) {
  1797.         mxf->edit_unit_byte_count = frame_size;
  1798.         return 1;
  1799.     }
  1800.  
  1801.     mxf->edit_unit_byte_count = KAG_SIZE;
  1802.     for (i = 0; i < s->nb_streams; i++) {
  1803.         AVStream *st = s->streams[i];
  1804.         MXFStreamContext *sc = st->priv_data;
  1805.         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  1806.             mxf->edit_unit_byte_count += 16 + 4 + sc->aic.samples[0]*sc->aic.sample_size;
  1807.             mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
  1808.         } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1809.             mxf->edit_unit_byte_count += 16 + 4 + frame_size;
  1810.             mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
  1811.         }
  1812.     }
  1813.  
  1814.     return 1;
  1815. }
  1816.  
  1817. static const struct {
  1818.     UID uid;
  1819.     int frame_size;
  1820.     int profile;
  1821.     uint8_t interlaced;
  1822. } mxf_h264_codec_uls[] = {
  1823.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x20,0x01 },      0, 110, 0 }, // AVC High 10 Intra
  1824.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 232960,   0, 1 }, // AVC Intra 50 1080i60
  1825.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 281088,   0, 1 }, // AVC Intra 50 1080i50
  1826.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 232960,   0, 0 }, // AVC Intra 50 1080p30
  1827.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 281088,   0, 0 }, // AVC Intra 50 1080p25
  1828.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x08 }, 116736,   0, 0 }, // AVC Intra 50 720p60
  1829.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x09 }, 140800,   0, 0 }, // AVC Intra 50 720p50
  1830.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x30,0x01 },      0, 122, 0 }, // AVC High 422 Intra
  1831.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x01 }, 472576,   0, 1 }, // AVC Intra 100 1080i60
  1832.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x02 }, 568832,   0, 1 }, // AVC Intra 100 1080i50
  1833.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x03 }, 472576,   0, 0 }, // AVC Intra 100 1080p30
  1834.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x04 }, 568832,   0, 0 }, // AVC Intra 100 1080p25
  1835.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x08 }, 236544,   0, 0 }, // AVC Intra 100 720p60
  1836.     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x09 }, 284672,   0, 0 }, // AVC Intra 100 720p50
  1837. };
  1838.  
  1839. static int mxf_parse_h264_frame(AVFormatContext *s, AVStream *st,
  1840.                                 AVPacket *pkt, MXFIndexEntry *e)
  1841. {
  1842.     MXFContext *mxf = s->priv_data;
  1843.     MXFStreamContext *sc = st->priv_data;
  1844.     static const int mxf_h264_num_codec_uls = sizeof(mxf_h264_codec_uls) / sizeof(mxf_h264_codec_uls[0]);
  1845.     const uint8_t *buf = pkt->data;
  1846.     const uint8_t *buf_end = pkt->data + pkt->size;
  1847.     uint32_t state = -1;
  1848.     int extra_size = 512; // support AVC Intra files without SPS/PPS header
  1849.     int i, frame_size;
  1850.     uint8_t uid_found;
  1851.  
  1852.     if (pkt->size > extra_size)
  1853.         buf_end -= pkt->size - extra_size; // no need to parse beyond SPS/PPS header
  1854.  
  1855.     for (;;) {
  1856.         buf = avpriv_find_start_code(buf, buf_end, &state);
  1857.         if (buf >= buf_end)
  1858.             break;
  1859.         --buf;
  1860.         switch (state & 0x1f) {
  1861.         case NAL_SPS:
  1862.             st->codec->profile = buf[1];
  1863.             e->flags |= 0x40;
  1864.             break;
  1865.         case NAL_PPS:
  1866.             if (e->flags & 0x40) { // sequence header present
  1867.                 e->flags |= 0x80; // random access
  1868.                 extra_size = 0;
  1869.                 buf = buf_end;
  1870.             }
  1871.             break;
  1872.         default:
  1873.             break;
  1874.         }
  1875.     }
  1876.  
  1877.     if (mxf->header_written)
  1878.         return 1;
  1879.  
  1880.     sc->aspect_ratio = (AVRational){ 16, 9 }; // 16:9 is mandatory for broadcast HD
  1881.     sc->component_depth = 10; // AVC Intra is always 10 Bit
  1882.     sc->interlaced = st->codec->field_order != AV_FIELD_PROGRESSIVE ? 1 : 0;
  1883.     if (sc->interlaced)
  1884.         sc->field_dominance = 1; // top field first is mandatory for AVC Intra
  1885.  
  1886.     uid_found = 0;
  1887.     frame_size = pkt->size + extra_size;
  1888.     for (i = 0; i < mxf_h264_num_codec_uls; i++) {
  1889.         if (frame_size == mxf_h264_codec_uls[i].frame_size && sc->interlaced == mxf_h264_codec_uls[i].interlaced) {
  1890.             sc->codec_ul = &mxf_h264_codec_uls[i].uid;
  1891.             return 1;
  1892.         } else if (st->codec->profile == mxf_h264_codec_uls[i].profile) {
  1893.             sc->codec_ul = &mxf_h264_codec_uls[i].uid;
  1894.             uid_found = 1;
  1895.         }
  1896.     }
  1897.  
  1898.     if (!uid_found) {
  1899.         av_log(s, AV_LOG_ERROR, "AVC Intra 50/100 supported only\n");
  1900.         return 0;
  1901.     }
  1902.  
  1903.     return 1;
  1904. }
  1905.  
  1906. static const UID mxf_mpeg2_codec_uls[] = {
  1907.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
  1908.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
  1909.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
  1910.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
  1911.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
  1912.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
  1913.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
  1914.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
  1915.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x02,0x00 }, // MP@H-14 I-Frame
  1916.     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x03,0x00 }, // MP@H-14 Long GOP
  1917. };
  1918.  
  1919. static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
  1920. {
  1921.     int long_gop = avctx->gop_size > 1 || avctx->has_b_frames;
  1922.  
  1923.     if (avctx->profile == 4) { // Main
  1924.         if (avctx->level == 8) // Main
  1925.             return &mxf_mpeg2_codec_uls[0+long_gop];
  1926.         else if (avctx->level == 4) // High
  1927.             return &mxf_mpeg2_codec_uls[4+long_gop];
  1928.         else if (avctx->level == 6) // High 14
  1929.             return &mxf_mpeg2_codec_uls[8+long_gop];
  1930.     } else if (avctx->profile == 0) { // 422
  1931.         if (avctx->level == 5) // Main
  1932.             return &mxf_mpeg2_codec_uls[2+long_gop];
  1933.         else if (avctx->level == 2) // High
  1934.             return &mxf_mpeg2_codec_uls[6+long_gop];
  1935.     }
  1936.     return NULL;
  1937. }
  1938.  
  1939. static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
  1940.                                  AVPacket *pkt, MXFIndexEntry *e)
  1941. {
  1942.     MXFStreamContext *sc = st->priv_data;
  1943.     uint32_t c = -1;
  1944.     int i;
  1945.  
  1946.     for(i = 0; i < pkt->size - 4; i++) {
  1947.         c = (c<<8) + pkt->data[i];
  1948.         if (c == 0x1b5) {
  1949.             if ((pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
  1950.                 st->codec->profile = pkt->data[i+1] & 0x07;
  1951.                 st->codec->level   = pkt->data[i+2] >> 4;
  1952.             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
  1953.                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
  1954.                 if (sc->interlaced)
  1955.                     sc->field_dominance = 1 + !(pkt->data[i+4] & 0x80); // top field first
  1956.                 break;
  1957.             }
  1958.         } else if (c == 0x1b8) { // gop
  1959.             if (pkt->data[i+4]>>6 & 0x01) { // closed
  1960.                 sc->closed_gop = 1;
  1961.                 if (e->flags & 0x40) // sequence header present
  1962.                     e->flags |= 0x80; // random access
  1963.             }
  1964.         } else if (c == 0x1b3) { // seq
  1965.             e->flags |= 0x40;
  1966.             switch ((pkt->data[i+4]>>4) & 0xf) {
  1967.             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
  1968.             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
  1969.             case 4:  sc->aspect_ratio = (AVRational){221,100}; break;
  1970.             default:
  1971.                 av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
  1972.                           st->codec->width, st->codec->height, 1024*1024);
  1973.             }
  1974.         } else if (c == 0x100) { // pic
  1975.             int pict_type = (pkt->data[i+2]>>3) & 0x07;
  1976.             e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
  1977.             if (pict_type == 2) { // P frame
  1978.                 e->flags |= 0x22;
  1979.                 sc->closed_gop = 0; // reset closed gop, don't matter anymore
  1980.             } else if (pict_type == 3) { // B frame
  1981.                 if (sc->closed_gop)
  1982.                     e->flags |= 0x13; // only backward prediction
  1983.                 else
  1984.                     e->flags |= 0x33;
  1985.                 sc->temporal_reordering = -1;
  1986.             } else if (!pict_type) {
  1987.                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
  1988.                 return 0;
  1989.             }
  1990.         }
  1991.     }
  1992.     if (s->oformat != &ff_mxf_d10_muxer)
  1993.         sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
  1994.     return !!sc->codec_ul;
  1995. }
  1996.  
  1997. static uint64_t mxf_parse_timestamp(time_t timestamp)
  1998. {
  1999.     struct tm tmbuf;
  2000.     struct tm *time = gmtime_r(&timestamp, &tmbuf);
  2001.     if (!time)
  2002.         return 0;
  2003.     return (uint64_t)(time->tm_year+1900) << 48 |
  2004.            (uint64_t)(time->tm_mon+1)     << 40 |
  2005.            (uint64_t) time->tm_mday       << 32 |
  2006.                       time->tm_hour       << 24 |
  2007.                       time->tm_min        << 16 |
  2008.                       time->tm_sec        << 8;
  2009. }
  2010.  
  2011. static void mxf_gen_umid(AVFormatContext *s)
  2012. {
  2013.     MXFContext *mxf = s->priv_data;
  2014.     uint32_t seed = av_get_random_seed();
  2015.     uint64_t umid = seed + 0x5294713400000000LL;
  2016.  
  2017.     AV_WB64(mxf->umid  , umid);
  2018.     AV_WB64(mxf->umid+8, umid>>8);
  2019.  
  2020.     mxf->instance_number = seed & 0xFFFFFF;
  2021. }
  2022.  
  2023. static int mxf_init_timecode(AVFormatContext *s, AVStream *st, AVRational rate)
  2024. {
  2025.     MXFContext *mxf = s->priv_data;
  2026.     AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  2027.     if (!tcr)
  2028.         tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  2029.  
  2030.     if (tcr)
  2031.         return av_timecode_init_from_string(&mxf->tc, rate, tcr->value, s);
  2032.     else
  2033.         return av_timecode_init(&mxf->tc, rate, 0, 0, s);
  2034. }
  2035.  
  2036. static int mxf_write_header(AVFormatContext *s)
  2037. {
  2038.     MXFContext *mxf = s->priv_data;
  2039.     int i, ret;
  2040.     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
  2041.     const MXFSamplesPerFrame *spf = NULL;
  2042.     AVDictionaryEntry *t;
  2043.     int64_t timestamp = 0;
  2044.  
  2045.     if (!s->nb_streams)
  2046.         return -1;
  2047.  
  2048.     if (s->oformat == &ff_mxf_opatom_muxer && s->nb_streams !=1){
  2049.         av_log(s, AV_LOG_ERROR, "there must be exactly one stream for mxf opatom\n");
  2050.         return -1;
  2051.     }
  2052.  
  2053.     if (!av_dict_get(s->metadata, "comment_", NULL, AV_DICT_IGNORE_SUFFIX))
  2054.         mxf->store_user_comments = 0;
  2055.  
  2056.     for (i = 0; i < s->nb_streams; i++) {
  2057.         AVStream *st = s->streams[i];
  2058.         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
  2059.         if (!sc)
  2060.             return AVERROR(ENOMEM);
  2061.         st->priv_data = sc;
  2062.  
  2063.         if (((i == 0) ^ (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)) && s->oformat != &ff_mxf_opatom_muxer) {
  2064.             av_log(s, AV_LOG_ERROR, "there must be exactly one video stream and it must be the first one\n");
  2065.             return -1;
  2066.         }
  2067.  
  2068.         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2069.             const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(st->codec->pix_fmt);
  2070.             // TODO: should be avg_frame_rate
  2071.             AVRational rate, tbc = st->time_base;
  2072.             // Default component depth to 8
  2073.             sc->component_depth = 8;
  2074.             sc->h_chroma_sub_sample = 2;
  2075.             sc->color_siting = 0xFF;
  2076.  
  2077.             if (pix_desc) {
  2078.                 sc->component_depth     = pix_desc->comp[0].depth_minus1 + 1;
  2079.                 sc->h_chroma_sub_sample = 1 << pix_desc->log2_chroma_w;
  2080.             }
  2081.             switch (ff_choose_chroma_location(s, st)) {
  2082.             case AVCHROMA_LOC_TOPLEFT: sc->color_siting = 0; break;
  2083.             case AVCHROMA_LOC_LEFT:    sc->color_siting = 6; break;
  2084.             case AVCHROMA_LOC_TOP:     sc->color_siting = 1; break;
  2085.             case AVCHROMA_LOC_CENTER:  sc->color_siting = 3; break;
  2086.             }
  2087.  
  2088.             mxf->timecode_base = (tbc.den + tbc.num/2) / tbc.num;
  2089.             spf = ff_mxf_get_samples_per_frame(s, tbc);
  2090.             if (!spf) {
  2091.                 av_log(s, AV_LOG_ERROR, "Unsupported video frame rate %d/%d\n",
  2092.                        tbc.den, tbc.num);
  2093.                 return AVERROR(EINVAL);
  2094.             }
  2095.             mxf->time_base = spf->time_base;
  2096.             rate = av_inv_q(mxf->time_base);
  2097.             avpriv_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
  2098.             if((ret = mxf_init_timecode(s, st, rate)) < 0)
  2099.                 return ret;
  2100.  
  2101.             sc->video_bit_rate = st->codec->bit_rate ? st->codec->bit_rate : st->codec->rc_max_rate;
  2102.             if (s->oformat == &ff_mxf_d10_muxer) {
  2103.                 if ((sc->video_bit_rate == 50000000) && (mxf->time_base.den == 25)) {
  2104.                     sc->index = 3;
  2105.                 } else if ((sc->video_bit_rate == 49999840 || sc->video_bit_rate == 50000000) && (mxf->time_base.den != 25)) {
  2106.                     sc->index = 5;
  2107.                 } else if (sc->video_bit_rate == 40000000) {
  2108.                     if (mxf->time_base.den == 25) sc->index = 7;
  2109.                     else                          sc->index = 9;
  2110.                 } else if (sc->video_bit_rate == 30000000) {
  2111.                     if (mxf->time_base.den == 25) sc->index = 11;
  2112.                     else                          sc->index = 13;
  2113.                 } else {
  2114.                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
  2115.                     return -1;
  2116.                 }
  2117.  
  2118.                 mxf->edit_unit_byte_count = KAG_SIZE; // system element
  2119.                 mxf->edit_unit_byte_count += 16 + 4 + (uint64_t)sc->video_bit_rate *
  2120.                     mxf->time_base.num / (8*mxf->time_base.den);
  2121.                 mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
  2122.                 mxf->edit_unit_byte_count += 16 + 4 + 4 + spf->samples_per_frame[0]*8*4;
  2123.                 mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
  2124.  
  2125.                 sc->signal_standard = 1;
  2126.             }
  2127.             if (mxf->signal_standard >= 0)
  2128.                 sc->signal_standard = mxf->signal_standard;
  2129.         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  2130.             if (st->codec->sample_rate != 48000) {
  2131.                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
  2132.                 return -1;
  2133.             }
  2134.             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
  2135.             if (s->oformat == &ff_mxf_d10_muxer) {
  2136.                 if (st->index != 1) {
  2137.                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
  2138.                     return -1;
  2139.                 }
  2140.                 if (st->codec->codec_id != AV_CODEC_ID_PCM_S16LE &&
  2141.                     st->codec->codec_id != AV_CODEC_ID_PCM_S24LE) {
  2142.                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support 16 or 24 bits le audio\n");
  2143.                 }
  2144.                 sc->index = ((MXFStreamContext*)s->streams[0]->priv_data)->index + 1;
  2145.             } else if (s->oformat == &ff_mxf_opatom_muxer) {
  2146.                 AVRational tbc = av_inv_q(mxf->audio_edit_rate);
  2147.  
  2148.                 if (st->codec->codec_id != AV_CODEC_ID_PCM_S16LE &&
  2149.                     st->codec->codec_id != AV_CODEC_ID_PCM_S24LE) {
  2150.                     av_log(s, AV_LOG_ERROR, "Only pcm_s16le and pcm_s24le audio codecs are implemented\n");
  2151.                     return AVERROR_PATCHWELCOME;
  2152.                 }
  2153.                 if (st->codec->channels != 1) {
  2154.                     av_log(s, AV_LOG_ERROR, "MXF OPAtom only supports single channel audio\n");
  2155.                     return AVERROR(EINVAL);
  2156.                 }
  2157.  
  2158.                 spf = ff_mxf_get_samples_per_frame(s, tbc);
  2159.                 if (!spf){
  2160.                     av_log(s, AV_LOG_ERROR, "Unsupported timecode frame rate %d/%d\n", tbc.den, tbc.num);
  2161.                     return AVERROR(EINVAL);
  2162.                 }
  2163.  
  2164.                 mxf->time_base = st->time_base;
  2165.                 if((ret = mxf_init_timecode(s, st, av_inv_q(spf->time_base))) < 0)
  2166.                     return ret;
  2167.  
  2168.                 mxf->timecode_base = (tbc.den + tbc.num/2) / tbc.num;
  2169.                 mxf->edit_unit_byte_count = (av_get_bits_per_sample(st->codec->codec_id) * st->codec->channels) >> 3;
  2170.                 sc->index = 2;
  2171.             } else {
  2172.                 mxf->slice_count = 1;
  2173.             }
  2174.         }
  2175.  
  2176.         if (!sc->index) {
  2177.             sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
  2178.             if (sc->index == -1) {
  2179.                 av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
  2180.                        "codec not currently supported in container\n", i);
  2181.                 return -1;
  2182.             }
  2183.         }
  2184.  
  2185.         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
  2186.  
  2187.         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
  2188.         sc->track_essence_element_key[15] = present[sc->index];
  2189.         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
  2190.  
  2191.         if (!present[sc->index])
  2192.             mxf->essence_container_count++;
  2193.         present[sc->index]++;
  2194.     }
  2195.  
  2196.     if (s->oformat == &ff_mxf_d10_muxer || s->oformat == &ff_mxf_opatom_muxer) {
  2197.         mxf->essence_container_count = 1;
  2198.     }
  2199.  
  2200.     if (!(s->flags & AVFMT_FLAG_BITEXACT))
  2201.         mxf_gen_umid(s);
  2202.  
  2203.     for (i = 0; i < s->nb_streams; i++) {
  2204.         MXFStreamContext *sc = s->streams[i]->priv_data;
  2205.         // update element count
  2206.         sc->track_essence_element_key[13] = present[sc->index];
  2207.         if (!memcmp(sc->track_essence_element_key, mxf_essence_container_uls[15].element_ul, 13)) // DV
  2208.             sc->order = (0x15 << 24) | AV_RB32(sc->track_essence_element_key+13);
  2209.         else
  2210.             sc->order = AV_RB32(sc->track_essence_element_key+12);
  2211.     }
  2212.  
  2213.     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
  2214.         timestamp = ff_iso8601_to_unix_time(t->value);
  2215.     if (timestamp)
  2216.         mxf->timestamp = mxf_parse_timestamp(timestamp);
  2217.     mxf->duration = -1;
  2218.  
  2219.     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
  2220.     if (!mxf->timecode_track)
  2221.         return AVERROR(ENOMEM);
  2222.     mxf->timecode_track->priv_data = av_mallocz(sizeof(MXFStreamContext));
  2223.     if (!mxf->timecode_track->priv_data)
  2224.         return AVERROR(ENOMEM);
  2225.     mxf->timecode_track->index = -1;
  2226.  
  2227.     if (!spf)
  2228.         spf = ff_mxf_get_samples_per_frame(s, (AVRational){ 1, 25 });
  2229.  
  2230.     if (ff_audio_interleave_init(s, spf->samples_per_frame, mxf->time_base) < 0)
  2231.         return -1;
  2232.  
  2233.     return 0;
  2234. }
  2235.  
  2236. static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
  2237. static const uint8_t system_metadata_package_set_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x43,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x02,0x01 };
  2238.  
  2239. static void mxf_write_system_item(AVFormatContext *s)
  2240. {
  2241.     MXFContext *mxf = s->priv_data;
  2242.     AVIOContext *pb = s->pb;
  2243.     unsigned frame;
  2244.     uint32_t time_code;
  2245.  
  2246.     frame = mxf->last_indexed_edit_unit + mxf->edit_units_count;
  2247.  
  2248.     // write system metadata pack
  2249.     avio_write(pb, system_metadata_pack_key, 16);
  2250.     klv_encode_ber4_length(pb, 57);
  2251.     avio_w8(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
  2252.     avio_w8(pb, 0x04); // content package rate
  2253.     avio_w8(pb, 0x00); // content package type
  2254.     avio_wb16(pb, 0x00); // channel handle
  2255.     avio_wb16(pb, (mxf->tc.start + frame) & 0xFFFF); // continuity count, supposed to overflow
  2256.     if (mxf->essence_container_count > 1)
  2257.         avio_write(pb, multiple_desc_ul, 16);
  2258.     else {
  2259.         MXFStreamContext *sc = s->streams[0]->priv_data;
  2260.         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
  2261.     }
  2262.     avio_w8(pb, 0);
  2263.     avio_wb64(pb, 0);
  2264.     avio_wb64(pb, 0); // creation date/time stamp
  2265.  
  2266.     avio_w8(pb, 0x81); // SMPTE 12M time code
  2267.     time_code = av_timecode_get_smpte_from_framenum(&mxf->tc, frame);
  2268.     avio_wb32(pb, time_code);
  2269.     avio_wb32(pb, 0); // binary group data
  2270.     avio_wb64(pb, 0);
  2271.  
  2272.     // write system metadata package set
  2273.     avio_write(pb, system_metadata_package_set_key, 16);
  2274.     klv_encode_ber4_length(pb, 35);
  2275.     avio_w8(pb, 0x83); // UMID
  2276.     avio_wb16(pb, 0x20);
  2277.     mxf_write_umid(s, 1);
  2278. }
  2279.  
  2280. static void mxf_write_d10_video_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  2281. {
  2282.     MXFContext *mxf = s->priv_data;
  2283.     AVIOContext *pb = s->pb;
  2284.     MXFStreamContext *sc = st->priv_data;
  2285.     int packet_size = (uint64_t)sc->video_bit_rate*mxf->time_base.num /
  2286.         (8*mxf->time_base.den); // frame size
  2287.     int pad;
  2288.  
  2289.     packet_size += 16 + 4;
  2290.     packet_size += klv_fill_size(packet_size);
  2291.  
  2292.     klv_encode_ber4_length(pb, pkt->size);
  2293.     avio_write(pb, pkt->data, pkt->size);
  2294.  
  2295.     // ensure CBR muxing by padding to correct video frame size
  2296.     pad = packet_size - pkt->size - 16 - 4;
  2297.     if (pad > 20) {
  2298.         avio_write(s->pb, klv_fill_key, 16);
  2299.         pad -= 16 + 4;
  2300.         klv_encode_ber4_length(s->pb, pad);
  2301.         ffio_fill(s->pb, 0, pad);
  2302.         av_assert1(!(avio_tell(s->pb) & (KAG_SIZE-1)));
  2303.     } else {
  2304.         av_log(s, AV_LOG_WARNING, "cannot fill d-10 video packet\n");
  2305.         ffio_fill(s->pb, 0, pad);
  2306.     }
  2307. }
  2308.  
  2309. static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  2310. {
  2311.     MXFContext *mxf = s->priv_data;
  2312.     AVIOContext *pb = s->pb;
  2313.     int frame_size = pkt->size / st->codec->block_align;
  2314.     uint8_t *samples = pkt->data;
  2315.     uint8_t *end = pkt->data + pkt->size;
  2316.     int i;
  2317.  
  2318.     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
  2319.  
  2320.     avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
  2321.     avio_wl16(pb, frame_size);
  2322.     avio_w8(pb, (1<<st->codec->channels)-1);
  2323.  
  2324.     while (samples < end) {
  2325.         for (i = 0; i < st->codec->channels; i++) {
  2326.             uint32_t sample;
  2327.             if (st->codec->codec_id == AV_CODEC_ID_PCM_S24LE) {
  2328.                 sample = AV_RL24(samples)<< 4;
  2329.                 samples += 3;
  2330.             } else {
  2331.                 sample = AV_RL16(samples)<<12;
  2332.                 samples += 2;
  2333.             }
  2334.             avio_wl32(pb, sample | i);
  2335.         }
  2336.         for (; i < 8; i++)
  2337.             avio_wl32(pb, i);
  2338.     }
  2339. }
  2340.  
  2341. static int mxf_write_opatom_body_partition(AVFormatContext *s)
  2342. {
  2343.     MXFContext *mxf = s->priv_data;
  2344.     AVIOContext *pb = s->pb;
  2345.     AVStream *st = s->streams[0];
  2346.     MXFStreamContext *sc = st->priv_data;
  2347.     const uint8_t *key = NULL;
  2348.  
  2349.     int err;
  2350.  
  2351.     if (!mxf->header_written)
  2352.         key = body_partition_key;
  2353.  
  2354.     if ((err = mxf_write_partition(s, 1, 0, key, 0)) < 0)
  2355.         return err;
  2356.     mxf_write_klv_fill(s);
  2357.     avio_write(pb, sc->track_essence_element_key, 16);
  2358.     klv_encode_ber9_length(pb, mxf->body_offset);
  2359.     return 0;
  2360. }
  2361.  
  2362. static int mxf_write_opatom_packet(AVFormatContext *s, AVPacket *pkt, MXFIndexEntry *ie)
  2363. {
  2364.     MXFContext *mxf = s->priv_data;
  2365.     AVIOContext *pb = s->pb;
  2366.  
  2367.     int err;
  2368.  
  2369.     if (!mxf->header_written) {
  2370.         if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
  2371.             return err;
  2372.         mxf_write_klv_fill(s);
  2373.  
  2374.         if ((err = mxf_write_opatom_body_partition(s)) < 0)
  2375.             return err;
  2376.         mxf->header_written = 1;
  2377.     }
  2378.  
  2379.     if (!mxf->edit_unit_byte_count) {
  2380.         mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
  2381.         mxf->index_entries[mxf->edit_units_count].flags = ie->flags;
  2382.         mxf->index_entries[mxf->edit_units_count].temporal_ref = ie->temporal_ref;
  2383.     }
  2384.     mxf->edit_units_count++;
  2385.     avio_write(pb, pkt->data, pkt->size);
  2386.     mxf->body_offset += pkt->size;
  2387.     avio_flush(pb);
  2388.  
  2389.     return 0;
  2390. }
  2391.  
  2392. static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
  2393. {
  2394.     MXFContext *mxf = s->priv_data;
  2395.     AVIOContext *pb = s->pb;
  2396.     AVStream *st = s->streams[pkt->stream_index];
  2397.     MXFStreamContext *sc = st->priv_data;
  2398.     MXFIndexEntry ie = {0};
  2399.     int err;
  2400.  
  2401.     if (!mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
  2402.         if ((err = av_reallocp_array(&mxf->index_entries, mxf->edit_units_count
  2403.                                      + EDIT_UNITS_PER_BODY, sizeof(*mxf->index_entries))) < 0) {
  2404.             mxf->edit_units_count = 0;
  2405.             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
  2406.             return err;
  2407.         }
  2408.     }
  2409.  
  2410.     if (st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  2411.         if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
  2412.             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
  2413.             return -1;
  2414.         }
  2415.     } else if (st->codec->codec_id == AV_CODEC_ID_DNXHD) {
  2416.         if (!mxf_parse_dnxhd_frame(s, st, pkt)) {
  2417.             av_log(s, AV_LOG_ERROR, "could not get dnxhd profile\n");
  2418.             return -1;
  2419.         }
  2420.     } else if (st->codec->codec_id == AV_CODEC_ID_DVVIDEO) {
  2421.         if (!mxf_parse_dv_frame(s, st, pkt)) {
  2422.             av_log(s, AV_LOG_ERROR, "could not get dv profile\n");
  2423.             return -1;
  2424.         }
  2425.     } else if (st->codec->codec_id == AV_CODEC_ID_H264) {
  2426.         if (!mxf_parse_h264_frame(s, st, pkt, &ie)) {
  2427.             av_log(s, AV_LOG_ERROR, "could not get h264 profile\n");
  2428.             return -1;
  2429.         }
  2430.     }
  2431.  
  2432.     if (s->oformat == &ff_mxf_opatom_muxer)
  2433.         return mxf_write_opatom_packet(s, pkt, &ie);
  2434.  
  2435.     if (!mxf->header_written) {
  2436.         if (mxf->edit_unit_byte_count) {
  2437.             if ((err = mxf_write_partition(s, 1, 2, header_open_partition_key, 1)) < 0)
  2438.                 return err;
  2439.             mxf_write_klv_fill(s);
  2440.             mxf_write_index_table_segment(s);
  2441.         } else {
  2442.             if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
  2443.                 return err;
  2444.         }
  2445.         mxf->header_written = 1;
  2446.     }
  2447.  
  2448.     if (st->index == 0) {
  2449.         if (!mxf->edit_unit_byte_count &&
  2450.             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
  2451.             !(ie.flags & 0x33)) { // I frame, Gop start
  2452.             mxf_write_klv_fill(s);
  2453.             if ((err = mxf_write_partition(s, 1, 2, body_partition_key, 0)) < 0)
  2454.                 return err;
  2455.             mxf_write_klv_fill(s);
  2456.             mxf_write_index_table_segment(s);
  2457.         }
  2458.  
  2459.         mxf_write_klv_fill(s);
  2460.         mxf_write_system_item(s);
  2461.  
  2462.         if (!mxf->edit_unit_byte_count) {
  2463.             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
  2464.             mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
  2465.             mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
  2466.             mxf->body_offset += KAG_SIZE; // size of system element
  2467.         }
  2468.         mxf->edit_units_count++;
  2469.     } else if (!mxf->edit_unit_byte_count && st->index == 1) {
  2470.         if (!mxf->edit_units_count) {
  2471.             av_log(s, AV_LOG_ERROR, "No packets in first stream\n");
  2472.             return AVERROR_PATCHWELCOME;
  2473.         }
  2474.         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
  2475.             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
  2476.     }
  2477.  
  2478.     mxf_write_klv_fill(s);
  2479.     avio_write(pb, sc->track_essence_element_key, 16); // write key
  2480.     if (s->oformat == &ff_mxf_d10_muxer) {
  2481.         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2482.             mxf_write_d10_video_packet(s, st, pkt);
  2483.         else
  2484.             mxf_write_d10_audio_packet(s, st, pkt);
  2485.     } else {
  2486.         klv_encode_ber4_length(pb, pkt->size); // write length
  2487.         avio_write(pb, pkt->data, pkt->size);
  2488.         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
  2489.     }
  2490.  
  2491.     avio_flush(pb);
  2492.  
  2493.     return 0;
  2494. }
  2495.  
  2496. static void mxf_write_random_index_pack(AVFormatContext *s)
  2497. {
  2498.     MXFContext *mxf = s->priv_data;
  2499.     AVIOContext *pb = s->pb;
  2500.     uint64_t pos = avio_tell(pb);
  2501.     int i;
  2502.  
  2503.     avio_write(pb, random_index_pack_key, 16);
  2504.     klv_encode_ber_length(pb, 28 + 12LL*mxf->body_partitions_count);
  2505.  
  2506.     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer)
  2507.         avio_wb32(pb, 1); // BodySID of header partition
  2508.     else
  2509.         avio_wb32(pb, 0);
  2510.     avio_wb64(pb, 0); // offset of header partition
  2511.  
  2512.     for (i = 0; i < mxf->body_partitions_count; i++) {
  2513.         avio_wb32(pb, 1); // BodySID
  2514.         avio_wb64(pb, mxf->body_partition_offset[i]);
  2515.     }
  2516.  
  2517.     avio_wb32(pb, 0); // BodySID of footer partition
  2518.     avio_wb64(pb, mxf->footer_partition_offset);
  2519.  
  2520.     avio_wb32(pb, avio_tell(pb) - pos + 4);
  2521. }
  2522.  
  2523. static int mxf_write_footer(AVFormatContext *s)
  2524. {
  2525.     MXFContext *mxf = s->priv_data;
  2526.     AVIOContext *pb = s->pb;
  2527.     int err = 0;
  2528.  
  2529.     if (!mxf->header_written ||
  2530.         (s->oformat == &ff_mxf_opatom_muxer && !mxf->body_partition_offset)) {
  2531.         /* reason could be invalid options/not supported codec/out of memory */
  2532.         err = AVERROR_UNKNOWN;
  2533.         goto end;
  2534.     }
  2535.  
  2536.     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
  2537.  
  2538.     mxf_write_klv_fill(s);
  2539.     mxf->footer_partition_offset = avio_tell(pb);
  2540.     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) { // no need to repeat index
  2541.         if ((err = mxf_write_partition(s, 0, 0, footer_partition_key, 0)) < 0)
  2542.             goto end;
  2543.     } else {
  2544.         if ((err = mxf_write_partition(s, 0, 2, footer_partition_key, 0)) < 0)
  2545.             goto end;
  2546.         mxf_write_klv_fill(s);
  2547.         mxf_write_index_table_segment(s);
  2548.     }
  2549.  
  2550.     mxf_write_klv_fill(s);
  2551.     mxf_write_random_index_pack(s);
  2552.  
  2553.     if (s->pb->seekable) {
  2554.         if (s->oformat == &ff_mxf_opatom_muxer){
  2555.             /* rewrite body partition to update lengths */
  2556.             avio_seek(pb, mxf->body_partition_offset[0], SEEK_SET);
  2557.             if ((err = mxf_write_opatom_body_partition(s)) < 0)
  2558.                 goto end;
  2559.         }
  2560.  
  2561.         avio_seek(pb, 0, SEEK_SET);
  2562.         if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) {
  2563.             if ((err = mxf_write_partition(s, 1, 2, header_closed_partition_key, 1)) < 0)
  2564.                 goto end;
  2565.             mxf_write_klv_fill(s);
  2566.             mxf_write_index_table_segment(s);
  2567.         } else {
  2568.             if ((err = mxf_write_partition(s, 0, 0, header_closed_partition_key, 1)) < 0)
  2569.                 goto end;
  2570.         }
  2571.     }
  2572.  
  2573. end:
  2574.     ff_audio_interleave_close(s);
  2575.  
  2576.     av_freep(&mxf->index_entries);
  2577.     av_freep(&mxf->body_partition_offset);
  2578.     av_freep(&mxf->timecode_track->priv_data);
  2579.     av_freep(&mxf->timecode_track);
  2580.  
  2581.     mxf_free(s);
  2582.  
  2583.     return err < 0 ? err : 0;
  2584. }
  2585.  
  2586. static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
  2587. {
  2588.     int i, stream_count = 0;
  2589.  
  2590.     for (i = 0; i < s->nb_streams; i++)
  2591.         stream_count += !!s->streams[i]->last_in_packet_buffer;
  2592.  
  2593.     if (stream_count && (s->nb_streams == stream_count || flush)) {
  2594.         AVPacketList *pktl = s->internal->packet_buffer;
  2595.         if (s->nb_streams != stream_count) {
  2596.             AVPacketList *last = NULL;
  2597.             // find last packet in edit unit
  2598.             while (pktl) {
  2599.                 if (!stream_count || pktl->pkt.stream_index == 0)
  2600.                     break;
  2601.                 last = pktl;
  2602.                 pktl = pktl->next;
  2603.                 stream_count--;
  2604.             }
  2605.             // purge packet queue
  2606.             while (pktl) {
  2607.                 AVPacketList *next = pktl->next;
  2608.  
  2609.                 if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
  2610.                     s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
  2611.                 av_free_packet(&pktl->pkt);
  2612.                 av_freep(&pktl);
  2613.                 pktl = next;
  2614.             }
  2615.             if (last)
  2616.                 last->next = NULL;
  2617.             else {
  2618.                 s->internal->packet_buffer = NULL;
  2619.                 s->internal->packet_buffer_end= NULL;
  2620.                 goto out;
  2621.             }
  2622.             pktl = s->internal->packet_buffer;
  2623.         }
  2624.  
  2625.         *out = pktl->pkt;
  2626.         av_log(s, AV_LOG_TRACE, "out st:%d dts:%"PRId64"\n", (*out).stream_index, (*out).dts);
  2627.         s->internal->packet_buffer = pktl->next;
  2628.         if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
  2629.             s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
  2630.         if(!s->internal->packet_buffer)
  2631.             s->internal->packet_buffer_end= NULL;
  2632.         av_freep(&pktl);
  2633.         return 1;
  2634.     } else {
  2635.     out:
  2636.         av_init_packet(out);
  2637.         return 0;
  2638.     }
  2639. }
  2640.  
  2641. static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
  2642. {
  2643.     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
  2644.     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
  2645.  
  2646.     return next->dts > pkt->dts ||
  2647.         (next->dts == pkt->dts && sc->order < sc2->order);
  2648. }
  2649.  
  2650. static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
  2651. {
  2652.     return ff_audio_rechunk_interleave(s, out, pkt, flush,
  2653.                                mxf_interleave_get_packet, mxf_compare_timestamps);
  2654. }
  2655.  
  2656. #define MXF_COMMON_OPTIONS \
  2657.     { "signal_standard", "Force/set Sigal Standard",\
  2658.       offsetof(MXFContext, signal_standard), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
  2659.     { "bt601", "ITU-R BT.601 and BT.656, also SMPTE 125M (525 and 625 line interlaced)",\
  2660.       0, AV_OPT_TYPE_CONST, {.i64 = 1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
  2661.     { "bt1358", "ITU-R BT.1358 and ITU-R BT.799-3, also SMPTE 293M (525 and 625 line progressive)",\
  2662.       0, AV_OPT_TYPE_CONST, {.i64 = 2}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
  2663.     { "smpte347m", "SMPTE 347M (540 Mbps mappings)",\
  2664.       0, AV_OPT_TYPE_CONST, {.i64 = 3}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
  2665.     { "smpte274m", "SMPTE 274M (1125 line)",\
  2666.       0, AV_OPT_TYPE_CONST, {.i64 = 4}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
  2667.     { "smpte296m", "SMPTE 296M (750 line progressive)",\
  2668.       0, AV_OPT_TYPE_CONST, {.i64 = 5}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
  2669.     { "smpte349m", "SMPTE 349M (1485 Mbps mappings)",\
  2670.       0, AV_OPT_TYPE_CONST, {.i64 = 6}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
  2671.     { "smpte428", "SMPTE 428-1 DCDM",\
  2672.       0, AV_OPT_TYPE_CONST, {.i64 = 7}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},
  2673.  
  2674.  
  2675.  
  2676. static const AVOption mxf_options[] = {
  2677.     MXF_COMMON_OPTIONS
  2678.     { "store_user_comments", "",
  2679.       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  2680.     { NULL },
  2681. };
  2682.  
  2683. static const AVClass mxf_muxer_class = {
  2684.     .class_name     = "MXF muxer",
  2685.     .item_name      = av_default_item_name,
  2686.     .option         = mxf_options,
  2687.     .version        = LIBAVUTIL_VERSION_INT,
  2688. };
  2689.  
  2690. static const AVOption d10_options[] = {
  2691.     { "d10_channelcount", "Force/set channelcount in generic sound essence descriptor",
  2692.       offsetof(MXFContext, channel_count), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 8, AV_OPT_FLAG_ENCODING_PARAM},
  2693.     MXF_COMMON_OPTIONS
  2694.     { "store_user_comments", "",
  2695.       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  2696.     { NULL },
  2697. };
  2698.  
  2699. static const AVClass mxf_d10_muxer_class = {
  2700.     .class_name     = "MXF-D10 muxer",
  2701.     .item_name      = av_default_item_name,
  2702.     .option         = d10_options,
  2703.     .version        = LIBAVUTIL_VERSION_INT,
  2704. };
  2705.  
  2706. static const AVOption opatom_options[] = {
  2707.     { "mxf_audio_edit_rate", "Audio edit rate for timecode",
  2708.         offsetof(MXFContext, audio_edit_rate), AV_OPT_TYPE_RATIONAL, {.dbl=25}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
  2709.     MXF_COMMON_OPTIONS
  2710.     { NULL },
  2711. };
  2712.  
  2713. static const AVClass mxf_opatom_muxer_class = {
  2714.     .class_name     = "MXF-OPAtom muxer",
  2715.     .item_name      = av_default_item_name,
  2716.     .option         = opatom_options,
  2717.     .version        = LIBAVUTIL_VERSION_INT,
  2718. };
  2719.  
  2720. AVOutputFormat ff_mxf_muxer = {
  2721.     .name              = "mxf",
  2722.     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
  2723.     .mime_type         = "application/mxf",
  2724.     .extensions        = "mxf",
  2725.     .priv_data_size    = sizeof(MXFContext),
  2726.     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
  2727.     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
  2728.     .write_header      = mxf_write_header,
  2729.     .write_packet      = mxf_write_packet,
  2730.     .write_trailer     = mxf_write_footer,
  2731.     .flags             = AVFMT_NOTIMESTAMPS,
  2732.     .interleave_packet = mxf_interleave,
  2733.     .priv_class        = &mxf_muxer_class,
  2734. };
  2735.  
  2736. AVOutputFormat ff_mxf_d10_muxer = {
  2737.     .name              = "mxf_d10",
  2738.     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) D-10 Mapping"),
  2739.     .mime_type         = "application/mxf",
  2740.     .priv_data_size    = sizeof(MXFContext),
  2741.     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
  2742.     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
  2743.     .write_header      = mxf_write_header,
  2744.     .write_packet      = mxf_write_packet,
  2745.     .write_trailer     = mxf_write_footer,
  2746.     .flags             = AVFMT_NOTIMESTAMPS,
  2747.     .interleave_packet = mxf_interleave,
  2748.     .priv_class        = &mxf_d10_muxer_class,
  2749. };
  2750.  
  2751. AVOutputFormat ff_mxf_opatom_muxer = {
  2752.     .name              = "mxf_opatom",
  2753.     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) Operational Pattern Atom"),
  2754.     .mime_type         = "application/mxf",
  2755.     .extensions        = "mxf",
  2756.     .priv_data_size    = sizeof(MXFContext),
  2757.     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
  2758.     .video_codec       = AV_CODEC_ID_DNXHD,
  2759.     .write_header      = mxf_write_header,
  2760.     .write_packet      = mxf_write_packet,
  2761.     .write_trailer     = mxf_write_footer,
  2762.     .flags             = AVFMT_NOTIMESTAMPS,
  2763.     .interleave_packet = mxf_interleave,
  2764.     .priv_class        = &mxf_opatom_muxer_class,
  2765. };
  2766.