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