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