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