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