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