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