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