encode klv fill item length in fixed ber 4 bytes
[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_mpegvideo_desc(AVFormatContext *s, AVStream *st)
709 {
710     MXFStreamContext *sc = st->priv_data;
711     ByteIOContext *pb = s->pb;
712     int stored_height = (st->codec->height+15)/16*16;
713     AVRational dar;
714     int f1, f2;
715
716     mxf_write_generic_desc(s, st, mxf_mpegvideo_descriptor_key, 169+sc->interlaced*4);
717
718     mxf_write_local_tag(pb, 4, 0x3203);
719     put_be32(pb, st->codec->width);
720
721     mxf_write_local_tag(pb, 4, 0x3202);
722     put_be32(pb, stored_height>>sc->interlaced);
723
724     mxf_write_local_tag(pb, 4, 0x3209);
725     put_be32(pb, st->codec->width);
726
727     mxf_write_local_tag(pb, 4, 0x3208);
728     put_be32(pb, st->codec->height>>sc->interlaced);
729
730     // component depth
731     mxf_write_local_tag(pb, 4, 0x3301);
732     put_be32(pb, 8);
733
734     // horizontal subsampling
735     mxf_write_local_tag(pb, 4, 0x3302);
736     put_be32(pb, 2);
737
738     // bit rate
739     mxf_write_local_tag(pb, 4, 0x8000);
740     put_be32(pb, st->codec->bit_rate);
741
742     // frame layout
743     mxf_write_local_tag(pb, 1, 0x320C);
744     put_byte(pb, sc->interlaced);
745
746     // video line map
747     switch (st->codec->height) {
748     case  576: f1 = 23; f2 = 336; break;
749     case  608: f1 =  7; f2 = 320; break;
750     case  480: f1 = 20; f2 = 283; break;
751     case  512: f1 =  7; f2 = 270; break;
752     case  720: f1 = 26; f2 =   0; break; // progressive
753     case 1080: f1 = 21; f2 = 584; break;
754     default:   f1 =  0; f2 =   0; break;
755     }
756
757     if (!sc->interlaced) {
758         f2  = 0;
759         f1 *= 2;
760     }
761
762     mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
763     put_be32(pb, sc->interlaced ? 2 : 1);
764     put_be32(pb, 4);
765     put_be32(pb, f1);
766     if (sc->interlaced)
767         put_be32(pb, f2);
768
769     av_reduce(&dar.num, &dar.den,
770               st->codec->width*st->codec->sample_aspect_ratio.num,
771               st->codec->height*st->codec->sample_aspect_ratio.den,
772               1024*1024);
773
774     mxf_write_local_tag(pb, 8, 0x320E);
775     put_be32(pb, dar.num);
776     put_be32(pb, dar.den);
777
778     mxf_write_local_tag(pb, 16, 0x3201);
779     put_buffer(pb, *sc->codec_ul, 16);
780 }
781
782 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
783 {
784     ByteIOContext *pb = s->pb;
785
786     mxf_write_generic_desc(s, st, key, size);
787
788     // audio locked
789     mxf_write_local_tag(pb, 1, 0x3D02);
790     put_byte(pb, 1);
791
792     // write audio sampling rate
793     mxf_write_local_tag(pb, 8, 0x3D03);
794     put_be32(pb, st->codec->sample_rate);
795     put_be32(pb, 1);
796
797     mxf_write_local_tag(pb, 4, 0x3D07);
798     put_be32(pb, st->codec->channels);
799
800     mxf_write_local_tag(pb, 4, 0x3D01);
801     put_be32(pb, av_get_bits_per_sample(st->codec->codec_id));
802 }
803
804 static void mxf_write_wav_common_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
805 {
806     ByteIOContext *pb = s->pb;
807
808     mxf_write_generic_sound_desc(s, st, key, size);
809
810     mxf_write_local_tag(pb, 2, 0x3D0A);
811     put_be16(pb, st->codec->block_align);
812
813     // avg bytes per sec
814     mxf_write_local_tag(pb, 4, 0x3D09);
815     put_be32(pb, st->codec->block_align*st->codec->sample_rate);
816 }
817
818 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
819 {
820     mxf_write_wav_common_desc(s, st, mxf_wav_descriptor_key, 107);
821 }
822
823 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
824 {
825     mxf_write_wav_common_desc(s, st, mxf_aes3_descriptor_key, 107);
826 }
827
828 static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
829 {
830     MXFContext *mxf = s->priv_data;
831     ByteIOContext *pb = s->pb;
832     int i, track_count;
833
834     if (type == MaterialPackage) {
835         track_count = s->nb_streams + 1; // add timecode track
836         mxf_write_metadata_key(pb, 0x013600);
837         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
838         klv_encode_ber_length(pb, 92 + 16*track_count);
839     } else {
840         track_count = s->nb_streams;
841         mxf_write_metadata_key(pb, 0x013700);
842         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
843         klv_encode_ber_length(pb, 112 + 16*track_count); // 20 bytes length for descriptor reference
844     }
845
846     // write uid
847     mxf_write_local_tag(pb, 16, 0x3C0A);
848     mxf_write_uuid(pb, type, 0);
849     av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
850     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
851
852     // write package umid
853     mxf_write_local_tag(pb, 32, 0x4401);
854     mxf_write_umid(pb, type, 0);
855     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
856
857     // package creation date
858     mxf_write_local_tag(pb, 8, 0x4405);
859     put_be64(pb, mxf->timestamp);
860
861     // package modified date
862     mxf_write_local_tag(pb, 8, 0x4404);
863     put_be64(pb, mxf->timestamp);
864
865     // write track refs
866     mxf_write_local_tag(pb, track_count*16 + 8, 0x4403);
867     mxf_write_refs_count(pb, track_count);
868     for (i = 0; i < s->nb_streams; i++)
869         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
870     if (type == MaterialPackage)
871         mxf_write_uuid(pb, Track, s->nb_streams); // timecode track
872
873     // write multiple descriptor reference
874     if (type == SourcePackage) {
875         mxf_write_local_tag(pb, 16, 0x4701);
876         if (s->nb_streams > 1) {
877             mxf_write_uuid(pb, MultipleDescriptor, 0);
878             mxf_write_multi_descriptor(s);
879         } else
880             mxf_write_uuid(pb, SubDescriptor, 0);
881     } else {
882         // write timecode track
883         mxf_write_track(s, mxf->timecode_track, type);
884         mxf_write_sequence(s, mxf->timecode_track, type);
885         mxf_write_timecode_component(s, mxf->timecode_track);
886     }
887
888     for (i = 0; i < s->nb_streams; i++) {
889         AVStream *st = s->streams[i];
890         mxf_write_track(s, st, type);
891         mxf_write_sequence(s, st, type);
892         mxf_write_structural_component(s, st, type);
893
894         if (type == SourcePackage) {
895             MXFStreamContext *sc = st->priv_data;
896             mxf_essence_container_uls[sc->index].write_desc(s, st);
897         }
898     }
899 }
900
901 static int mxf_write_essence_container_data(AVFormatContext *s)
902 {
903     ByteIOContext *pb = s->pb;
904
905     mxf_write_metadata_key(pb, 0x012300);
906     klv_encode_ber_length(pb, 72);
907
908     mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
909     mxf_write_uuid(pb, EssenceContainerData, 0);
910
911     mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
912     mxf_write_umid(pb, SourcePackage, 0);
913
914     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
915     put_be32(pb, 1);
916
917     mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
918     put_be32(pb, 2);
919
920     return 0;
921 }
922
923 static int mxf_write_header_metadata_sets(AVFormatContext *s)
924 {
925     mxf_write_preface(s);
926     mxf_write_identification(s);
927     mxf_write_content_storage(s);
928     mxf_write_package(s, MaterialPackage);
929     mxf_write_package(s, SourcePackage);
930     mxf_write_essence_container_data(s);
931     return 0;
932 }
933
934 static unsigned klv_fill_size(uint64_t size)
935 {
936     unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
937     if (pad < 20) // smallest fill item possible
938         return pad + KAG_SIZE;
939     else
940         return pad & (KAG_SIZE-1);
941 }
942
943 static void mxf_write_index_table_segment(AVFormatContext *s)
944 {
945     MXFContext *mxf = s->priv_data;
946     ByteIOContext *pb = s->pb;
947     int i, j;
948     int temporal_reordering = 0;
949     int key_index = mxf->last_key_index;
950
951     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
952
953     if (!mxf->edit_units_count)
954         return;
955
956     put_buffer(pb, index_table_segment_key, 16);
957     klv_encode_ber_length(pb, 109 + (s->nb_streams+1)*6 +
958                           mxf->edit_units_count*(11+mxf->slice_count*4));
959
960     // instance id
961     mxf_write_local_tag(pb, 16, 0x3C0A);
962     mxf_write_uuid(pb, IndexTableSegment, 0);
963
964     // index edit rate
965     mxf_write_local_tag(pb, 8, 0x3F0B);
966     put_be32(pb, mxf->time_base.num);
967     put_be32(pb, mxf->time_base.den);
968
969     // index start position
970     mxf_write_local_tag(pb, 8, 0x3F0C);
971     put_be64(pb, mxf->last_indexed_edit_unit);
972
973     // index duration
974     mxf_write_local_tag(pb, 8, 0x3F0D);
975     put_be64(pb, mxf->edit_units_count);
976
977     // edit unit byte count
978     mxf_write_local_tag(pb, 4, 0x3F05);
979     put_be32(pb, 0);
980
981     // index sid
982     mxf_write_local_tag(pb, 4, 0x3F06);
983     put_be32(pb, 2);
984
985     // body sid
986     mxf_write_local_tag(pb, 4, 0x3F07);
987     put_be32(pb, 1);
988
989     // real slice count - 1
990     mxf_write_local_tag(pb, 1, 0x3F08);
991     put_byte(pb, mxf->slice_count);
992
993     // delta entry array
994     mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);
995     put_be32(pb, s->nb_streams+1); // num of entries
996     put_be32(pb, 6);             // size of one entry
997     // write system item delta entry
998     put_byte(pb, 0);
999     put_byte(pb, 0); // slice entry
1000     put_be32(pb, 0); // element delta
1001     for (i = 0; i < s->nb_streams; i++) {
1002         AVStream *st = s->streams[i];
1003         MXFStreamContext *sc = st->priv_data;
1004         put_byte(pb, sc->temporal_reordering);
1005         if (sc->temporal_reordering)
1006             temporal_reordering = 1;
1007         // slice number
1008         if (i == 0) { // video track
1009             put_byte(pb, 0); // slice number
1010             put_be32(pb, KAG_SIZE); // system item size including klv fill
1011         } else { // audio track
1012             unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;
1013             audio_frame_size += klv_fill_size(audio_frame_size);
1014             put_byte(pb, 1);
1015             put_be32(pb, (i-1)*audio_frame_size); // element delta
1016         }
1017     }
1018
1019     mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A);
1020     put_be32(pb, mxf->edit_units_count);  // num of entries
1021     put_be32(pb, 11+mxf->slice_count*4);  // size of one entry
1022     for (i = 0; i < mxf->edit_units_count; i++) {
1023         if (temporal_reordering) {
1024             int temporal_offset = 0;
1025             for (j = i+1; j < mxf->edit_units_count; j++) {
1026                 temporal_offset++;
1027                 if (mxf->index_entries[j].flags & 0x10) { // backward prediction
1028                     // next is not b, so is reordered
1029                     if (!(mxf->index_entries[i+1].flags & 0x10)) {
1030                         if ((mxf->index_entries[i].flags & 0x11) == 0) // i frame
1031                             temporal_offset = 0;
1032                         else
1033                             temporal_offset = -temporal_offset;
1034                     }
1035                     break;
1036                 }
1037             }
1038             put_byte(pb, temporal_offset);
1039         } else
1040             put_byte(pb, 0);
1041         if (!(mxf->index_entries[i].flags & 0x33)) { // I frame
1042             mxf->last_key_index = key_index;
1043             key_index = i;
1044         }
1045         if (mxf->index_entries[i].flags & 0x10 && // backward prediction
1046             !(mxf->index_entries[key_index].flags & 0x80)) { // open gop
1047             put_byte(pb, mxf->last_key_index - i);
1048         } else {
1049             put_byte(pb, key_index - i); // key frame offset
1050             if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
1051                 mxf->last_key_index = key_index;
1052         }
1053         put_byte(pb, mxf->index_entries[i].flags);
1054         // stream offset
1055         put_be64(pb, mxf->index_entries[i].offset - mxf->first_edit_unit_offset);
1056         if (s->nb_streams > 1)
1057             put_be32(pb, mxf->index_entries[i].slice_offset);
1058     }
1059
1060     mxf->last_key_index = key_index - mxf->edit_units_count;
1061     mxf->last_indexed_edit_unit += mxf->edit_units_count;
1062     mxf->edit_units_count = 0;
1063 }
1064
1065 static void mxf_write_klv_fill(AVFormatContext *s)
1066 {
1067     unsigned pad = klv_fill_size(url_ftell(s->pb));
1068     if (pad) {
1069         put_buffer(s->pb, klv_fill_key, 16);
1070         pad -= 16 + 4;
1071         klv_encode_ber4_length(s->pb, pad);
1072         for (; pad; pad--)
1073             put_byte(s->pb, 0);
1074         assert(!(url_ftell(s->pb) & (KAG_SIZE-1)));
1075     }
1076 }
1077
1078 static void mxf_write_partition(AVFormatContext *s, int bodysid,
1079                                 int indexsid,
1080                                 const uint8_t *key, int write_metadata)
1081 {
1082     MXFContext *mxf = s->priv_data;
1083     ByteIOContext *pb = s->pb;
1084     int64_t header_byte_count_offset;
1085     unsigned index_byte_count = 0;
1086     uint64_t partition_offset = url_ftell(pb);
1087
1088     if (mxf->edit_units_count) {
1089         index_byte_count = 109 + (s->nb_streams+1)*6 +
1090             mxf->edit_units_count*(11+mxf->slice_count*4);
1091         // add encoded ber length
1092         index_byte_count += 16 + klv_ber_length(index_byte_count);
1093         index_byte_count += klv_fill_size(index_byte_count);
1094     }
1095
1096     if (!memcmp(key, body_partition_key, 16)) {
1097         mxf->body_partition_offset =
1098             av_realloc(mxf->body_partition_offset,
1099                        (mxf->body_partitions_count+1)*
1100                        sizeof(*mxf->body_partition_offset));
1101         mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;
1102     }
1103
1104     // write klv
1105     put_buffer(pb, key, 16);
1106
1107     klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
1108
1109     // write partition value
1110     put_be16(pb, 1); // majorVersion
1111     put_be16(pb, 2); // minorVersion
1112     put_be32(pb, KAG_SIZE); // KAGSize
1113
1114     put_be64(pb, partition_offset); // ThisPartition
1115
1116     if (!memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
1117         put_be64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
1118     else if (!memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
1119         put_be64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
1120     else
1121         put_be64(pb, 0);
1122
1123     put_be64(pb, mxf->footer_partition_offset); // footerPartition
1124
1125     // set offset
1126     header_byte_count_offset = url_ftell(pb);
1127     put_be64(pb, 0); // headerByteCount, update later
1128
1129     // indexTable
1130     put_be64(pb, index_byte_count); // indexByteCount
1131     put_be32(pb, index_byte_count ? indexsid : 0); // indexSID
1132
1133     // BodyOffset
1134     if (bodysid && mxf->edit_units_count) {
1135         uint64_t partition_end = url_ftell(pb) + 8 + 4 + 16 + 8 +
1136             16*mxf->essence_container_count;
1137         put_be64(pb, partition_end + klv_fill_size(partition_end) +
1138                  index_byte_count - mxf->first_edit_unit_offset);
1139     } else
1140         put_be64(pb, 0);
1141
1142     put_be32(pb, bodysid); // bodySID
1143
1144     // operational pattern
1145     if (s->nb_streams > 1) {
1146         put_buffer(pb, op1a_ul, 14);
1147         put_be16(pb, 0x0900); // multi track
1148     } else {
1149         put_buffer(pb, op1a_ul, 16);
1150     }
1151
1152     // essence container
1153     mxf_write_essence_container_refs(s);
1154
1155     if (write_metadata) {
1156         // mark the start of the headermetadata and calculate metadata size
1157         int64_t pos, start;
1158         unsigned header_byte_count;
1159
1160         mxf_write_klv_fill(s);
1161         start = url_ftell(s->pb);
1162         mxf_write_primer_pack(s);
1163         mxf_write_header_metadata_sets(s);
1164         pos = url_ftell(s->pb);
1165         header_byte_count = pos - start + klv_fill_size(pos);
1166
1167         // update header_byte_count
1168         url_fseek(pb, header_byte_count_offset, SEEK_SET);
1169         put_be64(pb, header_byte_count);
1170         url_fseek(pb, pos, SEEK_SET);
1171     }
1172
1173     put_flush_packet(pb);
1174 }
1175
1176 static const UID mxf_mpeg2_codec_uls[] = {
1177     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
1178     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
1179     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
1180     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
1181     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
1182     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
1183     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
1184     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
1185 };
1186
1187 static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
1188 {
1189     if (avctx->profile == 4) { // Main
1190         if (avctx->level == 8) // Main
1191             return avctx->gop_size ?
1192                 &mxf_mpeg2_codec_uls[1] :
1193                 &mxf_mpeg2_codec_uls[0];
1194         else if (avctx->level == 4) // High
1195             return avctx->gop_size ?
1196                 &mxf_mpeg2_codec_uls[5] :
1197                 &mxf_mpeg2_codec_uls[4];
1198     } else if (avctx->profile == 0) { // 422
1199         if (avctx->level == 5) // Main
1200             return avctx->gop_size ?
1201                 &mxf_mpeg2_codec_uls[3] :
1202                 &mxf_mpeg2_codec_uls[2];
1203         else if (avctx->level == 2) // High
1204             return avctx->gop_size ?
1205                 &mxf_mpeg2_codec_uls[7] :
1206                 &mxf_mpeg2_codec_uls[6];
1207     }
1208     return NULL;
1209 }
1210
1211 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt, int *flags)
1212 {
1213     MXFStreamContext *sc = st->priv_data;
1214     MXFContext *mxf = s->priv_data;
1215     uint32_t c = -1;
1216     int i;
1217
1218     *flags = 0;
1219
1220     for(i = 0; i < pkt->size - 4; i++) {
1221         c = (c<<8) + pkt->data[i];
1222         if (c == 0x1B5) {
1223             if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1224                 st->codec->profile = pkt->data[i+1] & 0x07;
1225                 st->codec->level   = pkt->data[i+2] >> 4;
1226             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1227                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1228                 break;
1229             }
1230         } else if (c == 0x1b8) { // gop
1231             if (i + 4 < pkt->size) {
1232                 if (pkt->data[i+4]>>6 & 0x01) // closed
1233                     *flags |= 0x80; // random access
1234                 if (!mxf->header_written) {
1235                     unsigned hours   =  (pkt->data[i+1]>>2) & 0x1f;
1236                     unsigned minutes = ((pkt->data[i+1] & 0x03) << 4) | (pkt->data[i+2]>>4);
1237                     unsigned seconds = ((pkt->data[i+2] & 0x07) << 3) | (pkt->data[i+3]>>5);
1238                     unsigned frames  = ((pkt->data[i+3] & 0x1f) << 1) | (pkt->data[i+4]>>7);
1239                     mxf->timecode_drop_frame = !!(pkt->data[i+1] & 0x80);
1240                     mxf->timecode_start = (hours*3600 + minutes*60 + seconds) *
1241                         mxf->timecode_base + frames;
1242                     if (mxf->timecode_drop_frame) {
1243                         unsigned tminutes = 60 * hours + minutes;
1244                         mxf->timecode_start -= 2 * (tminutes - tminutes / 10);
1245                     }
1246                     av_log(s, AV_LOG_DEBUG, "frame %d %d:%d:%d%c%d\n", mxf->timecode_start,
1247                            hours, minutes, seconds, mxf->timecode_drop_frame ? ';':':', frames);
1248                 }
1249             }
1250         } else if (c == 0x1b3) { // seq
1251             *flags |= 0x40;
1252         } else if (c == 0x100) { // pic
1253             int pict_type = (pkt->data[i+2]>>3) & 0x07;
1254             if (pict_type == 2) { // P frame
1255                 *flags |= 0x22;
1256                 st->codec->gop_size = 1;
1257             } else if (pict_type == 3) { // B frame
1258                 *flags |= 0x33;
1259                 sc->temporal_reordering = -1;
1260             } else if (!pict_type) {
1261                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1262                 return 0;
1263             }
1264         }
1265     }
1266     sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1267     return !!sc->codec_ul;
1268 }
1269
1270 static uint64_t mxf_parse_timestamp(time_t timestamp)
1271 {
1272     struct tm *time = localtime(&timestamp);
1273     return (uint64_t)(time->tm_year+1900) << 48 |
1274            (uint64_t)(time->tm_mon+1)     << 40 |
1275            (uint64_t) time->tm_mday       << 32 |
1276                       time->tm_hour       << 24 |
1277                       time->tm_min        << 16 |
1278                       time->tm_sec        << 8;
1279 }
1280
1281 static int mxf_write_header(AVFormatContext *s)
1282 {
1283     MXFContext *mxf = s->priv_data;
1284     int i;
1285     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
1286     const int *samples_per_frame = NULL;
1287
1288     for (i = 0; i < s->nb_streams; i++) {
1289         AVStream *st = s->streams[i];
1290         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
1291         if (!sc)
1292             return AVERROR(ENOMEM);
1293         st->priv_data = sc;
1294
1295         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1296             if (i != 0) {
1297                 av_log(s, AV_LOG_ERROR, "video stream must be first track\n");
1298                 return -1;
1299             }
1300             if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1301                 samples_per_frame = PAL_samples_per_frame;
1302                 mxf->time_base = (AVRational){ 1, 25 };
1303                 mxf->timecode_base = 25;
1304             } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1305                 samples_per_frame = NTSC_samples_per_frame;
1306                 mxf->time_base = (AVRational){ 1001, 30000 };
1307                 mxf->timecode_base = 30;
1308             } else {
1309                 av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1310                 return -1;
1311             }
1312             av_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
1313         } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1314             if (st->codec->sample_rate != 48000) {
1315                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1316                 return -1;
1317             }
1318             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1319             mxf->slice_count = 1;
1320         }
1321
1322         sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
1323         if (sc->index == -1) {
1324             av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
1325                    "codec not currently supported in container\n", i);
1326             return -1;
1327         }
1328
1329         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1330
1331         if (!present[sc->index]) {
1332             mxf->essence_containers_indices[mxf->essence_container_count++] = sc->index;
1333             present[sc->index] = 1;
1334         } else
1335             present[sc->index]++;
1336         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
1337         sc->track_essence_element_key[15] = present[sc->index];
1338         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
1339     }
1340
1341     for (i = 0; i < s->nb_streams; i++) {
1342         MXFStreamContext *sc = s->streams[i]->priv_data;
1343         // update element count
1344         sc->track_essence_element_key[13] = present[sc->index];
1345         sc->order = AV_RB32(sc->track_essence_element_key+12);
1346     }
1347
1348     mxf->timestamp = mxf_parse_timestamp(s->timestamp);
1349     mxf->duration = -1;
1350
1351     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
1352     if (!mxf->timecode_track)
1353         return AVERROR(ENOMEM);
1354     mxf->timecode_track->priv_data = av_mallocz(sizeof(MXFStreamContext));
1355     if (!mxf->timecode_track->priv_data)
1356         return AVERROR(ENOMEM);
1357     mxf->timecode_track->index = s->nb_streams;
1358
1359     if (!samples_per_frame)
1360         samples_per_frame = PAL_samples_per_frame;
1361
1362     if (ff_audio_interleave_init(s, samples_per_frame, mxf->time_base) < 0)
1363         return -1;
1364
1365     return 0;
1366 }
1367
1368 static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
1369 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 };
1370
1371 static uint32_t ff_framenum_to_12m_time_code(unsigned frame, int drop, int fps)
1372 {
1373     return (0                                    << 31) | // color frame flag
1374            (0                                    << 30) | // drop  frame flag
1375            ( ((frame % fps) / 10)                << 28) | // tens  of frames
1376            ( ((frame % fps) % 10)                << 24) | // units of frames
1377            (0                                    << 23) | // field phase (NTSC), b0 (PAL)
1378            ((((frame / fps) % 60) / 10)          << 20) | // tens  of seconds
1379            ((((frame / fps) % 60) % 10)          << 16) | // units of seconds
1380            (0                                    << 15) | // b0 (NTSC), b2 (PAL)
1381            ((((frame / (fps * 60)) % 60) / 10)   << 12) | // tens  of minutes
1382            ((((frame / (fps * 60)) % 60) % 10)   <<  8) | // units of minutes
1383            (0                                    <<  7) | // b1
1384            (0                                    <<  6) | // b2 (NSC), field phase (PAL)
1385            ((((frame / (fps * 3600) % 24)) / 10) <<  4) | // tens  of hours
1386            (  (frame / (fps * 3600) % 24)) % 10;          // units of hours
1387 }
1388
1389 static void mxf_write_system_item(AVFormatContext *s)
1390 {
1391     MXFContext *mxf = s->priv_data;
1392     ByteIOContext *pb = s->pb;
1393     unsigned frame;
1394     uint32_t time_code;
1395
1396     frame = mxf->timecode_start + mxf->last_indexed_edit_unit + mxf->edit_units_count;
1397
1398     // write system metadata pack
1399     put_buffer(pb, system_metadata_pack_key, 16);
1400     klv_encode_ber_length(pb, 57);
1401     put_byte(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
1402     put_byte(pb, 0x04); // content package rate
1403     put_byte(pb, 0x00); // content package type
1404     put_be16(pb, 0x00); // channel handle
1405     put_be16(pb, frame); // continuity count
1406     if (mxf->essence_container_count > 1)
1407         put_buffer(pb, multiple_desc_ul, 16);
1408     else
1409         put_buffer(pb, mxf_essence_container_uls[mxf->essence_containers_indices[0]].container_ul, 16);
1410     put_byte(pb, 0);
1411     put_be64(pb, 0);
1412     put_be64(pb, 0); // creation date/time stamp
1413
1414     put_byte(pb, 0x81); // SMPTE 12M time code
1415     time_code = ff_framenum_to_12m_time_code(frame, mxf->timecode_drop_frame, mxf->timecode_base);
1416     put_be32(pb, time_code);
1417     put_be32(pb, 0); // binary group data
1418     put_be64(pb, 0);
1419
1420     // write system metadata package set
1421     put_buffer(pb, system_metadata_package_set_key, 16);
1422     klv_encode_ber_length(pb, 35);
1423     put_byte(pb, 0x83); // UMID
1424     put_be16(pb, 0x20);
1425     mxf_write_umid(pb, SourcePackage, 0);
1426 }
1427
1428 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1429 {
1430     MXFContext *mxf = s->priv_data;
1431     ByteIOContext *pb = s->pb;
1432     AVStream *st = s->streams[pkt->stream_index];
1433     MXFStreamContext *sc = st->priv_data;
1434     int flags = 0;
1435
1436     if (!(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
1437         mxf->index_entries = av_realloc(mxf->index_entries,
1438             (mxf->edit_units_count + EDIT_UNITS_PER_BODY)*sizeof(*mxf->index_entries));
1439         if (!mxf->index_entries) {
1440             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1441             return -1;
1442         }
1443     }
1444
1445     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1446         if (!mxf_parse_mpeg2_frame(s, st, pkt, &flags)) {
1447             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1448             return -1;
1449         }
1450     }
1451
1452     if (!mxf->header_written) {
1453         mxf_write_partition(s, 0, 0, header_open_partition_key, 1);
1454         mxf->header_written = 1;
1455     }
1456
1457     if (st->index == 0) {
1458         if ((!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
1459             !(flags & 0x33)) { // I frame, Gop start
1460             mxf_write_klv_fill(s);
1461             mxf_write_partition(s, 1, 2, body_partition_key, 0);
1462
1463             mxf_write_klv_fill(s);
1464             mxf_write_index_table_segment(s);
1465         }
1466
1467         mxf_write_klv_fill(s);
1468         mxf->index_entries[mxf->edit_units_count].offset = url_ftell(pb);
1469         mxf->index_entries[mxf->edit_units_count].flags = flags;
1470         if (!mxf->first_edit_unit_offset)
1471             mxf->first_edit_unit_offset = mxf->index_entries[0].offset;
1472         mxf_write_system_item(s);
1473
1474         mxf->edit_units_count++;
1475     } else if (st->index == 1) {
1476         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
1477             url_ftell(pb) - mxf->index_entries[mxf->edit_units_count-1].offset;
1478     }
1479
1480     mxf_write_klv_fill(s);
1481     put_buffer(pb, sc->track_essence_element_key, 16); // write key
1482     klv_encode_ber_length(pb, pkt->size); // write length
1483     put_buffer(pb, pkt->data, pkt->size); // write value
1484
1485     put_flush_packet(pb);
1486     return 0;
1487 }
1488
1489 static void mxf_write_random_index_pack(AVFormatContext *s)
1490 {
1491     MXFContext *mxf = s->priv_data;
1492     ByteIOContext *pb = s->pb;
1493     uint64_t pos = url_ftell(pb);
1494     int i;
1495
1496     put_buffer(pb, random_index_pack_key, 16);
1497     klv_encode_ber_length(pb, 28 + 12*mxf->body_partitions_count);
1498
1499     put_be32(pb, 0); // BodySID of header partition
1500     put_be64(pb, 0); // offset of header partition
1501
1502     for (i = 0; i < mxf->body_partitions_count; i++) {
1503         put_be32(pb, 1); // BodySID
1504         put_be64(pb, mxf->body_partition_offset[i]);
1505     }
1506
1507     put_be32(pb, 0); // BodySID of footer partition
1508     put_be64(pb, mxf->footer_partition_offset);
1509
1510     put_be32(pb, url_ftell(pb) - pos + 4);
1511 }
1512
1513 static int mxf_write_footer(AVFormatContext *s)
1514 {
1515     MXFContext *mxf = s->priv_data;
1516     ByteIOContext *pb = s->pb;
1517
1518     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
1519
1520     mxf_write_klv_fill(s);
1521     mxf->footer_partition_offset = url_ftell(pb);
1522     mxf_write_partition(s, 0, 2, footer_partition_key, 0);
1523
1524     mxf_write_klv_fill(s);
1525     mxf_write_index_table_segment(s);
1526
1527     mxf_write_klv_fill(s);
1528     mxf_write_random_index_pack(s);
1529
1530     if (!url_is_streamed(s->pb)) {
1531         url_fseek(pb, 0, SEEK_SET);
1532         mxf_write_partition(s, 0, 0, header_closed_partition_key, 1);
1533     }
1534
1535     ff_audio_interleave_close(s);
1536
1537     av_freep(&mxf->index_entries);
1538     av_freep(&mxf->body_partition_offset);
1539     av_freep(&mxf->timecode_track->priv_data);
1540     av_freep(&mxf->timecode_track);
1541
1542     mxf_free(s);
1543     return 0;
1544 }
1545
1546 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1547 {
1548     AVPacketList *pktl;
1549     int stream_count = 0;
1550     int streams[MAX_STREAMS];
1551
1552     memset(streams, 0, sizeof(streams));
1553     pktl = s->packet_buffer;
1554     while (pktl) {
1555         //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
1556         if (!streams[pktl->pkt.stream_index])
1557             stream_count++;
1558         streams[pktl->pkt.stream_index]++;
1559         pktl = pktl->next;
1560     }
1561
1562     if (stream_count && (s->nb_streams == stream_count || flush)) {
1563         pktl = s->packet_buffer;
1564         if (s->nb_streams != stream_count) {
1565             AVPacketList *first = NULL;
1566             AVPacketList *last = NULL;
1567             // find first packet in edit unit
1568             while (pktl) {
1569                 AVStream *st = s->streams[pktl->pkt.stream_index];
1570                 if (st->index == 0)
1571                     break;
1572                 else if (!first)
1573                     first = pktl;
1574                 last = pktl;
1575                 pktl = pktl->next;
1576             }
1577             if (last)
1578                 last->next = NULL;
1579             // purge packet queue
1580             while (pktl) {
1581                 AVPacketList *next = pktl->next;
1582                 av_free_packet(&pktl->pkt);
1583                 av_freep(&pktl);
1584                 pktl = next;
1585             }
1586             if (!first)
1587                 goto out;
1588             pktl = first;
1589         }
1590
1591         *out = pktl->pkt;
1592         //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1593         s->packet_buffer = pktl->next;
1594         av_freep(&pktl);
1595         return 1;
1596     } else {
1597     out:
1598         av_init_packet(out);
1599         return 0;
1600     }
1601 }
1602
1603 static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1604 {
1605     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
1606     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
1607
1608     return next->dts > pkt->dts ||
1609         (next->dts == pkt->dts && sc->order < sc2->order);
1610 }
1611
1612 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1613 {
1614     return ff_audio_rechunk_interleave(s, out, pkt, flush,
1615                                mxf_interleave_get_packet, mxf_compare_timestamps);
1616 }
1617
1618 AVOutputFormat mxf_muxer = {
1619     "mxf",
1620     NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1621     NULL,
1622     "mxf",
1623     sizeof(MXFContext),
1624     CODEC_ID_PCM_S16LE,
1625     CODEC_ID_MPEG2VIDEO,
1626     mxf_write_header,
1627     mxf_write_packet,
1628     mxf_write_footer,
1629     AVFMT_NOTIMESTAMPS,
1630     NULL,
1631     mxf_interleave,
1632 };