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