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