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