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