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