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