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