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