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