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