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