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