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