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