]> git.sesse.net Git - ffmpeg/blob - libavformat/mxfenc.c
Merge commit '37394ef01b040605f8e1c98e73aa12b1c0bcba07'
[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  * signal_standard, color_siting, store_user_comments, sample rate and klv_fill_key version
25  * fixes sponsored by NOA GmbH
26  */
27
28 /*
29  * References
30  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
31  * SMPTE 377M MXF File Format Specifications
32  * SMPTE 379M MXF Generic Container
33  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
34  * SMPTE 422M Mapping JPEG 2000 Codestreams into the MXF Generic Container
35  * SMPTE RP210: SMPTE Metadata Dictionary
36  * SMPTE RP224: Registry of SMPTE Universal Labels
37  */
38
39 #include <inttypes.h>
40 #include <math.h>
41 #include <time.h>
42
43 #include "libavutil/opt.h"
44 #include "libavutil/random_seed.h"
45 #include "libavutil/timecode.h"
46 #include "libavutil/avassert.h"
47 #include "libavutil/pixdesc.h"
48 #include "libavutil/time_internal.h"
49 #include "libavcodec/bytestream.h"
50 #include "libavcodec/dnxhddata.h"
51 #include "libavcodec/dv_profile.h"
52 #include "libavcodec/h264.h"
53 #include "libavcodec/internal.h"
54 #include "audiointerleave.h"
55 #include "avformat.h"
56 #include "avio_internal.h"
57 #include "internal.h"
58 #include "mxf.h"
59 #include "config.h"
60
61 extern AVOutputFormat ff_mxf_d10_muxer;
62 extern AVOutputFormat ff_mxf_opatom_muxer;
63
64 #define EDIT_UNITS_PER_BODY 250
65 #define KAG_SIZE 512
66
67 typedef struct MXFLocalTagPair {
68     int local_tag;
69     UID uid;
70 } MXFLocalTagPair;
71
72 typedef struct MXFIndexEntry {
73     uint8_t flags;
74     uint64_t offset;
75     unsigned slice_offset; ///< offset of audio slice
76     uint16_t temporal_ref;
77 } MXFIndexEntry;
78
79 typedef struct MXFStreamContext {
80     AudioInterleaveContext aic;
81     UID track_essence_element_key;
82     int index;               ///< index in mxf_essence_container_uls table
83     const UID *codec_ul;
84     int order;               ///< interleaving order if dts are equal
85     int interlaced;          ///< whether picture is interlaced
86     int field_dominance;     ///< tff=1, bff=2
87     int component_depth;
88     int color_siting;
89     int signal_standard;
90     int h_chroma_sub_sample;
91     int v_chroma_sub_sample;
92     int temporal_reordering;
93     AVRational aspect_ratio; ///< display aspect ratio
94     int closed_gop;          ///< gop is closed, used in mpeg-2 frame parsing
95     int video_bit_rate;
96     int slice_offset;
97     int frame_size;          ///< frame size in bytes
98     int seq_closed_gop;      ///< all gops in sequence are closed, used in mpeg-2 descriptor
99     int max_gop;             ///< maximum gop size, used by mpeg-2 descriptor
100     int b_picture_count;     ///< maximum number of consecutive b pictures, used in mpeg-2 descriptor
101     int low_delay;           ///< low delay, used in mpeg-2 descriptor
102 } MXFStreamContext;
103
104 typedef struct MXFContainerEssenceEntry {
105     UID container_ul;
106     UID element_ul;
107     UID codec_ul;
108     void (*write_desc)(AVFormatContext *, AVStream *);
109 } MXFContainerEssenceEntry;
110
111 typedef struct MXFPackage {
112     char *name;
113     enum MXFMetadataSetType type;
114     int instance;
115     struct MXFPackage *ref;
116 } MXFPackage;
117
118 enum ULIndex {
119     INDEX_MPEG2 = 0,
120     INDEX_AES3,
121     INDEX_WAV,
122     INDEX_D10_625_50_50_VIDEO,
123     INDEX_D10_625_50_50_AUDIO,
124     INDEX_D10_525_60_50_VIDEO,
125     INDEX_D10_525_60_50_AUDIO,
126     INDEX_D10_625_50_40_VIDEO,
127     INDEX_D10_625_50_40_AUDIO,
128     INDEX_D10_525_60_40_VIDEO,
129     INDEX_D10_525_60_40_AUDIO,
130     INDEX_D10_625_50_30_VIDEO,
131     INDEX_D10_625_50_30_AUDIO,
132     INDEX_D10_525_60_30_VIDEO,
133     INDEX_D10_525_60_30_AUDIO,
134     INDEX_DV,
135     INDEX_DV25_525_60,
136     INDEX_DV25_625_50,
137     INDEX_DV25_525_60_IEC,
138     INDEX_DV25_625_50_IEC,
139     INDEX_DV50_525_60,
140     INDEX_DV50_625_50,
141     INDEX_DV100_1080_60,
142     INDEX_DV100_1080_50,
143     INDEX_DV100_720_60,
144     INDEX_DV100_720_50,
145     INDEX_DNXHD,
146     INDEX_JPEG2000,
147     INDEX_H264,
148     INDEX_S436M,
149     INDEX_PRORES,
150 };
151
152 static const struct {
153     enum AVCodecID id;
154     enum ULIndex index;
155 } mxf_essence_mappings[] = {
156     { AV_CODEC_ID_MPEG2VIDEO, INDEX_MPEG2 },
157     { AV_CODEC_ID_PCM_S24LE,  INDEX_AES3 },
158     { AV_CODEC_ID_PCM_S16LE,  INDEX_AES3 },
159     { AV_CODEC_ID_DVVIDEO,    INDEX_DV },
160     { AV_CODEC_ID_DNXHD,      INDEX_DNXHD },
161     { AV_CODEC_ID_JPEG2000,   INDEX_JPEG2000 },
162     { AV_CODEC_ID_H264,       INDEX_H264 },
163     { AV_CODEC_ID_PRORES,     INDEX_PRORES },
164     { AV_CODEC_ID_NONE }
165 };
166
167 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
168 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
169 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
170 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st);
171 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st);
172 static void mxf_write_s436m_anc_desc(AVFormatContext *s, AVStream *st);
173
174 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
175     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
176       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
177       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
178       mxf_write_mpegvideo_desc },
179     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
180       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
181       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
182       mxf_write_aes3_desc },
183     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
184       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
185       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
186       mxf_write_wav_desc },
187     // D-10 625/50 PAL 50mb/s
188     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
189       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
190       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 },
191       mxf_write_cdci_desc },
192     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
193       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
194       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
195       mxf_write_generic_sound_desc },
196     // D-10 525/60 NTSC 50mb/s
197     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 },
198       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
199       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x02 },
200       mxf_write_cdci_desc },
201     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 },
202       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
203       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
204       mxf_write_generic_sound_desc },
205     // D-10 625/50 PAL 40mb/s
206     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 },
207       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
208       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x03 },
209       mxf_write_cdci_desc },
210     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 },
211       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
212       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
213       mxf_write_generic_sound_desc },
214     // D-10 525/60 NTSC 40mb/s
215     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 },
216       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
217       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x04 },
218       mxf_write_cdci_desc },
219     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 },
220       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
221       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
222       mxf_write_generic_sound_desc },
223     // D-10 625/50 PAL 30mb/s
224     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 },
225       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
226       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 },
227       mxf_write_cdci_desc },
228     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 },
229       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
230       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
231       mxf_write_generic_sound_desc },
232     // D-10 525/60 NTSC 30mb/s
233     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 },
234       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
235       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x06 },
236       mxf_write_cdci_desc },
237     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 },
238       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
239       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
240       mxf_write_generic_sound_desc },
241     // DV Unknown
242     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x7F,0x01 },
243       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
244       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x00,0x00,0x00 },
245       mxf_write_cdci_desc },
246
247     // DV25 525/60
248     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x40,0x01 },
249       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
250       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x01,0x00 },
251       mxf_write_cdci_desc },
252     // DV25 625/50
253     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 },
254       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
255       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x02,0x00 },
256       mxf_write_cdci_desc },
257
258     // IEC DV25 525/60
259     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x01,0x01 },
260       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
261       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x01,0x00 },
262       mxf_write_cdci_desc },
263     // IEC DV25 625/50
264     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x02,0x01 },
265       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
266       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x02,0x00 },
267       mxf_write_cdci_desc },
268
269       // DV50 525/60
270     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x50,0x01 },
271       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
272       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x03,0x00 },
273       mxf_write_cdci_desc },
274     // DV50 625/50
275     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x51,0x01 },
276       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
277       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x04,0x00 },
278       mxf_write_cdci_desc },
279     // DV100 1080/60
280     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x60,0x01 },
281       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
282       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x05,0x00 },
283       mxf_write_cdci_desc },
284     // DV100 1080/50
285     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x61,0x01 },
286       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
287       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x06,0x00 },
288       mxf_write_cdci_desc },
289     // DV100 720/60
290     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x62,0x01 },
291       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
292       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x07,0x00 },
293       mxf_write_cdci_desc },
294     // DV100 720/50
295     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x63,0x01 },
296       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
297       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x08,0x00 },
298       mxf_write_cdci_desc },
299     // DNxHD
300     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
301       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
302       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 },
303       mxf_write_cdci_desc },
304     // JPEG2000
305     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 },
306       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x08,0x00 },
307       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 },
308       mxf_write_cdci_desc },
309     // H.264
310     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x10,0x60,0x01 },
311       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
312       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
313       mxf_write_mpegvideo_desc },
314     // S436M ANC
315     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 },
316       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x17,0x01,0x02,0x00 },
317       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x01,0x5C,0x00 },
318       mxf_write_s436m_anc_desc },
319     // ProRes
320     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 },
321       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x17,0x00 },
322       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 },
323       mxf_write_cdci_desc },
324     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
325       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
326       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
327       NULL },
328 };
329
330 typedef struct MXFContext {
331     AVClass *av_class;
332     int64_t footer_partition_offset;
333     int essence_container_count;
334     AVRational time_base;
335     int header_written;
336     MXFIndexEntry *index_entries;
337     unsigned edit_units_count;
338     uint64_t timestamp;   ///< timestamp, as year(16),month(8),day(8),hour(8),minutes(8),msec/4(8)
339     uint8_t slice_count;  ///< index slice count minus 1 (1 if no audio, 0 otherwise)
340     int last_indexed_edit_unit;
341     uint64_t *body_partition_offset;
342     unsigned body_partitions_count;
343     int last_key_index;  ///< index of last key frame
344     uint64_t duration;
345     AVTimecode tc;       ///< timecode context
346     AVStream *timecode_track;
347     int timecode_base;       ///< rounded time code base (25 or 30)
348     int edit_unit_byte_count; ///< fixed edit unit byte count
349     int content_package_rate; ///< content package rate in system element, see SMPTE 326M
350     uint64_t body_offset;
351     uint32_t instance_number;
352     uint8_t umid[16];        ///< unique material identifier
353     int channel_count;
354     int signal_standard;
355     uint32_t tagged_value_count;
356     AVRational audio_edit_rate;
357     int store_user_comments;
358     int track_instance_count; // used to generate MXFTrack uuids
359     int cbr_index;           ///< use a constant bitrate index
360 } MXFContext;
361
362 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
363 static const uint8_t umid_ul[]              = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13 };
364
365 /**
366  * complete key for operation pattern, partitions, and primer pack
367  */
368 static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x09,0x00 };
369 static const uint8_t opatom_ul[]                   = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x02,0x01,0x10,0x03,0x00,0x00 };
370 static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
371 static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
372 static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
373 static const uint8_t random_index_pack_key[]       = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
374 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
375 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
376 static const uint8_t klv_fill_key[]                = { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x10,0x01,0x00,0x00,0x00 };
377 static const uint8_t body_partition_key[]          = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }; // ClosedComplete
378
379 /**
380  * partial key for header metadata
381  */
382 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
383 static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
384
385 /**
386  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
387  *             https://smpte-ra.org/sites/default/files/Labels.xml
388  */
389 static const MXFLocalTagPair mxf_local_tag_batch[] = {
390     // preface set
391     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
392     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
393     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
394     { 0x3B07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x04,0x00,0x00,0x00}}, /* Object Model Version */
395     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
396     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
397     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
398     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
399     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
400     // Identification
401     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
402     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
403     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
404     { 0x3C03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x04,0x00,0x00,0x00}}, /* Product Version */
405     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
406     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
407     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
408     { 0x3C07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x0A,0x00,0x00,0x00}}, /* Toolkit Version */
409     { 0x3C08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x06,0x01,0x00,0x00}}, /* Platform */
410     // Content Storage
411     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
412     { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
413     // Essence Container Data
414     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
415     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
416     // Package
417     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
418     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
419     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
420     { 0x4402, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x03,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Package Name */
421     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
422     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
423     // Track
424     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
425     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
426     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
427     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
428     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
429     // Sequence
430     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
431     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
432     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
433     // Source Clip
434     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
435     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
436     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
437     // Timecode Component
438     { 0x1501, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x05,0x00,0x00}}, /* Start Time Code */
439     { 0x1502, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x04,0x01,0x01,0x02,0x06,0x00,0x00}}, /* Rounded Time Code Base */
440     { 0x1503, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x04,0x01,0x01,0x05,0x00,0x00,0x00}}, /* Drop Frame */
441     // File Descriptor
442     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
443     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
444     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
445     { 0x3002, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x02,0x00,0x00,0x00,0x00}}, /* ContainerDuration */
446     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
447     // Generic Picture Essence Descriptor
448     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
449     { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
450     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
451     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
452     { 0x3216, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x03,0x02,0x08,0x00,0x00,0x00}}, /* Stored F2 Offset */
453     { 0x3205, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x08,0x00,0x00,0x00}}, /* Sampled Width */
454     { 0x3204, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x07,0x00,0x00,0x00}}, /* Sampled Height */
455     { 0x3206, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x09,0x00,0x00,0x00}}, /* Sampled X Offset */
456     { 0x3207, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0A,0x00,0x00,0x00}}, /* Sampled Y Offset */
457     { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
458     { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
459     { 0x320A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0D,0x00,0x00,0x00}}, /* Display X offset */
460     { 0x320B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0E,0x00,0x00,0x00}}, /* Presentation Y offset */
461     { 0x3217, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x03,0x02,0x07,0x00,0x00,0x00}}, /* Display F2 offset */
462     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
463     { 0x3210, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x02,0x01,0x01,0x01,0x02,0x00}}, /* Transfer characteristic */
464     { 0x3213, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x02,0x00,0x00,0x00,0x00}}, /* Image Start Offset */
465     { 0x3214, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Image End Offset */
466     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
467     { 0x3212, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x01,0x06,0x00,0x00,0x00}}, /* Field Dominance (Opt) */
468     { 0x3215, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x05,0x01,0x13,0x00,0x00,0x00,0x00}}, /* Signal Standard */
469     // CDCI Picture Essence Descriptor
470     { 0x3301, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x0A,0x00,0x00,0x00}}, /* Component Depth */
471     { 0x3302, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x05,0x00,0x00,0x00}}, /* Horizontal Subsampling */
472     { 0x3308, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x01,0x10,0x00,0x00,0x00}}, /* Vertical Subsampling */
473     { 0x3303, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x06,0x00,0x00,0x00}}, /* Color Siting */
474     { 0x3307, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x04,0x00,0x00,0x00,0x00}}, /* Padding Bits */
475     { 0x3304, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x03,0x03,0x00,0x00,0x00}}, /* Black Ref level */
476     { 0x3305, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x03,0x04,0x00,0x00,0x00}}, /* White Ref level */
477     { 0x3306, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x05,0x00,0x00,0x00}}, /* Color Range */
478     // Generic Sound Essence Descriptor
479     { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
480     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
481     { 0x3D04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x02,0x01,0x01,0x03,0x00,0x00,0x00}}, /* Audio Ref Level */
482     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
483     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
484     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
485     // Index Table Segment
486     { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
487     { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
488     { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
489     { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
490     { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
491     { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
492     { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
493     { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
494     // MPEG video Descriptor
495     { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
496     { 0x8003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x05,0x00,0x00}}, /* LowDelay */
497     { 0x8004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x06,0x00,0x00}}, /* ClosedGOP */
498     { 0x8006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x08,0x00,0x00}}, /* MaxGOP */
499     { 0x8007, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0A,0x00,0x00}}, /* ProfileAndLevel */
500     { 0x8008, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x09,0x00,0x00}}, /* BPictureCount */
501     // Wave Audio Essence Descriptor
502     { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
503     { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
504 };
505
506 static const MXFLocalTagPair mxf_user_comments_local_tag[] = {
507     { 0x4406, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0C,0x00,0x00,0x00}}, /* User Comments */
508     { 0x5001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x09,0x01,0x00,0x00}}, /* Name */
509     { 0x5003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0A,0x01,0x00,0x00}}, /* Value */
510 };
511
512 static void mxf_write_uuid(AVIOContext *pb, enum MXFMetadataSetType type, int value)
513 {
514     avio_write(pb, uuid_base, 12);
515     avio_wb16(pb, type);
516     avio_wb16(pb, value);
517 }
518
519 static void mxf_write_umid(AVFormatContext *s, int type)
520 {
521     MXFContext *mxf = s->priv_data;
522     avio_write(s->pb, umid_ul, 13);
523     avio_wb24(s->pb, mxf->instance_number);
524     avio_write(s->pb, mxf->umid, 15);
525     avio_w8(s->pb, type);
526 }
527
528 static void mxf_write_refs_count(AVIOContext *pb, int ref_count)
529 {
530     avio_wb32(pb, ref_count);
531     avio_wb32(pb, 16);
532 }
533
534 static int klv_ber_length(uint64_t len)
535 {
536     if (len < 128)
537         return 1;
538     else
539         return (av_log2(len) >> 3) + 2;
540 }
541
542 static int klv_encode_ber_length(AVIOContext *pb, uint64_t len)
543 {
544     // Determine the best BER size
545     int size;
546     if (len < 128) {
547         //short form
548         avio_w8(pb, len);
549         return 1;
550     }
551
552     size = (av_log2(len) >> 3) + 1;
553
554     // long form
555     avio_w8(pb, 0x80 + size);
556     while(size) {
557         size--;
558         avio_w8(pb, len >> 8 * size & 0xff);
559     }
560     return 0;
561 }
562
563 static void klv_encode_ber4_length(AVIOContext *pb, int len)
564 {
565     avio_w8(pb, 0x80 + 3);
566     avio_wb24(pb, len);
567 }
568
569 static void klv_encode_ber9_length(AVIOContext *pb, uint64_t len)
570 {
571     avio_w8(pb, 0x80 + 8);
572     avio_wb64(pb, len);
573 }
574
575 /*
576  * Get essence container ul index
577  */
578 static int mxf_get_essence_container_ul_index(enum AVCodecID id)
579 {
580     int i;
581     for (i = 0; mxf_essence_mappings[i].id; i++)
582         if (mxf_essence_mappings[i].id == id)
583             return mxf_essence_mappings[i].index;
584     return -1;
585 }
586
587 static void mxf_write_primer_pack(AVFormatContext *s)
588 {
589     MXFContext *mxf = s->priv_data;
590     AVIOContext *pb = s->pb;
591     int local_tag_number, i = 0;
592
593     local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
594     local_tag_number += mxf->store_user_comments * FF_ARRAY_ELEMS(mxf_user_comments_local_tag);
595
596     avio_write(pb, primer_pack_key, 16);
597     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
598
599     avio_wb32(pb, local_tag_number); // local_tag num
600     avio_wb32(pb, 18); // item size, always 18 according to the specs
601
602     for (i = 0; i < FF_ARRAY_ELEMS(mxf_local_tag_batch); i++) {
603         avio_wb16(pb, mxf_local_tag_batch[i].local_tag);
604         avio_write(pb, mxf_local_tag_batch[i].uid, 16);
605     }
606     if (mxf->store_user_comments)
607         for (i = 0; i < FF_ARRAY_ELEMS(mxf_user_comments_local_tag); i++) {
608             avio_wb16(pb, mxf_user_comments_local_tag[i].local_tag);
609             avio_write(pb, mxf_user_comments_local_tag[i].uid, 16);
610         }
611 }
612
613 static void mxf_write_local_tag(AVIOContext *pb, int size, int tag)
614 {
615     avio_wb16(pb, tag);
616     avio_wb16(pb, size);
617 }
618
619 static void mxf_write_metadata_key(AVIOContext *pb, unsigned int value)
620 {
621     avio_write(pb, header_metadata_key, 13);
622     avio_wb24(pb, value);
623 }
624
625 static void mxf_free(AVFormatContext *s)
626 {
627     int i;
628
629     for (i = 0; i < s->nb_streams; i++) {
630         AVStream *st = s->streams[i];
631         av_freep(&st->priv_data);
632     }
633 }
634
635 static const MXFCodecUL *mxf_get_data_definition_ul(int type)
636 {
637     const MXFCodecUL *uls = ff_mxf_data_definition_uls;
638     while (uls->uid[0]) {
639         if (type == uls->id)
640             break;
641         uls++;
642     }
643     return uls;
644 }
645
646 //one EC -> one descriptor. N ECs -> MultipleDescriptor + N descriptors
647 #define DESCRIPTOR_COUNT(essence_container_count) \
648     (essence_container_count > 1 ? essence_container_count + 1 : essence_container_count)
649
650 static void mxf_write_essence_container_refs(AVFormatContext *s)
651 {
652     MXFContext *c = s->priv_data;
653     AVIOContext *pb = s->pb;
654     int i;
655
656     mxf_write_refs_count(pb, DESCRIPTOR_COUNT(c->essence_container_count));
657     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
658     for (i = 0; i < s->nb_streams; i++) {
659         MXFStreamContext *sc = s->streams[i]->priv_data;
660         // check first track of essence container type and only write it once
661         if (sc->track_essence_element_key[15] != 0)
662             continue;
663         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
664         if (c->essence_container_count == 1)
665             break;
666     }
667
668     if (c->essence_container_count > 1)
669         avio_write(pb, multiple_desc_ul, 16);
670 }
671
672 static void mxf_write_preface(AVFormatContext *s)
673 {
674     MXFContext *mxf = s->priv_data;
675     AVIOContext *pb = s->pb;
676
677     mxf_write_metadata_key(pb, 0x012f00);
678     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
679     klv_encode_ber_length(pb, 138 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
680
681     // write preface set uid
682     mxf_write_local_tag(pb, 16, 0x3C0A);
683     mxf_write_uuid(pb, Preface, 0);
684     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
685
686     // last modified date
687     mxf_write_local_tag(pb, 8, 0x3B02);
688     avio_wb64(pb, mxf->timestamp);
689
690     // write version
691     mxf_write_local_tag(pb, 2, 0x3B05);
692     avio_wb16(pb, 259); // v1.3
693
694     // Object Model Version
695     mxf_write_local_tag(pb, 4, 0x3B07);
696     avio_wb32(pb, 1);
697
698     // write identification_refs
699     mxf_write_local_tag(pb, 16 + 8, 0x3B06);
700     mxf_write_refs_count(pb, 1);
701     mxf_write_uuid(pb, Identification, 0);
702
703     // write content_storage_refs
704     mxf_write_local_tag(pb, 16, 0x3B03);
705     mxf_write_uuid(pb, ContentStorage, 0);
706
707     // operational pattern
708     mxf_write_local_tag(pb, 16, 0x3B09);
709     if (s->oformat == &ff_mxf_opatom_muxer)
710         avio_write(pb, opatom_ul, 16);
711     else
712         avio_write(pb, op1a_ul, 16);
713
714     // write essence_container_refs
715     mxf_write_local_tag(pb, 8 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count), 0x3B0A);
716     mxf_write_essence_container_refs(s);
717
718     // write dm_scheme_refs
719     mxf_write_local_tag(pb, 8, 0x3B0B);
720     avio_wb64(pb, 0);
721 }
722
723 /*
724  * Returns the length of the UTF-16 string, in 16-bit characters, that would result
725  * from decoding the utf-8 string.
726  */
727 static uint64_t mxf_utf16len(const char *utf8_str)
728 {
729     const uint8_t *q = utf8_str;
730     uint64_t size = 0;
731     while (*q) {
732         uint32_t ch;
733         GET_UTF8(ch, *q++, goto invalid;)
734         if (ch < 0x10000)
735             size++;
736         else
737             size += 2;
738         continue;
739 invalid:
740         av_log(NULL, AV_LOG_ERROR, "Invalid UTF8 sequence in mxf_utf16len\n\n");
741     }
742     size += 1;
743     return size;
744 }
745
746 /*
747  * Returns the calculated length a local tag containing an utf-8 string as utf-16
748  */
749 static int mxf_utf16_local_tag_length(const char *utf8_str)
750 {
751     uint64_t size;
752
753     if (!utf8_str)
754         return 0;
755
756     size = mxf_utf16len(utf8_str);
757     if (size >= UINT16_MAX/2) {
758         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
759         return 0;
760     }
761
762     return 4 + size * 2;
763 }
764
765 /*
766  * Write a local tag containing an utf-8 string as utf-16
767  */
768 static void mxf_write_local_tag_utf16(AVIOContext *pb, int tag, const char *value)
769 {
770     uint64_t size = mxf_utf16len(value);
771
772     if (size >= UINT16_MAX/2) {
773         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
774         return;
775     }
776
777     mxf_write_local_tag(pb, size*2, tag);
778     avio_put_str16be(pb, value);
779 }
780
781 static void store_version(AVFormatContext *s){
782     AVIOContext *pb = s->pb;
783
784     if (s->flags & AVFMT_FLAG_BITEXACT) {
785         avio_wb16(pb, 0); // major
786         avio_wb16(pb, 0); // minor
787         avio_wb16(pb, 0); // tertiary
788     } else {
789         avio_wb16(pb, LIBAVFORMAT_VERSION_MAJOR); // major
790         avio_wb16(pb, LIBAVFORMAT_VERSION_MINOR); // minor
791         avio_wb16(pb, LIBAVFORMAT_VERSION_MICRO); // tertiary
792     }
793     avio_wb16(pb, 0); // patch
794     avio_wb16(pb, 0); // release
795 }
796
797 static void mxf_write_identification(AVFormatContext *s)
798 {
799     MXFContext *mxf = s->priv_data;
800     AVIOContext *pb = s->pb;
801     const char *company = "FFmpeg";
802     const char *product = s->oformat != &ff_mxf_opatom_muxer ? "OP1a Muxer" : "OPAtom Muxer";
803     const char *version;
804     int length;
805
806     mxf_write_metadata_key(pb, 0x013000);
807     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
808
809     version = s->flags & AVFMT_FLAG_BITEXACT ?
810         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
811     length = 100 +mxf_utf16_local_tag_length(company) +
812                   mxf_utf16_local_tag_length(product) +
813                   mxf_utf16_local_tag_length(version);
814     klv_encode_ber_length(pb, length);
815
816     // write uid
817     mxf_write_local_tag(pb, 16, 0x3C0A);
818     mxf_write_uuid(pb, Identification, 0);
819     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
820
821     // write generation uid
822     mxf_write_local_tag(pb, 16, 0x3C09);
823     mxf_write_uuid(pb, Identification, 1);
824     mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
825     mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
826
827     mxf_write_local_tag(pb, 10, 0x3C03); // Product Version
828     store_version(s);
829
830     mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
831
832     // write product uid
833     mxf_write_local_tag(pb, 16, 0x3C05);
834     mxf_write_uuid(pb, Identification, 2);
835
836     // modification date
837     mxf_write_local_tag(pb, 8, 0x3C06);
838     avio_wb64(pb, mxf->timestamp);
839
840     mxf_write_local_tag(pb, 10, 0x3C07); // Toolkit Version
841     store_version(s);
842 }
843
844 static void mxf_write_content_storage(AVFormatContext *s, MXFPackage *packages, int package_count)
845 {
846     AVIOContext *pb = s->pb;
847     int i;
848
849     mxf_write_metadata_key(pb, 0x011800);
850     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
851     klv_encode_ber_length(pb, 60 + (16 * package_count));
852
853     // write uid
854     mxf_write_local_tag(pb, 16, 0x3C0A);
855     mxf_write_uuid(pb, ContentStorage, 0);
856     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
857
858     // write package reference
859     mxf_write_local_tag(pb, 16 * package_count + 8, 0x1901);
860     mxf_write_refs_count(pb, package_count);
861     for (i = 0; i < package_count; i++) {
862         mxf_write_uuid(pb, packages[i].type, packages[i].instance);
863     }
864
865     // write essence container data
866     mxf_write_local_tag(pb, 8 + 16, 0x1902);
867     mxf_write_refs_count(pb, 1);
868     mxf_write_uuid(pb, EssenceContainerData, 0);
869 }
870
871 static void mxf_write_track(AVFormatContext *s, AVStream *st, MXFPackage *package)
872 {
873     MXFContext *mxf = s->priv_data;
874     AVIOContext *pb = s->pb;
875     MXFStreamContext *sc = st->priv_data;
876
877     mxf_write_metadata_key(pb, 0x013b00);
878     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
879     klv_encode_ber_length(pb, 80);
880
881     // write track uid
882     mxf_write_local_tag(pb, 16, 0x3C0A);
883     mxf_write_uuid(pb, Track, mxf->track_instance_count);
884     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
885
886     // write track id
887     mxf_write_local_tag(pb, 4, 0x4801);
888     avio_wb32(pb, st->index+2);
889
890     // write track number
891     mxf_write_local_tag(pb, 4, 0x4804);
892     if (package->type == MaterialPackage)
893         avio_wb32(pb, 0); // track number of material package is 0
894     else
895         avio_write(pb, sc->track_essence_element_key + 12, 4);
896
897     // write edit rate
898     mxf_write_local_tag(pb, 8, 0x4B01);
899
900     if (st == mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer) {
901         avio_wb32(pb, mxf->tc.rate.num);
902         avio_wb32(pb, mxf->tc.rate.den);
903     } else {
904         avio_wb32(pb, mxf->time_base.den);
905         avio_wb32(pb, mxf->time_base.num);
906     }
907
908     // write origin
909     mxf_write_local_tag(pb, 8, 0x4B02);
910     avio_wb64(pb, 0);
911
912     // write sequence refs
913     mxf_write_local_tag(pb, 16, 0x4803);
914     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
915 }
916
917 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 };
918
919 static void mxf_write_common_fields(AVFormatContext *s, AVStream *st)
920 {
921     MXFContext *mxf = s->priv_data;
922     AVIOContext *pb = s->pb;
923
924     // find data define uls
925     mxf_write_local_tag(pb, 16, 0x0201);
926     if (st == mxf->timecode_track)
927         avio_write(pb, smpte_12m_timecode_track_data_ul, 16);
928     else {
929         const MXFCodecUL *data_def_ul = mxf_get_data_definition_ul(st->codecpar->codec_type);
930         avio_write(pb, data_def_ul->uid, 16);
931     }
932
933     // write duration
934     mxf_write_local_tag(pb, 8, 0x0202);
935
936     if (st != mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
937         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
938     } else {
939         avio_wb64(pb, mxf->duration);
940     }
941 }
942
943 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, MXFPackage *package)
944 {
945     MXFContext *mxf = s->priv_data;
946     AVIOContext *pb = s->pb;
947     enum MXFMetadataSetType component;
948
949     mxf_write_metadata_key(pb, 0x010f00);
950     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
951     klv_encode_ber_length(pb, 80);
952
953     mxf_write_local_tag(pb, 16, 0x3C0A);
954     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
955
956     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
957     mxf_write_common_fields(s, st);
958
959     // write structural component
960     mxf_write_local_tag(pb, 16 + 8, 0x1001);
961     mxf_write_refs_count(pb, 1);
962     if (st == mxf->timecode_track)
963         component = TimecodeComponent;
964     else
965         component = SourceClip;
966
967     mxf_write_uuid(pb, component, mxf->track_instance_count);
968 }
969
970 static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
971 {
972     MXFContext *mxf = s->priv_data;
973     AVIOContext *pb = s->pb;
974
975     mxf_write_metadata_key(pb, 0x011400);
976     klv_encode_ber_length(pb, 75);
977
978     // UID
979     mxf_write_local_tag(pb, 16, 0x3C0A);
980     mxf_write_uuid(pb, TimecodeComponent, mxf->track_instance_count);
981
982     mxf_write_common_fields(s, st);
983
984     // Start Time Code
985     mxf_write_local_tag(pb, 8, 0x1501);
986     avio_wb64(pb, mxf->tc.start);
987
988     // Rounded Time Code Base
989     mxf_write_local_tag(pb, 2, 0x1502);
990     avio_wb16(pb, mxf->timecode_base);
991
992     // Drop Frame
993     mxf_write_local_tag(pb, 1, 0x1503);
994     avio_w8(pb, !!(mxf->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
995 }
996
997 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
998 {
999     MXFContext *mxf = s->priv_data;
1000     AVIOContext *pb = s->pb;
1001     int i;
1002
1003     mxf_write_metadata_key(pb, 0x011100);
1004     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
1005     klv_encode_ber_length(pb, 108);
1006
1007     // write uid
1008     mxf_write_local_tag(pb, 16, 0x3C0A);
1009     mxf_write_uuid(pb, SourceClip, mxf->track_instance_count);
1010
1011     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
1012     mxf_write_common_fields(s, st);
1013
1014     // write start_position
1015     mxf_write_local_tag(pb, 8, 0x1201);
1016     avio_wb64(pb, 0);
1017
1018     // write source package uid, end of the reference
1019     mxf_write_local_tag(pb, 32, 0x1101);
1020     if (!package->ref) {
1021         for (i = 0; i < 4; i++)
1022             avio_wb64(pb, 0);
1023     } else
1024         mxf_write_umid(s, package->ref->instance);
1025
1026     // write source track id
1027     mxf_write_local_tag(pb, 4, 0x1102);
1028     if (package->type == SourcePackage && !package->ref)
1029         avio_wb32(pb, 0);
1030     else
1031         avio_wb32(pb, st->index+2);
1032 }
1033
1034 static void mxf_write_tape_descriptor(AVFormatContext *s)
1035 {
1036     AVIOContext *pb = s->pb;
1037
1038     mxf_write_metadata_key(pb, 0x012e00);
1039     PRINT_KEY(s, "tape descriptor key", pb->buf_ptr - 16);
1040     klv_encode_ber_length(pb, 20);
1041     mxf_write_local_tag(pb, 16, 0x3C0A);
1042     mxf_write_uuid(pb, TapeDescriptor, 0);
1043     PRINT_KEY(s, "tape_desc uid", pb->buf_ptr - 16);
1044 }
1045
1046
1047 static void mxf_write_multi_descriptor(AVFormatContext *s)
1048 {
1049     MXFContext *mxf = s->priv_data;
1050     AVIOContext *pb = s->pb;
1051     const uint8_t *ul;
1052     int i;
1053
1054     mxf_write_metadata_key(pb, 0x014400);
1055     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
1056     klv_encode_ber_length(pb, 64 + 16LL * s->nb_streams);
1057
1058     mxf_write_local_tag(pb, 16, 0x3C0A);
1059     mxf_write_uuid(pb, MultipleDescriptor, 0);
1060     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
1061
1062     // write sample rate
1063     mxf_write_local_tag(pb, 8, 0x3001);
1064     avio_wb32(pb, mxf->time_base.den);
1065     avio_wb32(pb, mxf->time_base.num);
1066
1067     // write essence container ul
1068     mxf_write_local_tag(pb, 16, 0x3004);
1069     if (mxf->essence_container_count > 1)
1070         ul = multiple_desc_ul;
1071     else {
1072         MXFStreamContext *sc = s->streams[0]->priv_data;
1073         ul = mxf_essence_container_uls[sc->index].container_ul;
1074     }
1075     avio_write(pb, ul, 16);
1076
1077     // write sub descriptor refs
1078     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
1079     mxf_write_refs_count(pb, s->nb_streams);
1080     for (i = 0; i < s->nb_streams; i++)
1081         mxf_write_uuid(pb, SubDescriptor, i);
1082 }
1083
1084 static int64_t mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID key)
1085 {
1086     MXFContext *mxf = s->priv_data;
1087     MXFStreamContext *sc = st->priv_data;
1088     AVIOContext *pb = s->pb;
1089     int64_t pos;
1090
1091     avio_write(pb, key, 16);
1092     klv_encode_ber4_length(pb, 0);
1093     pos = avio_tell(pb);
1094
1095     mxf_write_local_tag(pb, 16, 0x3C0A);
1096     mxf_write_uuid(pb, SubDescriptor, st->index);
1097
1098     mxf_write_local_tag(pb, 4, 0x3006);
1099     avio_wb32(pb, st->index+2);
1100
1101     mxf_write_local_tag(pb, 8, 0x3001);
1102     if (s->oformat == &ff_mxf_d10_muxer) {
1103         avio_wb32(pb, mxf->time_base.den);
1104         avio_wb32(pb, mxf->time_base.num);
1105     } else {
1106         if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE ||
1107             st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
1108             avio_wb32(pb, st->codecpar->sample_rate);
1109             avio_wb32(pb, 1);
1110         } else {
1111             avio_wb32(pb, mxf->time_base.den);
1112             avio_wb32(pb, mxf->time_base.num);
1113         }
1114     }
1115
1116     mxf_write_local_tag(pb, 16, 0x3004);
1117     avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
1118
1119     return pos;
1120 }
1121
1122 static const UID mxf_s436m_anc_descriptor_key = { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 };
1123 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
1124 static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
1125 static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
1126 static const UID mxf_cdci_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x28,0x00 };
1127 static const UID mxf_generic_sound_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x42,0x00 };
1128
1129 static int get_trc(UID ul, enum AVColorTransferCharacteristic trc)
1130 {
1131     switch (trc){
1132     case AVCOL_TRC_GAMMA28   :
1133     case AVCOL_TRC_GAMMA22   :
1134         memcpy(ul, ((UID){0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x01,0x00,0x00}), 16);
1135         return 0;
1136     case AVCOL_TRC_BT709     :
1137     case AVCOL_TRC_SMPTE170M :
1138         memcpy(ul, ((UID){0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x02,0x00,0x00}), 16);
1139         return 0;
1140     case AVCOL_TRC_SMPTE240M :
1141         memcpy(ul, ((UID){0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x03,0x00,0x00}), 16);
1142         return 0;
1143     case AVCOL_TRC_BT1361_ECG:
1144         memcpy(ul, ((UID){0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x06,0x04,0x01,0x01,0x01,0x01,0x05,0x00,0x00}), 16);
1145         return 0;
1146     case AVCOL_TRC_LINEAR    :
1147         memcpy(ul, ((UID){0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x06,0x04,0x01,0x01,0x01,0x01,0x06,0x00,0x00}), 16);
1148         return 0;
1149     case AVCOL_TRC_SMPTE428  :
1150         memcpy(ul, ((UID){0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x08,0x04,0x01,0x01,0x01,0x01,0x07,0x00,0x00}), 16);
1151         return 0;
1152     default:
1153         return -1;
1154     }
1155 }
1156
1157 static int64_t mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID key)
1158 {
1159     MXFStreamContext *sc = st->priv_data;
1160     AVIOContext *pb = s->pb;
1161     int stored_width  = (st->codecpar->width +15)/16*16;
1162     int stored_height = (st->codecpar->height+15)/16*16;
1163     int display_height;
1164     int f1, f2;
1165     UID transfer_ul = {0};
1166     int64_t pos = mxf_write_generic_desc(s, st, key);
1167
1168     get_trc(transfer_ul, st->codecpar->color_trc);
1169
1170     mxf_write_local_tag(pb, 4, 0x3203);
1171     avio_wb32(pb, stored_width);
1172
1173     mxf_write_local_tag(pb, 4, 0x3202);
1174     avio_wb32(pb, stored_height>>sc->interlaced);
1175
1176     if (s->oformat == &ff_mxf_d10_muxer) {
1177         //Stored F2 Offset
1178         mxf_write_local_tag(pb, 4, 0x3216);
1179         avio_wb32(pb, 0);
1180
1181         //Image Start Offset
1182         mxf_write_local_tag(pb, 4, 0x3213);
1183         avio_wb32(pb, 0);
1184
1185         //Image End Offset
1186         mxf_write_local_tag(pb, 4, 0x3214);
1187         avio_wb32(pb, 0);
1188     }
1189
1190     //Sampled width
1191     mxf_write_local_tag(pb, 4, 0x3205);
1192     avio_wb32(pb, st->codecpar->width);
1193
1194     //Samples height
1195     mxf_write_local_tag(pb, 4, 0x3204);
1196     avio_wb32(pb, st->codecpar->height>>sc->interlaced);
1197
1198     //Sampled X Offset
1199     mxf_write_local_tag(pb, 4, 0x3206);
1200     avio_wb32(pb, 0);
1201
1202     //Sampled Y Offset
1203     mxf_write_local_tag(pb, 4, 0x3207);
1204     avio_wb32(pb, 0);
1205
1206     mxf_write_local_tag(pb, 4, 0x3209);
1207     avio_wb32(pb, st->codecpar->width);
1208
1209     if (st->codecpar->height == 608) // PAL + VBI
1210         display_height = 576;
1211     else if (st->codecpar->height == 512)  // NTSC + VBI
1212         display_height = 486;
1213     else
1214         display_height = st->codecpar->height;
1215
1216     mxf_write_local_tag(pb, 4, 0x3208);
1217     avio_wb32(pb, display_height>>sc->interlaced);
1218
1219     // display X offset
1220     mxf_write_local_tag(pb, 4, 0x320A);
1221     avio_wb32(pb, 0);
1222
1223     // display Y offset
1224     mxf_write_local_tag(pb, 4, 0x320B);
1225     avio_wb32(pb, (st->codecpar->height - display_height)>>sc->interlaced);
1226
1227     if (sc->interlaced) {
1228         //Display F2 Offset
1229         mxf_write_local_tag(pb, 4, 0x3217);
1230         avio_wb32(pb, -((st->codecpar->height - display_height)&1));
1231     }
1232
1233     // component depth
1234     mxf_write_local_tag(pb, 4, 0x3301);
1235     avio_wb32(pb, sc->component_depth);
1236
1237     // horizontal subsampling
1238     mxf_write_local_tag(pb, 4, 0x3302);
1239     avio_wb32(pb, sc->h_chroma_sub_sample);
1240
1241     // vertical subsampling
1242     mxf_write_local_tag(pb, 4, 0x3308);
1243     avio_wb32(pb, sc->v_chroma_sub_sample);
1244
1245     // color siting
1246     mxf_write_local_tag(pb, 1, 0x3303);
1247     avio_w8(pb, sc->color_siting);
1248
1249     // Padding Bits
1250     mxf_write_local_tag(pb, 2, 0x3307);
1251     avio_wb16(pb, 0);
1252
1253     if (st->codecpar->color_range != AVCOL_RANGE_UNSPECIFIED) {
1254         int black = 0,
1255             white = (1<<sc->component_depth) - 1,
1256             color = (1<<sc->component_depth) - 1;
1257         if (st->codecpar->color_range == AVCOL_RANGE_MPEG) {
1258             black = 1   << (sc->component_depth - 4);
1259             white = 235 << (sc->component_depth - 8);
1260             color = (14 << (sc->component_depth - 4)) + 1;
1261         }
1262         mxf_write_local_tag(pb, 4, 0x3304);
1263         avio_wb32(pb, black);
1264         mxf_write_local_tag(pb, 4, 0x3305);
1265         avio_wb32(pb, white);
1266         mxf_write_local_tag(pb, 4, 0x3306);
1267         avio_wb32(pb, color);
1268     }
1269
1270     if (sc->signal_standard) {
1271         mxf_write_local_tag(pb, 1, 0x3215);
1272         avio_w8(pb, sc->signal_standard);
1273     }
1274
1275     // frame layout
1276     mxf_write_local_tag(pb, 1, 0x320C);
1277     avio_w8(pb, sc->interlaced);
1278
1279     // video line map
1280     switch (st->codecpar->height) {
1281     case  576: f1 = 23; f2 = st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO ? 335 : 336; break;
1282     case  608: f1 =  7; f2 = 320; break;
1283     case  480: f1 = 20; f2 = st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO ? 285 : 283; break;
1284     case  512: f1 =  7; f2 = 270; break;
1285     case  720: f1 = 26; f2 =   0; break; // progressive
1286     case 1080: f1 = 21; f2 = 584; break;
1287     default:   f1 =  0; f2 =   0; break;
1288     }
1289
1290     if (!sc->interlaced && f2) {
1291         f2  = 0;
1292         f1 *= 2;
1293     }
1294
1295
1296     mxf_write_local_tag(pb, 16, 0x320D);
1297     avio_wb32(pb, 2);
1298     avio_wb32(pb, 4);
1299     avio_wb32(pb, f1);
1300     avio_wb32(pb, f2);
1301
1302     mxf_write_local_tag(pb, 8, 0x320E);
1303     avio_wb32(pb, sc->aspect_ratio.num);
1304     avio_wb32(pb, sc->aspect_ratio.den);
1305
1306     //Transfer characteristic
1307     if (transfer_ul[0]) {
1308         mxf_write_local_tag(pb, 16, 0x3210);
1309         avio_write(pb, transfer_ul, 16);
1310     };
1311
1312     mxf_write_local_tag(pb, 16, 0x3201);
1313     avio_write(pb, *sc->codec_ul, 16);
1314
1315     if (sc->interlaced && sc->field_dominance) {
1316         mxf_write_local_tag(pb, 1, 0x3212);
1317         avio_w8(pb, sc->field_dominance);
1318     }
1319
1320     return pos;
1321 }
1322
1323 static void mxf_update_klv_size(AVIOContext *pb, int64_t pos)
1324 {
1325     int64_t cur_pos = avio_tell(pb);
1326     int size = cur_pos - pos;
1327     avio_seek(pb, pos - 4, SEEK_SET);
1328     klv_encode_ber4_length(pb, size);
1329     avio_seek(pb, cur_pos, SEEK_SET);
1330 }
1331
1332 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st)
1333 {
1334     int64_t pos = mxf_write_cdci_common(s, st, mxf_cdci_descriptor_key);
1335     mxf_update_klv_size(s->pb, pos);
1336 }
1337
1338 static void mxf_write_s436m_anc_desc(AVFormatContext *s, AVStream *st)
1339 {
1340     int64_t pos = mxf_write_generic_desc(s, st, mxf_s436m_anc_descriptor_key);
1341     mxf_update_klv_size(s->pb, pos);
1342 }
1343
1344 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
1345 {
1346     AVIOContext *pb = s->pb;
1347     MXFStreamContext *sc = st->priv_data;
1348     int profile_and_level = (st->codecpar->profile<<4) | st->codecpar->level;
1349     int64_t pos = mxf_write_cdci_common(s, st, mxf_mpegvideo_descriptor_key);
1350
1351     if (st->codecpar->codec_id != AV_CODEC_ID_H264) {
1352         // bit rate
1353         mxf_write_local_tag(pb, 4, 0x8000);
1354         avio_wb32(pb, sc->video_bit_rate);
1355
1356         // profile and level
1357         mxf_write_local_tag(pb, 1, 0x8007);
1358         if (!st->codecpar->profile)
1359             profile_and_level |= 0x80; // escape bit
1360         avio_w8(pb, profile_and_level);
1361
1362         // low delay
1363         mxf_write_local_tag(pb, 1, 0x8003);
1364         avio_w8(pb, sc->low_delay);
1365
1366         // closed gop
1367         mxf_write_local_tag(pb, 1, 0x8004);
1368         avio_w8(pb, sc->seq_closed_gop);
1369
1370         // max gop
1371         mxf_write_local_tag(pb, 2, 0x8006);
1372         avio_wb16(pb, sc->max_gop);
1373
1374         // b picture count
1375         mxf_write_local_tag(pb, 2, 0x8008);
1376         avio_wb16(pb, sc->b_picture_count);
1377     }
1378
1379     mxf_update_klv_size(pb, pos);
1380 }
1381
1382 static int64_t mxf_write_generic_sound_common(AVFormatContext *s, AVStream *st, const UID key)
1383 {
1384     AVIOContext *pb = s->pb;
1385     MXFContext *mxf = s->priv_data;
1386     int show_warnings = !mxf->footer_partition_offset;
1387     int64_t pos = mxf_write_generic_desc(s, st, key);
1388
1389     if (s->oformat == &ff_mxf_opatom_muxer) {
1390         mxf_write_local_tag(pb, 8, 0x3002);
1391         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
1392     }
1393
1394     // audio locked
1395     mxf_write_local_tag(pb, 1, 0x3D02);
1396     avio_w8(pb, 1);
1397
1398     // write audio sampling rate
1399     mxf_write_local_tag(pb, 8, 0x3D03);
1400     avio_wb32(pb, st->codecpar->sample_rate);
1401     avio_wb32(pb, 1);
1402
1403     if (s->oformat == &ff_mxf_d10_muxer) {
1404         mxf_write_local_tag(pb, 1, 0x3D04);
1405         avio_w8(pb, 0);
1406     }
1407
1408     mxf_write_local_tag(pb, 4, 0x3D07);
1409     if (mxf->channel_count == -1) {
1410         if (show_warnings && (s->oformat == &ff_mxf_d10_muxer) && (st->codecpar->channels != 4) && (st->codecpar->channels != 8))
1411             av_log(s, AV_LOG_WARNING, "the number of audio channels shall be 4 or 8 : the output will not comply to MXF D-10 specs, use -d10_channelcount to fix this\n");
1412         avio_wb32(pb, st->codecpar->channels);
1413     } else if (s->oformat == &ff_mxf_d10_muxer) {
1414         if (show_warnings && (mxf->channel_count < st->codecpar->channels))
1415             av_log(s, AV_LOG_WARNING, "d10_channelcount < actual number of audio channels : some channels will be discarded\n");
1416         if (show_warnings && (mxf->channel_count != 4) && (mxf->channel_count != 8))
1417             av_log(s, AV_LOG_WARNING, "d10_channelcount shall be set to 4 or 8 : the output will not comply to MXF D-10 specs\n");
1418         avio_wb32(pb, mxf->channel_count);
1419     } else {
1420         avio_wb32(pb, st->codecpar->channels);
1421     }
1422
1423     mxf_write_local_tag(pb, 4, 0x3D01);
1424     avio_wb32(pb, av_get_bits_per_sample(st->codecpar->codec_id));
1425
1426     return pos;
1427 }
1428
1429 static int64_t mxf_write_wav_common(AVFormatContext *s, AVStream *st, const UID key)
1430 {
1431     AVIOContext *pb = s->pb;
1432     int64_t pos = mxf_write_generic_sound_common(s, st, key);
1433
1434     mxf_write_local_tag(pb, 2, 0x3D0A);
1435     avio_wb16(pb, st->codecpar->block_align);
1436
1437     // avg bytes per sec
1438     mxf_write_local_tag(pb, 4, 0x3D09);
1439     avio_wb32(pb, st->codecpar->block_align*st->codecpar->sample_rate);
1440
1441     return pos;
1442 }
1443
1444 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
1445 {
1446     int64_t pos = mxf_write_wav_common(s, st, mxf_wav_descriptor_key);
1447     mxf_update_klv_size(s->pb, pos);
1448 }
1449
1450 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
1451 {
1452     int64_t pos = mxf_write_wav_common(s, st, mxf_aes3_descriptor_key);
1453     mxf_update_klv_size(s->pb, pos);
1454 }
1455
1456 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st)
1457 {
1458     int64_t pos = mxf_write_generic_sound_common(s, st, mxf_generic_sound_descriptor_key);
1459     mxf_update_klv_size(s->pb, pos);
1460 }
1461
1462 static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
1463
1464 static int mxf_write_tagged_value(AVFormatContext *s, const char* name, const char* value)
1465 {
1466     MXFContext *mxf = s->priv_data;
1467     AVIOContext *pb = s->pb;
1468     int name_size = mxf_utf16_local_tag_length(name);
1469     int indirect_value_size = 13 + mxf_utf16_local_tag_length(value);
1470
1471     if (!name_size || indirect_value_size == 13)
1472         return 1;
1473
1474     mxf_write_metadata_key(pb, 0x013f00);
1475     klv_encode_ber_length(pb, 24 + name_size + indirect_value_size);
1476
1477     // write instance UID
1478     mxf_write_local_tag(pb, 16, 0x3C0A);
1479     mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count);
1480
1481     // write name
1482     mxf_write_local_tag_utf16(pb, 0x5001, name); // Name
1483
1484     // write indirect value
1485     mxf_write_local_tag(pb, indirect_value_size, 0x5003);
1486     avio_write(pb, mxf_indirect_value_utf16le, 17);
1487     avio_put_str16le(pb, value);
1488
1489     mxf->tagged_value_count++;
1490     return 0;
1491 }
1492
1493 static int mxf_write_user_comments(AVFormatContext *s, const AVDictionary *m)
1494 {
1495     MXFContext *mxf = s->priv_data;
1496     AVDictionaryEntry *t = NULL;
1497     int count = 0;
1498
1499     while ((t = av_dict_get(m, "comment_", t, AV_DICT_IGNORE_SUFFIX))) {
1500         if (mxf->tagged_value_count >= UINT16_MAX) {
1501             av_log(s, AV_LOG_ERROR, "too many tagged values, ignoring remaining\n");
1502             return count;
1503         }
1504
1505         if (mxf_write_tagged_value(s, t->key + 8, t->value) == 0)
1506             count++;
1507     }
1508     return count;
1509 }
1510
1511 static void mxf_write_package(AVFormatContext *s, MXFPackage *package)
1512 {
1513     MXFContext *mxf = s->priv_data;
1514     AVIOContext *pb = s->pb;
1515     int i, track_count = s->nb_streams+1;
1516     int name_size = mxf_utf16_local_tag_length(package->name);
1517     int user_comment_count = 0;
1518
1519     if (package->type == MaterialPackage) {
1520         if (mxf->store_user_comments)
1521             user_comment_count = mxf_write_user_comments(s, s->metadata);
1522         mxf_write_metadata_key(pb, 0x013600);
1523         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
1524         klv_encode_ber_length(pb, 92 + name_size + (16*track_count) + (16*user_comment_count) + 12LL*mxf->store_user_comments);
1525     } else {
1526         mxf_write_metadata_key(pb, 0x013700);
1527         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
1528         klv_encode_ber_length(pb, 112 + name_size + (16*track_count) + 12LL*mxf->store_user_comments); // 20 bytes length for descriptor reference
1529     }
1530
1531     // write uid
1532     mxf_write_local_tag(pb, 16, 0x3C0A);
1533     mxf_write_uuid(pb, package->type, package->instance);
1534     av_log(s, AV_LOG_DEBUG, "package type:%d\n", package->type);
1535     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
1536
1537     // write package umid
1538     mxf_write_local_tag(pb, 32, 0x4401);
1539     mxf_write_umid(s, package->instance);
1540     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
1541
1542     // package name
1543     if (name_size)
1544         mxf_write_local_tag_utf16(pb, 0x4402, package->name);
1545
1546     // package creation date
1547     mxf_write_local_tag(pb, 8, 0x4405);
1548     avio_wb64(pb, mxf->timestamp);
1549
1550     // package modified date
1551     mxf_write_local_tag(pb, 8, 0x4404);
1552     avio_wb64(pb, mxf->timestamp);
1553
1554     // write track refs
1555     mxf_write_local_tag(pb, track_count*16 + 8, 0x4403);
1556     mxf_write_refs_count(pb, track_count);
1557     // these are the uuids of the tracks the will be written in mxf_write_track
1558     for (i = 0; i < track_count; i++)
1559         mxf_write_uuid(pb, Track,  mxf->track_instance_count + i);
1560
1561     // write user comment refs
1562     if (mxf->store_user_comments) {
1563         mxf_write_local_tag(pb, user_comment_count*16 + 8, 0x4406);
1564         mxf_write_refs_count(pb, user_comment_count);
1565         for (i = 0; i < user_comment_count; i++)
1566             mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count - user_comment_count + i);
1567     }
1568
1569     // write multiple descriptor reference
1570     if (package->type == SourcePackage && package->instance == 1) {
1571         mxf_write_local_tag(pb, 16, 0x4701);
1572         if (s->nb_streams > 1) {
1573             mxf_write_uuid(pb, MultipleDescriptor, 0);
1574             mxf_write_multi_descriptor(s);
1575         } else
1576             mxf_write_uuid(pb, SubDescriptor, 0);
1577     } else if (package->type == SourcePackage && package->instance == 2) {
1578         mxf_write_local_tag(pb, 16, 0x4701);
1579         mxf_write_uuid(pb, TapeDescriptor, 0);
1580         mxf_write_tape_descriptor(s);
1581     }
1582
1583     /*
1584      * for every 1 track in a package there is 1 sequence and 1 component.
1585      * all 3 of these elements share the same instance number for generating
1586      * there instance uuids. mxf->track_instance_count stores this value.
1587      * mxf->track_instance_count is incremented after a group of all 3 of
1588      * these elements are written.
1589      */
1590
1591     // write timecode track
1592     mxf_write_track(s, mxf->timecode_track, package);
1593     mxf_write_sequence(s, mxf->timecode_track, package);
1594     mxf_write_timecode_component(s, mxf->timecode_track, package);
1595     mxf->track_instance_count++;
1596
1597     for (i = 0; i < s->nb_streams; i++) {
1598         AVStream *st = s->streams[i];
1599         mxf_write_track(s, st, package);
1600         mxf_write_sequence(s, st, package);
1601         mxf_write_structural_component(s, st, package);
1602         mxf->track_instance_count++;
1603
1604         if (package->type == SourcePackage && package->instance == 1) {
1605             MXFStreamContext *sc = st->priv_data;
1606             mxf_essence_container_uls[sc->index].write_desc(s, st);
1607         }
1608     }
1609 }
1610
1611 static int mxf_write_essence_container_data(AVFormatContext *s)
1612 {
1613     AVIOContext *pb = s->pb;
1614
1615     mxf_write_metadata_key(pb, 0x012300);
1616     klv_encode_ber_length(pb, 72);
1617
1618     mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
1619     mxf_write_uuid(pb, EssenceContainerData, 0);
1620
1621     mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
1622     mxf_write_umid(s, 1);
1623
1624     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
1625     avio_wb32(pb, 1);
1626
1627     mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
1628     avio_wb32(pb, 2);
1629
1630     return 0;
1631 }
1632
1633 static int mxf_write_header_metadata_sets(AVFormatContext *s)
1634 {
1635     MXFContext *mxf = s->priv_data;
1636     AVDictionaryEntry *entry = NULL;
1637     AVStream *st = NULL;
1638     int i;
1639     MXFPackage packages[3] = {{0}};
1640     int package_count = 2;
1641     packages[0].type = MaterialPackage;
1642     packages[1].type = SourcePackage;
1643     packages[1].instance = 1;
1644     packages[0].ref = &packages[1];
1645
1646
1647     if (entry = av_dict_get(s->metadata, "material_package_name", NULL, 0))
1648        packages[0].name = entry->value;
1649
1650     if (entry = av_dict_get(s->metadata, "file_package_name", NULL, 0)) {
1651         packages[1].name = entry->value;
1652     } else {
1653         /* check if any of the streams contain a file_package_name */
1654         for (i = 0; i < s->nb_streams; i++) {
1655             st = s->streams[i];
1656             if (entry = av_dict_get(st->metadata, "file_package_name", NULL, 0)) {
1657                 packages[1].name = entry->value;
1658                 break;
1659             }
1660         }
1661     }
1662
1663     entry = av_dict_get(s->metadata, "reel_name", NULL, 0);
1664     if (entry) {
1665         packages[2].name = entry->value;
1666         packages[2].type = SourcePackage;
1667         packages[2].instance = 2;
1668         packages[1].ref = &packages[2];
1669         package_count = 3;
1670     }
1671
1672     mxf_write_preface(s);
1673     mxf_write_identification(s);
1674     mxf_write_content_storage(s, packages, package_count);
1675     mxf->track_instance_count = 0;
1676     for (i = 0; i < package_count; i++)
1677         mxf_write_package(s, &packages[i]);
1678     mxf_write_essence_container_data(s);
1679     return 0;
1680 }
1681
1682 static unsigned klv_fill_size(uint64_t size)
1683 {
1684     unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
1685     if (pad < 20) // smallest fill item possible
1686         return pad + KAG_SIZE;
1687     else
1688         return pad & (KAG_SIZE-1);
1689 }
1690
1691 static void mxf_write_index_table_segment(AVFormatContext *s)
1692 {
1693     MXFContext *mxf = s->priv_data;
1694     AVIOContext *pb = s->pb;
1695     int i, j, temporal_reordering = 0;
1696     int key_index = mxf->last_key_index;
1697     int prev_non_b_picture = 0;
1698     int audio_frame_size = 0;
1699     int64_t pos;
1700
1701     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
1702
1703     if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)
1704         return;
1705
1706     avio_write(pb, index_table_segment_key, 16);
1707
1708     klv_encode_ber4_length(pb, 0);
1709     pos = avio_tell(pb);
1710
1711     // instance id
1712     mxf_write_local_tag(pb, 16, 0x3C0A);
1713     mxf_write_uuid(pb, IndexTableSegment, 0);
1714
1715     // index edit rate
1716     mxf_write_local_tag(pb, 8, 0x3F0B);
1717     avio_wb32(pb, mxf->time_base.den);
1718     avio_wb32(pb, mxf->time_base.num);
1719
1720     // index start position
1721     mxf_write_local_tag(pb, 8, 0x3F0C);
1722     avio_wb64(pb, mxf->last_indexed_edit_unit);
1723
1724     // index duration
1725     mxf_write_local_tag(pb, 8, 0x3F0D);
1726     if (mxf->edit_unit_byte_count)
1727         avio_wb64(pb, 0); // index table covers whole container
1728     else
1729         avio_wb64(pb, mxf->edit_units_count);
1730
1731     // edit unit byte count
1732     mxf_write_local_tag(pb, 4, 0x3F05);
1733     avio_wb32(pb, mxf->edit_unit_byte_count);
1734
1735     // index sid
1736     mxf_write_local_tag(pb, 4, 0x3F06);
1737     avio_wb32(pb, 2);
1738
1739     // body sid
1740     mxf_write_local_tag(pb, 4, 0x3F07);
1741     avio_wb32(pb, 1);
1742
1743     // real slice count - 1
1744     mxf_write_local_tag(pb, 1, 0x3F08);
1745     avio_w8(pb, !mxf->edit_unit_byte_count); // only one slice for CBR
1746
1747     // delta entry array
1748     mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);
1749     avio_wb32(pb, s->nb_streams+1); // num of entries
1750     avio_wb32(pb, 6);               // size of one entry
1751     // write system item delta entry
1752     avio_w8(pb, 0);
1753     avio_w8(pb, 0); // slice entry
1754     avio_wb32(pb, 0); // element delta
1755     // write each stream delta entry
1756     for (i = 0; i < s->nb_streams; i++) {
1757         AVStream *st = s->streams[i];
1758         MXFStreamContext *sc = st->priv_data;
1759         avio_w8(pb, sc->temporal_reordering);
1760         if (sc->temporal_reordering)
1761             temporal_reordering = 1;
1762         if (mxf->edit_unit_byte_count) {
1763             avio_w8(pb, 0); // slice number
1764             avio_wb32(pb, sc->slice_offset);
1765         } else if (i == 0) { // video track
1766             avio_w8(pb, 0); // slice number
1767             avio_wb32(pb, KAG_SIZE); // system item size including klv fill
1768         } else { // audio or data track
1769             if (!audio_frame_size) {
1770                 audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;
1771                 audio_frame_size += klv_fill_size(audio_frame_size);
1772             }
1773             avio_w8(pb, 1);
1774             avio_wb32(pb, (i-1)*audio_frame_size); // element delta
1775         }
1776     }
1777
1778     if (!mxf->edit_unit_byte_count) {
1779         MXFStreamContext *sc = s->streams[0]->priv_data;
1780         mxf_write_local_tag(pb, 8 + mxf->edit_units_count*15, 0x3F0A);
1781         avio_wb32(pb, mxf->edit_units_count);  // num of entries
1782         avio_wb32(pb, 15);  // size of one entry
1783
1784         for (i = 0; i < mxf->edit_units_count; i++) {
1785             int temporal_offset = 0;
1786
1787             if (!(mxf->index_entries[i].flags & 0x33)) { // I-frame
1788                 sc->max_gop = FFMAX(sc->max_gop, i - mxf->last_key_index);
1789                 mxf->last_key_index = key_index;
1790                 key_index = i;
1791             }
1792
1793             if (temporal_reordering) {
1794                 int pic_num_in_gop = i - key_index;
1795                 if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {
1796                     for (j = key_index; j < mxf->edit_units_count; j++) {
1797                         if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)
1798                             break;
1799                     }
1800                     if (j == mxf->edit_units_count)
1801                         av_log(s, AV_LOG_WARNING, "missing frames\n");
1802                     temporal_offset = j - key_index - pic_num_in_gop;
1803                 }
1804             }
1805             avio_w8(pb, temporal_offset);
1806
1807             if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction
1808                 sc->b_picture_count = FFMAX(sc->b_picture_count, i - prev_non_b_picture);
1809                 avio_w8(pb, mxf->last_key_index - i);
1810             } else {
1811                 avio_w8(pb, key_index - i); // key frame offset
1812                 if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
1813                     mxf->last_key_index = key_index;
1814                 prev_non_b_picture = i;
1815             }
1816
1817             if (!(mxf->index_entries[i].flags & 0x33) && // I-frame
1818                 mxf->index_entries[i].flags & 0x40 && !temporal_offset)
1819                 mxf->index_entries[i].flags |= 0x80; // random access
1820             avio_w8(pb, mxf->index_entries[i].flags);
1821             // stream offset
1822             avio_wb64(pb, mxf->index_entries[i].offset);
1823             if (s->nb_streams > 1)
1824                 avio_wb32(pb, mxf->index_entries[i].slice_offset);
1825             else
1826                 avio_wb32(pb, 0);
1827         }
1828
1829         mxf->last_key_index = key_index - mxf->edit_units_count;
1830         mxf->last_indexed_edit_unit += mxf->edit_units_count;
1831         mxf->edit_units_count = 0;
1832     }
1833
1834     mxf_update_klv_size(pb, pos);
1835 }
1836
1837 static void mxf_write_klv_fill(AVFormatContext *s)
1838 {
1839     unsigned pad = klv_fill_size(avio_tell(s->pb));
1840     if (pad) {
1841         avio_write(s->pb, klv_fill_key, 16);
1842         pad -= 16 + 4;
1843         klv_encode_ber4_length(s->pb, pad);
1844         ffio_fill(s->pb, 0, pad);
1845         av_assert1(!(avio_tell(s->pb) & (KAG_SIZE-1)));
1846     }
1847 }
1848
1849 static int mxf_write_partition(AVFormatContext *s, int bodysid,
1850                                 int indexsid,
1851                                 const uint8_t *key, int write_metadata)
1852 {
1853     MXFContext *mxf = s->priv_data;
1854     AVIOContext *pb = s->pb;
1855     int64_t header_byte_count_offset;
1856     unsigned index_byte_count = 0;
1857     uint64_t partition_offset = avio_tell(pb);
1858     int err;
1859
1860     if (!mxf->edit_unit_byte_count && mxf->edit_units_count)
1861         index_byte_count = 85 + 12+(s->nb_streams+1)*6 +
1862             12+mxf->edit_units_count*15;
1863     else if (mxf->edit_unit_byte_count && indexsid)
1864         index_byte_count = 80;
1865
1866     if (index_byte_count) {
1867         // add encoded ber length
1868         index_byte_count += 16 + klv_ber_length(index_byte_count);
1869         index_byte_count += klv_fill_size(index_byte_count);
1870     }
1871
1872     if (key && !memcmp(key, body_partition_key, 16)) {
1873         if ((err = av_reallocp_array(&mxf->body_partition_offset, mxf->body_partitions_count + 1,
1874                                      sizeof(*mxf->body_partition_offset))) < 0) {
1875             mxf->body_partitions_count = 0;
1876             return err;
1877         }
1878         mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;
1879     }
1880
1881     // write klv
1882     if (key)
1883         avio_write(pb, key, 16);
1884     else
1885         avio_write(pb, body_partition_key, 16);
1886
1887     klv_encode_ber4_length(pb, 88 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
1888
1889     // write partition value
1890     avio_wb16(pb, 1); // majorVersion
1891     avio_wb16(pb, 3); // minorVersion
1892     avio_wb32(pb, KAG_SIZE); // KAGSize
1893
1894     avio_wb64(pb, partition_offset); // ThisPartition
1895
1896     if (key && !memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
1897         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
1898     else if (key && !memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
1899         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
1900     else
1901         avio_wb64(pb, 0);
1902
1903     avio_wb64(pb, mxf->footer_partition_offset); // footerPartition
1904
1905     // set offset
1906     header_byte_count_offset = avio_tell(pb);
1907     avio_wb64(pb, 0); // headerByteCount, update later
1908
1909     // indexTable
1910     avio_wb64(pb, index_byte_count); // indexByteCount
1911     avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
1912
1913     // BodyOffset
1914     if (bodysid && mxf->edit_units_count && mxf->body_partitions_count && s->oformat != &ff_mxf_opatom_muxer)
1915         avio_wb64(pb, mxf->body_offset);
1916     else
1917         avio_wb64(pb, 0);
1918
1919     avio_wb32(pb, bodysid); // bodySID
1920
1921     // operational pattern
1922     if (s->oformat == &ff_mxf_opatom_muxer)
1923         avio_write(pb, opatom_ul, 16);
1924     else
1925         avio_write(pb, op1a_ul, 16);
1926
1927     // essence container
1928     mxf_write_essence_container_refs(s);
1929
1930     if (write_metadata) {
1931         // mark the start of the headermetadata and calculate metadata size
1932         int64_t pos, start;
1933         unsigned header_byte_count;
1934
1935         mxf_write_klv_fill(s);
1936         start = avio_tell(s->pb);
1937         mxf_write_primer_pack(s);
1938         mxf_write_klv_fill(s);
1939         mxf_write_header_metadata_sets(s);
1940         pos = avio_tell(s->pb);
1941         header_byte_count = pos - start + klv_fill_size(pos);
1942
1943         // update header_byte_count
1944         avio_seek(pb, header_byte_count_offset, SEEK_SET);
1945         avio_wb64(pb, header_byte_count);
1946         avio_seek(pb, pos, SEEK_SET);
1947     }
1948
1949     if(key)
1950         avio_flush(pb);
1951
1952     return 0;
1953 }
1954
1955 static const struct {
1956     int profile;
1957     UID codec_ul;
1958 } mxf_prores_codec_uls[] = {
1959     { FF_PROFILE_PRORES_PROXY,    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x01,0x00 } },
1960     { FF_PROFILE_PRORES_LT,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x02,0x00 } },
1961     { FF_PROFILE_PRORES_STANDARD, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 } },
1962     { FF_PROFILE_PRORES_HQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x04,0x00 } },
1963     { FF_PROFILE_PRORES_4444,     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x05,0x00 } },
1964     { FF_PROFILE_PRORES_XQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x06,0x00 } },
1965 };
1966
1967 static int mxf_parse_prores_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1968 {
1969     MXFContext *mxf = s->priv_data;
1970     MXFStreamContext *sc = st->priv_data;
1971     int i, profile;
1972
1973     if (mxf->header_written)
1974         return 1;
1975
1976     sc->codec_ul = NULL;
1977     profile = st->codecpar->profile;
1978     for (i = 0; i < FF_ARRAY_ELEMS(mxf_prores_codec_uls); i++) {
1979         if (profile == mxf_prores_codec_uls[i].profile) {
1980             sc->codec_ul = &mxf_prores_codec_uls[i].codec_ul;
1981             break;
1982         }
1983     }
1984     if (!sc->codec_ul)
1985         return 0;
1986
1987     sc->frame_size = pkt->size;
1988
1989     return 1;
1990 }
1991
1992 static const struct {
1993     int cid;
1994     UID codec_ul;
1995 } mxf_dnxhd_codec_uls[] = {
1996     { 1235, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 } }, // 1080p 10bit HIGH
1997     { 1237, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x03,0x00,0x00 } }, // 1080p 8bit MED
1998     { 1238, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x04,0x00,0x00 } }, // 1080p 8bit HIGH
1999     { 1241, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x07,0x00,0x00 } }, // 1080i 10bit HIGH
2000     { 1242, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x08,0x00,0x00 } }, // 1080i 8bit MED
2001     { 1243, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x09,0x00,0x00 } }, // 1080i 8bit HIGH
2002     { 1244, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x0a,0x00,0x00 } }, // 1080i 8bit TR
2003     { 1250, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x10,0x00,0x00 } }, // 720p 10bit
2004     { 1251, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x11,0x00,0x00 } }, // 720p 8bit HIGH
2005     { 1252, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x12,0x00,0x00 } }, // 720p 8bit MED
2006     { 1253, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x13,0x00,0x00 } }, // 720p 8bit LOW
2007     { 1256, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x16,0x00,0x00 } }, // 1080p 10bit 444
2008     { 1258, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x18,0x00,0x00 } }, // 720p 8bit TR
2009     { 1259, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x19,0x00,0x00 } }, // 1080p 8bit TR
2010     { 1260, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x1a,0x00,0x00 } }, // 1080i 8bit TR MBAFF
2011     { 1270, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x24,0x00,0x00 } }, // DNXHR 444
2012     { 1271, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x25,0x00,0x00 } }, // DNXHR HQX
2013     { 1272, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x26,0x00,0x00 } }, // DNXHR HQ
2014     { 1273, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x27,0x00,0x00 } }, // DNXHR SQ
2015     { 1274, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x28,0x00,0x00 } }, // DNXHR LB
2016 };
2017
2018 static int mxf_parse_dnxhd_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2019 {
2020     MXFContext *mxf = s->priv_data;
2021     MXFStreamContext *sc = st->priv_data;
2022     int i, cid, frame_size = 0;
2023
2024     if (mxf->header_written)
2025         return 1;
2026
2027     if (pkt->size < 43)
2028         return 0;
2029
2030     sc->codec_ul = NULL;
2031     cid = AV_RB32(pkt->data + 0x28);
2032     for (i = 0; i < FF_ARRAY_ELEMS(mxf_dnxhd_codec_uls); i++) {
2033         if (cid == mxf_dnxhd_codec_uls[i].cid) {
2034             sc->codec_ul = &mxf_dnxhd_codec_uls[i].codec_ul;
2035             break;
2036         }
2037     }
2038     if (!sc->codec_ul)
2039         return 0;
2040
2041     sc->component_depth = 0;
2042     switch (pkt->data[0x21] >> 5) {
2043     case 1: sc->component_depth = 8; break;
2044     case 2: sc->component_depth = 10; break;
2045     case 3: sc->component_depth = 12; break;
2046     }
2047     if (!sc->component_depth)
2048         return 0;
2049
2050     if ((frame_size = avpriv_dnxhd_get_frame_size(cid)) == DNXHD_VARIABLE) {
2051         frame_size = avpriv_dnxhd_get_hr_frame_size(cid, st->codecpar->width, st->codecpar->height);
2052     }
2053     if (frame_size < 0)
2054         return 0;
2055
2056     if ((sc->interlaced = avpriv_dnxhd_get_interlaced(cid)) < 0)
2057         return 0;
2058
2059     if (cid >= 1270) { // RI raster
2060         av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2061                   st->codecpar->width, st->codecpar->height,
2062                   INT_MAX);
2063     } else {
2064         sc->aspect_ratio = (AVRational){ 16, 9 };
2065     }
2066
2067     sc->frame_size = pkt->size;
2068
2069     return 1;
2070 }
2071
2072 static int mxf_parse_dv_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2073 {
2074     MXFContext *mxf = s->priv_data;
2075     MXFStreamContext *sc = st->priv_data;
2076     uint8_t *vs_pack, *vsc_pack;
2077     int ul_index, stype, pal;
2078     const AVDVProfile *profile;
2079
2080     if (mxf->header_written)
2081         return 1;
2082
2083     // Check for minimal frame size
2084     if (pkt->size < 120000)
2085         return -1;
2086
2087     profile = av_dv_frame_profile(NULL, pkt->data, pkt->size);
2088
2089     vs_pack  = pkt->data + 80*5 + 48;
2090     vsc_pack = pkt->data + 80*5 + 53;
2091     stype    = vs_pack[3] & 0x1f;
2092     pal      = (vs_pack[3] >> 5) & 0x1;
2093
2094     if ((vsc_pack[2] & 0x07) == 0x02) {
2095         sc->aspect_ratio = (AVRational){ 16, 9 };
2096     } else {
2097         sc->aspect_ratio = (AVRational){ 4, 3 };
2098     }
2099
2100     sc->interlaced = (vsc_pack[3] >> 4) & 0x01;
2101     // TODO: fix dv encoder to set proper FF/FS value in VSC pack
2102     // and set field dominance accordingly
2103     // av_log(s, AV_LOG_DEBUG, "DV vsc pack ff/ss = %x\n", vsc_pack[2] >> 6);
2104
2105     switch (stype) {
2106     case 0x18: // DV100 720p
2107         ul_index = INDEX_DV100_720_50 + pal;
2108         if (sc->interlaced) {
2109             av_log(s, AV_LOG_ERROR, "source marked as interlaced but codec profile is progressive\n");
2110             sc->interlaced = 0;
2111         }
2112         break;
2113     case 0x14: // DV100 1080i
2114         ul_index = INDEX_DV100_1080_50 + pal;
2115         break;
2116     case 0x04: // DV50
2117         ul_index = INDEX_DV50_525_60 + pal;
2118         break;
2119     default: // DV25
2120         if (profile && profile->pix_fmt == AV_PIX_FMT_YUV420P && pal) {
2121             ul_index = INDEX_DV25_525_60_IEC + pal;
2122             break;
2123         }
2124         ul_index = INDEX_DV25_525_60 + pal;
2125     }
2126
2127     sc->index = ul_index;
2128     sc->codec_ul =  &mxf_essence_container_uls[sc->index].codec_ul;
2129     sc->frame_size = pkt->size;
2130
2131     return 1;
2132 }
2133
2134 static const struct {
2135     UID uid;
2136     int frame_size;
2137     int profile;
2138     uint8_t interlaced;
2139     int long_gop; // 1 or 0 when there are separate UIDs for Long GOP and Intra, -1 when Intra/LGOP detection can be ignored
2140 } mxf_h264_codec_uls[] = {
2141     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x11,0x01 },      0,  66, 0, -1 }, // AVC Baseline, Unconstrained Coding
2142     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x20,0x01 },      0,  77, 0, -1 }, // AVC Main
2143     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x30,0x01 },      0,  88, 0, -1 }, // AVC Extended
2144     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x40,0x01 },      0, 100, 0, -1 }, // AVC High
2145     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x50,0x01 },      0, 110, 0,  1 }, // AVC High 10
2146     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x60,0x01 },      0, 122, 0,  1 }, // AVC High 422
2147     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x70,0x01 },      0, 244, 0,  1 }, // AVC High 444
2148     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x20,0x01 },      0, 110, 0,  0 }, // AVC High 10 Intra
2149     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 232960,   0, 1,  0 }, // AVC Intra 50 1080i60
2150     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 281088,   0, 1,  0 }, // AVC Intra 50 1080i50
2151     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 232960,   0, 0,  0 }, // AVC Intra 50 1080p30
2152     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 281088,   0, 0,  0 }, // AVC Intra 50 1080p25
2153     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x08 }, 116736,   0, 0,  0 }, // AVC Intra 50 720p60
2154     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x09 }, 140800,   0, 0,  0 }, // AVC Intra 50 720p50
2155     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x30,0x01 },      0, 122, 0,  0 }, // AVC High 422 Intra
2156     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x01 }, 472576,   0, 1,  0 }, // AVC Intra 100 1080i60
2157     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x02 }, 568832,   0, 1,  0 }, // AVC Intra 100 1080i50
2158     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x03 }, 472576,   0, 0,  0 }, // AVC Intra 100 1080p30
2159     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x04 }, 568832,   0, 0,  0 }, // AVC Intra 100 1080p25
2160     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x08 }, 236544,   0, 0,  0 }, // AVC Intra 100 720p60
2161     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x09 }, 284672,   0, 0,  0 }, // AVC Intra 100 720p50
2162     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x40,0x01 },      0, 244, 0,  0 }, // AVC High 444 Intra
2163     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x50,0x01 },      0,  44, 0, -1 }, // AVC CAVLC 444
2164 };
2165
2166 static int mxf_parse_h264_frame(AVFormatContext *s, AVStream *st,
2167                                 AVPacket *pkt, MXFIndexEntry *e)
2168 {
2169     MXFContext *mxf = s->priv_data;
2170     MXFStreamContext *sc = st->priv_data;
2171     AVCodecParameters *par = st->codecpar;
2172     static const int mxf_h264_num_codec_uls = sizeof(mxf_h264_codec_uls) / sizeof(mxf_h264_codec_uls[0]);
2173     const uint8_t *buf = pkt->data;
2174     const uint8_t *buf_end = pkt->data + pkt->size;
2175     uint32_t state = -1;
2176     int long_gop = 0; // assume intra when there is no SPS header
2177     int extra_size = 512; // support AVC Intra files without SPS/PPS header
2178     int i, frame_size;
2179     uint8_t uid_found;
2180
2181     if (pkt->size > extra_size)
2182         buf_end -= pkt->size - extra_size; // no need to parse beyond SPS/PPS header
2183
2184     for (;;) {
2185         buf = avpriv_find_start_code(buf, buf_end, &state);
2186         if (buf >= buf_end)
2187             break;
2188         --buf;
2189         switch (state & 0x1f) {
2190         case H264_NAL_SPS:
2191             par->profile = buf[1];
2192             long_gop = buf[2] & 0x10 ? 0 : 1; // constraint_set3_flag signals intra
2193             e->flags |= 0x40;
2194             break;
2195         case H264_NAL_PPS:
2196             if (e->flags & 0x40) { // sequence header present
2197                 e->flags |= 0x80; // random access
2198                 extra_size = 0;
2199                 buf = buf_end;
2200             }
2201             break;
2202         default:
2203             break;
2204         }
2205     }
2206
2207     if (mxf->header_written)
2208         return 1;
2209
2210     sc->aspect_ratio = (AVRational){ 16, 9 }; // 16:9 is mandatory for broadcast HD
2211     sc->interlaced = par->field_order != AV_FIELD_PROGRESSIVE ? 1 : 0;
2212
2213     uid_found = 0;
2214     frame_size = pkt->size + extra_size;
2215     for (i = 0; i < mxf_h264_num_codec_uls; i++) {
2216         if (frame_size == mxf_h264_codec_uls[i].frame_size && sc->interlaced == mxf_h264_codec_uls[i].interlaced) {
2217             sc->codec_ul = &mxf_h264_codec_uls[i].uid;
2218             sc->component_depth = 10; // AVC Intra is always 10 Bit
2219             if (sc->interlaced)
2220                 sc->field_dominance = 1; // top field first is mandatory for AVC Intra
2221             return 1;
2222         } else if ((mxf_h264_codec_uls[i].profile == par->profile) &&
2223                    ((mxf_h264_codec_uls[i].long_gop < 0) ||
2224                    (mxf_h264_codec_uls[i].long_gop == long_gop))) {
2225             sc->codec_ul = &mxf_h264_codec_uls[i].uid;
2226             uid_found = 1;
2227         }
2228     }
2229
2230     if (!uid_found) {
2231         av_log(s, AV_LOG_ERROR, "h264 profile not supported\n");
2232         return 0;
2233     }
2234
2235     return 1;
2236 }
2237
2238 static const UID mxf_mpeg2_codec_uls[] = {
2239     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
2240     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
2241     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
2242     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
2243     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
2244     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
2245     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
2246     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
2247     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x02,0x00 }, // MP@H-14 I-Frame
2248     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x03,0x00 }, // MP@H-14 Long GOP
2249 };
2250
2251 static const UID *mxf_get_mpeg2_codec_ul(AVCodecParameters *par)
2252 {
2253     int long_gop = 1;
2254
2255     if (par->profile == 4) { // Main
2256         if (par->level == 8) // Main
2257             return &mxf_mpeg2_codec_uls[0+long_gop];
2258         else if (par->level == 4) // High
2259             return &mxf_mpeg2_codec_uls[4+long_gop];
2260         else if (par->level == 6) // High 14
2261             return &mxf_mpeg2_codec_uls[8+long_gop];
2262     } else if (par->profile == 0) { // 422
2263         if (par->level == 5) // Main
2264             return &mxf_mpeg2_codec_uls[2+long_gop];
2265         else if (par->level == 2) // High
2266             return &mxf_mpeg2_codec_uls[6+long_gop];
2267     }
2268     return NULL;
2269 }
2270
2271 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
2272                                  AVPacket *pkt, MXFIndexEntry *e)
2273 {
2274     MXFStreamContext *sc = st->priv_data;
2275     uint32_t c = -1;
2276     int i;
2277
2278     for(i = 0; i < pkt->size - 4; i++) {
2279         c = (c<<8) + pkt->data[i];
2280         if (c == 0x1b5) {
2281             if ((pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
2282                 st->codecpar->profile = pkt->data[i+1] & 0x07;
2283                 st->codecpar->level   = pkt->data[i+2] >> 4;
2284                 sc->low_delay = pkt->data[i+6] >> 7;
2285             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
2286                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
2287                 if (sc->interlaced)
2288                     sc->field_dominance = 1 + !(pkt->data[i+4] & 0x80); // top field first
2289                 break;
2290             }
2291         } else if (c == 0x1b8) { // gop
2292             if (pkt->data[i+4]>>6 & 0x01) { // closed
2293                 if (sc->seq_closed_gop == -1)
2294                     sc->seq_closed_gop = 1;
2295                 sc->closed_gop = 1;
2296                 if (e->flags & 0x40) // sequence header present
2297                     e->flags |= 0x80; // random access
2298             } else {
2299                 sc->seq_closed_gop = 0;
2300                 sc->closed_gop = 0;
2301             }
2302         } else if (c == 0x1b3) { // seq
2303             e->flags |= 0x40;
2304             switch ((pkt->data[i+4]>>4) & 0xf) {
2305             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
2306             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
2307             case 4:  sc->aspect_ratio = (AVRational){221,100}; break;
2308             default:
2309                 av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2310                           st->codecpar->width, st->codecpar->height, 1024*1024);
2311             }
2312         } else if (c == 0x100) { // pic
2313             int pict_type = (pkt->data[i+2]>>3) & 0x07;
2314             e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
2315             if (pict_type == 2) { // P-frame
2316                 e->flags |= 0x22;
2317                 sc->closed_gop = 0; // reset closed GOP, don't matter anymore
2318             } else if (pict_type == 3) { // B-frame
2319                 if (sc->closed_gop)
2320                     e->flags |= 0x13; // only backward prediction
2321                 else
2322                     e->flags |= 0x33;
2323                 sc->temporal_reordering = -1;
2324             } else if (!pict_type) {
2325                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
2326                 return 0;
2327             }
2328         }
2329     }
2330     if (s->oformat != &ff_mxf_d10_muxer)
2331         sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codecpar);
2332     return !!sc->codec_ul;
2333 }
2334
2335 static uint64_t mxf_parse_timestamp(int64_t timestamp64)
2336 {
2337     time_t timestamp = timestamp64 / 1000000;
2338     struct tm tmbuf;
2339     struct tm *time = gmtime_r(&timestamp, &tmbuf);
2340     if (!time)
2341         return 0;
2342     return (uint64_t)(time->tm_year+1900) << 48 |
2343            (uint64_t)(time->tm_mon+1)     << 40 |
2344            (uint64_t) time->tm_mday       << 32 |
2345                       time->tm_hour       << 24 |
2346                       time->tm_min        << 16 |
2347                       time->tm_sec        << 8  |
2348                       (timestamp64 % 1000000) / 4000;
2349 }
2350
2351 static void mxf_gen_umid(AVFormatContext *s)
2352 {
2353     MXFContext *mxf = s->priv_data;
2354     uint32_t seed = av_get_random_seed();
2355     uint64_t umid = seed + 0x5294713400000000LL;
2356
2357     AV_WB64(mxf->umid  , umid);
2358     AV_WB64(mxf->umid+8, umid>>8);
2359
2360     mxf->instance_number = seed & 0xFFFFFF;
2361 }
2362
2363 static int mxf_init_timecode(AVFormatContext *s, AVStream *st, AVRational rate)
2364 {
2365     MXFContext *mxf = s->priv_data;
2366     AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
2367     if (!tcr)
2368         tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
2369
2370     if (tcr)
2371         return av_timecode_init_from_string(&mxf->tc, rate, tcr->value, s);
2372     else
2373         return av_timecode_init(&mxf->tc, rate, 0, 0, s);
2374 }
2375
2376 static int mxf_write_header(AVFormatContext *s)
2377 {
2378     MXFContext *mxf = s->priv_data;
2379     int i, ret;
2380     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
2381     const MXFSamplesPerFrame *spf = NULL;
2382     int64_t timestamp = 0;
2383
2384     if (!s->nb_streams)
2385         return -1;
2386
2387     if (s->oformat == &ff_mxf_opatom_muxer && s->nb_streams !=1) {
2388         av_log(s, AV_LOG_ERROR, "there must be exactly one stream for mxf opatom\n");
2389         return -1;
2390     }
2391
2392     if (!av_dict_get(s->metadata, "comment_", NULL, AV_DICT_IGNORE_SUFFIX))
2393         mxf->store_user_comments = 0;
2394
2395     for (i = 0; i < s->nb_streams; i++) {
2396         AVStream *st = s->streams[i];
2397         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
2398         if (!sc)
2399             return AVERROR(ENOMEM);
2400         st->priv_data = sc;
2401
2402         if (((i == 0) ^ (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) && s->oformat != &ff_mxf_opatom_muxer) {
2403             av_log(s, AV_LOG_ERROR, "there must be exactly one video stream and it must be the first one\n");
2404             return -1;
2405         }
2406
2407         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2408             const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(st->codecpar->format);
2409             // TODO: should be avg_frame_rate
2410             AVRational rate, tbc = st->time_base;
2411             // Default component depth to 8
2412             sc->component_depth = 8;
2413             sc->h_chroma_sub_sample = 2;
2414             sc->v_chroma_sub_sample = 2;
2415             sc->color_siting = 0xFF;
2416
2417             if (st->codecpar->sample_aspect_ratio.num && st->codecpar->sample_aspect_ratio.den) {
2418                 sc->aspect_ratio = av_mul_q(st->codecpar->sample_aspect_ratio,
2419                                             av_make_q(st->codecpar->width, st->codecpar->height));
2420             }
2421
2422             if (pix_desc) {
2423                 sc->component_depth     = pix_desc->comp[0].depth;
2424                 sc->h_chroma_sub_sample = 1 << pix_desc->log2_chroma_w;
2425                 sc->v_chroma_sub_sample = 1 << pix_desc->log2_chroma_h;
2426             }
2427             switch (ff_choose_chroma_location(s, st)) {
2428             case AVCHROMA_LOC_TOPLEFT: sc->color_siting = 0; break;
2429             case AVCHROMA_LOC_LEFT:    sc->color_siting = 6; break;
2430             case AVCHROMA_LOC_TOP:     sc->color_siting = 1; break;
2431             case AVCHROMA_LOC_CENTER:  sc->color_siting = 3; break;
2432             }
2433
2434             mxf->timecode_base = (tbc.den + tbc.num/2) / tbc.num;
2435             spf = ff_mxf_get_samples_per_frame(s, tbc);
2436             if (!spf) {
2437                 av_log(s, AV_LOG_ERROR, "Unsupported video frame rate %d/%d\n",
2438                        tbc.den, tbc.num);
2439                 return AVERROR(EINVAL);
2440             }
2441             mxf->content_package_rate = ff_mxf_get_content_package_rate(tbc);
2442             mxf->time_base = spf->time_base;
2443             rate = av_inv_q(mxf->time_base);
2444             avpriv_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
2445             if((ret = mxf_init_timecode(s, st, rate)) < 0)
2446                 return ret;
2447
2448             if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2449                 sc->seq_closed_gop = -1; // unknown yet
2450             }
2451
2452             sc->video_bit_rate = st->codecpar->bit_rate;
2453
2454             if (s->oformat == &ff_mxf_d10_muxer ||
2455                 st->codecpar->codec_id == AV_CODEC_ID_DNXHD ||
2456                 st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO)
2457                 mxf->cbr_index = 1;
2458
2459             if (s->oformat == &ff_mxf_d10_muxer) {
2460                 if (st->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
2461                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support MPEG-2 Video\n");
2462                     return AVERROR(EINVAL);
2463                 }
2464                 if ((sc->video_bit_rate == 50000000) && (mxf->time_base.den == 25)) {
2465                     sc->index = INDEX_D10_625_50_50_VIDEO;
2466                 } else if ((sc->video_bit_rate == 49999840 || sc->video_bit_rate == 50000000) && (mxf->time_base.den != 25)) {
2467                     sc->index = INDEX_D10_525_60_50_VIDEO;
2468                 } else if (sc->video_bit_rate == 40000000) {
2469                     if (mxf->time_base.den == 25) sc->index = INDEX_D10_625_50_40_VIDEO;
2470                     else                          sc->index = INDEX_D10_525_60_40_VIDEO;
2471                 } else if (sc->video_bit_rate == 30000000) {
2472                     if (mxf->time_base.den == 25) sc->index = INDEX_D10_625_50_30_VIDEO;
2473                     else                          sc->index = INDEX_D10_525_60_30_VIDEO;
2474                 } else {
2475                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
2476                     return -1;
2477                 }
2478
2479                 sc->signal_standard = 1;
2480                 sc->color_siting = 0;
2481                 sc->frame_size = (int64_t)sc->video_bit_rate *
2482                     mxf->time_base.num / (8*mxf->time_base.den);
2483             }
2484             if (mxf->signal_standard >= 0)
2485                 sc->signal_standard = mxf->signal_standard;
2486         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2487             if (st->codecpar->sample_rate != 48000) {
2488                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
2489                 return -1;
2490             }
2491             avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
2492             if (s->oformat == &ff_mxf_d10_muxer) {
2493                 if (st->index != 1) {
2494                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
2495                     return -1;
2496                 }
2497                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2498                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2499                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support 16 or 24 bits le audio\n");
2500                 }
2501                 sc->index = ((MXFStreamContext*)s->streams[0]->priv_data)->index + 1;
2502                 sc->frame_size = 4 + 8 * spf[0].samples_per_frame[0] * 4;
2503             } else if (s->oformat == &ff_mxf_opatom_muxer) {
2504                 AVRational tbc = av_inv_q(mxf->audio_edit_rate);
2505
2506                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2507                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2508                     av_log(s, AV_LOG_ERROR, "Only pcm_s16le and pcm_s24le audio codecs are implemented\n");
2509                     return AVERROR_PATCHWELCOME;
2510                 }
2511                 if (st->codecpar->channels != 1) {
2512                     av_log(s, AV_LOG_ERROR, "MXF OPAtom only supports single channel audio\n");
2513                     return AVERROR(EINVAL);
2514                 }
2515
2516                 spf = ff_mxf_get_samples_per_frame(s, tbc);
2517                 if (!spf) {
2518                     av_log(s, AV_LOG_ERROR, "Unsupported timecode frame rate %d/%d\n", tbc.den, tbc.num);
2519                     return AVERROR(EINVAL);
2520                 }
2521
2522                 mxf->time_base = st->time_base;
2523                 if((ret = mxf_init_timecode(s, st, av_inv_q(spf->time_base))) < 0)
2524                     return ret;
2525
2526                 mxf->timecode_base = (tbc.den + tbc.num/2) / tbc.num;
2527                 mxf->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3;
2528                 sc->index = INDEX_WAV;
2529             } else {
2530                 mxf->slice_count = 1;
2531                 sc->frame_size = (st->codecpar->channels * spf[0].samples_per_frame[0] *
2532                                   av_get_bits_per_sample(st->codecpar->codec_id)) / 8;
2533             }
2534         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
2535             AVDictionaryEntry *e = av_dict_get(st->metadata, "data_type", NULL, 0);
2536             if (e && !strcmp(e->value, "vbi_vanc_smpte_436M")) {
2537                 sc->index = INDEX_S436M;
2538             } else {
2539                 av_log(s, AV_LOG_ERROR, "track %d: unsupported data type\n", i);
2540                 return -1;
2541             }
2542             if (st->index != s->nb_streams - 1) {
2543                 av_log(s, AV_LOG_ERROR, "data track must be placed last\n");
2544                 return -1;
2545             }
2546         }
2547
2548         if (!sc->index) {
2549             sc->index = mxf_get_essence_container_ul_index(st->codecpar->codec_id);
2550             if (sc->index == -1) {
2551                 av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
2552                        "codec not currently supported in container\n", i);
2553                 return -1;
2554             }
2555         }
2556
2557         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
2558
2559         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
2560         sc->track_essence_element_key[15] = present[sc->index];
2561         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
2562
2563         if (!present[sc->index])
2564             mxf->essence_container_count++;
2565         present[sc->index]++;
2566     }
2567
2568     if (s->oformat == &ff_mxf_d10_muxer || s->oformat == &ff_mxf_opatom_muxer) {
2569         mxf->essence_container_count = 1;
2570     }
2571
2572     if (!(s->flags & AVFMT_FLAG_BITEXACT))
2573         mxf_gen_umid(s);
2574
2575     for (i = 0; i < s->nb_streams; i++) {
2576         MXFStreamContext *sc = s->streams[i]->priv_data;
2577         // update element count
2578         sc->track_essence_element_key[13] = present[sc->index];
2579         if (!memcmp(sc->track_essence_element_key, mxf_essence_container_uls[15].element_ul, 13)) // DV
2580             sc->order = (0x15 << 24) | AV_RB32(sc->track_essence_element_key+13);
2581         else
2582             sc->order = AV_RB32(sc->track_essence_element_key+12);
2583     }
2584
2585     if (ff_parse_creation_time_metadata(s, &timestamp, 0) > 0)
2586         mxf->timestamp = mxf_parse_timestamp(timestamp);
2587     mxf->duration = -1;
2588
2589     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
2590     if (!mxf->timecode_track)
2591         return AVERROR(ENOMEM);
2592     mxf->timecode_track->priv_data = av_mallocz(sizeof(MXFStreamContext));
2593     if (!mxf->timecode_track->priv_data)
2594         return AVERROR(ENOMEM);
2595     mxf->timecode_track->index = -1;
2596
2597     if (!spf)
2598         spf = ff_mxf_get_samples_per_frame(s, (AVRational){ 1, 25 });
2599
2600     if (ff_audio_interleave_init(s, spf->samples_per_frame, mxf->time_base) < 0)
2601         return -1;
2602
2603     return 0;
2604 }
2605
2606 static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
2607 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 };
2608
2609 static void mxf_write_system_item(AVFormatContext *s)
2610 {
2611     MXFContext *mxf = s->priv_data;
2612     AVIOContext *pb = s->pb;
2613     unsigned frame;
2614     uint32_t time_code;
2615     int i, system_item_bitmap = 0x58; // UL, user date/time stamp, picture present
2616
2617     frame = mxf->last_indexed_edit_unit + mxf->edit_units_count;
2618
2619     // write system metadata pack
2620     avio_write(pb, system_metadata_pack_key, 16);
2621     klv_encode_ber4_length(pb, 57);
2622
2623     for (i = 0; i < s->nb_streams; i++) {
2624         if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2625             system_item_bitmap |= 0x4;
2626         else if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2627             system_item_bitmap |= 0x2;
2628     }
2629     avio_w8(pb, system_item_bitmap);
2630     avio_w8(pb, mxf->content_package_rate); // content package rate
2631     avio_w8(pb, 0x00); // content package type
2632     avio_wb16(pb, 0x00); // channel handle
2633     avio_wb16(pb, (mxf->tc.start + frame) & 0xFFFF); // continuity count, supposed to overflow
2634     if (mxf->essence_container_count > 1)
2635         avio_write(pb, multiple_desc_ul, 16);
2636     else {
2637         MXFStreamContext *sc = s->streams[0]->priv_data;
2638         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
2639     }
2640     avio_w8(pb, 0);
2641     avio_wb64(pb, 0);
2642     avio_wb64(pb, 0); // creation date/time stamp
2643
2644     avio_w8(pb, 0x81); // SMPTE 12M time code
2645     time_code = av_timecode_get_smpte_from_framenum(&mxf->tc, frame);
2646     avio_wb32(pb, time_code);
2647     avio_wb32(pb, 0); // binary group data
2648     avio_wb64(pb, 0);
2649
2650     // write system metadata package set
2651     avio_write(pb, system_metadata_package_set_key, 16);
2652     klv_encode_ber4_length(pb, 35);
2653     avio_w8(pb, 0x83); // UMID
2654     avio_wb16(pb, 0x20);
2655     mxf_write_umid(s, 1);
2656 }
2657
2658 static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2659 {
2660     MXFContext *mxf = s->priv_data;
2661     AVIOContext *pb = s->pb;
2662     int frame_size = pkt->size / st->codecpar->block_align;
2663     uint8_t *samples = pkt->data;
2664     uint8_t *end = pkt->data + pkt->size;
2665     int i;
2666
2667     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
2668
2669     avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
2670     avio_wl16(pb, frame_size);
2671     avio_w8(pb, (1<<st->codecpar->channels)-1);
2672
2673     while (samples < end) {
2674         for (i = 0; i < st->codecpar->channels; i++) {
2675             uint32_t sample;
2676             if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
2677                 sample = AV_RL24(samples)<< 4;
2678                 samples += 3;
2679             } else {
2680                 sample = AV_RL16(samples)<<12;
2681                 samples += 2;
2682             }
2683             avio_wl32(pb, sample | i);
2684         }
2685         for (; i < 8; i++)
2686             avio_wl32(pb, i);
2687     }
2688 }
2689
2690 static int mxf_write_opatom_body_partition(AVFormatContext *s)
2691 {
2692     MXFContext *mxf = s->priv_data;
2693     AVIOContext *pb = s->pb;
2694     AVStream *st = s->streams[0];
2695     MXFStreamContext *sc = st->priv_data;
2696     const uint8_t *key = NULL;
2697
2698     int err;
2699
2700     if (!mxf->header_written)
2701         key = body_partition_key;
2702
2703     if ((err = mxf_write_partition(s, 1, 0, key, 0)) < 0)
2704         return err;
2705     mxf_write_klv_fill(s);
2706     avio_write(pb, sc->track_essence_element_key, 16);
2707     klv_encode_ber9_length(pb, mxf->body_offset);
2708     return 0;
2709 }
2710
2711 static int mxf_write_opatom_packet(AVFormatContext *s, AVPacket *pkt, MXFIndexEntry *ie)
2712 {
2713     MXFContext *mxf = s->priv_data;
2714     AVIOContext *pb = s->pb;
2715
2716     int err;
2717
2718     if (!mxf->header_written) {
2719         if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2720             return err;
2721         mxf_write_klv_fill(s);
2722
2723         if ((err = mxf_write_opatom_body_partition(s)) < 0)
2724             return err;
2725         mxf->header_written = 1;
2726     }
2727
2728     if (!mxf->edit_unit_byte_count) {
2729         mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
2730         mxf->index_entries[mxf->edit_units_count].flags = ie->flags;
2731         mxf->index_entries[mxf->edit_units_count].temporal_ref = ie->temporal_ref;
2732     }
2733     mxf->edit_units_count++;
2734     avio_write(pb, pkt->data, pkt->size);
2735     mxf->body_offset += pkt->size;
2736     avio_flush(pb);
2737
2738     return 0;
2739 }
2740
2741 static void mxf_compute_edit_unit_byte_count(AVFormatContext *s)
2742 {
2743     MXFContext *mxf = s->priv_data;
2744     int i;
2745
2746     if (s->oformat == &ff_mxf_opatom_muxer) {
2747         MXFStreamContext *sc = s->streams[0]->priv_data;
2748         mxf->edit_unit_byte_count = sc->frame_size;
2749         return;
2750     }
2751
2752     mxf->edit_unit_byte_count = KAG_SIZE; // system element
2753     for (i = 0; i < s->nb_streams; i++) {
2754         AVStream *st = s->streams[i];
2755         MXFStreamContext *sc = st->priv_data;
2756         sc->slice_offset = mxf->edit_unit_byte_count;
2757         mxf->edit_unit_byte_count += 16 + 4 + sc->frame_size;
2758         mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
2759     }
2760 }
2761
2762 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
2763 {
2764     MXFContext *mxf = s->priv_data;
2765     AVIOContext *pb = s->pb;
2766     AVStream *st = s->streams[pkt->stream_index];
2767     MXFStreamContext *sc = st->priv_data;
2768     MXFIndexEntry ie = {0};
2769     int err;
2770
2771     if (!mxf->cbr_index && !mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
2772         if ((err = av_reallocp_array(&mxf->index_entries, mxf->edit_units_count
2773                                      + EDIT_UNITS_PER_BODY, sizeof(*mxf->index_entries))) < 0) {
2774             mxf->edit_units_count = 0;
2775             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
2776             return err;
2777         }
2778     }
2779
2780     if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2781         if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
2782             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
2783             return -1;
2784         }
2785     } else if (st->codecpar->codec_id == AV_CODEC_ID_DNXHD) {
2786         if (!mxf_parse_dnxhd_frame(s, st, pkt)) {
2787             av_log(s, AV_LOG_ERROR, "could not get dnxhd profile\n");
2788             return -1;
2789         }
2790     } else if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2791         if (!mxf_parse_prores_frame(s, st, pkt)) {
2792             av_log(s, AV_LOG_ERROR, "could not get prores profile\n");
2793             return -1;
2794         }
2795     } else if (st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO) {
2796         if (!mxf_parse_dv_frame(s, st, pkt)) {
2797             av_log(s, AV_LOG_ERROR, "could not get dv profile\n");
2798             return -1;
2799         }
2800     } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
2801         if (!mxf_parse_h264_frame(s, st, pkt, &ie)) {
2802             av_log(s, AV_LOG_ERROR, "could not get h264 profile\n");
2803             return -1;
2804         }
2805     }
2806
2807     if (mxf->cbr_index) {
2808         if (pkt->size != sc->frame_size && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2809             av_log(s, AV_LOG_ERROR, "track %d: frame size does not match index unit size, %d != %d\n",
2810                    st->index, pkt->size, sc->frame_size);
2811             return -1;
2812         }
2813         if (!mxf->header_written)
2814             mxf_compute_edit_unit_byte_count(s);
2815     }
2816
2817     if (s->oformat == &ff_mxf_opatom_muxer)
2818         return mxf_write_opatom_packet(s, pkt, &ie);
2819
2820     if (!mxf->header_written) {
2821         if (mxf->edit_unit_byte_count) {
2822             if ((err = mxf_write_partition(s, 1, 2, header_open_partition_key, 1)) < 0)
2823                 return err;
2824             mxf_write_klv_fill(s);
2825             mxf_write_index_table_segment(s);
2826         } else {
2827             if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2828                 return err;
2829         }
2830         mxf->header_written = 1;
2831     }
2832
2833     if (st->index == 0) {
2834         if (!mxf->edit_unit_byte_count &&
2835             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
2836             !(ie.flags & 0x33)) { // I-frame, GOP start
2837             mxf_write_klv_fill(s);
2838             if ((err = mxf_write_partition(s, 1, 2, body_partition_key, 0)) < 0)
2839                 return err;
2840             mxf_write_klv_fill(s);
2841             mxf_write_index_table_segment(s);
2842         }
2843
2844         mxf_write_klv_fill(s);
2845         mxf_write_system_item(s);
2846
2847         if (!mxf->edit_unit_byte_count) {
2848             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
2849             mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
2850             mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
2851             mxf->body_offset += KAG_SIZE; // size of system element
2852         }
2853         mxf->edit_units_count++;
2854     } else if (!mxf->edit_unit_byte_count && st->index == 1) {
2855         if (!mxf->edit_units_count) {
2856             av_log(s, AV_LOG_ERROR, "No packets in first stream\n");
2857             return AVERROR_PATCHWELCOME;
2858         }
2859         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
2860             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
2861     }
2862
2863     mxf_write_klv_fill(s);
2864     avio_write(pb, sc->track_essence_element_key, 16); // write key
2865     if (s->oformat == &ff_mxf_d10_muxer &&
2866         st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2867         mxf_write_d10_audio_packet(s, st, pkt);
2868     } else {
2869         klv_encode_ber4_length(pb, pkt->size); // write length
2870         avio_write(pb, pkt->data, pkt->size);
2871         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
2872     }
2873
2874     avio_flush(pb);
2875
2876     return 0;
2877 }
2878
2879 static void mxf_write_random_index_pack(AVFormatContext *s)
2880 {
2881     MXFContext *mxf = s->priv_data;
2882     AVIOContext *pb = s->pb;
2883     uint64_t pos = avio_tell(pb);
2884     int i;
2885
2886     avio_write(pb, random_index_pack_key, 16);
2887     klv_encode_ber_length(pb, 28 + 12LL*mxf->body_partitions_count);
2888
2889     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer)
2890         avio_wb32(pb, 1); // BodySID of header partition
2891     else
2892         avio_wb32(pb, 0);
2893     avio_wb64(pb, 0); // offset of header partition
2894
2895     for (i = 0; i < mxf->body_partitions_count; i++) {
2896         avio_wb32(pb, 1); // BodySID
2897         avio_wb64(pb, mxf->body_partition_offset[i]);
2898     }
2899
2900     avio_wb32(pb, 0); // BodySID of footer partition
2901     avio_wb64(pb, mxf->footer_partition_offset);
2902
2903     avio_wb32(pb, avio_tell(pb) - pos + 4);
2904 }
2905
2906 static int mxf_write_footer(AVFormatContext *s)
2907 {
2908     MXFContext *mxf = s->priv_data;
2909     AVIOContext *pb = s->pb;
2910     int i, err = 0;
2911
2912     if (!mxf->header_written ||
2913         (s->oformat == &ff_mxf_opatom_muxer && !mxf->body_partition_offset)) {
2914         /* reason could be invalid options/not supported codec/out of memory */
2915         err = AVERROR_UNKNOWN;
2916         goto end;
2917     }
2918
2919     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
2920
2921     mxf_write_klv_fill(s);
2922     mxf->footer_partition_offset = avio_tell(pb);
2923     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) { // no need to repeat index
2924         if ((err = mxf_write_partition(s, 0, 0, footer_partition_key, 0)) < 0)
2925             goto end;
2926     } else {
2927         if ((err = mxf_write_partition(s, 0, 2, footer_partition_key, 0)) < 0)
2928             goto end;
2929         mxf_write_klv_fill(s);
2930         mxf_write_index_table_segment(s);
2931     }
2932
2933     mxf_write_klv_fill(s);
2934     mxf_write_random_index_pack(s);
2935
2936     if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
2937         if (s->oformat == &ff_mxf_opatom_muxer) {
2938             /* rewrite body partition to update lengths */
2939             avio_seek(pb, mxf->body_partition_offset[0], SEEK_SET);
2940             if ((err = mxf_write_opatom_body_partition(s)) < 0)
2941                 goto end;
2942         }
2943
2944         avio_seek(pb, 0, SEEK_SET);
2945         if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) {
2946             if ((err = mxf_write_partition(s, 1, 2, header_closed_partition_key, 1)) < 0)
2947                 goto end;
2948             mxf_write_klv_fill(s);
2949             mxf_write_index_table_segment(s);
2950         } else {
2951             if ((err = mxf_write_partition(s, 0, 0, header_closed_partition_key, 1)) < 0)
2952                 goto end;
2953         }
2954         // update footer partition offset
2955         for (i = 0; i < mxf->body_partitions_count; i++) {
2956             avio_seek(pb, mxf->body_partition_offset[i]+44, SEEK_SET);
2957             avio_wb64(pb, mxf->footer_partition_offset);
2958         }
2959     }
2960
2961 end:
2962     ff_audio_interleave_close(s);
2963
2964     av_freep(&mxf->index_entries);
2965     av_freep(&mxf->body_partition_offset);
2966     av_freep(&mxf->timecode_track->priv_data);
2967     av_freep(&mxf->timecode_track);
2968
2969     mxf_free(s);
2970
2971     return err < 0 ? err : 0;
2972 }
2973
2974 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
2975 {
2976     int i, stream_count = 0;
2977
2978     for (i = 0; i < s->nb_streams; i++)
2979         stream_count += !!s->streams[i]->last_in_packet_buffer;
2980
2981     if (stream_count && (s->nb_streams == stream_count || flush)) {
2982         AVPacketList *pktl = s->internal->packet_buffer;
2983         if (s->nb_streams != stream_count) {
2984             AVPacketList *last = NULL;
2985             // find last packet in edit unit
2986             while (pktl) {
2987                 if (!stream_count || pktl->pkt.stream_index == 0)
2988                     break;
2989                 // update last packet in packet buffer
2990                 if (s->streams[pktl->pkt.stream_index]->last_in_packet_buffer != pktl)
2991                     s->streams[pktl->pkt.stream_index]->last_in_packet_buffer = pktl;
2992                 last = pktl;
2993                 pktl = pktl->next;
2994                 stream_count--;
2995             }
2996             // purge packet queue
2997             while (pktl) {
2998                 AVPacketList *next = pktl->next;
2999                 av_packet_unref(&pktl->pkt);
3000                 av_freep(&pktl);
3001                 pktl = next;
3002             }
3003             if (last)
3004                 last->next = NULL;
3005             else {
3006                 s->internal->packet_buffer = NULL;
3007                 s->internal->packet_buffer_end= NULL;
3008                 goto out;
3009             }
3010             pktl = s->internal->packet_buffer;
3011         }
3012
3013         *out = pktl->pkt;
3014         av_log(s, AV_LOG_TRACE, "out st:%d dts:%"PRId64"\n", (*out).stream_index, (*out).dts);
3015         s->internal->packet_buffer = pktl->next;
3016         if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
3017             s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
3018         if(!s->internal->packet_buffer)
3019             s->internal->packet_buffer_end= NULL;
3020         av_freep(&pktl);
3021         return 1;
3022     } else {
3023     out:
3024         av_init_packet(out);
3025         return 0;
3026     }
3027 }
3028
3029 static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
3030 {
3031     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
3032     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
3033
3034     return next->dts > pkt->dts ||
3035         (next->dts == pkt->dts && sc->order < sc2->order);
3036 }
3037
3038 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
3039 {
3040     return ff_audio_rechunk_interleave(s, out, pkt, flush,
3041                                mxf_interleave_get_packet, mxf_compare_timestamps);
3042 }
3043
3044 #define MXF_COMMON_OPTIONS \
3045     { "signal_standard", "Force/set Signal Standard",\
3046       offsetof(MXFContext, signal_standard), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3047     { "bt601", "ITU-R BT.601 and BT.656, also SMPTE 125M (525 and 625 line interlaced)",\
3048       0, AV_OPT_TYPE_CONST, {.i64 = 1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3049     { "bt1358", "ITU-R BT.1358 and ITU-R BT.799-3, also SMPTE 293M (525 and 625 line progressive)",\
3050       0, AV_OPT_TYPE_CONST, {.i64 = 2}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3051     { "smpte347m", "SMPTE 347M (540 Mbps mappings)",\
3052       0, AV_OPT_TYPE_CONST, {.i64 = 3}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3053     { "smpte274m", "SMPTE 274M (1125 line)",\
3054       0, AV_OPT_TYPE_CONST, {.i64 = 4}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3055     { "smpte296m", "SMPTE 296M (750 line progressive)",\
3056       0, AV_OPT_TYPE_CONST, {.i64 = 5}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3057     { "smpte349m", "SMPTE 349M (1485 Mbps mappings)",\
3058       0, AV_OPT_TYPE_CONST, {.i64 = 6}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3059     { "smpte428", "SMPTE 428-1 DCDM",\
3060       0, AV_OPT_TYPE_CONST, {.i64 = 7}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},
3061
3062
3063
3064 static const AVOption mxf_options[] = {
3065     MXF_COMMON_OPTIONS
3066     { "store_user_comments", "",
3067       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3068     { NULL },
3069 };
3070
3071 static const AVClass mxf_muxer_class = {
3072     .class_name     = "MXF muxer",
3073     .item_name      = av_default_item_name,
3074     .option         = mxf_options,
3075     .version        = LIBAVUTIL_VERSION_INT,
3076 };
3077
3078 static const AVOption d10_options[] = {
3079     { "d10_channelcount", "Force/set channelcount in generic sound essence descriptor",
3080       offsetof(MXFContext, channel_count), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 8, AV_OPT_FLAG_ENCODING_PARAM},
3081     MXF_COMMON_OPTIONS
3082     { "store_user_comments", "",
3083       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3084     { NULL },
3085 };
3086
3087 static const AVClass mxf_d10_muxer_class = {
3088     .class_name     = "MXF-D10 muxer",
3089     .item_name      = av_default_item_name,
3090     .option         = d10_options,
3091     .version        = LIBAVUTIL_VERSION_INT,
3092 };
3093
3094 static const AVOption opatom_options[] = {
3095     { "mxf_audio_edit_rate", "Audio edit rate for timecode",
3096         offsetof(MXFContext, audio_edit_rate), AV_OPT_TYPE_RATIONAL, {.dbl=25}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
3097     MXF_COMMON_OPTIONS
3098     { "store_user_comments", "",
3099       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3100     { NULL },
3101 };
3102
3103 static const AVClass mxf_opatom_muxer_class = {
3104     .class_name     = "MXF-OPAtom muxer",
3105     .item_name      = av_default_item_name,
3106     .option         = opatom_options,
3107     .version        = LIBAVUTIL_VERSION_INT,
3108 };
3109
3110 AVOutputFormat ff_mxf_muxer = {
3111     .name              = "mxf",
3112     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
3113     .mime_type         = "application/mxf",
3114     .extensions        = "mxf",
3115     .priv_data_size    = sizeof(MXFContext),
3116     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3117     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3118     .write_header      = mxf_write_header,
3119     .write_packet      = mxf_write_packet,
3120     .write_trailer     = mxf_write_footer,
3121     .flags             = AVFMT_NOTIMESTAMPS,
3122     .interleave_packet = mxf_interleave,
3123     .priv_class        = &mxf_muxer_class,
3124 };
3125
3126 AVOutputFormat ff_mxf_d10_muxer = {
3127     .name              = "mxf_d10",
3128     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) D-10 Mapping"),
3129     .mime_type         = "application/mxf",
3130     .priv_data_size    = sizeof(MXFContext),
3131     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3132     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3133     .write_header      = mxf_write_header,
3134     .write_packet      = mxf_write_packet,
3135     .write_trailer     = mxf_write_footer,
3136     .flags             = AVFMT_NOTIMESTAMPS,
3137     .interleave_packet = mxf_interleave,
3138     .priv_class        = &mxf_d10_muxer_class,
3139 };
3140
3141 AVOutputFormat ff_mxf_opatom_muxer = {
3142     .name              = "mxf_opatom",
3143     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) Operational Pattern Atom"),
3144     .mime_type         = "application/mxf",
3145     .extensions        = "mxf",
3146     .priv_data_size    = sizeof(MXFContext),
3147     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3148     .video_codec       = AV_CODEC_ID_DNXHD,
3149     .write_header      = mxf_write_header,
3150     .write_packet      = mxf_write_packet,
3151     .write_trailer     = mxf_write_footer,
3152     .flags             = AVFMT_NOTIMESTAMPS,
3153     .interleave_packet = mxf_interleave,
3154     .priv_class        = &mxf_opatom_muxer_class,
3155 };