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