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