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