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