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