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