Statistics
| Branch: | Revision:

ffmpeg / libavformat / mxfenc.c @ 52e5cd2b

History | View | Annotate | Download (38.6 KB)

1
/*
2
 * MXF muxer
3
 * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
/*
23
 * References
24
 * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
25
 * SMPTE 377M MXF File Format Specifications
26
 * SMPTE 379M MXF Generic Container
27
 * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
28
 * SMPTE RP210: SMPTE Metadata Dictionary
29
 * SMPTE RP224: Registry of SMPTE Universal Labels
30
 */
31

    
32
//#define DEBUG
33

    
34
#include "libavutil/fifo.h"
35
#include "mxf.h"
36

    
37
static const int NTSC_samples_per_frame[] = { 1602, 1601, 1602, 1601, 1602, 0 };
38
static const int PAL_samples_per_frame[]  = { 1920, 0 };
39

    
40
typedef struct {
41
    AVFifoBuffer fifo;
42
    unsigned fifo_size; ///< current fifo size allocated
43
    uint64_t dts; ///< current dts
44
    int sample_size; ///< size of one sample all channels included
45
    const int *samples_per_frame; ///< must be 0 terminated
46
    const int *samples; ///< current samples per frame, pointer to samples_per_frame
47
} AudioInterleaveContext;
48

    
49
typedef struct {
50
    int local_tag;
51
    UID uid;
52
} MXFLocalTagPair;
53

    
54
typedef struct {
55
    AudioInterleaveContext aic;
56
    UID track_essence_element_key;
57
    int index; //<<< index in mxf_essence_container_uls table
58
    const UID *codec_ul;
59
    int64_t duration;
60
    int order; ///< interleaving order if dts are equal
61
    int interlaced; ///< wether picture is interlaced
62
} MXFStreamContext;
63

    
64
typedef struct {
65
    UID container_ul;
66
    UID element_ul;
67
    UID codec_ul;
68
    enum CodecID id;
69
    void (*write_desc)();
70
} MXFContainerEssenceEntry;
71

    
72
static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
73
static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
74

    
75
static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
76
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
77
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
78
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
79
      CODEC_ID_MPEG2VIDEO, mxf_write_mpegvideo_desc },
80
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
81
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
82
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
83
      CODEC_ID_PCM_S16LE, mxf_write_wav_desc },
84
    { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
85
      { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
86
      { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
87
      CODEC_ID_NONE, NULL },
88
};
89

    
90
typedef struct MXFContext {
91
    int64_t footer_partition_offset;
92
    int essence_container_count;
93
    uint8_t essence_containers_indices[FF_ARRAY_ELEMS(mxf_essence_container_uls)];
94
    AVRational time_base;
95
    int header_written;
96
} MXFContext;
97

    
98
static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
99
static const uint8_t umid_base[]            = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13,0x00,0x00,0x00 };
100

    
101
/**
102
 * complete key for operation pattern, partitions, and primer pack
103
 */
104
static const uint8_t op1a_ul[]              = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x01,0x00 };
105
static const uint8_t footer_partition_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
106
static const uint8_t primer_pack_key[]      = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
107

    
108

    
109
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
110
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
111

    
112
/**
113
 * partial key for header metadata
114
 */
115
static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
116

    
117
static const uint8_t multiple_desc_ul[] = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
118

    
119
/**
120
 * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
121
 */
