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