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