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