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