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