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