]> git.sesse.net Git - ffmpeg/blob - libavformat/mxfenc.c
avformat/mxf: Establish register of local tags
[ffmpeg] / libavformat / mxfenc.c
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
23 /*
24  * signal_standard, color_siting, store_user_comments, sample rate and klv_fill_key version
25  * fixes sponsored by NOA GmbH
26  */
27
28 /*
29  * References
30  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
31  * SMPTE 377M MXF File Format Specifications
32  * SMPTE 379M MXF Generic Container
33  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
34  * SMPTE 422M Mapping JPEG 2000 Codestreams into the MXF Generic Container
35  * SMPTE RP210: SMPTE Metadata Dictionary
36  * SMPTE RP224: Registry of SMPTE Universal Labels
37  */
38
39 #include <inttypes.h>
40 #include <math.h>
41 #include <time.h>
42
43 #include "libavutil/opt.h"
44 #include "libavutil/random_seed.h"
45 #include "libavutil/timecode.h"
46 #include "libavutil/avassert.h"
47 #include "libavutil/mastering_display_metadata.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/time_internal.h"
50 #include "libavcodec/bytestream.h"
51 #include "libavcodec/dnxhddata.h"
52 #include "libavcodec/dv_profile.h"
53 #include "libavcodec/h264_ps.h"
54 #include "libavcodec/golomb.h"
55 #include "libavcodec/internal.h"
56 #include "avformat.h"
57 #include "avio_internal.h"
58 #include "internal.h"
59 #include "avc.h"
60 #include "mxf.h"
61 #include "config.h"
62
63 extern AVOutputFormat ff_mxf_d10_muxer;
64 extern AVOutputFormat ff_mxf_opatom_muxer;
65
66 #define EDIT_UNITS_PER_BODY 250
67 #define KAG_SIZE 512
68
69 typedef struct MXFIndexEntry {
70     uint64_t offset;
71     unsigned slice_offset; ///< offset of audio slice
72     uint16_t temporal_ref;
73     uint8_t flags;
74 } MXFIndexEntry;
75
76 typedef struct MXFStreamContext {
77     int64_t pkt_cnt;         ///< pkt counter for muxed packets
78     UID track_essence_element_key;
79     int index;               ///< index in mxf_essence_container_uls table
80     const UID *codec_ul;
81     const UID *container_ul;
82     int order;               ///< interleaving order if dts are equal
83     int interlaced;          ///< whether picture is interlaced
84     int field_dominance;     ///< tff=1, bff=2
85     int component_depth;
86     int color_siting;
87     int signal_standard;
88     int h_chroma_sub_sample;
89     int v_chroma_sub_sample;
90     int temporal_reordering;
91     AVRational aspect_ratio; ///< display aspect ratio
92     int closed_gop;          ///< gop is closed, used in mpeg-2 frame parsing
93     int video_bit_rate;
94     int slice_offset;
95     int frame_size;          ///< frame size in bytes
96     int seq_closed_gop;      ///< all gops in sequence are closed, used in mpeg-2 descriptor
97     int max_gop;             ///< maximum gop size, used by mpeg-2 descriptor
98     int b_picture_count;     ///< maximum number of consecutive b pictures, used in mpeg-2 descriptor
99     int low_delay;           ///< low delay, used in mpeg-2 descriptor
100     int avc_intra;
101 } MXFStreamContext;
102
103 typedef struct MXFContainerEssenceEntry {
104     UID container_ul;
105     UID element_ul;
106     UID codec_ul;
107     void (*write_desc)(AVFormatContext *, AVStream *);
108 } MXFContainerEssenceEntry;
109
110 typedef struct MXFPackage {
111     char *name;
112     enum MXFMetadataSetType type;
113     int instance;
114     struct MXFPackage *ref;
115 } MXFPackage;
116
117 enum ULIndex {
118     INDEX_MPEG2 = 0,
119     INDEX_AES3,
120     INDEX_WAV,
121     INDEX_D10_VIDEO,
122     INDEX_D10_AUDIO,
123     INDEX_DV,
124     INDEX_DNXHD,
125     INDEX_JPEG2000,
126     INDEX_H264,
127     INDEX_S436M,
128     INDEX_PRORES,
129 };
130
131 static const struct {
132     enum AVCodecID id;
133     enum ULIndex index;
134 } mxf_essence_mappings[] = {
135     { AV_CODEC_ID_MPEG2VIDEO, INDEX_MPEG2 },
136     { AV_CODEC_ID_PCM_S24LE,  INDEX_AES3 },
137     { AV_CODEC_ID_PCM_S16LE,  INDEX_AES3 },
138     { AV_CODEC_ID_DVVIDEO,    INDEX_DV },
139     { AV_CODEC_ID_DNXHD,      INDEX_DNXHD },
140     { AV_CODEC_ID_JPEG2000,   INDEX_JPEG2000 },
141     { AV_CODEC_ID_H264,       INDEX_H264 },
142     { AV_CODEC_ID_PRORES,     INDEX_PRORES },
143     { AV_CODEC_ID_NONE }
144 };
145
146 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
147 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
148 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
149 static void mxf_write_h264_desc(AVFormatContext *s, AVStream *st);
150 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st);
151 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st);
152 static void mxf_write_s436m_anc_desc(AVFormatContext *s, AVStream *st);
153
154 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
155     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
156       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
157       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
158       mxf_write_mpegvideo_desc },
159     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
160       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
161       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
162       mxf_write_aes3_desc },
163     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
164       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
165       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
166       mxf_write_wav_desc },
167     // D-10 Video
168     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
169       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
170       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 },
171       mxf_write_cdci_desc },
172     // D-10 Audio
173     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
174       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
175       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
176       mxf_write_generic_sound_desc },
177     // DV
178     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x7F,0x01 },
179       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
180       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x00,0x00,0x00 },
181       mxf_write_cdci_desc },
182     // DNxHD
183     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
184       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
185       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 },
186       mxf_write_cdci_desc },
187     // JPEG2000
188     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 },
189       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x08,0x00 },
190       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 },
191       mxf_write_cdci_desc },
192     // H.264
193     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x10,0x60,0x01 },
194       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
195       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
196       mxf_write_h264_desc },
197     // S436M ANC
198     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 },
199       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x17,0x01,0x02,0x00 },
200       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x01,0x5C,0x00 },
201       mxf_write_s436m_anc_desc },
202     // ProRes
203     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 },
204       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x17,0x00 },
205       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 },
206       mxf_write_cdci_desc },
207     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
208       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
209       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
210       NULL },
211 };
212
213 static const UID mxf_d10_codec_uls[] = {
214     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 }, // D-10 625/50 PAL 50mb/s
215     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x02 }, // D-10 525/50 NTSC 50mb/s
216     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x03 }, // D-10 625/50 PAL 40mb/s
217     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x04 }, // D-10 525/50 NTSC 40mb/s
218     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 }, // D-10 625/50 PAL 30mb/s
219     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x06 }, // D-10 525/50 NTSC 30mb/s
220 };
221
222 static const UID mxf_d10_container_uls[] = {
223     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, // D-10 625/50 PAL 50mb/s
224     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 }, // D-10 525/50 NTSC 50mb/s
225     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 }, // D-10 625/50 PAL 40mb/s
226     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, // D-10 525/50 NTSC 40mb/s
227     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 }, // D-10 625/50 PAL 30mb/s
228     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 }, // D-10 525/50 NTSC 30mb/s
229 };
230
231 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
232 static const uint8_t umid_ul[]              = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13 };
233
234 /**
235  * complete key for operation pattern, partitions, and primer pack
236  */
237 static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x09,0x00 };
238 static const uint8_t opatom_ul[]                   = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x02,0x01,0x10,0x03,0x00,0x00 };
239 static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
240 static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
241 static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
242 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
243 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
244 static const uint8_t klv_fill_key[]                = { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x10,0x01,0x00,0x00,0x00 };
245 static const uint8_t body_partition_key[]          = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }; // ClosedComplete
246
247 /**
248  * partial key for header metadata
249  */
250 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
251 static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
252
253 /**
254  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
255  *             https://smpte-ra.org/sites/default/files/Labels.xml
256  */
257 static const MXFLocalTagPair mxf_local_tag_batch[] = {
258     // preface set
259     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
260     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
261     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
262     { 0x3B07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x04,0x00,0x00,0x00}}, /* Object Model Version */
263     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
264     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
265     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
266     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
267     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
268     // Identification
269     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
270     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
271     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
272     { 0x3C03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x04,0x00,0x00,0x00}}, /* Product Version */
273     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
274     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
275     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
276     { 0x3C07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x0A,0x00,0x00,0x00}}, /* Toolkit Version */
277     { 0x3C08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x06,0x01,0x00,0x00}}, /* Platform */
278     // Content Storage
279     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
280     { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
281     // Essence Container Data
282     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
283     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
284     // Package
285     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
286     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
287     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
288     { 0x4402, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x03,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Package Name */
289     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
290     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
291     // Track
292     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
293     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
294     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
295     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
296     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
297     // Sequence
298     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
299     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
300     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
301     // Source Clip
302     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
303     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
304     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
305     // Timecode Component
306     { 0x1501, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x05,0x00,0x00}}, /* Start Time Code */
307     { 0x1502, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x04,0x01,0x01,0x02,0x06,0x00,0x00}}, /* Rounded Time Code Base */
308     { 0x1503, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x04,0x01,0x01,0x05,0x00,0x00,0x00}}, /* Drop Frame */
309     // File Descriptor
310     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
311     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
312     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
313     { 0x3002, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x02,0x00,0x00,0x00,0x00}}, /* ContainerDuration */
314     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
315     // Generic Picture Essence Descriptor
316     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
317     { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
318     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
319     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
320     { 0x3216, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x03,0x02,0x08,0x00,0x00,0x00}}, /* Stored F2 Offset */
321     { 0x3205, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x08,0x00,0x00,0x00}}, /* Sampled Width */
322     { 0x3204, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x07,0x00,0x00,0x00}}, /* Sampled Height */
323     { 0x3206, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x09,0x00,0x00,0x00}}, /* Sampled X Offset */
324     { 0x3207, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0A,0x00,0x00,0x00}}, /* Sampled Y Offset */
325     { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
326     { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
327     { 0x320A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0D,0x00,0x00,0x00}}, /* Display X offset */
328     { 0x320B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0E,0x00,0x00,0x00}}, /* Presentation Y offset */
329     { 0x3217, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x03,0x02,0x07,0x00,0x00,0x00}}, /* Display F2 offset */
330     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
331     { 0x3210, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x02,0x01,0x01,0x01,0x02,0x00}}, /* Transfer characteristic */
332     { 0x321A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x02,0x01,0x01,0x03,0x01,0x00}}, /* Coding Equations (color space) */
333     { 0x3219, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x09,0x04,0x01,0x02,0x01,0x01,0x06,0x01,0x00}}, /* Color Primaries */
334     { 0x3213, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x02,0x00,0x00,0x00,0x00}}, /* Image Start Offset */
335     { 0x3214, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Image End Offset */
336     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
337     { 0x3212, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x01,0x06,0x00,0x00,0x00}}, /* Field Dominance (Opt) */
338     { 0x3215, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x05,0x01,0x13,0x00,0x00,0x00,0x00}}, /* Signal Standard */
339     // CDCI Picture Essence Descriptor
340     { 0x3301, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x0A,0x00,0x00,0x00}}, /* Component Depth */
341     { 0x3302, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x05,0x00,0x00,0x00}}, /* Horizontal Subsampling */
342     { 0x3308, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x01,0x10,0x00,0x00,0x00}}, /* Vertical Subsampling */
343     { 0x3303, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x06,0x00,0x00,0x00}}, /* Color Siting */
344     { 0x3307, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x04,0x00,0x00,0x00,0x00}}, /* Padding Bits */
345     { 0x3304, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x03,0x03,0x00,0x00,0x00}}, /* Black Ref level */
346     { 0x3305, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x03,0x04,0x00,0x00,0x00}}, /* White Ref level */
347     { 0x3306, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x05,0x00,0x00,0x00}}, /* Color Range */
348     // Generic Sound Essence Descriptor
349     { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
350     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
351     { 0x3D04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x02,0x01,0x01,0x03,0x00,0x00,0x00}}, /* Audio Ref Level */
352     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
353     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
354     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
355     // Index Table Segment
356     { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
357     { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
358     { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
359     { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
360     { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
361     { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
362     { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
363     { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
364     // MPEG video Descriptor
365     { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
366     { 0x8003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x05,0x00,0x00}}, /* LowDelay */
367     { 0x8004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x06,0x00,0x00}}, /* ClosedGOP */
368     { 0x8006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x08,0x00,0x00}}, /* MaxGOP */
369     { 0x8007, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0A,0x00,0x00}}, /* ProfileAndLevel */
370     { 0x8008, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x09,0x00,0x00}}, /* BPictureCount */
371     // Wave Audio Essence Descriptor
372     { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
373     { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
374     // mxf_user_comments_local_tag
375     { 0x4406, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0C,0x00,0x00,0x00}}, /* User Comments */
376     { 0x5001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x09,0x01,0x00,0x00}}, /* Name */
377     { 0x5003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0A,0x01,0x00,0x00}}, /* Value */
378     // mxf_avc_subdescriptor_local_tags
379     { 0x8100, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x04,0x06,0x10,0x00,0x00}}, /* SubDescriptors */
380     { 0x8200, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x0E,0x04,0x01,0x06,0x06,0x01,0x0E,0x00,0x00}}, /* AVC Decoding Delay */
381     { 0x8201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x0E,0x04,0x01,0x06,0x06,0x01,0x0A,0x00,0x00}}, /* AVC Profile */
382     { 0x8202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x0E,0x04,0x01,0x06,0x06,0x01,0x0D,0x00,0x00}}, /* AVC Level */
383     // ff_mxf_mastering_display_local_tags
384     { 0x8301, FF_MXF_MasteringDisplayPrimaries },
385     { 0x8302, FF_MXF_MasteringDisplayWhitePointChromaticity },
386     { 0x8303, FF_MXF_MasteringDisplayMaximumLuminance },
387     { 0x8304, FF_MXF_MasteringDisplayMinimumLuminance },
388 };
389
390 #define MXF_NUM_TAGS FF_ARRAY_ELEMS(mxf_local_tag_batch)
391
392 typedef struct MXFContext {
393     AVClass *av_class;
394     int64_t footer_partition_offset;
395     int essence_container_count;
396     AVRational time_base;
397     int header_written;
398     MXFIndexEntry *index_entries;
399     unsigned edit_units_count;
400     uint64_t timestamp;   ///< timestamp, as year(16),month(8),day(8),hour(8),minutes(8),msec/4(8)
401     uint8_t slice_count;  ///< index slice count minus 1 (1 if no audio, 0 otherwise)
402     int last_indexed_edit_unit;
403     uint64_t *body_partition_offset;
404     unsigned body_partitions_count;
405     int last_key_index;  ///< index of last key frame
406     uint64_t duration;
407     AVTimecode tc;       ///< timecode context
408     AVStream *timecode_track;
409     int timecode_base;       ///< rounded time code base (25 or 30)
410     int edit_unit_byte_count; ///< fixed edit unit byte count
411     int content_package_rate; ///< content package rate in system element, see SMPTE 326M
412     uint64_t body_offset;
413     uint32_t instance_number;
414     uint8_t umid[16];        ///< unique material identifier
415     int channel_count;
416     int signal_standard;
417     uint32_t tagged_value_count;
418     AVRational audio_edit_rate;
419     int store_user_comments;
420     int track_instance_count; // used to generate MXFTrack uuids
421     int cbr_index;           ///< use a constant bitrate index
422     uint8_t unused_tags[MXF_NUM_TAGS];  ///< local tags that we know will not be used
423 } MXFContext;
424
425 static void mxf_write_uuid(AVIOContext *pb, enum MXFMetadataSetType type, int value)
426 {
427     avio_write(pb, uuid_base, 12);
428     avio_wb16(pb, type);
429     avio_wb16(pb, value);
430 }
431
432 static void mxf_write_umid(AVFormatContext *s, int type)
433 {
434     MXFContext *mxf = s->priv_data;
435     avio_write(s->pb, umid_ul, 13);
436     avio_wb24(s->pb, mxf->instance_number);
437     avio_write(s->pb, mxf->umid, 15);
438     avio_w8(s->pb, type);
439 }
440
441 static void mxf_write_refs_count(AVIOContext *pb, int ref_count)
442 {
443     avio_wb32(pb, ref_count);
444     avio_wb32(pb, 16);
445 }
446
447 static int klv_ber_length(uint64_t len)
448 {
449     if (len < 128)
450         return 1;
451     else
452         return (av_log2(len) >> 3) + 2;
453 }
454
455 static int klv_encode_ber_length(AVIOContext *pb, uint64_t len)
456 {
457     // Determine the best BER size
458     int size = klv_ber_length(len);
459     if (size == 1) {
460         //short form
461         avio_w8(pb, len);
462         return 1;
463     }
464
465     size --;
466     // long form
467     avio_w8(pb, 0x80 + size);
468     while(size) {
469         size--;
470         avio_w8(pb, len >> 8 * size & 0xff);
471     }
472     return 0;
473 }
474
475 static void klv_encode_ber4_length(AVIOContext *pb, int len)
476 {
477     avio_w8(pb, 0x80 + 3);
478     avio_wb24(pb, len);
479 }
480
481 static void klv_encode_ber9_length(AVIOContext *pb, uint64_t len)
482 {
483     avio_w8(pb, 0x80 + 8);
484     avio_wb64(pb, len);
485 }
486
487 /*
488  * Get essence container ul index
489  */
490 static int mxf_get_essence_container_ul_index(enum AVCodecID id)
491 {
492     int i;
493     for (i = 0; mxf_essence_mappings[i].id; i++)
494         if (mxf_essence_mappings[i].id == id)
495             return mxf_essence_mappings[i].index;
496     return -1;
497 }
498
499 static const MXFLocalTagPair* mxf_lookup_local_tag(int tag)
500 {
501     for (int i = 0; i < MXF_NUM_TAGS; i++) {
502         if (mxf_local_tag_batch[i].local_tag == tag) {
503             return &mxf_local_tag_batch[i];
504         }
505     }
506
507     // this assert can only be hit during development
508     av_assert0(0 && "you forgot to add your new tag to mxf_local_tag_batch");
509 }
510
511 static void mxf_mark_tag_unused(MXFContext *mxf, int tag)
512 {
513     const MXFLocalTagPair *pair = mxf_lookup_local_tag(tag);
514     mxf->unused_tags[pair - mxf_local_tag_batch] = 1;
515 }
516
517 static void mxf_write_primer_pack(AVFormatContext *s)
518 {
519     MXFContext *mxf = s->priv_data;
520     AVIOContext *pb = s->pb;
521     int local_tag_number = MXF_NUM_TAGS, i;
522     int will_have_avc_tags = 0, will_have_mastering_tags = 0;
523
524     for (i = 0; i < s->nb_streams; i++) {
525         MXFStreamContext *sc = s->streams[i]->priv_data;
526         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_H264 && !sc->avc_intra) {
527             will_have_avc_tags = 1;
528         }
529         if (av_stream_get_side_data(s->streams[i], AV_PKT_DATA_MASTERING_DISPLAY_METADATA, NULL)) {
530             will_have_mastering_tags = 1;
531         }
532     }
533
534     if (!mxf->store_user_comments) {
535         mxf_mark_tag_unused(mxf, 0x4406);
536         mxf_mark_tag_unused(mxf, 0x5001);
537         mxf_mark_tag_unused(mxf, 0x5003);
538     }
539
540     if (!will_have_avc_tags) {
541         mxf_mark_tag_unused(mxf, 0x8100);
542         mxf_mark_tag_unused(mxf, 0x8200);
543         mxf_mark_tag_unused(mxf, 0x8201);
544         mxf_mark_tag_unused(mxf, 0x8202);
545     }
546
547     if (!will_have_mastering_tags) {
548         mxf_mark_tag_unused(mxf, 0x8301);
549         mxf_mark_tag_unused(mxf, 0x8302);
550         mxf_mark_tag_unused(mxf, 0x8303);
551         mxf_mark_tag_unused(mxf, 0x8304);
552     }
553
554     for (i = 0; i < MXF_NUM_TAGS; i++) {
555         if (mxf->unused_tags[i]) {
556             local_tag_number--;
557         }
558     }
559
560     avio_write(pb, primer_pack_key, 16);
561     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
562
563     avio_wb32(pb, local_tag_number); // local_tag num
564     avio_wb32(pb, 18); // item size, always 18 according to the specs
565
566     for (i = 0; i < MXF_NUM_TAGS; i++) {
567         if (mxf->unused_tags[i] == 0) {
568             avio_wb16(pb, mxf_local_tag_batch[i].local_tag);
569             avio_write(pb, mxf_local_tag_batch[i].uid, 16);
570         }
571     }
572 }
573
574 static void mxf_write_local_tag(AVFormatContext *s, int size, int tag)
575 {
576     MXFContext *mxf = s->priv_data;
577     AVIOContext *pb = s->pb;
578     const MXFLocalTagPair *pair = mxf_lookup_local_tag(tag);
579
580     // make sure the tag was not declared unnecessary upfront
581     av_assert0(mxf->unused_tags[pair - mxf_local_tag_batch] == 0);
582
583     avio_wb16(pb, tag);
584     avio_wb16(pb, size);
585 }
586
587 static void mxf_write_metadata_key(AVIOContext *pb, unsigned int value)
588 {
589     avio_write(pb, header_metadata_key, 13);
590     avio_wb24(pb, value);
591 }
592
593 static const MXFCodecUL *mxf_get_codec_ul_by_id(const MXFCodecUL *uls, int id)
594 {
595     while (uls->uid[0]) {
596         if (id == uls->id)
597             break;
598         uls++;
599     }
600     return uls;
601 }
602
603 //one EC -> one descriptor. N ECs -> MultipleDescriptor + N descriptors
604 #define DESCRIPTOR_COUNT(essence_container_count) \
605     (essence_container_count > 1 ? essence_container_count + 1 : essence_container_count)
606
607 static void mxf_write_essence_container_refs(AVFormatContext *s)
608 {
609     MXFContext *c = s->priv_data;
610     AVIOContext *pb = s->pb;
611     int i;
612
613     mxf_write_refs_count(pb, DESCRIPTOR_COUNT(c->essence_container_count));
614     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
615     for (i = 0; i < s->nb_streams; i++) {
616         MXFStreamContext *sc = s->streams[i]->priv_data;
617         // check first track of essence container type and only write it once
618         if (sc->track_essence_element_key[15] != 0)
619             continue;
620         avio_write(pb, *sc->container_ul, 16);
621         if (c->essence_container_count == 1)
622             break;
623     }
624
625     if (c->essence_container_count > 1)
626         avio_write(pb, multiple_desc_ul, 16);
627 }
628
629 static void mxf_write_preface(AVFormatContext *s)
630 {
631     MXFContext *mxf = s->priv_data;
632     AVIOContext *pb = s->pb;
633
634     mxf_write_metadata_key(pb, 0x012f00);
635     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
636     klv_encode_ber_length(pb, 138 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
637
638     // write preface set uid
639     mxf_write_local_tag(s, 16, 0x3C0A);
640     mxf_write_uuid(pb, Preface, 0);
641     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
642
643     // last modified date
644     mxf_write_local_tag(s, 8, 0x3B02);
645     avio_wb64(pb, mxf->timestamp);
646
647     // write version
648     mxf_write_local_tag(s, 2, 0x3B05);
649     avio_wb16(pb, 259); // v1.3
650
651     // Object Model Version
652     mxf_write_local_tag(s, 4, 0x3B07);
653     avio_wb32(pb, 1);
654
655     // write identification_refs
656     mxf_write_local_tag(s, 16 + 8, 0x3B06);
657     mxf_write_refs_count(pb, 1);
658     mxf_write_uuid(pb, Identification, 0);
659
660     // write content_storage_refs
661     mxf_write_local_tag(s, 16, 0x3B03);
662     mxf_write_uuid(pb, ContentStorage, 0);
663
664     // operational pattern
665     mxf_write_local_tag(s, 16, 0x3B09);
666     if (s->oformat == &ff_mxf_opatom_muxer)
667         avio_write(pb, opatom_ul, 16);
668     else
669         avio_write(pb, op1a_ul, 16);
670
671     // write essence_container_refs
672     mxf_write_local_tag(s, 8 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count), 0x3B0A);
673     mxf_write_essence_container_refs(s);
674
675     // write dm_scheme_refs
676     mxf_write_local_tag(s, 8, 0x3B0B);
677     avio_wb64(pb, 0);
678 }
679
680 /*
681  * Returns the length of the UTF-16 string, in 16-bit characters, that would result
682  * from decoding the utf-8 string.
683  */
684 static uint64_t mxf_utf16len(const char *utf8_str)
685 {
686     const uint8_t *q = utf8_str;
687     uint64_t size = 0;
688     while (*q) {
689         uint32_t ch;
690         GET_UTF8(ch, *q++, goto invalid;)
691         if (ch < 0x10000)
692             size++;
693         else
694             size += 2;
695         continue;
696 invalid:
697         av_log(NULL, AV_LOG_ERROR, "Invalid UTF8 sequence in mxf_utf16len\n\n");
698     }
699     size += 1;
700     return size;
701 }
702
703 /*
704  * Returns the calculated length a local tag containing an utf-8 string as utf-16
705  */
706 static int mxf_utf16_local_tag_length(const char *utf8_str)
707 {
708     uint64_t size;
709
710     if (!utf8_str)
711         return 0;
712
713     size = mxf_utf16len(utf8_str);
714     if (size >= UINT16_MAX/2) {
715         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
716         return 0;
717     }
718
719     return 4 + size * 2;
720 }
721
722 /*
723  * Write a local tag containing an utf-8 string as utf-16
724  */
725 static void mxf_write_local_tag_utf16(AVFormatContext *s, int tag, const char *value)
726 {
727     AVIOContext *pb = s->pb;
728     uint64_t size = mxf_utf16len(value);
729
730     if (size >= UINT16_MAX/2) {
731         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
732         return;
733     }
734
735     mxf_write_local_tag(s, size*2, tag);
736     avio_put_str16be(pb, value);
737 }
738
739 static void store_version(AVFormatContext *s){
740     AVIOContext *pb = s->pb;
741
742     if (s->flags & AVFMT_FLAG_BITEXACT) {
743         avio_wb16(pb, 0); // major
744         avio_wb16(pb, 0); // minor
745         avio_wb16(pb, 0); // tertiary
746     } else {
747         avio_wb16(pb, LIBAVFORMAT_VERSION_MAJOR); // major
748         avio_wb16(pb, LIBAVFORMAT_VERSION_MINOR); // minor
749         avio_wb16(pb, LIBAVFORMAT_VERSION_MICRO); // tertiary
750     }
751     avio_wb16(pb, 0); // patch
752     avio_wb16(pb, 0); // release
753 }
754
755 static void mxf_write_identification(AVFormatContext *s)
756 {
757     MXFContext *mxf = s->priv_data;
758     AVIOContext *pb = s->pb;
759     const char *company = "FFmpeg";
760     const char *product = s->oformat != &ff_mxf_opatom_muxer ? "OP1a Muxer" : "OPAtom Muxer";
761     const char *version;
762     int length;
763
764     mxf_write_metadata_key(pb, 0x013000);
765     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
766
767     version = s->flags & AVFMT_FLAG_BITEXACT ?
768         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
769     length = 100 +mxf_utf16_local_tag_length(company) +
770                   mxf_utf16_local_tag_length(product) +
771                   mxf_utf16_local_tag_length(version);
772     klv_encode_ber_length(pb, length);
773
774     // write uid
775     mxf_write_local_tag(s, 16, 0x3C0A);
776     mxf_write_uuid(pb, Identification, 0);
777     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
778
779     // write generation uid
780     mxf_write_local_tag(s, 16, 0x3C09);
781     mxf_write_uuid(pb, Identification, 1);
782     mxf_write_local_tag_utf16(s, 0x3C01, company); // Company Name
783     mxf_write_local_tag_utf16(s, 0x3C02, product); // Product Name
784
785     mxf_write_local_tag(s, 10, 0x3C03); // Product Version
786     store_version(s);
787
788     mxf_write_local_tag_utf16(s, 0x3C04, version); // Version String
789
790     // write product uid
791     mxf_write_local_tag(s, 16, 0x3C05);
792     mxf_write_uuid(pb, Identification, 2);
793
794     // modification date
795     mxf_write_local_tag(s, 8, 0x3C06);
796     avio_wb64(pb, mxf->timestamp);
797
798     mxf_write_local_tag(s, 10, 0x3C07); // Toolkit Version
799     store_version(s);
800 }
801
802 static void mxf_write_content_storage(AVFormatContext *s, MXFPackage *packages, int package_count)
803 {
804     AVIOContext *pb = s->pb;
805     int i;
806
807     mxf_write_metadata_key(pb, 0x011800);
808     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
809     klv_encode_ber_length(pb, 60 + (16 * package_count));
810
811     // write uid
812     mxf_write_local_tag(s, 16, 0x3C0A);
813     mxf_write_uuid(pb, ContentStorage, 0);
814     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
815
816     // write package reference
817     mxf_write_local_tag(s, 16 * package_count + 8, 0x1901);
818     mxf_write_refs_count(pb, package_count);
819     for (i = 0; i < package_count; i++) {
820         mxf_write_uuid(pb, packages[i].type, packages[i].instance);
821     }
822
823     // write essence container data
824     mxf_write_local_tag(s, 8 + 16, 0x1902);
825     mxf_write_refs_count(pb, 1);
826     mxf_write_uuid(pb, EssenceContainerData, 0);
827 }
828
829 static void mxf_write_track(AVFormatContext *s, AVStream *st, MXFPackage *package)
830 {
831     MXFContext *mxf = s->priv_data;
832     AVIOContext *pb = s->pb;
833     MXFStreamContext *sc = st->priv_data;
834
835     mxf_write_metadata_key(pb, 0x013b00);
836     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
837     klv_encode_ber_length(pb, 80);
838
839     // write track uid
840     mxf_write_local_tag(s, 16, 0x3C0A);
841     mxf_write_uuid(pb, Track, mxf->track_instance_count);
842     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
843
844     // write track id
845     mxf_write_local_tag(s, 4, 0x4801);
846     avio_wb32(pb, st->index+2);
847
848     // write track number
849     mxf_write_local_tag(s, 4, 0x4804);
850     if (package->type == MaterialPackage)
851         avio_wb32(pb, 0); // track number of material package is 0
852     else
853         avio_write(pb, sc->track_essence_element_key + 12, 4);
854
855     // write edit rate
856     mxf_write_local_tag(s, 8, 0x4B01);
857
858     if (st == mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer) {
859         avio_wb32(pb, mxf->tc.rate.num);
860         avio_wb32(pb, mxf->tc.rate.den);
861     } else {
862         avio_wb32(pb, mxf->time_base.den);
863         avio_wb32(pb, mxf->time_base.num);
864     }
865
866     // write origin
867     mxf_write_local_tag(s, 8, 0x4B02);
868     avio_wb64(pb, 0);
869
870     // write sequence refs
871     mxf_write_local_tag(s, 16, 0x4803);
872     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
873 }
874
875 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 };
876
877 static void mxf_write_common_fields(AVFormatContext *s, AVStream *st)
878 {
879     MXFContext *mxf = s->priv_data;
880     AVIOContext *pb = s->pb;
881
882     // find data define uls
883     mxf_write_local_tag(s, 16, 0x0201);
884     if (st == mxf->timecode_track)
885         avio_write(pb, smpte_12m_timecode_track_data_ul, 16);
886     else {
887         const MXFCodecUL *data_def_ul = mxf_get_codec_ul_by_id(ff_mxf_data_definition_uls, st->codecpar->codec_type);
888         avio_write(pb, data_def_ul->uid, 16);
889     }
890
891     // write duration
892     mxf_write_local_tag(s, 8, 0x0202);
893
894     if (st != mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
895         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
896     } else {
897         avio_wb64(pb, mxf->duration);
898     }
899 }
900
901 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, MXFPackage *package)
902 {
903     MXFContext *mxf = s->priv_data;
904     AVIOContext *pb = s->pb;
905     enum MXFMetadataSetType component;
906
907     mxf_write_metadata_key(pb, 0x010f00);
908     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
909     klv_encode_ber_length(pb, 80);
910
911     mxf_write_local_tag(s, 16, 0x3C0A);
912     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
913
914     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
915     mxf_write_common_fields(s, st);
916
917     // write structural component
918     mxf_write_local_tag(s, 16 + 8, 0x1001);
919     mxf_write_refs_count(pb, 1);
920     if (st == mxf->timecode_track)
921         component = TimecodeComponent;
922     else
923         component = SourceClip;
924
925     mxf_write_uuid(pb, component, mxf->track_instance_count);
926 }
927
928 static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
929 {
930     MXFContext *mxf = s->priv_data;
931     AVIOContext *pb = s->pb;
932
933     mxf_write_metadata_key(pb, 0x011400);
934     klv_encode_ber_length(pb, 75);
935
936     // UID
937     mxf_write_local_tag(s, 16, 0x3C0A);
938     mxf_write_uuid(pb, TimecodeComponent, mxf->track_instance_count);
939
940     mxf_write_common_fields(s, st);
941
942     // Start Time Code
943     mxf_write_local_tag(s, 8, 0x1501);
944     avio_wb64(pb, mxf->tc.start);
945
946     // Rounded Time Code Base
947     mxf_write_local_tag(s, 2, 0x1502);
948     avio_wb16(pb, mxf->timecode_base);
949
950     // Drop Frame
951     mxf_write_local_tag(s, 1, 0x1503);
952     avio_w8(pb, !!(mxf->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
953 }
954
955 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
956 {
957     MXFContext *mxf = s->priv_data;
958     AVIOContext *pb = s->pb;
959     int i;
960
961     mxf_write_metadata_key(pb, 0x011100);
962     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
963     klv_encode_ber_length(pb, 108);
964
965     // write uid
966     mxf_write_local_tag(s, 16, 0x3C0A);
967     mxf_write_uuid(pb, SourceClip, mxf->track_instance_count);
968
969     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
970     mxf_write_common_fields(s, st);
971
972     // write start_position
973     mxf_write_local_tag(s, 8, 0x1201);
974     avio_wb64(pb, 0);
975
976     // write source package uid, end of the reference
977     mxf_write_local_tag(s, 32, 0x1101);
978     if (!package->ref) {
979         for (i = 0; i < 4; i++)
980             avio_wb64(pb, 0);
981     } else
982         mxf_write_umid(s, package->ref->instance);
983
984     // write source track id
985     mxf_write_local_tag(s, 4, 0x1102);
986     if (package->type == SourcePackage && !package->ref)
987         avio_wb32(pb, 0);
988     else
989         avio_wb32(pb, st->index+2);
990 }
991
992 static void mxf_write_tape_descriptor(AVFormatContext *s)
993 {
994     AVIOContext *pb = s->pb;
995
996     mxf_write_metadata_key(pb, 0x012e00);
997     PRINT_KEY(s, "tape descriptor key", pb->buf_ptr - 16);
998     klv_encode_ber_length(pb, 20);
999     mxf_write_local_tag(s, 16, 0x3C0A);
1000     mxf_write_uuid(pb, TapeDescriptor, 0);
1001     PRINT_KEY(s, "tape_desc uid", pb->buf_ptr - 16);
1002 }
1003
1004
1005 static void mxf_write_multi_descriptor(AVFormatContext *s)
1006 {
1007     MXFContext *mxf = s->priv_data;
1008     AVIOContext *pb = s->pb;
1009     const uint8_t *ul;
1010     int i;
1011
1012     mxf_write_metadata_key(pb, 0x014400);
1013     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
1014     klv_encode_ber_length(pb, 64 + 16LL * s->nb_streams);
1015
1016     mxf_write_local_tag(s, 16, 0x3C0A);
1017     mxf_write_uuid(pb, MultipleDescriptor, 0);
1018     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
1019
1020     // write sample rate
1021     mxf_write_local_tag(s, 8, 0x3001);
1022     avio_wb32(pb, mxf->time_base.den);
1023     avio_wb32(pb, mxf->time_base.num);
1024
1025     // write essence container ul
1026     mxf_write_local_tag(s, 16, 0x3004);
1027     if (mxf->essence_container_count > 1)
1028         ul = multiple_desc_ul;
1029     else {
1030         MXFStreamContext *sc = s->streams[0]->priv_data;
1031         ul = *sc->container_ul;
1032     }
1033     avio_write(pb, ul, 16);
1034
1035     // write sub descriptor refs
1036     mxf_write_local_tag(s, s->nb_streams * 16 + 8, 0x3F01);
1037     mxf_write_refs_count(pb, s->nb_streams);
1038     for (i = 0; i < s->nb_streams; i++)
1039         mxf_write_uuid(pb, SubDescriptor, i);
1040 }
1041
1042 static int64_t mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID key)
1043 {
1044     MXFContext *mxf = s->priv_data;
1045     MXFStreamContext *sc = st->priv_data;
1046     AVIOContext *pb = s->pb;
1047     int64_t pos;
1048
1049     avio_write(pb, key, 16);
1050     klv_encode_ber4_length(pb, 0);
1051     pos = avio_tell(pb);
1052
1053     mxf_write_local_tag(s, 16, 0x3C0A);
1054     mxf_write_uuid(pb, SubDescriptor, st->index);
1055
1056     mxf_write_local_tag(s, 4, 0x3006);
1057     avio_wb32(pb, st->index+2);
1058
1059     mxf_write_local_tag(s, 8, 0x3001);
1060     if (s->oformat == &ff_mxf_d10_muxer) {
1061         avio_wb32(pb, mxf->time_base.den);
1062         avio_wb32(pb, mxf->time_base.num);
1063     } else {
1064         if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE ||
1065             st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
1066             avio_wb32(pb, st->codecpar->sample_rate);
1067             avio_wb32(pb, 1);
1068         } else {
1069             avio_wb32(pb, mxf->time_base.den);
1070             avio_wb32(pb, mxf->time_base.num);
1071         }
1072     }
1073
1074     mxf_write_local_tag(s, 16, 0x3004);
1075     avio_write(pb, *sc->container_ul, 16);
1076
1077     return pos;
1078 }
1079
1080 static const UID mxf_s436m_anc_descriptor_key = { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 };
1081 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
1082 static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
1083 static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
1084 static const UID mxf_cdci_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x28,0x00 };
1085 static const UID mxf_generic_sound_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x42,0x00 };
1086
1087 static const UID mxf_avc_subdescriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x6E,0x00 };
1088
1089 static inline uint16_t rescale_mastering_chroma(AVRational q)
1090 {
1091     return av_clip_uint16(av_rescale(q.num, FF_MXF_MASTERING_CHROMA_DEN, q.den));
1092 }
1093
1094 static inline uint32_t rescale_mastering_luma(AVRational q)
1095 {
1096     return av_rescale(q.num, FF_MXF_MASTERING_LUMA_DEN, q.den);
1097 }
1098
1099 static int64_t mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID key)
1100 {
1101     MXFStreamContext *sc = st->priv_data;
1102     AVIOContext *pb = s->pb;
1103     int stored_width = 0;
1104     int stored_height = (st->codecpar->height+15)/16*16;
1105     int display_height;
1106     int f1, f2;
1107     const MXFCodecUL *color_primaries_ul;
1108     const MXFCodecUL *color_trc_ul;
1109     const MXFCodecUL *color_space_ul;
1110     int64_t pos = mxf_write_generic_desc(s, st, key);
1111     uint8_t *side_data;
1112
1113     color_primaries_ul = mxf_get_codec_ul_by_id(ff_mxf_color_primaries_uls, st->codecpar->color_primaries);
1114     color_trc_ul       = mxf_get_codec_ul_by_id(ff_mxf_color_trc_uls, st->codecpar->color_trc);
1115     color_space_ul     = mxf_get_codec_ul_by_id(ff_mxf_color_space_uls, st->codecpar->color_space);
1116
1117     if (st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO) {
1118         if (st->codecpar->height == 1080)
1119             stored_width = 1920;
1120         else if (st->codecpar->height == 720)
1121             stored_width = 1280;
1122     }
1123     if (!stored_width)
1124         stored_width = (st->codecpar->width+15)/16*16;
1125
1126     mxf_write_local_tag(s, 4, 0x3203);
1127     avio_wb32(pb, stored_width);
1128
1129     mxf_write_local_tag(s, 4, 0x3202);
1130     avio_wb32(pb, stored_height>>sc->interlaced);
1131
1132     if (s->oformat == &ff_mxf_d10_muxer) {
1133         //Stored F2 Offset
1134         mxf_write_local_tag(s, 4, 0x3216);
1135         avio_wb32(pb, 0);
1136
1137         //Image Start Offset
1138         mxf_write_local_tag(s, 4, 0x3213);
1139         avio_wb32(pb, 0);
1140
1141         //Image End Offset
1142         mxf_write_local_tag(s, 4, 0x3214);
1143         avio_wb32(pb, 0);
1144     }
1145
1146     //Sampled width
1147     mxf_write_local_tag(s, 4, 0x3205);
1148     avio_wb32(pb, stored_width);
1149
1150     //Samples height
1151     mxf_write_local_tag(s, 4, 0x3204);
1152     avio_wb32(pb, st->codecpar->height>>sc->interlaced);
1153
1154     //Sampled X Offset
1155     mxf_write_local_tag(s, 4, 0x3206);
1156     avio_wb32(pb, 0);
1157
1158     //Sampled Y Offset
1159     mxf_write_local_tag(s, 4, 0x3207);
1160     avio_wb32(pb, 0);
1161
1162     mxf_write_local_tag(s, 4, 0x3209);
1163     avio_wb32(pb, stored_width);
1164
1165     if (st->codecpar->height == 608) // PAL + VBI
1166         display_height = 576;
1167     else if (st->codecpar->height == 512)  // NTSC + VBI
1168         display_height = 486;
1169     else
1170         display_height = st->codecpar->height;
1171
1172     mxf_write_local_tag(s, 4, 0x3208);
1173     avio_wb32(pb, display_height>>sc->interlaced);
1174
1175     // display X offset
1176     mxf_write_local_tag(s, 4, 0x320A);
1177     avio_wb32(pb, 0);
1178
1179     // display Y offset
1180     mxf_write_local_tag(s, 4, 0x320B);
1181     avio_wb32(pb, (st->codecpar->height - display_height)>>sc->interlaced);
1182
1183     if (sc->interlaced) {
1184         //Display F2 Offset
1185         mxf_write_local_tag(s, 4, 0x3217);
1186         avio_wb32(pb, -((st->codecpar->height - display_height)&1));
1187     }
1188
1189     // component depth
1190     mxf_write_local_tag(s, 4, 0x3301);
1191     avio_wb32(pb, sc->component_depth);
1192
1193     // horizontal subsampling
1194     mxf_write_local_tag(s, 4, 0x3302);
1195     avio_wb32(pb, sc->h_chroma_sub_sample);
1196
1197     // vertical subsampling
1198     mxf_write_local_tag(s, 4, 0x3308);
1199     avio_wb32(pb, sc->v_chroma_sub_sample);
1200
1201     // color siting
1202     mxf_write_local_tag(s, 1, 0x3303);
1203     avio_w8(pb, sc->color_siting);
1204
1205     // Padding Bits
1206     mxf_write_local_tag(s, 2, 0x3307);
1207     avio_wb16(pb, 0);
1208
1209     if (st->codecpar->color_range != AVCOL_RANGE_UNSPECIFIED) {
1210         int black = 0,
1211             white = (1<<sc->component_depth) - 1,
1212             color = (1<<sc->component_depth);
1213         if (st->codecpar->color_range == AVCOL_RANGE_MPEG) {
1214             black = 1   << (sc->component_depth - 4);
1215             white = 235 << (sc->component_depth - 8);
1216             color = (14 << (sc->component_depth - 4)) + 1;
1217         }
1218         mxf_write_local_tag(s, 4, 0x3304);
1219         avio_wb32(pb, black);
1220         mxf_write_local_tag(s, 4, 0x3305);
1221         avio_wb32(pb, white);
1222         mxf_write_local_tag(s, 4, 0x3306);
1223         avio_wb32(pb, color);
1224     }
1225
1226     if (sc->signal_standard) {
1227         mxf_write_local_tag(s, 1, 0x3215);
1228         avio_w8(pb, sc->signal_standard);
1229     }
1230
1231     // frame layout
1232     mxf_write_local_tag(s, 1, 0x320C);
1233     avio_w8(pb, sc->interlaced);
1234
1235     // video line map
1236     switch (st->codecpar->height) {
1237     case  576: f1 = 23; f2 = st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO ? 335 : 336; break;
1238     case  608: f1 =  7; f2 = 320; break;
1239     case  480: f1 = 20; f2 = st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO ? 285 : 283; break;
1240     case  512: f1 =  7; f2 = 270; break;
1241     case  720: f1 = 26; f2 =   0; break; // progressive
1242     case 1080: f1 = 21; f2 = 584; break;
1243     default:   f1 =  0; f2 =   0; break;
1244     }
1245
1246     if (!sc->interlaced && f2) {
1247         f2  = 0;
1248         f1 *= 2;
1249     }
1250
1251
1252     mxf_write_local_tag(s, 16, 0x320D);
1253     avio_wb32(pb, 2);
1254     avio_wb32(pb, 4);
1255     avio_wb32(pb, f1);
1256     avio_wb32(pb, f2);
1257
1258     mxf_write_local_tag(s, 8, 0x320E);
1259     avio_wb32(pb, sc->aspect_ratio.num);
1260     avio_wb32(pb, sc->aspect_ratio.den);
1261
1262     if (color_primaries_ul->uid[0]) {
1263         mxf_write_local_tag(s, 16, 0x3219);
1264         avio_write(pb, color_primaries_ul->uid, 16);
1265     };
1266
1267     if (color_trc_ul->uid[0]) {
1268         mxf_write_local_tag(s, 16, 0x3210);
1269         avio_write(pb, color_trc_ul->uid, 16);
1270     };
1271
1272     if (color_space_ul->uid[0]) {
1273         mxf_write_local_tag(s, 16, 0x321A);
1274         avio_write(pb, color_space_ul->uid, 16);
1275     };
1276
1277     mxf_write_local_tag(s, 16, 0x3201);
1278     avio_write(pb, *sc->codec_ul, 16);
1279
1280     // Mastering Display metadata
1281     side_data = av_stream_get_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, NULL);
1282     if (side_data) {
1283         const AVMasteringDisplayMetadata *metadata = (const AVMasteringDisplayMetadata*)side_data;
1284         if (metadata->has_primaries) {
1285             mxf_write_local_tag(s, 12, 0x8301);
1286             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[0][0]));
1287             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[0][1]));
1288             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[1][0]));
1289             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[1][1]));
1290             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[2][0]));
1291             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[2][1]));
1292             mxf_write_local_tag(s, 4, 0x8302);
1293             avio_wb16(pb, rescale_mastering_chroma(metadata->white_point[0]));
1294             avio_wb16(pb, rescale_mastering_chroma(metadata->white_point[1]));
1295         } else {
1296             av_log(NULL, AV_LOG_VERBOSE, "Not writing mastering display primaries. Missing data.\n");
1297         }
1298         if (metadata->has_luminance) {
1299             mxf_write_local_tag(s, 4, 0x8303);
1300             avio_wb32(pb, rescale_mastering_luma(metadata->max_luminance));
1301             mxf_write_local_tag(s, 4, 0x8304);
1302             avio_wb32(pb, rescale_mastering_luma(metadata->min_luminance));
1303         } else {
1304             av_log(NULL, AV_LOG_VERBOSE, "Not writing mastering display luminances. Missing data.\n");
1305         }
1306     }
1307
1308     if (sc->interlaced && sc->field_dominance) {
1309         mxf_write_local_tag(s, 1, 0x3212);
1310         avio_w8(pb, sc->field_dominance);
1311     }
1312
1313     if (st->codecpar->codec_id == AV_CODEC_ID_H264 && !sc->avc_intra) {
1314         // write avc sub descriptor ref
1315         mxf_write_local_tag(s, 8 + 16, 0x8100);
1316         mxf_write_refs_count(pb, 1);
1317         mxf_write_uuid(pb, AVCSubDescriptor, 0);
1318     }
1319
1320     return pos;
1321 }
1322
1323 static void mxf_update_klv_size(AVIOContext *pb, int64_t pos)
1324 {
1325     int64_t cur_pos = avio_tell(pb);
1326     int size = cur_pos - pos;
1327     avio_seek(pb, pos - 4, SEEK_SET);
1328     klv_encode_ber4_length(pb, size);
1329     avio_seek(pb, cur_pos, SEEK_SET);
1330 }
1331
1332 static void mxf_write_avc_subdesc(AVFormatContext *s, AVStream *st)
1333 {
1334     AVIOContext *pb = s->pb;
1335     int64_t pos;
1336
1337     avio_write(pb, mxf_avc_subdescriptor_key, 16);
1338     klv_encode_ber4_length(pb, 0);
1339     pos = avio_tell(pb);
1340
1341     mxf_write_local_tag(s, 16, 0x3C0A);
1342     mxf_write_uuid(pb, AVCSubDescriptor, 0);
1343
1344     mxf_write_local_tag(s, 1, 0x8200);
1345     avio_w8(pb, 0xFF); // AVC Decoding Delay, unknown
1346
1347     mxf_write_local_tag(s, 1, 0x8201);
1348     avio_w8(pb, st->codecpar->profile); // AVC Profile
1349
1350     mxf_write_local_tag(s, 1, 0x8202);
1351     avio_w8(pb, st->codecpar->level); // AVC Level
1352
1353     mxf_update_klv_size(s->pb, pos);
1354 }
1355
1356 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st)
1357 {
1358     int64_t pos = mxf_write_cdci_common(s, st, mxf_cdci_descriptor_key);
1359     mxf_update_klv_size(s->pb, pos);
1360
1361     if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1362         mxf_write_avc_subdesc(s, st);
1363     }
1364 }
1365
1366 static void mxf_write_h264_desc(AVFormatContext *s, AVStream *st)
1367 {
1368     MXFStreamContext *sc = st->priv_data;
1369     if (sc->avc_intra) {
1370         mxf_write_mpegvideo_desc(s, st);
1371     } else {
1372         int64_t pos = mxf_write_cdci_common(s, st, mxf_cdci_descriptor_key);
1373         mxf_update_klv_size(s->pb, pos);
1374         mxf_write_avc_subdesc(s, st);
1375     }
1376 }
1377
1378 static void mxf_write_s436m_anc_desc(AVFormatContext *s, AVStream *st)
1379 {
1380     int64_t pos = mxf_write_generic_desc(s, st, mxf_s436m_anc_descriptor_key);
1381     mxf_update_klv_size(s->pb, pos);
1382 }
1383
1384 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
1385 {
1386     AVIOContext *pb = s->pb;
1387     MXFStreamContext *sc = st->priv_data;
1388     int profile_and_level = (st->codecpar->profile<<4) | st->codecpar->level;
1389     int64_t pos = mxf_write_cdci_common(s, st, mxf_mpegvideo_descriptor_key);
1390
1391     if (st->codecpar->codec_id != AV_CODEC_ID_H264) {
1392         // bit rate
1393         mxf_write_local_tag(s, 4, 0x8000);
1394         avio_wb32(pb, sc->video_bit_rate);
1395
1396         // profile and level
1397         mxf_write_local_tag(s, 1, 0x8007);
1398         if (!st->codecpar->profile)
1399             profile_and_level |= 0x80; // escape bit
1400         avio_w8(pb, profile_and_level);
1401
1402         // low delay
1403         mxf_write_local_tag(s, 1, 0x8003);
1404         avio_w8(pb, sc->low_delay);
1405
1406         // closed gop
1407         mxf_write_local_tag(s, 1, 0x8004);
1408         avio_w8(pb, sc->seq_closed_gop);
1409
1410         // max gop
1411         mxf_write_local_tag(s, 2, 0x8006);
1412         avio_wb16(pb, sc->max_gop);
1413
1414         // b picture count
1415         mxf_write_local_tag(s, 2, 0x8008);
1416         avio_wb16(pb, sc->b_picture_count);
1417     }
1418
1419     mxf_update_klv_size(pb, pos);
1420 }
1421
1422 static int64_t mxf_write_generic_sound_common(AVFormatContext *s, AVStream *st, const UID key)
1423 {
1424     AVIOContext *pb = s->pb;
1425     MXFContext *mxf = s->priv_data;
1426     int show_warnings = !mxf->footer_partition_offset;
1427     int64_t pos = mxf_write_generic_desc(s, st, key);
1428
1429     if (s->oformat == &ff_mxf_opatom_muxer) {
1430         mxf_write_local_tag(s, 8, 0x3002);
1431         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
1432     }
1433
1434     // audio locked
1435     mxf_write_local_tag(s, 1, 0x3D02);
1436     avio_w8(pb, 1);
1437
1438     // write audio sampling rate
1439     mxf_write_local_tag(s, 8, 0x3D03);
1440     avio_wb32(pb, st->codecpar->sample_rate);
1441     avio_wb32(pb, 1);
1442
1443     if (s->oformat == &ff_mxf_d10_muxer) {
1444         mxf_write_local_tag(s, 1, 0x3D04);
1445         avio_w8(pb, 0);
1446     }
1447
1448     mxf_write_local_tag(s, 4, 0x3D07);
1449     if (mxf->channel_count == -1) {
1450         if (show_warnings && (s->oformat == &ff_mxf_d10_muxer) && (st->codecpar->channels != 4) && (st->codecpar->channels != 8))
1451             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");
1452         avio_wb32(pb, st->codecpar->channels);
1453     } else if (s->oformat == &ff_mxf_d10_muxer) {
1454         if (show_warnings && (mxf->channel_count < st->codecpar->channels))
1455             av_log(s, AV_LOG_WARNING, "d10_channelcount < actual number of audio channels : some channels will be discarded\n");
1456         if (show_warnings && (mxf->channel_count != 4) && (mxf->channel_count != 8))
1457             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");
1458         avio_wb32(pb, mxf->channel_count);
1459     } else {
1460         avio_wb32(pb, st->codecpar->channels);
1461     }
1462
1463     mxf_write_local_tag(s, 4, 0x3D01);
1464     avio_wb32(pb, av_get_bits_per_sample(st->codecpar->codec_id));
1465
1466     return pos;
1467 }
1468
1469 static int64_t mxf_write_wav_common(AVFormatContext *s, AVStream *st, const UID key)
1470 {
1471     AVIOContext *pb = s->pb;
1472     int64_t pos = mxf_write_generic_sound_common(s, st, key);
1473
1474     mxf_write_local_tag(s, 2, 0x3D0A);
1475     avio_wb16(pb, st->codecpar->block_align);
1476
1477     // avg bytes per sec
1478     mxf_write_local_tag(s, 4, 0x3D09);
1479     avio_wb32(pb, st->codecpar->block_align*st->codecpar->sample_rate);
1480
1481     return pos;
1482 }
1483
1484 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
1485 {
1486     int64_t pos = mxf_write_wav_common(s, st, mxf_wav_descriptor_key);
1487     mxf_update_klv_size(s->pb, pos);
1488 }
1489
1490 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
1491 {
1492     int64_t pos = mxf_write_wav_common(s, st, mxf_aes3_descriptor_key);
1493     mxf_update_klv_size(s->pb, pos);
1494 }
1495
1496 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st)
1497 {
1498     int64_t pos = mxf_write_generic_sound_common(s, st, mxf_generic_sound_descriptor_key);
1499     mxf_update_klv_size(s->pb, pos);
1500 }
1501
1502 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 };
1503
1504 static int mxf_write_tagged_value(AVFormatContext *s, const char* name, const char* value)
1505 {
1506     MXFContext *mxf = s->priv_data;
1507     AVIOContext *pb = s->pb;
1508     int name_size = mxf_utf16_local_tag_length(name);
1509     int indirect_value_size = 13 + mxf_utf16_local_tag_length(value);
1510
1511     if (!name_size || indirect_value_size == 13)
1512         return 1;
1513
1514     mxf_write_metadata_key(pb, 0x013f00);
1515     klv_encode_ber_length(pb, 24 + name_size + indirect_value_size);
1516
1517     // write instance UID
1518     mxf_write_local_tag(s, 16, 0x3C0A);
1519     mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count);
1520
1521     // write name
1522     mxf_write_local_tag_utf16(s, 0x5001, name); // Name
1523
1524     // write indirect value
1525     mxf_write_local_tag(s, indirect_value_size, 0x5003);
1526     avio_write(pb, mxf_indirect_value_utf16le, 17);
1527     avio_put_str16le(pb, value);
1528
1529     mxf->tagged_value_count++;
1530     return 0;
1531 }
1532
1533 static int mxf_write_user_comments(AVFormatContext *s, const AVDictionary *m)
1534 {
1535     MXFContext *mxf = s->priv_data;
1536     AVDictionaryEntry *t = NULL;
1537     int count = 0;
1538
1539     while ((t = av_dict_get(m, "comment_", t, AV_DICT_IGNORE_SUFFIX))) {
1540         if (mxf->tagged_value_count >= UINT16_MAX) {
1541             av_log(s, AV_LOG_ERROR, "too many tagged values, ignoring remaining\n");
1542             return count;
1543         }
1544
1545         if (mxf_write_tagged_value(s, t->key + 8, t->value) == 0)
1546             count++;
1547     }
1548     return count;
1549 }
1550
1551 static void mxf_write_package(AVFormatContext *s, MXFPackage *package)
1552 {
1553     MXFContext *mxf = s->priv_data;
1554     AVIOContext *pb = s->pb;
1555     int i, track_count = s->nb_streams+1;
1556     int name_size = mxf_utf16_local_tag_length(package->name);
1557     int user_comment_count = 0;
1558
1559     if (package->type == MaterialPackage) {
1560         if (mxf->store_user_comments)
1561             user_comment_count = mxf_write_user_comments(s, s->metadata);
1562         mxf_write_metadata_key(pb, 0x013600);
1563         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
1564         klv_encode_ber_length(pb, 92 + name_size + (16*track_count) + (16*user_comment_count) + 12LL*mxf->store_user_comments);
1565     } else {
1566         mxf_write_metadata_key(pb, 0x013700);
1567         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
1568         klv_encode_ber_length(pb, 112 + name_size + (16*track_count) + 12LL*mxf->store_user_comments); // 20 bytes length for descriptor reference
1569     }
1570
1571     // write uid
1572     mxf_write_local_tag(s, 16, 0x3C0A);
1573     mxf_write_uuid(pb, package->type, package->instance);
1574     av_log(s, AV_LOG_DEBUG, "package type:%d\n", package->type);
1575     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
1576
1577     // write package umid
1578     mxf_write_local_tag(s, 32, 0x4401);
1579     mxf_write_umid(s, package->instance);
1580     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
1581
1582     // package name
1583     if (name_size)
1584         mxf_write_local_tag_utf16(s, 0x4402, package->name);
1585
1586     // package creation date
1587     mxf_write_local_tag(s, 8, 0x4405);
1588     avio_wb64(pb, mxf->timestamp);
1589
1590     // package modified date
1591     mxf_write_local_tag(s, 8, 0x4404);
1592     avio_wb64(pb, mxf->timestamp);
1593
1594     // write track refs
1595     mxf_write_local_tag(s, track_count*16 + 8, 0x4403);
1596     mxf_write_refs_count(pb, track_count);
1597     // these are the uuids of the tracks the will be written in mxf_write_track
1598     for (i = 0; i < track_count; i++)
1599         mxf_write_uuid(pb, Track,  mxf->track_instance_count + i);
1600
1601     // write user comment refs
1602     if (mxf->store_user_comments) {
1603         mxf_write_local_tag(s, user_comment_count*16 + 8, 0x4406);
1604         mxf_write_refs_count(pb, user_comment_count);
1605         for (i = 0; i < user_comment_count; i++)
1606             mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count - user_comment_count + i);
1607     }
1608
1609     // write multiple descriptor reference
1610     if (package->type == SourcePackage && package->instance == 1) {
1611         mxf_write_local_tag(s, 16, 0x4701);
1612         if (s->nb_streams > 1) {
1613             mxf_write_uuid(pb, MultipleDescriptor, 0);
1614             mxf_write_multi_descriptor(s);
1615         } else
1616             mxf_write_uuid(pb, SubDescriptor, 0);
1617     } else if (package->type == SourcePackage && package->instance == 2) {
1618         mxf_write_local_tag(s, 16, 0x4701);
1619         mxf_write_uuid(pb, TapeDescriptor, 0);
1620         mxf_write_tape_descriptor(s);
1621     }
1622
1623     /*
1624      * for every 1 track in a package there is 1 sequence and 1 component.
1625      * all 3 of these elements share the same instance number for generating
1626      * there instance uuids. mxf->track_instance_count stores this value.
1627      * mxf->track_instance_count is incremented after a group of all 3 of
1628      * these elements are written.
1629      */
1630
1631     // write timecode track
1632     mxf_write_track(s, mxf->timecode_track, package);
1633     mxf_write_sequence(s, mxf->timecode_track, package);
1634     mxf_write_timecode_component(s, mxf->timecode_track, package);
1635     mxf->track_instance_count++;
1636
1637     for (i = 0; i < s->nb_streams; i++) {
1638         AVStream *st = s->streams[i];
1639         mxf_write_track(s, st, package);
1640         mxf_write_sequence(s, st, package);
1641         mxf_write_structural_component(s, st, package);
1642         mxf->track_instance_count++;
1643
1644         if (package->type == SourcePackage && package->instance == 1) {
1645             MXFStreamContext *sc = st->priv_data;
1646             mxf_essence_container_uls[sc->index].write_desc(s, st);
1647         }
1648     }
1649 }
1650
1651 static int mxf_write_essence_container_data(AVFormatContext *s)
1652 {
1653     AVIOContext *pb = s->pb;
1654
1655     mxf_write_metadata_key(pb, 0x012300);
1656     klv_encode_ber_length(pb, 72);
1657
1658     mxf_write_local_tag(s, 16, 0x3C0A); // Instance UID
1659     mxf_write_uuid(pb, EssenceContainerData, 0);
1660
1661     mxf_write_local_tag(s, 32, 0x2701); // Linked Package UID
1662     mxf_write_umid(s, 1);
1663
1664     mxf_write_local_tag(s, 4, 0x3F07); // BodySID
1665     avio_wb32(pb, 1);
1666
1667     mxf_write_local_tag(s, 4, 0x3F06); // IndexSID
1668     avio_wb32(pb, 2);
1669
1670     return 0;
1671 }
1672
1673 static int mxf_write_header_metadata_sets(AVFormatContext *s)
1674 {
1675     MXFContext *mxf = s->priv_data;
1676     AVDictionaryEntry *entry = NULL;
1677     AVStream *st = NULL;
1678     int i;
1679     MXFPackage packages[3] = {{0}};
1680     int package_count = 2;
1681     packages[0].type = MaterialPackage;
1682     packages[1].type = SourcePackage;
1683     packages[1].instance = 1;
1684     packages[0].ref = &packages[1];
1685
1686
1687     if (entry = av_dict_get(s->metadata, "material_package_name", NULL, 0))
1688        packages[0].name = entry->value;
1689
1690     if (entry = av_dict_get(s->metadata, "file_package_name", NULL, 0)) {
1691         packages[1].name = entry->value;
1692     } else {
1693         /* check if any of the streams contain a file_package_name */
1694         for (i = 0; i < s->nb_streams; i++) {
1695             st = s->streams[i];
1696             if (entry = av_dict_get(st->metadata, "file_package_name", NULL, 0)) {
1697                 packages[1].name = entry->value;
1698                 break;
1699             }
1700         }
1701     }
1702
1703     entry = av_dict_get(s->metadata, "reel_name", NULL, 0);
1704     if (entry) {
1705         packages[2].name = entry->value;
1706         packages[2].type = SourcePackage;
1707         packages[2].instance = 2;
1708         packages[1].ref = &packages[2];
1709         package_count = 3;
1710     }
1711
1712     mxf_write_preface(s);
1713     mxf_write_identification(s);
1714     mxf_write_content_storage(s, packages, package_count);
1715     mxf->track_instance_count = 0;
1716     for (i = 0; i < package_count; i++)
1717         mxf_write_package(s, &packages[i]);
1718     mxf_write_essence_container_data(s);
1719     return 0;
1720 }
1721
1722 static unsigned klv_fill_size(uint64_t size)
1723 {
1724     unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
1725     if (pad < 20) // smallest fill item possible
1726         return pad + KAG_SIZE;
1727     else
1728         return pad & (KAG_SIZE-1);
1729 }
1730
1731 static void mxf_write_index_table_segment(AVFormatContext *s)
1732 {
1733     MXFContext *mxf = s->priv_data;
1734     AVIOContext *pb = s->pb;
1735     int i, j, temporal_reordering = 0;
1736     int key_index = mxf->last_key_index;
1737     int prev_non_b_picture = 0;
1738     int audio_frame_size = 0;
1739     int64_t pos;
1740
1741     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
1742
1743     if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)
1744         return;
1745
1746     avio_write(pb, index_table_segment_key, 16);
1747
1748     klv_encode_ber4_length(pb, 0);
1749     pos = avio_tell(pb);
1750
1751     // instance id
1752     mxf_write_local_tag(s, 16, 0x3C0A);
1753     mxf_write_uuid(pb, IndexTableSegment, 0);
1754
1755     // index edit rate
1756     mxf_write_local_tag(s, 8, 0x3F0B);
1757     avio_wb32(pb, mxf->time_base.den);
1758     avio_wb32(pb, mxf->time_base.num);
1759
1760     // index start position
1761     mxf_write_local_tag(s, 8, 0x3F0C);
1762     avio_wb64(pb, mxf->last_indexed_edit_unit);
1763
1764     // index duration
1765     mxf_write_local_tag(s, 8, 0x3F0D);
1766     if (mxf->edit_unit_byte_count)
1767         avio_wb64(pb, 0); // index table covers whole container
1768     else
1769         avio_wb64(pb, mxf->edit_units_count);
1770
1771     // edit unit byte count
1772     mxf_write_local_tag(s, 4, 0x3F05);
1773     avio_wb32(pb, mxf->edit_unit_byte_count);
1774
1775     // index sid
1776     mxf_write_local_tag(s, 4, 0x3F06);
1777     avio_wb32(pb, 2);
1778
1779     // body sid
1780     mxf_write_local_tag(s, 4, 0x3F07);
1781     avio_wb32(pb, 1);
1782
1783     // real slice count - 1
1784     mxf_write_local_tag(s, 1, 0x3F08);
1785     avio_w8(pb, !mxf->edit_unit_byte_count); // only one slice for CBR
1786
1787     // delta entry array
1788     mxf_write_local_tag(s, 8 + (s->nb_streams+1)*6, 0x3F09);
1789     avio_wb32(pb, s->nb_streams+1); // num of entries
1790     avio_wb32(pb, 6);               // size of one entry
1791     // write system item delta entry
1792     avio_w8(pb, 0);
1793     avio_w8(pb, 0); // slice entry
1794     avio_wb32(pb, 0); // element delta
1795     // write each stream delta entry
1796     for (i = 0; i < s->nb_streams; i++) {
1797         AVStream *st = s->streams[i];
1798         MXFStreamContext *sc = st->priv_data;
1799         avio_w8(pb, sc->temporal_reordering);
1800         if (sc->temporal_reordering)
1801             temporal_reordering = 1;
1802         if (mxf->edit_unit_byte_count) {
1803             avio_w8(pb, 0); // slice number
1804             avio_wb32(pb, sc->slice_offset);
1805         } else if (i == 0) { // video track
1806             avio_w8(pb, 0); // slice number
1807             avio_wb32(pb, KAG_SIZE); // system item size including klv fill
1808         } else { // audio or data track
1809             if (!audio_frame_size) {
1810                 audio_frame_size = sc->frame_size;
1811                 audio_frame_size += klv_fill_size(audio_frame_size);
1812             }
1813             avio_w8(pb, 1);
1814             avio_wb32(pb, (i-1)*audio_frame_size); // element delta
1815         }
1816     }
1817
1818     if (!mxf->edit_unit_byte_count) {
1819         MXFStreamContext *sc = s->streams[0]->priv_data;
1820         mxf_write_local_tag(s, 8 + mxf->edit_units_count*15, 0x3F0A);
1821         avio_wb32(pb, mxf->edit_units_count);  // num of entries
1822         avio_wb32(pb, 15);  // size of one entry
1823
1824         for (i = 0; i < mxf->edit_units_count; i++) {
1825             int temporal_offset = 0;
1826
1827             if (!(mxf->index_entries[i].flags & 0x33)) { // I-frame
1828                 sc->max_gop = FFMAX(sc->max_gop, i - mxf->last_key_index);
1829                 mxf->last_key_index = key_index;
1830                 key_index = i;
1831             }
1832
1833             if (temporal_reordering) {
1834                 int pic_num_in_gop = i - key_index;
1835                 if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {
1836                     for (j = key_index; j < mxf->edit_units_count; j++) {
1837                         if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)
1838                             break;
1839                     }
1840                     if (j == mxf->edit_units_count)
1841                         av_log(s, AV_LOG_WARNING, "missing frames\n");
1842                     temporal_offset = j - key_index - pic_num_in_gop;
1843                 }
1844             }
1845             avio_w8(pb, temporal_offset);
1846
1847             if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction
1848                 sc->b_picture_count = FFMAX(sc->b_picture_count, i - prev_non_b_picture);
1849                 avio_w8(pb, mxf->last_key_index - i);
1850             } else {
1851                 avio_w8(pb, key_index - i); // key frame offset
1852                 if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
1853                     mxf->last_key_index = key_index;
1854                 prev_non_b_picture = i;
1855             }
1856
1857             if (!(mxf->index_entries[i].flags & 0x33) && // I-frame
1858                 mxf->index_entries[i].flags & 0x40 && !temporal_offset)
1859                 mxf->index_entries[i].flags |= 0x80; // random access
1860             avio_w8(pb, mxf->index_entries[i].flags);
1861             // stream offset
1862             avio_wb64(pb, mxf->index_entries[i].offset);
1863             if (s->nb_streams > 1)
1864                 avio_wb32(pb, mxf->index_entries[i].slice_offset);
1865             else
1866                 avio_wb32(pb, 0);
1867         }
1868
1869         mxf->last_key_index = key_index - mxf->edit_units_count;
1870         mxf->last_indexed_edit_unit += mxf->edit_units_count;
1871         mxf->edit_units_count = 0;
1872     }
1873
1874     mxf_update_klv_size(pb, pos);
1875 }
1876
1877 static void mxf_write_klv_fill(AVFormatContext *s)
1878 {
1879     unsigned pad = klv_fill_size(avio_tell(s->pb));
1880     if (pad) {
1881         avio_write(s->pb, klv_fill_key, 16);
1882         pad -= 16 + 4;
1883         klv_encode_ber4_length(s->pb, pad);
1884         ffio_fill(s->pb, 0, pad);
1885         av_assert1(!(avio_tell(s->pb) & (KAG_SIZE-1)));
1886     }
1887 }
1888
1889 static int mxf_write_partition(AVFormatContext *s, int bodysid,
1890                                 int indexsid,
1891                                 const uint8_t *key, int write_metadata)
1892 {
1893     MXFContext *mxf = s->priv_data;
1894     AVIOContext *pb = s->pb;
1895     int64_t header_byte_count_offset;
1896     unsigned index_byte_count = 0;
1897     uint64_t partition_offset = avio_tell(pb);
1898     int err;
1899
1900     if (!mxf->edit_unit_byte_count && mxf->edit_units_count)
1901         index_byte_count = 85 + 12+(s->nb_streams+1)*6 +
1902             12+mxf->edit_units_count*15;
1903     else if (mxf->edit_unit_byte_count && indexsid)
1904         index_byte_count = 80;
1905
1906     if (index_byte_count) {
1907         index_byte_count += 16 + 4; // add encoded ber4 length
1908         index_byte_count += klv_fill_size(index_byte_count);
1909     }
1910
1911     if (key && !memcmp(key, body_partition_key, 16)) {
1912         if ((err = av_reallocp_array(&mxf->body_partition_offset, mxf->body_partitions_count + 1,
1913                                      sizeof(*mxf->body_partition_offset))) < 0) {
1914             mxf->body_partitions_count = 0;
1915             return err;
1916         }
1917         mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;
1918     }
1919
1920     // write klv
1921     if (key)
1922         avio_write(pb, key, 16);
1923     else
1924         avio_write(pb, body_partition_key, 16);
1925
1926     klv_encode_ber4_length(pb, 88 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
1927
1928     // write partition value
1929     avio_wb16(pb, 1); // majorVersion
1930     avio_wb16(pb, 3); // minorVersion
1931     avio_wb32(pb, KAG_SIZE); // KAGSize
1932
1933     avio_wb64(pb, partition_offset); // ThisPartition
1934
1935     if (key && !memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
1936         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
1937     else if (key && !memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
1938         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
1939     else
1940         avio_wb64(pb, 0);
1941
1942     avio_wb64(pb, mxf->footer_partition_offset); // footerPartition
1943
1944     // set offset
1945     header_byte_count_offset = avio_tell(pb);
1946     avio_wb64(pb, 0); // headerByteCount, update later
1947
1948     // indexTable
1949     avio_wb64(pb, index_byte_count); // indexByteCount
1950     avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
1951
1952     // BodyOffset
1953     if (bodysid && mxf->edit_units_count && mxf->body_partitions_count && s->oformat != &ff_mxf_opatom_muxer)
1954         avio_wb64(pb, mxf->body_offset);
1955     else
1956         avio_wb64(pb, 0);
1957
1958     avio_wb32(pb, bodysid); // bodySID
1959
1960     // operational pattern
1961     if (s->oformat == &ff_mxf_opatom_muxer)
1962         avio_write(pb, opatom_ul, 16);
1963     else
1964         avio_write(pb, op1a_ul, 16);
1965
1966     // essence container
1967     mxf_write_essence_container_refs(s);
1968
1969     if (write_metadata) {
1970         // mark the start of the headermetadata and calculate metadata size
1971         int64_t pos, start;
1972         unsigned header_byte_count;
1973
1974         mxf_write_klv_fill(s);
1975         start = avio_tell(s->pb);
1976         mxf_write_primer_pack(s);
1977         mxf_write_klv_fill(s);
1978         mxf_write_header_metadata_sets(s);
1979         pos = avio_tell(s->pb);
1980         header_byte_count = pos - start + klv_fill_size(pos);
1981
1982         // update header_byte_count
1983         avio_seek(pb, header_byte_count_offset, SEEK_SET);
1984         avio_wb64(pb, header_byte_count);
1985         avio_seek(pb, pos, SEEK_SET);
1986     }
1987
1988     if(key)
1989         avio_write_marker(pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
1990
1991     return 0;
1992 }
1993
1994 static const struct {
1995     int profile;
1996     UID codec_ul;
1997 } mxf_prores_codec_uls[] = {
1998     { FF_PROFILE_PRORES_PROXY,    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x01,0x00 } },
1999     { FF_PROFILE_PRORES_LT,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x02,0x00 } },
2000     { FF_PROFILE_PRORES_STANDARD, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 } },
2001     { FF_PROFILE_PRORES_HQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x04,0x00 } },
2002     { FF_PROFILE_PRORES_4444,     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x05,0x00 } },
2003     { FF_PROFILE_PRORES_XQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x06,0x00 } },
2004 };
2005
2006 static int mxf_parse_prores_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2007 {
2008     MXFContext *mxf = s->priv_data;
2009     MXFStreamContext *sc = st->priv_data;
2010     int i, profile;
2011
2012     if (mxf->header_written)
2013         return 1;
2014
2015     sc->codec_ul = NULL;
2016     profile = st->codecpar->profile;
2017     for (i = 0; i < FF_ARRAY_ELEMS(mxf_prores_codec_uls); i++) {
2018         if (profile == mxf_prores_codec_uls[i].profile) {
2019             sc->codec_ul = &mxf_prores_codec_uls[i].codec_ul;
2020             break;
2021         }
2022     }
2023     if (!sc->codec_ul)
2024         return 0;
2025
2026     sc->frame_size = pkt->size;
2027
2028     return 1;
2029 }
2030
2031 static const struct {
2032     int cid;
2033     UID codec_ul;
2034 } mxf_dnxhd_codec_uls[] = {
2035     { 1235, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 } }, // 1080p 10bit HIGH
2036     { 1237, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x03,0x00,0x00 } }, // 1080p 8bit MED
2037     { 1238, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x04,0x00,0x00 } }, // 1080p 8bit HIGH
2038     { 1241, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x07,0x00,0x00 } }, // 1080i 10bit HIGH
2039     { 1242, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x08,0x00,0x00 } }, // 1080i 8bit MED
2040     { 1243, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x09,0x00,0x00 } }, // 1080i 8bit HIGH
2041     { 1244, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x0a,0x00,0x00 } }, // 1080i 8bit TR
2042     { 1250, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x10,0x00,0x00 } }, // 720p 10bit
2043     { 1251, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x11,0x00,0x00 } }, // 720p 8bit HIGH
2044     { 1252, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x12,0x00,0x00 } }, // 720p 8bit MED
2045     { 1253, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x13,0x00,0x00 } }, // 720p 8bit LOW
2046     { 1256, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x16,0x00,0x00 } }, // 1080p 10bit 444
2047     { 1258, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x18,0x00,0x00 } }, // 720p 8bit TR
2048     { 1259, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x19,0x00,0x00 } }, // 1080p 8bit TR
2049     { 1260, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x1a,0x00,0x00 } }, // 1080i 8bit TR MBAFF
2050     { 1270, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x24,0x00,0x00 } }, // DNXHR 444
2051     { 1271, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x25,0x00,0x00 } }, // DNXHR HQX
2052     { 1272, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x26,0x00,0x00 } }, // DNXHR HQ
2053     { 1273, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x27,0x00,0x00 } }, // DNXHR SQ
2054     { 1274, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x28,0x00,0x00 } }, // DNXHR LB
2055 };
2056
2057 static int mxf_parse_dnxhd_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2058 {
2059     MXFContext *mxf = s->priv_data;
2060     MXFStreamContext *sc = st->priv_data;
2061     int i, cid, frame_size = 0;
2062
2063     if (mxf->header_written)
2064         return 1;
2065
2066     if (pkt->size < 43)
2067         return 0;
2068
2069     sc->codec_ul = NULL;
2070     cid = AV_RB32(pkt->data + 0x28);
2071     for (i = 0; i < FF_ARRAY_ELEMS(mxf_dnxhd_codec_uls); i++) {
2072         if (cid == mxf_dnxhd_codec_uls[i].cid) {
2073             sc->codec_ul = &mxf_dnxhd_codec_uls[i].codec_ul;
2074             break;
2075         }
2076     }
2077     if (!sc->codec_ul)
2078         return 0;
2079
2080     sc->component_depth = 0;
2081     switch (pkt->data[0x21] >> 5) {
2082     case 1: sc->component_depth = 8; break;
2083     case 2: sc->component_depth = 10; break;
2084     case 3: sc->component_depth = 12; break;
2085     }
2086     if (!sc->component_depth)
2087         return 0;
2088
2089     if ((frame_size = avpriv_dnxhd_get_frame_size(cid)) == DNXHD_VARIABLE) {
2090         frame_size = avpriv_dnxhd_get_hr_frame_size(cid, st->codecpar->width, st->codecpar->height);
2091     }
2092     if (frame_size < 0)
2093         return 0;
2094
2095     if ((sc->interlaced = avpriv_dnxhd_get_interlaced(cid)) < 0)
2096         return 0;
2097
2098     if (cid >= 1270) { // RI raster
2099         av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2100                   st->codecpar->width, st->codecpar->height,
2101                   INT_MAX);
2102     } else {
2103         sc->aspect_ratio = (AVRational){ 16, 9 };
2104     }
2105
2106     sc->frame_size = pkt->size;
2107
2108     return 1;
2109 }
2110
2111 static const struct {
2112     const UID container_ul;
2113     const UID codec_ul;
2114 } mxf_dv_uls[] = {
2115     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x01,0x01 }, // IEC DV25 525/60
2116       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x01,0x00 } },
2117     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x02,0x01 }, // IEC DV25 626/50
2118       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x02,0x00 } },
2119     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x40,0x01 }, // DV25 525/60
2120       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x01,0x00 }, },
2121     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, // DV25 625/50
2122       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x02,0x00 }, },
2123     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x50,0x01 }, // DV50 525/60
2124       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x03,0x00 }, },
2125     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x51,0x01 }, // DV50 625/50
2126       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x04,0x00 }, },
2127     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x60,0x01 }, // DV100 1080/60
2128       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x05,0x00 }, },
2129     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x61,0x01 }, // DV100 1080/50
2130       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x06,0x00 }, },
2131     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x62,0x01 }, // DV100 720/60
2132       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x07,0x00 }, },
2133     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x63,0x01 }, // DV100 720/50
2134       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x08,0x00 }, },
2135 };
2136
2137 static int mxf_parse_dv_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2138 {
2139     MXFContext *mxf = s->priv_data;
2140     MXFStreamContext *sc = st->priv_data;
2141     uint8_t *vs_pack, *vsc_pack;
2142     int apt, ul_index, stype, pal;
2143
2144     if (mxf->header_written)
2145         return 1;
2146
2147     // Check for minimal frame size
2148     if (pkt->size < 120000)
2149         return -1;
2150
2151     apt      = pkt->data[4] & 0x7;
2152     vs_pack  = pkt->data + 80*5 + 48;
2153     vsc_pack = pkt->data + 80*5 + 53;
2154     stype    = vs_pack[3] & 0x1f;
2155     pal      = (vs_pack[3] >> 5) & 0x1;
2156
2157     if ((vsc_pack[2] & 0x07) == 0x02) {
2158         sc->aspect_ratio = (AVRational){ 16, 9 };
2159     } else {
2160         sc->aspect_ratio = (AVRational){ 4, 3 };
2161     }
2162
2163     sc->interlaced = (vsc_pack[3] >> 4) & 0x01;
2164     // TODO: fix dv encoder to set proper FF/FS value in VSC pack
2165     // and set field dominance accordingly
2166     // av_log(s, AV_LOG_DEBUG, "DV vsc pack ff/ss = %x\n", vsc_pack[2] >> 6);
2167
2168     switch (stype) {
2169     case 0x18: // DV100 720p
2170         ul_index = 8+pal;
2171         if (sc->interlaced) {
2172             av_log(s, AV_LOG_ERROR, "source marked as interlaced but codec profile is progressive\n");
2173             sc->interlaced = 0;
2174         }
2175         break;
2176     case 0x14: // DV100 1080i
2177         ul_index = 6+pal;
2178         break;
2179     case 0x04: // DV50
2180         ul_index = 4+pal;
2181         break;
2182     default: // DV25
2183         if (!apt) { // IEC
2184             ul_index = 0+pal;
2185         } else {
2186             ul_index = 2+pal;
2187         }
2188     }
2189
2190     sc->container_ul = &mxf_dv_uls[ul_index].container_ul;
2191     sc->codec_ul = &mxf_dv_uls[ul_index].codec_ul;
2192
2193     sc->frame_size = pkt->size;
2194
2195     return 1;
2196 }
2197
2198 static const struct {
2199     UID uid;
2200     int frame_size;
2201     int profile;
2202     uint8_t interlaced;
2203     int intra_only; // 1 or 0 when there are separate UIDs for Long GOP and Intra, -1 when Intra/LGOP detection can be ignored
2204 } mxf_h264_codec_uls[] = {
2205     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x11,0x01 },      0,  66, 0, -1 }, // AVC Baseline
2206     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x20,0x01 },      0,  77, 0, -1 }, // AVC Main
2207     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x30,0x01 },      0,  88, 0, -1 }, // AVC Extended
2208     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x40,0x01 },      0, 100, 0, -1 }, // AVC High
2209     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x50,0x01 },      0, 110, 0,  0 }, // AVC High 10
2210     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x60,0x01 },      0, 122, 0,  0 }, // AVC High 422
2211     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x70,0x01 },      0, 244, 0,  0 }, // AVC High 444
2212     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x20,0x01 },      0, 110, 0,  1 }, // AVC High 10 Intra
2213     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 232960, 110, 1,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/59.94i
2214     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 281088, 110, 1,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/50i
2215     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 232960, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/29.97p
2216     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 281088, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/25p
2217     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x08 }, 116736, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 720/59.94p
2218     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x09 }, 140800, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 720/50p
2219     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x30,0x01 },      0, 122, 0,  1 }, // AVC High 422 Intra
2220     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x01 }, 472576, 122, 1,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/59.94i
2221     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x02 }, 568832, 122, 1,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/50i
2222     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x03 }, 472576, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/29.97p
2223     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x04 }, 568832, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/25p
2224     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x08 }, 236544, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 720/59.94p
2225     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x09 }, 284672, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 720/50p
2226     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x40,0x01 },      0, 244, 0,  1 }, // AVC High 444 Intra
2227     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x50,0x01 },      0,  44, 0, -1 }, // AVC CAVLC 444
2228 };
2229
2230 static int mxf_parse_h264_frame(AVFormatContext *s, AVStream *st,
2231                                 AVPacket *pkt, MXFIndexEntry *e)
2232 {
2233     MXFContext *mxf = s->priv_data;
2234     MXFStreamContext *sc = st->priv_data;
2235     H264SPS seq, *const sps = &seq;
2236     GetBitContext gb;
2237     const uint8_t *buf = pkt->data;
2238     const uint8_t *buf_end = pkt->data + pkt->size;
2239     const uint8_t *nal_end;
2240     uint32_t state = -1;
2241     int extra_size = 512; // support AVC Intra files without SPS/PPS header
2242     int i, frame_size, slice_type, has_sps = 0, intra_only = 0, ret;
2243
2244     for (;;) {
2245         buf = avpriv_find_start_code(buf, buf_end, &state);
2246         if (buf >= buf_end)
2247             break;
2248
2249         switch (state & 0x1f) {
2250         case H264_NAL_SPS:
2251             e->flags |= 0x40;
2252
2253             if (mxf->header_written)
2254                 break;
2255
2256             nal_end = ff_avc_find_startcode(buf, buf_end);
2257             ret = ff_avc_decode_sps(sps, buf, nal_end - buf);
2258             if (ret < 0) {
2259                 av_log(s, AV_LOG_ERROR, "error parsing sps\n");
2260                 return 0;
2261             }
2262             has_sps = 1;
2263
2264             sc->aspect_ratio.num = st->codecpar->width * sps->sar.num;
2265             sc->aspect_ratio.den = st->codecpar->height * sps->sar.den;
2266             av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2267                       sc->aspect_ratio.num, sc->aspect_ratio.den, 1024*1024);
2268             intra_only = (sps->constraint_set_flags >> 3) & 1;
2269             sc->interlaced = !sps->frame_mbs_only_flag;
2270             sc->component_depth = sps->bit_depth_luma;
2271
2272             buf = nal_end;
2273             break;
2274         case H264_NAL_PPS:
2275             if (e->flags & 0x40) { // sequence header present
2276                 e->flags |= 0x80; // random access
2277                 extra_size = 0;
2278             }
2279             break;
2280         case H264_NAL_IDR_SLICE:
2281             e->flags |= 0x04; // IDR Picture
2282             buf = buf_end;
2283             break;
2284         case H264_NAL_SLICE:
2285             init_get_bits8(&gb, buf, buf_end - buf);
2286             get_ue_golomb_long(&gb); // skip first_mb_in_slice
2287             slice_type = get_ue_golomb_31(&gb);
2288             switch (slice_type % 5) {
2289             case 0:
2290                 e->flags |= 0x20; // P Picture
2291                 e->flags |= 0x06; // P Picture
2292                 break;
2293             case 1:
2294                 e->flags |= 0x30; // B Picture
2295                 e->flags |= 0x03; // non-referenced B Picture
2296                 break;
2297             }
2298             buf = buf_end;
2299             break;
2300         default:
2301             break;
2302         }
2303     }
2304
2305     if (mxf->header_written)
2306         return 1;
2307
2308     if (!has_sps)
2309         sc->interlaced = st->codecpar->field_order != AV_FIELD_PROGRESSIVE ? 1 : 0;
2310     sc->codec_ul = NULL;
2311     frame_size = pkt->size + extra_size;
2312
2313     for (i = 0; i < FF_ARRAY_ELEMS(mxf_h264_codec_uls); i++) {
2314         if (frame_size == mxf_h264_codec_uls[i].frame_size && sc->interlaced == mxf_h264_codec_uls[i].interlaced) {
2315             sc->codec_ul = &mxf_h264_codec_uls[i].uid;
2316             sc->component_depth = 10; // AVC Intra is always 10 Bit
2317             sc->aspect_ratio = (AVRational){ 16, 9 }; // 16:9 is mandatory for broadcast HD
2318             st->codecpar->profile = mxf_h264_codec_uls[i].profile;
2319             sc->avc_intra = 1;
2320             mxf->cbr_index = 1;
2321             sc->frame_size = pkt->size;
2322             if (sc->interlaced)
2323                 sc->field_dominance = 1; // top field first is mandatory for AVC Intra
2324             break;
2325         } else if (has_sps && mxf_h264_codec_uls[i].frame_size == 0 &&
2326                    mxf_h264_codec_uls[i].profile == sps->profile_idc &&
2327                    (mxf_h264_codec_uls[i].intra_only < 0 ||
2328                     mxf_h264_codec_uls[i].intra_only == intra_only)) {
2329             sc->codec_ul = &mxf_h264_codec_uls[i].uid;
2330             st->codecpar->profile = sps->profile_idc;
2331             st->codecpar->level = sps->level_idc;
2332             // continue to check for avc intra
2333         }
2334     }
2335
2336     if (!sc->codec_ul) {
2337         av_log(s, AV_LOG_ERROR, "h264 profile not supported\n");
2338         return 0;
2339     }
2340
2341     return 1;
2342 }
2343
2344 static const UID mxf_mpeg2_codec_uls[] = {
2345     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
2346     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
2347     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
2348     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
2349     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
2350     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
2351     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
2352     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
2353     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x02,0x00 }, // MP@H-14 I-Frame
2354     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x03,0x00 }, // MP@H-14 Long GOP
2355 };
2356
2357 static const UID *mxf_get_mpeg2_codec_ul(AVCodecParameters *par)
2358 {
2359     int long_gop = 1;
2360
2361     if (par->profile == 4) { // Main
2362         if (par->level == 8) // Main
2363             return &mxf_mpeg2_codec_uls[0+long_gop];
2364         else if (par->level == 4) // High
2365             return &mxf_mpeg2_codec_uls[4+long_gop];
2366         else if (par->level == 6) // High 14
2367             return &mxf_mpeg2_codec_uls[8+long_gop];
2368     } else if (par->profile == 0) { // 422
2369         if (par->level == 5) // Main
2370             return &mxf_mpeg2_codec_uls[2+long_gop];
2371         else if (par->level == 2) // High
2372             return &mxf_mpeg2_codec_uls[6+long_gop];
2373     }
2374     return NULL;
2375 }
2376
2377 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
2378                                  AVPacket *pkt, MXFIndexEntry *e)
2379 {
2380     MXFStreamContext *sc = st->priv_data;
2381     uint32_t c = -1;
2382     int i;
2383
2384     for(i = 0; i < pkt->size - 4; i++) {
2385         c = (c<<8) + pkt->data[i];
2386         if (c == 0x1b5) {
2387             if ((pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
2388                 st->codecpar->profile = pkt->data[i+1] & 0x07;
2389                 st->codecpar->level   = pkt->data[i+2] >> 4;
2390                 sc->low_delay = pkt->data[i+6] >> 7;
2391             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
2392                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
2393                 if (sc->interlaced)
2394                     sc->field_dominance = 1 + !(pkt->data[i+4] & 0x80); // top field first
2395                 break;
2396             }
2397         } else if (c == 0x1b8) { // gop
2398             if (pkt->data[i+4]>>6 & 0x01) { // closed
2399                 if (sc->seq_closed_gop == -1)
2400                     sc->seq_closed_gop = 1;
2401                 sc->closed_gop = 1;
2402                 if (e->flags & 0x40) // sequence header present
2403                     e->flags |= 0x80; // random access
2404             } else {
2405                 sc->seq_closed_gop = 0;
2406                 sc->closed_gop = 0;
2407             }
2408         } else if (c == 0x1b3) { // seq
2409             e->flags |= 0x40;
2410             switch ((pkt->data[i+4]>>4) & 0xf) {
2411             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
2412             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
2413             case 4:  sc->aspect_ratio = (AVRational){221,100}; break;
2414             default:
2415                 av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2416                           st->codecpar->width, st->codecpar->height, 1024*1024);
2417             }
2418         } else if (c == 0x100) { // pic
2419             int pict_type = (pkt->data[i+2]>>3) & 0x07;
2420             e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
2421             if (pict_type == 2) { // P-frame
2422                 e->flags |= 0x22;
2423                 sc->closed_gop = 0; // reset closed GOP, don't matter anymore
2424             } else if (pict_type == 3) { // B-frame
2425                 if (sc->closed_gop)
2426                     e->flags |= 0x13; // only backward prediction
2427                 else
2428                     e->flags |= 0x33;
2429                 sc->temporal_reordering = -1;
2430             } else if (!pict_type) {
2431                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
2432                 return 0;
2433             }
2434         }
2435     }
2436     if (s->oformat != &ff_mxf_d10_muxer)
2437         sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codecpar);
2438     return !!sc->codec_ul;
2439 }
2440
2441 static uint64_t mxf_parse_timestamp(int64_t timestamp64)
2442 {
2443     time_t timestamp = timestamp64 / 1000000;
2444     struct tm tmbuf;
2445     struct tm *time = gmtime_r(&timestamp, &tmbuf);
2446     if (!time)
2447         return 0;
2448     return (uint64_t)(time->tm_year+1900) << 48 |
2449            (uint64_t)(time->tm_mon+1)     << 40 |
2450            (uint64_t) time->tm_mday       << 32 |
2451                       time->tm_hour       << 24 |
2452                       time->tm_min        << 16 |
2453                       time->tm_sec        << 8  |
2454                       (timestamp64 % 1000000) / 4000;
2455 }
2456
2457 static void mxf_gen_umid(AVFormatContext *s)
2458 {
2459     MXFContext *mxf = s->priv_data;
2460     uint32_t seed = av_get_random_seed();
2461     uint64_t umid = seed + 0x5294713400000000LL;
2462
2463     AV_WB64(mxf->umid  , umid);
2464     AV_WB64(mxf->umid+8, umid>>8);
2465
2466     mxf->instance_number = seed & 0xFFFFFF;
2467 }
2468
2469 static int mxf_init_timecode(AVFormatContext *s, AVStream *st, AVRational tbc)
2470 {
2471     MXFContext *mxf = s->priv_data;
2472     AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
2473
2474     if (!ff_mxf_get_content_package_rate(tbc)) {
2475         if (s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
2476             av_log(s, AV_LOG_ERROR, "Unsupported frame rate %d/%d. Set -strict option to 'unofficial' or lower in order to allow it!\n", tbc.den, tbc.num);
2477             return AVERROR(EINVAL);
2478         } else {
2479             av_log(s, AV_LOG_WARNING, "Unofficial frame rate %d/%d.\n", tbc.den, tbc.num);
2480         }
2481     }
2482
2483     mxf->timecode_base = (tbc.den + tbc.num/2) / tbc.num;
2484     if (!tcr)
2485         tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
2486
2487     if (tcr)
2488         return av_timecode_init_from_string(&mxf->tc, av_inv_q(tbc), tcr->value, s);
2489     else
2490         return av_timecode_init(&mxf->tc, av_inv_q(tbc), 0, 0, s);
2491 }
2492
2493 static int mxf_write_header(AVFormatContext *s)
2494 {
2495     MXFContext *mxf = s->priv_data;
2496     int i, ret;
2497     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
2498     int64_t timestamp = 0;
2499
2500     if (!s->nb_streams)
2501         return -1;
2502
2503     if (s->oformat == &ff_mxf_opatom_muxer && s->nb_streams !=1) {
2504         av_log(s, AV_LOG_ERROR, "there must be exactly one stream for mxf opatom\n");
2505         return -1;
2506     }
2507
2508     if (!av_dict_get(s->metadata, "comment_", NULL, AV_DICT_IGNORE_SUFFIX))
2509         mxf->store_user_comments = 0;
2510
2511     for (i = 0; i < s->nb_streams; i++) {
2512         AVStream *st = s->streams[i];
2513         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
2514         if (!sc)
2515             return AVERROR(ENOMEM);
2516         st->priv_data = sc;
2517         sc->index = -1;
2518
2519         if (((i == 0) ^ (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) && s->oformat != &ff_mxf_opatom_muxer) {
2520             av_log(s, AV_LOG_ERROR, "there must be exactly one video stream and it must be the first one\n");
2521             return -1;
2522         }
2523
2524         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2525             const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(st->codecpar->format);
2526             // TODO: should be avg_frame_rate
2527             AVRational tbc = st->time_base;
2528             // Default component depth to 8
2529             sc->component_depth = 8;
2530             sc->h_chroma_sub_sample = 2;
2531             sc->v_chroma_sub_sample = 2;
2532             sc->color_siting = 0xFF;
2533
2534             if (st->codecpar->sample_aspect_ratio.num && st->codecpar->sample_aspect_ratio.den) {
2535                 sc->aspect_ratio = av_mul_q(st->codecpar->sample_aspect_ratio,
2536                                             av_make_q(st->codecpar->width, st->codecpar->height));
2537             }
2538
2539             if (pix_desc) {
2540                 sc->component_depth     = pix_desc->comp[0].depth;
2541                 sc->h_chroma_sub_sample = 1 << pix_desc->log2_chroma_w;
2542                 sc->v_chroma_sub_sample = 1 << pix_desc->log2_chroma_h;
2543             }
2544             switch (ff_choose_chroma_location(s, st)) {
2545             case AVCHROMA_LOC_TOPLEFT: sc->color_siting = 0; break;
2546             case AVCHROMA_LOC_LEFT:    sc->color_siting = 6; break;
2547             case AVCHROMA_LOC_TOP:     sc->color_siting = 1; break;
2548             case AVCHROMA_LOC_CENTER:  sc->color_siting = 3; break;
2549             }
2550
2551             mxf->content_package_rate = ff_mxf_get_content_package_rate(tbc);
2552             mxf->time_base = tbc;
2553             avpriv_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
2554             if((ret = mxf_init_timecode(s, st, tbc)) < 0)
2555                 return ret;
2556
2557             if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2558                 sc->seq_closed_gop = -1; // unknown yet
2559             }
2560
2561             sc->video_bit_rate = st->codecpar->bit_rate;
2562
2563             if (s->oformat == &ff_mxf_d10_muxer ||
2564                 st->codecpar->codec_id == AV_CODEC_ID_DNXHD ||
2565                 st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO)
2566                 mxf->cbr_index = 1;
2567
2568             if (s->oformat == &ff_mxf_d10_muxer) {
2569                 int ntsc = mxf->time_base.den != 25;
2570                 int ul_index;
2571
2572                 if (st->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
2573                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support MPEG-2 Video\n");
2574                     return AVERROR(EINVAL);
2575                 }
2576                 if ((sc->video_bit_rate == 50000000) && (mxf->time_base.den == 25)) {
2577                     ul_index = 0;
2578                 } else if ((sc->video_bit_rate == 49999840 || sc->video_bit_rate == 50000000) && ntsc) {
2579                     ul_index = 1;
2580                 } else if (sc->video_bit_rate == 40000000) {
2581                     ul_index = 2+ntsc;
2582                 } else if (sc->video_bit_rate == 30000000) {
2583                     ul_index = 4+ntsc;
2584                 } else {
2585                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
2586                     return -1;
2587                 }
2588
2589                 sc->codec_ul = &mxf_d10_codec_uls[ul_index];
2590                 sc->container_ul = &mxf_d10_container_uls[ul_index];
2591                 sc->index = INDEX_D10_VIDEO;
2592                 sc->signal_standard = 1;
2593                 sc->color_siting = 0;
2594                 sc->frame_size = (int64_t)sc->video_bit_rate *
2595                     mxf->time_base.num / (8*mxf->time_base.den);
2596             }
2597             if (mxf->signal_standard >= 0)
2598                 sc->signal_standard = mxf->signal_standard;
2599         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2600             char bsf_arg[32];
2601             if (st->codecpar->sample_rate != 48000) {
2602                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
2603                 return -1;
2604             }
2605             avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
2606             if (s->oformat == &ff_mxf_d10_muxer) {
2607                 if (st->index != 1) {
2608                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
2609                     return -1;
2610                 }
2611                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2612                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2613                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support 16 or 24 bits le audio\n");
2614                 }
2615                 sc->index = INDEX_D10_AUDIO;
2616                 sc->container_ul = ((MXFStreamContext*)s->streams[0]->priv_data)->container_ul;
2617                 sc->frame_size = 4 + 8 * av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num, mxf->time_base.den, AV_ROUND_UP) * 4;
2618             } else if (s->oformat == &ff_mxf_opatom_muxer) {
2619                 AVRational tbc = av_inv_q(mxf->audio_edit_rate);
2620
2621                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2622                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2623                     av_log(s, AV_LOG_ERROR, "Only pcm_s16le and pcm_s24le audio codecs are implemented\n");
2624                     return AVERROR_PATCHWELCOME;
2625                 }
2626                 if (st->codecpar->channels != 1) {
2627                     av_log(s, AV_LOG_ERROR, "MXF OPAtom only supports single channel audio\n");
2628                     return AVERROR(EINVAL);
2629                 }
2630
2631                 mxf->time_base = st->time_base;
2632                 if((ret = mxf_init_timecode(s, st, tbc)) < 0)
2633                     return ret;
2634
2635                 mxf->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3;
2636                 sc->index = INDEX_WAV;
2637             } else {
2638                 mxf->slice_count = 1;
2639                 sc->frame_size = st->codecpar->channels *
2640                                  av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num, mxf->time_base.den, AV_ROUND_UP) *
2641                                  av_get_bits_per_sample(st->codecpar->codec_id) / 8;
2642             }
2643             snprintf(bsf_arg, sizeof(bsf_arg), "r=%d/%d", mxf->tc.rate.num, mxf->tc.rate.den);
2644             ret = ff_stream_add_bitstream_filter(st, "pcm_rechunk", bsf_arg);
2645             if (ret < 0)
2646                 return ret;
2647         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
2648             AVDictionaryEntry *e = av_dict_get(st->metadata, "data_type", NULL, 0);
2649             if (e && !strcmp(e->value, "vbi_vanc_smpte_436M")) {
2650                 sc->index = INDEX_S436M;
2651             } else {
2652                 av_log(s, AV_LOG_ERROR, "track %d: unsupported data type\n", i);
2653                 return -1;
2654             }
2655             if (st->index != s->nb_streams - 1) {
2656                 av_log(s, AV_LOG_ERROR, "data track must be placed last\n");
2657                 return -1;
2658             }
2659         }
2660
2661         if (sc->index == -1) {
2662             sc->index = mxf_get_essence_container_ul_index(st->codecpar->codec_id);
2663             if (sc->index == -1) {
2664                 av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
2665                        "codec not currently supported in container\n", i);
2666                 return -1;
2667             }
2668         }
2669
2670         if (!sc->codec_ul)
2671             sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
2672         if (!sc->container_ul)
2673             sc->container_ul = &mxf_essence_container_uls[sc->index].container_ul;
2674
2675         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
2676         sc->track_essence_element_key[15] = present[sc->index];
2677         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
2678
2679         if (!present[sc->index])
2680             mxf->essence_container_count++;
2681         present[sc->index]++;
2682     }
2683
2684     if (s->oformat == &ff_mxf_d10_muxer || s->oformat == &ff_mxf_opatom_muxer) {
2685         mxf->essence_container_count = 1;
2686     }
2687
2688     if (!(s->flags & AVFMT_FLAG_BITEXACT))
2689         mxf_gen_umid(s);
2690
2691     for (i = 0; i < s->nb_streams; i++) {
2692         MXFStreamContext *sc = s->streams[i]->priv_data;
2693         // update element count
2694         sc->track_essence_element_key[13] = present[sc->index];
2695         if (!memcmp(sc->track_essence_element_key, mxf_essence_container_uls[INDEX_DV].element_ul, 13)) // DV
2696             sc->order = (0x15 << 24) | AV_RB32(sc->track_essence_element_key+13);
2697         else
2698             sc->order = AV_RB32(sc->track_essence_element_key+12);
2699     }
2700
2701     if (ff_parse_creation_time_metadata(s, &timestamp, 0) > 0)
2702         mxf->timestamp = mxf_parse_timestamp(timestamp);
2703     mxf->duration = -1;
2704
2705     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
2706     if (!mxf->timecode_track)
2707         return AVERROR(ENOMEM);
2708     mxf->timecode_track->priv_data = av_mallocz(sizeof(MXFStreamContext));
2709     if (!mxf->timecode_track->priv_data)
2710         return AVERROR(ENOMEM);
2711     mxf->timecode_track->index = -1;
2712
2713     return 0;
2714 }
2715
2716 static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
2717 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 };
2718
2719 static void mxf_write_system_item(AVFormatContext *s)
2720 {
2721     MXFContext *mxf = s->priv_data;
2722     AVIOContext *pb = s->pb;
2723     unsigned frame;
2724     uint32_t time_code;
2725     int i, system_item_bitmap = 0x58; // UL, user date/time stamp, picture present
2726
2727     frame = mxf->last_indexed_edit_unit + mxf->edit_units_count;
2728
2729     // write system metadata pack
2730     avio_write(pb, system_metadata_pack_key, 16);
2731     klv_encode_ber4_length(pb, 57);
2732
2733     for (i = 0; i < s->nb_streams; i++) {
2734         if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2735             system_item_bitmap |= 0x4;
2736         else if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2737             system_item_bitmap |= 0x2;
2738     }
2739     avio_w8(pb, system_item_bitmap);
2740     avio_w8(pb, mxf->content_package_rate); // content package rate
2741     avio_w8(pb, 0x00); // content package type
2742     avio_wb16(pb, 0x00); // channel handle
2743     avio_wb16(pb, frame & 0xFFFF); // continuity count, supposed to overflow
2744     if (mxf->essence_container_count > 1)
2745         avio_write(pb, multiple_desc_ul, 16);
2746     else {
2747         MXFStreamContext *sc = s->streams[0]->priv_data;
2748         avio_write(pb, *sc->container_ul, 16);
2749     }
2750     avio_w8(pb, 0);
2751     avio_wb64(pb, 0);
2752     avio_wb64(pb, 0); // creation date/time stamp
2753
2754     avio_w8(pb, 0x81); // SMPTE 12M time code
2755     time_code = av_timecode_get_smpte_from_framenum(&mxf->tc, frame);
2756     avio_wb32(pb, time_code);
2757     avio_wb32(pb, 0); // binary group data
2758     avio_wb64(pb, 0);
2759
2760     // write system metadata package set
2761     avio_write(pb, system_metadata_package_set_key, 16);
2762     klv_encode_ber4_length(pb, 35);
2763     avio_w8(pb, 0x83); // UMID
2764     avio_wb16(pb, 0x20);
2765     mxf_write_umid(s, 1);
2766 }
2767
2768 static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2769 {
2770     MXFContext *mxf = s->priv_data;
2771     AVIOContext *pb = s->pb;
2772     int frame_size = pkt->size / st->codecpar->block_align;
2773     uint8_t *samples = pkt->data;
2774     uint8_t *end = pkt->data + pkt->size;
2775     int i;
2776
2777     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
2778
2779     avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
2780     avio_wl16(pb, frame_size);
2781     avio_w8(pb, (1<<st->codecpar->channels)-1);
2782
2783     while (samples < end) {
2784         for (i = 0; i < st->codecpar->channels; i++) {
2785             uint32_t sample;
2786             if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
2787                 sample = AV_RL24(samples)<< 4;
2788                 samples += 3;
2789             } else {
2790                 sample = AV_RL16(samples)<<12;
2791                 samples += 2;
2792             }
2793             avio_wl32(pb, sample | i);
2794         }
2795         for (; i < 8; i++)
2796             avio_wl32(pb, i);
2797     }
2798 }
2799
2800 static int mxf_write_opatom_body_partition(AVFormatContext *s)
2801 {
2802     MXFContext *mxf = s->priv_data;
2803     AVIOContext *pb = s->pb;
2804     AVStream *st = s->streams[0];
2805     MXFStreamContext *sc = st->priv_data;
2806     const uint8_t *key = NULL;
2807
2808     int err;
2809
2810     if (!mxf->header_written)
2811         key = body_partition_key;
2812
2813     if ((err = mxf_write_partition(s, 1, 0, key, 0)) < 0)
2814         return err;
2815     mxf_write_klv_fill(s);
2816     avio_write(pb, sc->track_essence_element_key, 16);
2817     klv_encode_ber9_length(pb, mxf->body_offset);
2818     return 0;
2819 }
2820
2821 static int mxf_write_opatom_packet(AVFormatContext *s, AVPacket *pkt, MXFIndexEntry *ie)
2822 {
2823     MXFContext *mxf = s->priv_data;
2824     AVIOContext *pb = s->pb;
2825
2826     int err;
2827
2828     if (!mxf->header_written) {
2829         if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2830             return err;
2831         mxf_write_klv_fill(s);
2832
2833         if ((err = mxf_write_opatom_body_partition(s)) < 0)
2834             return err;
2835         mxf->header_written = 1;
2836     }
2837
2838     if (!mxf->edit_unit_byte_count) {
2839         mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
2840         mxf->index_entries[mxf->edit_units_count].flags = ie->flags;
2841         mxf->index_entries[mxf->edit_units_count].temporal_ref = ie->temporal_ref;
2842     }
2843     mxf->edit_units_count++;
2844     avio_write(pb, pkt->data, pkt->size);
2845     mxf->body_offset += pkt->size;
2846
2847     return 0;
2848 }
2849
2850 static void mxf_compute_edit_unit_byte_count(AVFormatContext *s)
2851 {
2852     MXFContext *mxf = s->priv_data;
2853     int i;
2854
2855     if (s->oformat == &ff_mxf_opatom_muxer) {
2856         MXFStreamContext *sc = s->streams[0]->priv_data;
2857         mxf->edit_unit_byte_count = sc->frame_size;
2858         return;
2859     }
2860
2861     mxf->edit_unit_byte_count = KAG_SIZE; // system element
2862     for (i = 0; i < s->nb_streams; i++) {
2863         AVStream *st = s->streams[i];
2864         MXFStreamContext *sc = st->priv_data;
2865         sc->slice_offset = mxf->edit_unit_byte_count;
2866         mxf->edit_unit_byte_count += 16 + 4 + sc->frame_size;
2867         mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
2868     }
2869 }
2870
2871 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
2872 {
2873     MXFContext *mxf = s->priv_data;
2874     AVIOContext *pb = s->pb;
2875     AVStream *st = s->streams[pkt->stream_index];
2876     MXFStreamContext *sc = st->priv_data;
2877     MXFIndexEntry ie = {0};
2878     int err;
2879
2880     if (!mxf->cbr_index && !mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
2881         if ((err = av_reallocp_array(&mxf->index_entries, mxf->edit_units_count
2882                                      + EDIT_UNITS_PER_BODY, sizeof(*mxf->index_entries))) < 0) {
2883             mxf->edit_units_count = 0;
2884             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
2885             return err;
2886         }
2887     }
2888
2889     if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2890         if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
2891             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
2892             return -1;
2893         }
2894     } else if (st->codecpar->codec_id == AV_CODEC_ID_DNXHD) {
2895         if (!mxf_parse_dnxhd_frame(s, st, pkt)) {
2896             av_log(s, AV_LOG_ERROR, "could not get dnxhd profile\n");
2897             return -1;
2898         }
2899     } else if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2900         if (!mxf_parse_prores_frame(s, st, pkt)) {
2901             av_log(s, AV_LOG_ERROR, "could not get prores profile\n");
2902             return -1;
2903         }
2904     } else if (st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO) {
2905         if (!mxf_parse_dv_frame(s, st, pkt)) {
2906             av_log(s, AV_LOG_ERROR, "could not get dv profile\n");
2907             return -1;
2908         }
2909     } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
2910         if (!mxf_parse_h264_frame(s, st, pkt, &ie)) {
2911             av_log(s, AV_LOG_ERROR, "could not get h264 profile\n");
2912             return -1;
2913         }
2914     }
2915
2916     if (mxf->cbr_index) {
2917         if (pkt->size != sc->frame_size && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2918             av_log(s, AV_LOG_ERROR, "track %d: frame size does not match index unit size, %d != %d\n",
2919                    st->index, pkt->size, sc->frame_size);
2920             return -1;
2921         }
2922         if (!mxf->header_written)
2923             mxf_compute_edit_unit_byte_count(s);
2924     }
2925
2926     if (s->oformat == &ff_mxf_opatom_muxer)
2927         return mxf_write_opatom_packet(s, pkt, &ie);
2928
2929     if (!mxf->header_written) {
2930         if (mxf->edit_unit_byte_count) {
2931             if ((err = mxf_write_partition(s, 1, 2, header_open_partition_key, 1)) < 0)
2932                 return err;
2933             mxf_write_klv_fill(s);
2934             mxf_write_index_table_segment(s);
2935         } else {
2936             if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2937                 return err;
2938         }
2939         mxf->header_written = 1;
2940     }
2941
2942     if (st->index == 0) {
2943         if (!mxf->edit_unit_byte_count &&
2944             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
2945             !(ie.flags & 0x33)) { // I-frame, GOP start
2946             mxf_write_klv_fill(s);
2947             if ((err = mxf_write_partition(s, 1, 2, body_partition_key, 0)) < 0)
2948                 return err;
2949             mxf_write_klv_fill(s);
2950             mxf_write_index_table_segment(s);
2951         }
2952
2953         mxf_write_klv_fill(s);
2954         mxf_write_system_item(s);
2955
2956         if (!mxf->edit_unit_byte_count) {
2957             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
2958             mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
2959             mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
2960             mxf->body_offset += KAG_SIZE; // size of system element
2961         }
2962         mxf->edit_units_count++;
2963     } else if (!mxf->edit_unit_byte_count && st->index == 1) {
2964         if (!mxf->edit_units_count) {
2965             av_log(s, AV_LOG_ERROR, "No packets in first stream\n");
2966             return AVERROR_PATCHWELCOME;
2967         }
2968         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
2969             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
2970     }
2971
2972     mxf_write_klv_fill(s);
2973     avio_write(pb, sc->track_essence_element_key, 16); // write key
2974     if (s->oformat == &ff_mxf_d10_muxer &&
2975         st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2976         mxf_write_d10_audio_packet(s, st, pkt);
2977     } else {
2978         klv_encode_ber4_length(pb, pkt->size); // write length
2979         avio_write(pb, pkt->data, pkt->size);
2980         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
2981     }
2982
2983     return 0;
2984 }
2985
2986 static void mxf_write_random_index_pack(AVFormatContext *s)
2987 {
2988     MXFContext *mxf = s->priv_data;
2989     AVIOContext *pb = s->pb;
2990     uint64_t pos = avio_tell(pb);
2991     int i;
2992
2993     avio_write(pb, ff_mxf_random_index_pack_key, 16);
2994     klv_encode_ber_length(pb, 28 + 12LL*mxf->body_partitions_count);
2995
2996     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer)
2997         avio_wb32(pb, 1); // BodySID of header partition
2998     else
2999         avio_wb32(pb, 0);
3000     avio_wb64(pb, 0); // offset of header partition
3001
3002     for (i = 0; i < mxf->body_partitions_count; i++) {
3003         avio_wb32(pb, 1); // BodySID
3004         avio_wb64(pb, mxf->body_partition_offset[i]);
3005     }
3006
3007     avio_wb32(pb, 0); // BodySID of footer partition
3008     avio_wb64(pb, mxf->footer_partition_offset);
3009
3010     avio_wb32(pb, avio_tell(pb) - pos + 4);
3011 }
3012
3013 static int mxf_write_footer(AVFormatContext *s)
3014 {
3015     MXFContext *mxf = s->priv_data;
3016     AVIOContext *pb = s->pb;
3017     int i, err;
3018
3019     if (!mxf->header_written ||
3020         (s->oformat == &ff_mxf_opatom_muxer && !mxf->body_partition_offset)) {
3021         /* reason could be invalid options/not supported codec/out of memory */
3022         return AVERROR_UNKNOWN;
3023     }
3024
3025     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
3026
3027     mxf_write_klv_fill(s);
3028     mxf->footer_partition_offset = avio_tell(pb);
3029     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) { // no need to repeat index
3030         if ((err = mxf_write_partition(s, 0, 0, footer_partition_key, 0)) < 0)
3031             return err;
3032     } else {
3033         if ((err = mxf_write_partition(s, 0, 2, footer_partition_key, 0)) < 0)
3034             return err;
3035         mxf_write_klv_fill(s);
3036         mxf_write_index_table_segment(s);
3037     }
3038
3039     mxf_write_klv_fill(s);
3040     mxf_write_random_index_pack(s);
3041
3042     if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
3043         if (s->oformat == &ff_mxf_opatom_muxer) {
3044             /* rewrite body partition to update lengths */
3045             avio_seek(pb, mxf->body_partition_offset[0], SEEK_SET);
3046             if ((err = mxf_write_opatom_body_partition(s)) < 0)
3047                 return err;
3048         }
3049
3050         avio_seek(pb, 0, SEEK_SET);
3051         if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) {
3052             if ((err = mxf_write_partition(s, 1, 2, header_closed_partition_key, 1)) < 0)
3053                 return err;
3054             mxf_write_klv_fill(s);
3055             mxf_write_index_table_segment(s);
3056         } else {
3057             if ((err = mxf_write_partition(s, 0, 0, header_closed_partition_key, 1)) < 0)
3058                 return err;
3059         }
3060         // update footer partition offset
3061         for (i = 0; i < mxf->body_partitions_count; i++) {
3062             avio_seek(pb, mxf->body_partition_offset[i]+44, SEEK_SET);
3063             avio_wb64(pb, mxf->footer_partition_offset);
3064         }
3065     }
3066
3067     return 0;
3068 }
3069
3070 static void mxf_deinit(AVFormatContext *s)
3071 {
3072     MXFContext *mxf = s->priv_data;
3073
3074     av_freep(&mxf->index_entries);
3075     av_freep(&mxf->body_partition_offset);
3076     if (mxf->timecode_track) {
3077         av_freep(&mxf->timecode_track->priv_data);
3078         av_freep(&mxf->timecode_track);
3079     }
3080 }
3081
3082 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
3083 {
3084     int i, stream_count = 0;
3085
3086     for (i = 0; i < s->nb_streams; i++)
3087         stream_count += !!s->streams[i]->internal->last_in_packet_buffer;
3088
3089     if (stream_count && (s->nb_streams == stream_count || flush)) {
3090         AVPacketList *pktl = s->internal->packet_buffer;
3091         if (s->nb_streams != stream_count) {
3092             AVPacketList *last = NULL;
3093             // find last packet in edit unit
3094             while (pktl) {
3095                 if (!stream_count || pktl->pkt.stream_index == 0)
3096                     break;
3097                 // update last packet in packet buffer
3098                 if (s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer != pktl)
3099                     s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer = pktl;
3100                 last = pktl;
3101                 pktl = pktl->next;
3102                 stream_count--;
3103             }
3104             // purge packet queue
3105             while (pktl) {
3106                 AVPacketList *next = pktl->next;
3107                 av_packet_unref(&pktl->pkt);
3108                 av_freep(&pktl);
3109                 pktl = next;
3110             }
3111             if (last)
3112                 last->next = NULL;
3113             else {
3114                 s->internal->packet_buffer = NULL;
3115                 s->internal->packet_buffer_end= NULL;
3116                 goto out;
3117             }
3118             pktl = s->internal->packet_buffer;
3119         }
3120
3121         *out = pktl->pkt;
3122         av_log(s, AV_LOG_TRACE, "out st:%d dts:%"PRId64"\n", (*out).stream_index, (*out).dts);
3123         s->internal->packet_buffer = pktl->next;
3124         if(s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer == pktl)
3125             s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer= NULL;
3126         if(!s->internal->packet_buffer)
3127             s->internal->packet_buffer_end= NULL;
3128         av_freep(&pktl);
3129         return 1;
3130     } else {
3131     out:
3132         return 0;
3133     }
3134 }
3135
3136 static int mxf_compare_timestamps(AVFormatContext *s, const AVPacket *next,
3137                                                       const AVPacket *pkt)
3138 {
3139     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
3140     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
3141
3142     return next->dts > pkt->dts ||
3143         (next->dts == pkt->dts && sc->order < sc2->order);
3144 }
3145
3146 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
3147 {
3148     int ret;
3149     if (pkt) {
3150         MXFStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
3151         pkt->pts = pkt->dts = sc->pkt_cnt++;
3152         if ((ret = ff_interleave_add_packet(s, pkt, mxf_compare_timestamps)) < 0)
3153             return ret;
3154     }
3155     return mxf_interleave_get_packet(s, out, NULL, flush);
3156 }
3157
3158 #define MXF_COMMON_OPTIONS \
3159     { "signal_standard", "Force/set Signal Standard",\
3160       offsetof(MXFContext, signal_standard), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3161     { "bt601", "ITU-R BT.601 and BT.656, also SMPTE 125M (525 and 625 line interlaced)",\
3162       0, AV_OPT_TYPE_CONST, {.i64 = 1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3163     { "bt1358", "ITU-R BT.1358 and ITU-R BT.799-3, also SMPTE 293M (525 and 625 line progressive)",\
3164       0, AV_OPT_TYPE_CONST, {.i64 = 2}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3165     { "smpte347m", "SMPTE 347M (540 Mbps mappings)",\
3166       0, AV_OPT_TYPE_CONST, {.i64 = 3}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3167     { "smpte274m", "SMPTE 274M (1125 line)",\
3168       0, AV_OPT_TYPE_CONST, {.i64 = 4}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3169     { "smpte296m", "SMPTE 296M (750 line progressive)",\
3170       0, AV_OPT_TYPE_CONST, {.i64 = 5}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3171     { "smpte349m", "SMPTE 349M (1485 Mbps mappings)",\
3172       0, AV_OPT_TYPE_CONST, {.i64 = 6}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3173     { "smpte428", "SMPTE 428-1 DCDM",\
3174       0, AV_OPT_TYPE_CONST, {.i64 = 7}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},
3175
3176
3177
3178 static const AVOption mxf_options[] = {
3179     MXF_COMMON_OPTIONS
3180     { "store_user_comments", "",
3181       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3182     { NULL },
3183 };
3184
3185 static const AVClass mxf_muxer_class = {
3186     .class_name     = "MXF muxer",
3187     .item_name      = av_default_item_name,
3188     .option         = mxf_options,
3189     .version        = LIBAVUTIL_VERSION_INT,
3190 };
3191
3192 static const AVOption d10_options[] = {
3193     { "d10_channelcount", "Force/set channelcount in generic sound essence descriptor",
3194       offsetof(MXFContext, channel_count), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 8, AV_OPT_FLAG_ENCODING_PARAM},
3195     MXF_COMMON_OPTIONS
3196     { "store_user_comments", "",
3197       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3198     { NULL },
3199 };
3200
3201 static const AVClass mxf_d10_muxer_class = {
3202     .class_name     = "MXF-D10 muxer",
3203     .item_name      = av_default_item_name,
3204     .option         = d10_options,
3205     .version        = LIBAVUTIL_VERSION_INT,
3206 };
3207
3208 static const AVOption opatom_options[] = {
3209     { "mxf_audio_edit_rate", "Audio edit rate for timecode",
3210         offsetof(MXFContext, audio_edit_rate), AV_OPT_TYPE_RATIONAL, {.dbl=25}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
3211     MXF_COMMON_OPTIONS
3212     { "store_user_comments", "",
3213       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3214     { NULL },
3215 };
3216
3217 static const AVClass mxf_opatom_muxer_class = {
3218     .class_name     = "MXF-OPAtom muxer",
3219     .item_name      = av_default_item_name,
3220     .option         = opatom_options,
3221     .version        = LIBAVUTIL_VERSION_INT,
3222 };
3223
3224 AVOutputFormat ff_mxf_muxer = {
3225     .name              = "mxf",
3226     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
3227     .mime_type         = "application/mxf",
3228     .extensions        = "mxf",
3229     .priv_data_size    = sizeof(MXFContext),
3230     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3231     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3232     .write_header      = mxf_write_header,
3233     .write_packet      = mxf_write_packet,
3234     .write_trailer     = mxf_write_footer,
3235     .deinit            = mxf_deinit,
3236     .flags             = AVFMT_NOTIMESTAMPS,
3237     .interleave_packet = mxf_interleave,
3238     .priv_class        = &mxf_muxer_class,
3239 };
3240
3241 AVOutputFormat ff_mxf_d10_muxer = {
3242     .name              = "mxf_d10",
3243     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) D-10 Mapping"),
3244     .mime_type         = "application/mxf",
3245     .priv_data_size    = sizeof(MXFContext),
3246     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3247     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3248     .write_header      = mxf_write_header,
3249     .write_packet      = mxf_write_packet,
3250     .write_trailer     = mxf_write_footer,
3251     .deinit            = mxf_deinit,
3252     .flags             = AVFMT_NOTIMESTAMPS,
3253     .interleave_packet = mxf_interleave,
3254     .priv_class        = &mxf_d10_muxer_class,
3255 };
3256
3257 AVOutputFormat ff_mxf_opatom_muxer = {
3258     .name              = "mxf_opatom",
3259     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) Operational Pattern Atom"),
3260     .mime_type         = "application/mxf",
3261     .extensions        = "mxf",
3262     .priv_data_size    = sizeof(MXFContext),
3263     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3264     .video_codec       = AV_CODEC_ID_DNXHD,
3265     .write_header      = mxf_write_header,
3266     .write_packet      = mxf_write_packet,
3267     .write_trailer     = mxf_write_footer,
3268     .deinit            = mxf_deinit,
3269     .flags             = AVFMT_NOTIMESTAMPS,
3270     .interleave_packet = mxf_interleave,
3271     .priv_class        = &mxf_opatom_muxer_class,
3272 };