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