122
static const MXFLocalTagPair mxf_local_tag_batch[] = {
123
    // preface set
124
    { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
125
    { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
126
    { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
127
    { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
128
    { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
129
    { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
130
    { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
131
    { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
132
    // Identification
133
    { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
134
    { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
135
    { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
136
    { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
137
    { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
138
    { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
139
    // Content Storage
140
    { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
141
    { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
142
    // Essence Container Data
143
    { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
144
    { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
145
    // Package
146
    { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
147
    { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
148
    { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
149
    { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
150
    { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
151
    // Track
152
    { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
153
    { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
154
    { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
155
    { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
156
    { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
157
    // Sequence
158
    { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
159
    { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
160
    { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
161
    // Source Clip
162
    { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
163
    { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
164
    { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
165
    // File Descriptor
166
    { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
167
    { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
168
    { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
169
    { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
170
    // Generic Picture Essence Descriptor
171
    { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
172
    { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
173
    { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
174
    { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
175
    // Generic Sound Essence Descriptor
176
    { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
177
    { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
178
    { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
179
    { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
180
};
181

    
182
static void mxf_write_uuid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
183
{
184
    put_buffer(pb, uuid_base, 12);
185
    put_be16(pb, type);
186
    put_be16(pb, value);
187
}
188

    
189
static void mxf_write_umid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
190
{
191
    put_buffer(pb, umid_base, 16);
192
    mxf_write_uuid(pb, type, value);
193
}
194

    
195
static void mxf_write_refs_count(ByteIOContext *pb, int ref_count)
196
{
197
    put_be32(pb, ref_count);
198
    put_be32(pb, 16);
199
}
200

    
201
static int klv_encode_ber_length(ByteIOContext *pb, uint64_t len)
202
{
203
    // Determine the best BER size
204
    int size;
205
    if (len < 128) {
206
        //short form
207
        put_byte(pb, len);
208
        return 1;
209
    }
210

    
211
    size = (av_log2(len) >> 3) + 1;
212

    
213
    // long form
214
    put_byte(pb, 0x80 + size);
215
    while(size) {
216
        size --;
217
        put_byte(pb, len >> 8 * size & 0xff);
218
    }
219
    return 0;
220
}
221

    
222
/*
223
 * Get essence container ul index
224
 */
225
static int mxf_get_essence_container_ul_index(enum CodecID id)
226
{
227
    int i;
228
    for (i = 0; i < FF_ARRAY_ELEMS(mxf_essence_container_uls); i++)
229
        if (mxf_essence_container_uls[i].id == id)
230
            return i;
231
    return -1;
232
}
233

    
234
static void mxf_write_primer_pack(AVFormatContext *s)
235
{
236
    ByteIOContext *pb = s->pb;
237
    int local_tag_number, i = 0;
238

    
239
    local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
240

    
241
    put_buffer(pb, primer_pack_key, 16);
242
    klv_encode_ber_length(pb, local_tag_number * 18 + 8);
243

    
244
    put_be32(pb, local_tag_number); // local_tag num
245
    put_be32(pb, 18); // item size, always 18 according to the specs
246

    
247
    for (i = 0; i < local_tag_number; i++) {
248
        put_be16(pb, mxf_local_tag_batch[i].local_tag);
249
        put_buffer(pb, mxf_local_tag_batch[i].uid, 16);
250
    }
251
}
252

    
253
static void mxf_write_local_tag(ByteIOContext *pb, int size, int tag)
254
{
255
    put_be16(pb, tag);
256
    put_be16(pb, size);
257
}
258

    
259
static void mxf_write_metadata_key(ByteIOContext *pb, unsigned int value)
260
{
261
    put_buffer(pb, header_metadata_key, 13);
262
    put_be24(pb, value);
263
}
264

    
265
static void mxf_free(AVFormatContext *s)
266
{
267
    int i;
268

    
269
    for (i = 0; i < s->nb_streams; i++) {
270
        AVStream *st = s->streams[i];
271
        av_freep(&st->priv_data);
272
    }
273
}
274

    
275
static const MXFDataDefinitionUL *mxf_get_data_definition_ul(enum CodecType type)
276
{
277
    const MXFDataDefinitionUL *uls = ff_mxf_data_definition_uls;
278
    while (uls->type != CODEC_TYPE_DATA) {
279
        if (type == uls->type)
280
            break;
281
        uls++;
282
    }
283
    return uls;
284
}
285

    
286
static void mxf_write_essence_container_refs(AVFormatContext *s)
287
{
288
    MXFContext *c = s->priv_data;
289
    ByteIOContext *pb = s->pb;
290
    int i;
291

    
292
    mxf_write_refs_count(pb, c->essence_container_count);
293
    av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
294
    for (i = 0; i < c->essence_container_count; i++) {
295
        put_buffer(pb, mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul, 16);
296
        PRINT_KEY(s, "essence container ul:\n", mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul);
297
    }
298
}
299

    
300
static void mxf_write_preface(AVFormatContext *s)
301
{
302
    MXFContext *mxf = s->priv_data;
303
    ByteIOContext *pb = s->pb;
304

    
305
    mxf_write_metadata_key(pb, 0x012f00);
306
    PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
307
    klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
308

    
309
    // write preface set uid
310
    mxf_write_local_tag(pb, 16, 0x3C0A);
311
    mxf_write_uuid(pb, Preface, 0);
312
    PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
313

    
314
    // write create date as unknown
315
    mxf_write_local_tag(pb, 8, 0x3B02);
316
    put_be64(pb, 0);
317

    
318
    // write version
319
    mxf_write_local_tag(pb, 2, 0x3B05);
320
    put_be16(pb, 1);
321

    
322
    // write identification_refs
323
    mxf_write_local_tag(pb, 16 + 8, 0x3B06);
324
    mxf_write_refs_count(pb, 1);
325
    mxf_write_uuid(pb, Identification, 0);
326

    
327
    // write content_storage_refs
328
    mxf_write_local_tag(pb, 16, 0x3B03);
329
    mxf_write_uuid(pb, ContentStorage, 0);
330

    
331
    mxf_write_local_tag(pb, 16, 0x3B09);
332
    put_buffer(pb, op1a_ul, 16);
333

    
334
    // write essence_container_refs
335
    mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
336
    mxf_write_essence_container_refs(s);
337

    
338
    // write dm_scheme_refs
339
    mxf_write_local_tag(pb, 8, 0x3B0B);
340
    put_be64(pb, 0);
341
}
342

    
343
/*
344
 * Write a local tag containing an ascii string as utf-16
345
 */
346
static void mxf_write_local_tag_utf16(ByteIOContext *pb, int tag, const char *value)
347
{
348
    int i, size = strlen(value);
349
    mxf_write_local_tag(pb, size*2, tag);
350
    for (i = 0; i < size; i++)
351
        put_be16(pb, value[i]);
352
}
353

    
354
static void mxf_write_identification(AVFormatContext *s)
355
{
356
    ByteIOContext *pb = s->pb;
357
    const char *company = "FFmpeg";
358
    const char *product = "OP1a Muxer";
359
    const char *version;
360
    int length;
361

    
362
    mxf_write_metadata_key(pb, 0x013000);
363
    PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
364

    
365
    version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?
366
        "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
367
    length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
368
    klv_encode_ber_length(pb, length);
369

    
370
    // write uid
371
    mxf_write_local_tag(pb, 16, 0x3C0A);
372
    mxf_write_uuid(pb, Identification, 0);
373
    PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
374

    
375
    // write generation uid
376
    mxf_write_local_tag(pb, 16, 0x3C09);
377
    mxf_write_uuid(pb, Identification, 1);
378

    
379
    mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
380
    mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
381
    mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
382

    
383
    // write product uid
384
    mxf_write_local_tag(pb, 16, 0x3C05);
385
    mxf_write_uuid(pb, Identification, 2);
386

    
387
    // write modified date
388
    mxf_write_local_tag(pb, 8, 0x3C06);
389
    put_be64(pb, 0);
390
}
391

    
392
static void mxf_write_content_storage(AVFormatContext *s)
393
{
394
    ByteIOContext *pb = s->pb;
395

    
396
    mxf_write_metadata_key(pb, 0x011800);
397
    PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
398
    klv_encode_ber_length(pb, 92);
399

    
400
    // write uid
401
    mxf_write_local_tag(pb, 16, 0x3C0A);
402
    mxf_write_uuid(pb, ContentStorage, 0);
403
    PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
404

    
405
    // write package reference
406
    mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
407
    mxf_write_refs_count(pb, 2);
408
    mxf_write_uuid(pb, MaterialPackage, 0);
409
    mxf_write_uuid(pb, SourcePackage, 0);
410

    
411
    // write essence container data
412
    mxf_write_local_tag(pb, 8 + 16, 0x1902);
413
    mxf_write_refs_count(pb, 1);
414
    mxf_write_uuid(pb, EssenceContainerData, 0);
415
}
416

    
417
static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
418
{
419
    ByteIOContext *pb = s->pb;
420
    MXFStreamContext *sc = st->priv_data;
421

    
422
    mxf_write_metadata_key(pb, 0x013b00);
423
    PRINT_KEY(s, "track key", pb->buf_ptr - 16);
424
    klv_encode_ber_length(pb, 80);
425

    
426
    // write track uid
427
    mxf_write_local_tag(pb, 16, 0x3C0A);
428
    mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
429
    PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
430

    
431
    // write track id
432
    mxf_write_local_tag(pb, 4, 0x4801);
433
    put_be32(pb, st->index);
434

    
435
    // write track number
436
    mxf_write_local_tag(pb, 4, 0x4804);
437
    if (type == MaterialPackage)
438
        put_be32(pb, 0); // track number of material package is 0
439
    else
440
        put_buffer(pb, sc->track_essence_element_key + 12, 4);
441

    
442
    mxf_write_local_tag(pb, 8, 0x4B01);
443
    put_be32(pb, st->time_base.den);
444
    put_be32(pb, st->time_base.num);
445

    
446
    // write origin
447
    mxf_write_local_tag(pb, 8, 0x4B02);
448
    put_be64(pb, 0);
449

    
450
    // write sequence refs
451
    mxf_write_local_tag(pb, 16, 0x4803);
452
    mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
453
}
454

    
455
static void mxf_write_common_fields(ByteIOContext *pb, AVStream *st)
456
{
457
    const MXFDataDefinitionUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
458
    MXFStreamContext *sc = st->priv_data;
459

    
460
    // find data define uls
461
    mxf_write_local_tag(pb, 16, 0x0201);
462
    put_buffer(pb, data_def_ul->uid, 16);
463

    
464
    // write duration
465
    mxf_write_local_tag(pb, 8, 0x0202);
466
    put_be64(pb, sc->duration);
467
}
468

    
469
static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
470
{
471
    ByteIOContext *pb = s->pb;
472

    
473
    mxf_write_metadata_key(pb, 0x010f00);
474
    PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
475
    klv_encode_ber_length(pb, 80);
476

    
477
    mxf_write_local_tag(pb, 16, 0x3C0A);
478
    mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
479

    
480
    PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
481
    mxf_write_common_fields(pb, st);
482

    
483
    // write structural component
484
    mxf_write_local_tag(pb, 16 + 8, 0x1001);
485
    mxf_write_refs_count(pb, 1);
486
    mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
487
}
488

    
489
static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
490
{
491
    ByteIOContext *pb = s->pb;
492
    int i;
493

    
494
    mxf_write_metadata_key(pb, 0x011100);
495
    PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
496
    klv_encode_ber_length(pb, 108);
497

    
498
    // write uid
499
    mxf_write_local_tag(pb, 16, 0x3C0A);
500
    mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
501

    
502
    PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
503
    mxf_write_common_fields(pb, st);
504

    
505
    // write start_position
506
    mxf_write_local_tag(pb, 8, 0x1201);
507
    put_be64(pb, 0);
508

    
509
    // write source package uid, end of the reference
510
    mxf_write_local_tag(pb, 32, 0x1101);
511
    if (type == SourcePackage) {
512
        for (i = 0; i < 4; i++)
513
            put_be64(pb, 0);
514
    } else
515
        mxf_write_umid(pb, SourcePackage, 0);
516

    
517
    // write source track id
518
    mxf_write_local_tag(pb, 4, 0x1102);
519
    if (type == SourcePackage)
520
        put_be32(pb, 0);
521
    else
522
        put_be32(pb, st->index);
523
}
524

    
525
static void mxf_write_multi_descriptor(AVFormatContext *s)
526
{
527
    ByteIOContext *pb = s->pb;
528
    int i;
529

    
530
    mxf_write_metadata_key(pb, 0x014400);
531
    PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
532
    klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
533

    
534
    mxf_write_local_tag(pb, 16, 0x3C0A);
535
    mxf_write_uuid(pb, MultipleDescriptor, 0);
536
    PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
537

    
538
    // write sample rate
539
    mxf_write_local_tag(pb, 8, 0x3001);
540
    put_be32(pb, s->streams[0]->time_base.den);
541
    put_be32(pb, s->streams[0]->time_base.num);
542

    
543
    // write essence container ul
544
    mxf_write_local_tag(pb, 16, 0x3004);
545
    put_buffer(pb, multiple_desc_ul, 16);
546

    
547
    // write sub descriptor refs
548
    mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
549
    mxf_write_refs_count(pb, s->nb_streams);
550
    for (i = 0; i < s->nb_streams; i++)
551
        mxf_write_uuid(pb, SubDescriptor, i);
552
}
553

    
554
static void mxf_write_generic_desc(ByteIOContext *pb, AVStream *st, const UID key)
555
{
556
    MXFStreamContext *sc = st->priv_data;
557

    
558
    put_buffer(pb, key, 16);
559
    klv_encode_ber_length(pb, 108);
560

    
561
    mxf_write_local_tag(pb, 16, 0x3C0A);
562
    mxf_write_uuid(pb, SubDescriptor, st->index);
563

    
564
    mxf_write_local_tag(pb, 4, 0x3006);
565
    put_be32(pb, st->index);
566

    
567
    mxf_write_local_tag(pb, 8, 0x3001);
568
    put_be32(pb, st->time_base.den);
569
    put_be32(pb, st->time_base.num);
570

    
571
    mxf_write_local_tag(pb, 16, 0x3004);
572
    put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
573

    
574
    mxf_write_local_tag(pb, 16, 0x3201);
575
    put_buffer(pb, *sc->codec_ul, 16);
576
}
577

    
578
static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
579
static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
580

    
581
static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
582
{
583
    ByteIOContext *pb = s->pb;
584
    int stored_height = (st->codec->height+15)/16*16;
585
    AVRational dar;
586

    
587
    mxf_write_generic_desc(pb, st, mxf_mpegvideo_descriptor_key);
588

    
589
    mxf_write_local_tag(pb, 4, 0x3203);
590
    put_be32(pb, st->codec->width);
591

    
592
    mxf_write_local_tag(pb, 4, 0x3202);
593
    put_be32(pb, stored_height);
594

    
595
    av_reduce(&dar.num, &dar.den,
596
              st->codec->width*st->codec->sample_aspect_ratio.num,
597
              st->codec->height*st->codec->sample_aspect_ratio.den,
598
              1024*1024);
599

    
600
    mxf_write_local_tag(pb, 8, 0x320E);
601
    put_be32(pb, dar.num);
602
    put_be32(pb, dar.den);
603
}
604

    
605
static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
606
{
607
    ByteIOContext *pb = s->pb;
608

    
609
    mxf_write_generic_desc(pb, st, mxf_wav_descriptor_key);
610

    
611
    // write audio sampling rate
612
    mxf_write_local_tag(pb, 8, 0x3D03);
613
    put_be32(pb, st->codec->sample_rate);
614
    put_be32(pb, 1);
615

    
616
    mxf_write_local_tag(pb, 4, 0x3D07);
617
    put_be32(pb, st->codec->channels);
618

    
619
    mxf_write_local_tag(pb, 4, 0x3D01);
620
    put_be32(pb, st->codec->bits_per_coded_sample);
621
}
622

    
623
static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
624
{
625
    ByteIOContext *pb = s->pb;
626
    int i;
627

    
628
    if (type == MaterialPackage) {
629
        mxf_write_metadata_key(pb, 0x013600);
630
        PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
631
        klv_encode_ber_length(pb, 92 + 16 * s->nb_streams);
632
    } else {
633
        mxf_write_metadata_key(pb, 0x013700);
634
        PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
635
        klv_encode_ber_length(pb, 112 + 16 * s->nb_streams); // 20 bytes length for descriptor reference
636
    }
637

    
638
    // write uid
639
    mxf_write_local_tag(pb, 16, 0x3C0A);
640
    mxf_write_uuid(pb, type, 0);
641
    av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
642
    PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
643

    
644
    // write package umid
645
    mxf_write_local_tag(pb, 32, 0x4401);
646
    mxf_write_umid(pb, type, 0);
647
    PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
648

    
649
    // write create date
650
    mxf_write_local_tag(pb, 8, 0x4405);
651
    put_be64(pb, 0);
652

    
653
    // write modified date
654
    mxf_write_local_tag(pb, 8, 0x4404);
655
    put_be64(pb, 0);
656

    
657
    // write track refs
658
    mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x4403);
659
    mxf_write_refs_count(pb, s->nb_streams);
660
    for (i = 0; i < s->nb_streams; i++)
661
        mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
662

    
663
    // write multiple descriptor reference
664
    if (type == SourcePackage) {
665
        mxf_write_local_tag(pb, 16, 0x4701);
666
        if (s->nb_streams > 1) {
667
            mxf_write_uuid(pb, MultipleDescriptor, 0);
668
            mxf_write_multi_descriptor(s);
669
        } else
670
            mxf_write_uuid(pb, SubDescriptor, 0);
671
    }
672

    
673
    for (i = 0; i < s->nb_streams; i++) {
674
        AVStream *st = s->streams[i];
675
        mxf_write_track(s, st, type);
676
        mxf_write_sequence(s, st, type);
677
        mxf_write_structural_component(s, st, type);
678

    
679
        if (type == SourcePackage) {
680
            MXFStreamContext *sc = st->priv_data;
681
            mxf_essence_container_uls[sc->index].write_desc(s, st);
682
        }
683
    }
684
}
685

    
686
static int mxf_write_essence_container_data(AVFormatContext *s)
687
{
688
    ByteIOContext *pb = s->pb;
689

    
690
    mxf_write_metadata_key(pb, 0x012300);
691
    klv_encode_ber_length(pb, 64);
692

    
693
    mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
694
    mxf_write_uuid(pb, EssenceContainerData, 0);
695

    
696
    mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
697
    mxf_write_umid(pb, SourcePackage, 0);
698

    
699
    mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
700
    put_be32(pb, 1);
701

    
702
    return 0;
703
}
704

    
705
static int mxf_write_header_metadata_sets(AVFormatContext *s)
706
{
707
    mxf_write_preface(s);
708
    mxf_write_identification(s);
709
    mxf_write_content_storage(s);
710
    mxf_write_package(s, MaterialPackage);
711
    mxf_write_package(s, SourcePackage);
712
    mxf_write_essence_container_data(s);
713
    return 0;
714
}
715

    
716
static void mxf_write_partition(AVFormatContext *s, int bodysid, const uint8_t *key, int write_metadata)
717
{
718
    MXFContext *mxf = s->priv_data;
719
    ByteIOContext *pb = s->pb;
720
    int64_t header_byte_count_offset;
721

    
722
    // write klv
723
    put_buffer(pb, key, 16);
724

    
725
    klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
726

    
727
    // write partition value
728
    put_be16(pb, 1); // majorVersion
729
    put_be16(pb, 2); // minorVersion
730
    put_be32(pb, 1); // kagSize
731

    
732
    put_be64(pb, url_ftell(pb) - 25); // thisPartition
733
    put_be64(pb, 0); // previousPartition
734

    
735
    put_be64(pb, mxf->footer_partition_offset); // footerPartition
736

    
737
    // set offset
738
    header_byte_count_offset = url_ftell(pb);
739
    put_be64(pb, 0); // headerByteCount, update later
740

    
741
    // no indexTable
742
    put_be64(pb, 0); // indexByteCount
743
    put_be32(pb, 0); // indexSID
744
    put_be64(pb, 0); // bodyOffset
745

    
746
    put_be32(pb, bodysid); // bodySID
747
    put_buffer(pb, op1a_ul, 16); // operational pattern
748

    
749
    // essence container
750
    mxf_write_essence_container_refs(s);
751

    
752
    if (write_metadata) {
753
        // mark the start of the headermetadata and calculate metadata size
754
        int64_t pos, start = url_ftell(s->pb);
755
        mxf_write_primer_pack(s);
756
        mxf_write_header_metadata_sets(s);
757
        pos = url_ftell(s->pb);
758
        // update header_byte_count
759
        url_fseek(pb, header_byte_count_offset, SEEK_SET);
760
        put_be64(pb, pos - start);
761
        url_fseek(pb, pos, SEEK_SET);
762
    }
763

    
764
    put_flush_packet(pb);
765
}
766

    
767
static const UID mxf_mpeg2_codec_uls[] = {
768
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
769
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
770
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
771
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
772
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
773
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
774
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
775
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
776
};
777

    
778
static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
779
{
780
    if (avctx->profile == 4) { // Main
781
        if (avctx->level == 8) // Main
782
            return avctx->gop_size ?
783
                &mxf_mpeg2_codec_uls[1] :
784
                &mxf_mpeg2_codec_uls[0];
785
        else if (avctx->level == 4) // High
786
            return avctx->gop_size ?
787
                &mxf_mpeg2_codec_uls[5] :
788
                &mxf_mpeg2_codec_uls[4];
789
    } else if (avctx->profile == 0) { // 422
790
        if (avctx->level == 5) // Main
791
            return avctx->gop_size ?
792
                &mxf_mpeg2_codec_uls[3] :
793
                &mxf_mpeg2_codec_uls[2];
794
        else if (avctx->level == 2) // High
795
            return avctx->gop_size ?
796
                &mxf_mpeg2_codec_uls[7] :
797
                &mxf_mpeg2_codec_uls[6];
798
    }
799
    return NULL;
800
}
801

    
802
static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
803
{
804
    MXFStreamContext *sc = st->priv_data;
805
    uint32_t c = -1;
806
    int i;
807

    
808
    for(i = 0; i < pkt->size - 4; i++) {
809
        c = (c<<8) + pkt->data[i];
810
        if (c == 0x1B5) {
811
            if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
812
                st->codec->profile = pkt->data[i+1] & 0x07;
813
                st->codec->level   = pkt->data[i+2] >> 4;
814
            } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
815
                sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
816
                break;
817
            }
818
        }
819
    }
820
    sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
821
    return !!sc->codec_ul;
822
}
823

    
824
static int ff_audio_interleave_init(AVFormatContext *s, const int *samples_per_frame)
825
{
826
    int i;
827

    
828
    if (!samples_per_frame)
829
        samples_per_frame = PAL_samples_per_frame;
830

    
831
    for (i = 0; i < s->nb_streams; i++) {
832
        AVStream *st = s->streams[i];
833
        AudioInterleaveContext *aic = st->priv_data;
834

    
835
        if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
836
            aic->sample_size = (st->codec->channels *
837
                                av_get_bits_per_sample(st->codec->codec_id)) / 8;
838
            if (!aic->sample_size) {
839
                av_log(s, AV_LOG_ERROR, "could not compute sample size\n");
840
                return -1;
841
            }
842
            aic->samples_per_frame = samples_per_frame;
843
            aic->samples = aic->samples_per_frame;
844

    
845
            av_fifo_init(&aic->fifo, 100 * *aic->samples);
846
        }
847
    }
848

    
849
    return 0;
850
}
851

    
852
static int mxf_write_header(AVFormatContext *s)
853
{
854
    MXFContext *mxf = s->priv_data;
855
    int i;
856
    uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
857
    const int *samples_per_frame = NULL;
858

    
859
    for (i = 0; i < s->nb_streams; i++) {
860
        AVStream *st = s->streams[i];
861
        MXFStreamContext *sc = av_mallocz(sizeof(*sc));
862
        if (!sc)
863
            return AVERROR(ENOMEM);
864
        st->priv_data = sc;
865

    
866
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
867
            if (!av_cmp_q(st->codec->time_base, (AVRational){ 1, 25 })) {
868
                samples_per_frame = PAL_samples_per_frame;
869
                mxf->time_base = (AVRational){ 1, 25 };
870
            } else if (!av_cmp_q(st->codec->time_base, (AVRational){ 1001, 30000 })) {
871
                samples_per_frame = NTSC_samples_per_frame;
872
                mxf->time_base = (AVRational){ 1001, 30000 };
873
            } else {
874
                av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
875
                return -1;
876
            }
877
        } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
878
            if (st->codec->sample_rate != 48000) {
879
                av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
880
                return -1;
881
            }
882
        }
883
        sc->duration = -1;
884

    
885
        sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
886
        if (sc->index == -1) {
887
            av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
888
                   "codec not currently supported in container\n", i);
889
            return -1;
890
        }
891

    
892
        sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
893

    
894
        if (!present[sc->index]) {
895
            mxf->essence_containers_indices[mxf->essence_container_count++] = sc->index;
896
            present[sc->index] = 1;
897
        } else
898
            present[sc->index]++;
899
        memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
900
        sc->track_essence_element_key[15] = present[sc->index];
901
        PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
902
    }
903

    
904
    for (i = 0; i < s->nb_streams; i++) {
905
        MXFStreamContext *sc = s->streams[i]->priv_data;
906
        av_set_pts_info(s->streams[i], 64, mxf->time_base.num, mxf->time_base.den);
907
        // update element count
908
        sc->track_essence_element_key[13] = present[sc->index];
909
        sc->order = AV_RB32(sc->track_essence_element_key+12);
910
    }
911

    
912
    if (ff_audio_interleave_init(s, samples_per_frame) < 0)
913
        return -1;
914

    
915
    return 0;
916
}
917

    
918
static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
919
{
920
    MXFContext *mxf = s->priv_data;
921
    ByteIOContext *pb = s->pb;
922
    AVStream *st = s->streams[pkt->stream_index];
923
    MXFStreamContext *sc = st->priv_data;
924

    
925
    if (!mxf->header_written) {
926
        if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
927
            if (!mxf_parse_mpeg2_frame(s, st, pkt)) {
928
                av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
929
                return -1;
930
            }
931
        }
932
        mxf_write_partition(s, 1, header_open_partition_key, 1);
933
        mxf->header_written = 1;
934
    }
935

    
936
    put_buffer(pb, sc->track_essence_element_key, 16); // write key
937
    klv_encode_ber_length(pb, pkt->size); // write length
938
    put_buffer(pb, pkt->data, pkt->size); // write value
939

    
940
    sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
941

    
942
    put_flush_packet(pb);
943
    return 0;
944
}
945

    
946
static int mxf_write_footer(AVFormatContext *s)
947
{
948
    MXFContext *mxf = s->priv_data;
949
    ByteIOContext *pb = s->pb;
950

    
951
    mxf->footer_partition_offset = url_ftell(pb);
952
    mxf_write_partition(s, 0, footer_partition_key, 0);
953
    if (!url_is_streamed(s->pb)) {
954
        url_fseek(pb, 0, SEEK_SET);
955
        mxf_write_partition(s, 1, header_closed_partition_key, 1);
956
    }
957
    mxf_free(s);
958
    return 0;
959
}
960

    
961
static int mxf_interleave_new_audio_packet(AVFormatContext *s, AVPacket *pkt,
962
                                           int stream_index, int flush)
963
{
964
    AVStream *st = s->streams[stream_index];
965
    AudioInterleaveContext *aic = st->priv_data;
966

    
967
    int size = FFMIN(av_fifo_size(&aic->fifo), *aic->samples * aic->sample_size);
968
    if (!size || (!flush && size == av_fifo_size(&aic->fifo)))
969
        return 0;
970

    
971
    av_new_packet(pkt, size);
972
    av_fifo_read(&aic->fifo, pkt->data, size);
973

    
974
    pkt->dts = pkt->pts = aic->dts;
975
    pkt->duration = av_rescale_q(*aic->samples,
976
                                 (AVRational){ 1, st->codec->sample_rate },
977
                                 st->time_base);
978
    pkt->stream_index = stream_index;
979
    aic->dts += pkt->duration;
980

    
981
    aic->samples++;
982
    if (!*aic->samples)
983
        aic->samples = aic->samples_per_frame;
984

    
985
    return size;
986
}
987

    
988
static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, int flush)
989
{
990
    AVPacketList *pktl;
991
    int stream_count = 0;
992
    int streams[MAX_STREAMS];
993

    
994
    memset(streams, 0, sizeof(streams));
995
    pktl = s->packet_buffer;
996
    while (pktl) {
997
        //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
998
        if (!streams[pktl->pkt.stream_index])
999
            stream_count++;
1000
        streams[pktl->pkt.stream_index]++;
1001
        pktl = pktl->next;
1002
    }
1003

    
1004
    if (stream_count && (s->nb_streams == stream_count || flush)) {
1005
        pktl = s->packet_buffer;
1006
        *out = pktl->pkt;
1007
        //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1008
        s->packet_buffer = pktl->next;
1009
        av_freep(&pktl);
1010

    
1011
        if (flush && stream_count < s->nb_streams) {
1012
            // purge packet queue
1013
            pktl = s->packet_buffer;
1014
            while (pktl) {
1015
                AVPacketList *next = pktl->next;
1016
                av_free_packet(&pktl->pkt);
1017
                av_freep(&pktl);
1018
                pktl = next;
1019
            }
1020
            s->packet_buffer = NULL;
1021
        }
1022

    
1023
        return 1;
1024
    } else {
1025
        av_init_packet(out);
1026
        return 0;
1027
    }
1028
}
1029

    
1030
static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1031
{
1032
    AVStream *st  = s->streams[pkt ->stream_index];
1033
    AVStream *st2 = s->streams[next->stream_index];
1034
    MXFStreamContext *sc  = st ->priv_data;
1035
    MXFStreamContext *sc2 = st2->priv_data;
1036

    
1037
    int64_t left  = st2->time_base.num * (int64_t)st ->time_base.den;
1038
    int64_t right = st ->time_base.num * (int64_t)st2->time_base.den;
1039

    
1040
    return next->dts * left > pkt->dts * right || // FIXME this can overflow
1041
        (next->dts * left == pkt->dts * right && sc->order < sc2->order);
1042
}
1043

    
1044
static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1045
{
1046
    int i;
1047

    
1048
    if (pkt) {
1049
        AVStream *st = s->streams[pkt->stream_index];
1050
        AudioInterleaveContext *aic = st->priv_data;
1051
        if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1052
            av_fifo_generic_write(&aic->fifo, pkt->data, pkt->size, NULL);
1053
        } else {
1054
            // rewrite pts and dts to be decoded time line position
1055
            pkt->pts = pkt->dts = aic->dts;
1056
            aic->dts += pkt->duration;
1057
            ff_interleave_add_packet(s, pkt, mxf_compare_timestamps);
1058
        }
1059
    }
1060

    
1061
    for (i = 0; i < s->nb_streams; i++) {
1062
        AVStream *st = s->streams[i];
1063
        if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1064
            AVPacket new_pkt;
1065
            while (mxf_interleave_new_audio_packet(s, &new_pkt, i, flush))
1066
                ff_interleave_add_packet(s, &new_pkt, mxf_compare_timestamps);
1067
        }
1068
    }
1069

    
1070
    return mxf_interleave_get_packet(s, out, flush);
1071
}
1072

    
1073
AVOutputFormat mxf_muxer = {
1074
    "mxf",
1075
    NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1076
    NULL,
1077
    "mxf",
1078
    sizeof(MXFContext),
1079
    CODEC_ID_PCM_S16LE,
1080
    CODEC_ID_MPEG2VIDEO,
1081
    mxf_write_header,
1082
    mxf_write_packet,
1083
    mxf_write_footer,
1084
    0,
1085
    NULL,
1086
    mxf_interleave,
1087
};
1088

    
1089