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