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