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