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