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