Statistics
| Branch: | Revision:

ffmpeg / libavformat / mxfenc.c @ 425c9962

History | View | Annotate | Download (53.2 KB)

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

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

    
33
//#define DEBUG
34

    
35
#include <math.h>
36
#include <time.h>
37

    
38
#include "libavutil/fifo.h"
39
#include "libavcodec/bytestream.h"
40
#include "audiointerleave.h"
41
#include "avformat.h"
42
#include "mxf.h"
43

    
44
static const int NTSC_samples_per_frame[] = { 1602, 1601, 1602, 1601, 1602, 0 };
45
static const int PAL_samples_per_frame[]  = { 1920, 0 };
46

    
47
#define MXF_INDEX_CLUSTER_SIZE 4096
48
#define KAG_SIZE 512
49

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

    
55
typedef struct {
56
    uint8_t flags;
57
    uint64_t offset;
58
    unsigned slice_offset; ///< offset of audio slice
59
} MXFIndexEntry;
60

    
61
typedef struct {
62
    AudioInterleaveContext aic;
63
    UID track_essence_element_key;
64
    int index;            ///< index in mxf_essence_container_uls table
65
    const UID *codec_ul;
66
    int64_t duration;
67
    int order;            ///< interleaving order if dts are equal
68
    int interlaced;       ///< wether picture is interlaced
69
    int temporal_reordering;
70
} MXFStreamContext;
71

    
72
typedef struct {
73
    UID container_ul;
74
    UID element_ul;
75
    UID codec_ul;
76
    void (*write_desc)();
77
} MXFContainerEssenceEntry;
78

    
79
static const struct {
80
    enum CodecID id;
81
    int index;
82
} mxf_essence_mappings[] = {
83
    { CODEC_ID_MPEG2VIDEO, 0 },
84
    { CODEC_ID_PCM_S24LE,  1 },
85
    { CODEC_ID_PCM_S16LE,  1 },
86
    { 0 }
87
};
88

    
89
static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
90
static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
91
static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
92

    
93
static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
94
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
95
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
96
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
97
      mxf_write_mpegvideo_desc },
98
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
99
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
100
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
101
      mxf_write_aes3_desc },
102
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
103
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
104
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
105
      mxf_write_wav_desc },
106
    { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
107
      { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
108
      { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
109
      NULL },
110
};
111

    
112
typedef struct MXFContext {
113
    int64_t footer_partition_offset;
114
    int essence_container_count;
115
    uint8_t essence_containers_indices[FF_ARRAY_ELEMS(mxf_essence_container_uls)];
116
    AVRational time_base;
117
    int header_written;
118
    MXFIndexEntry *index_entries;
119
    unsigned edit_units_count;
120
    uint64_t timestamp;   ///< timestamp, as year(16),month(8),day(8),hour(8),minutes(8),msec/4(8)
121
    uint8_t slice_count;  ///< index slice count minus 1 (1 if no audio, 0 otherwise)
122
} MXFContext;
123

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

    
127
/**
128
 * complete key for operation pattern, partitions, and primer pack
129
 */
130
static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x01,0x00 };
131
static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
132
static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
133
static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
134
static const uint8_t random_index_pack_key[]       = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
135
static const uint8_t header_open_partition_key[]   = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }; // OpenIncomplete
136
static const uint8_t header_closed_partition_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }; // ClosedComplete
137
static const uint8_t klv_fill_key[]                = { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x03,0x01,0x02,0x10,0x01,0x00,0x00,0x00 };
138

    
139
/**
140
 * partial key for header metadata
141
 */
142
static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
143
static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
144

    
145
/**
146
 * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
147
 */
148
static const MXFLocalTagPair mxf_local_tag_batch[] = {
149
    // preface set
150
    { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
151
    { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
152
    { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
153
    { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
154
    { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
155
    { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
156
    { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
157
    { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
158
    // Identification
159
    { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
160
    { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
161
    { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
162
    { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
163
    { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
164
    { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
165
    // Content Storage
166
    { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
167
    { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
168
    // Essence Container Data
169
    { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
170
    { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
171
    // Package
172
    { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
173
    { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
174
    { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
175
    { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
176
    { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
177
    // Track
178
    { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
179
    { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
180
    { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
181
    { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
182
    { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
183
    // Sequence
184
    { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
185
    { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
186
    { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
187
    // Source Clip
188
    { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
189
    { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
190
    { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
191
    // File Descriptor
192
    { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
193
    { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
194
    { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
195
    { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
196
    // Generic Picture Essence Descriptor
197
    { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
198
    { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
199
    { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
200
    { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
201
    { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
202
    { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
203
    { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
204
    { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
205
    // Generic Sound Essence Descriptor
206
    { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
207
    { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
208
    { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
209
    { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
210
    { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
211
    // Index Table Segment
212
    { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
213
    { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
214
    { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
215
    { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
216
    { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
217
    { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
218
    { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
219
    { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
220
    // MPEG video Descriptor
221
    { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
222
    // Wave Audio Essence Descriptor
223
    { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
224
    { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
225
};
226

    
227
static void mxf_write_uuid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
228
{
229
    put_buffer(pb, uuid_base, 12);
230
    put_be16(pb, type);
231
    put_be16(pb, value);
232
}
233

    
234
static void mxf_write_umid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
235
{
236
    put_buffer(pb, umid_base, 16);
237
    mxf_write_uuid(pb, type, value);
238
}
239

    
240
static void mxf_write_refs_count(ByteIOContext *pb, int ref_count)
241
{
242
    put_be32(pb, ref_count);
243
    put_be32(pb, 16);
244
}
245

    
246
static int klv_ber_length(uint64_t len)
247
{
248
    if (len < 128)
249
        return 1;
250
    else
251
        return (av_log2(len) >> 3) + 2;
252
}
253

    
254
static int klv_encode_ber_length(ByteIOContext *pb, uint64_t len)
255
{
256
    // Determine the best BER size
257
    int size;
258
    if (len < 128) {
259
        //short form
260
        put_byte(pb, len);
261
        return 1;
262
    }
263

    
264
    size = (av_log2(len) >> 3) + 1;
265

    
266
    // long form
267
    put_byte(pb, 0x80 + size);
268
    while(size) {
269
        size--;
270
        put_byte(pb, len >> 8 * size & 0xff);
271
    }
272
    return 0;
273
}
274

    
275
/*
276
 * Get essence container ul index
277
 */
278
static int mxf_get_essence_container_ul_index(enum CodecID id)
279
{
280
    int i;
281
    for (i = 0; mxf_essence_mappings[i].id; i++)
282
        if (mxf_essence_mappings[i].id == id)
283
            return mxf_essence_mappings[i].index;
284
    return -1;
285
}
286

    
287
static void mxf_write_primer_pack(AVFormatContext *s)
288
{
289
    ByteIOContext *pb = s->pb;
290
    int local_tag_number, i = 0;
291

    
292
    local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
293

    
294
    put_buffer(pb, primer_pack_key, 16);
295
    klv_encode_ber_length(pb, local_tag_number * 18 + 8);
296

    
297
    put_be32(pb, local_tag_number); // local_tag num
298
    put_be32(pb, 18); // item size, always 18 according to the specs
299

    
300
    for (i = 0; i < local_tag_number; i++) {
301
        put_be16(pb, mxf_local_tag_batch[i].local_tag);
302
        put_buffer(pb, mxf_local_tag_batch[i].uid, 16);
303
    }
304
}
305

    
306
static void mxf_write_local_tag(ByteIOContext *pb, int size, int tag)
307
{
308
    put_be16(pb, tag);
309
    put_be16(pb, size);
310
}
311

    
312
static void mxf_write_metadata_key(ByteIOContext *pb, unsigned int value)
313
{
314
    put_buffer(pb, header_metadata_key, 13);
315
    put_be24(pb, value);
316
}
317

    
318
static void mxf_free(AVFormatContext *s)
319
{
320
    int i;
321

    
322
    for (i = 0; i < s->nb_streams; i++) {
323
        AVStream *st = s->streams[i];
324
        av_freep(&st->priv_data);
325
    }
326
}
327

    
328
static const MXFCodecUL *mxf_get_data_definition_ul(int type)
329
{
330
    const MXFCodecUL *uls = ff_mxf_data_definition_uls;
331
    while (uls->uid[0]) {
332
        if (type == uls->id)
333
            break;
334
        uls++;
335
    }
336
    return uls;
337
}
338

    
339
static void mxf_write_essence_container_refs(AVFormatContext *s)
340
{
341
    MXFContext *c = s->priv_data;
342
    ByteIOContext *pb = s->pb;
343
    int i;
344

    
345
    mxf_write_refs_count(pb, c->essence_container_count);
346
    av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
347
    for (i = 0; i < c->essence_container_count; i++) {
348
        put_buffer(pb, mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul, 16);
349
        PRINT_KEY(s, "essence container ul:\n", mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul);
350
    }
351
}
352

    
353
static void mxf_write_preface(AVFormatContext *s)
354
{
355
    MXFContext *mxf = s->priv_data;
356
    ByteIOContext *pb = s->pb;
357

    
358
    mxf_write_metadata_key(pb, 0x012f00);
359
    PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
360
    klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
361

    
362
    // write preface set uid
363
    mxf_write_local_tag(pb, 16, 0x3C0A);
364
    mxf_write_uuid(pb, Preface, 0);
365
    PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
366

    
367
    // last modified date
368
    mxf_write_local_tag(pb, 8, 0x3B02);
369
    put_be64(pb, mxf->timestamp);
370

    
371
    // write version
372
    mxf_write_local_tag(pb, 2, 0x3B05);
373
    put_be16(pb, 1);
374

    
375
    // write identification_refs
376
    mxf_write_local_tag(pb, 16 + 8, 0x3B06);
377
    mxf_write_refs_count(pb, 1);
378
    mxf_write_uuid(pb, Identification, 0);
379

    
380
    // write content_storage_refs
381
    mxf_write_local_tag(pb, 16, 0x3B03);
382
    mxf_write_uuid(pb, ContentStorage, 0);
383

    
384
    mxf_write_local_tag(pb, 16, 0x3B09);
385
    put_buffer(pb, op1a_ul, 16);
386

    
387
    // write essence_container_refs
388
    mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
389
    mxf_write_essence_container_refs(s);
390

    
391
    // write dm_scheme_refs
392
    mxf_write_local_tag(pb, 8, 0x3B0B);
393
    put_be64(pb, 0);
394
}
395

    
396
/*
397
 * Write a local tag containing an ascii string as utf-16
398
 */
399
static void mxf_write_local_tag_utf16(ByteIOContext *pb, int tag, const char *value)
400
{
401
    int i, size = strlen(value);
402
    mxf_write_local_tag(pb, size*2, tag);
403
    for (i = 0; i < size; i++)
404
        put_be16(pb, value[i]);
405
}
406

    
407
static void mxf_write_identification(AVFormatContext *s)
408
{
409
    MXFContext *mxf = s->priv_data;
410
    ByteIOContext *pb = s->pb;
411
    const char *company = "FFmpeg";
412
    const char *product = "OP1a Muxer";
413
    const char *version;
414
    int length;
415

    
416
    mxf_write_metadata_key(pb, 0x013000);
417
    PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
418

    
419
    version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?
420
        "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
421
    length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
422
    klv_encode_ber_length(pb, length);
423

    
424
    // write uid
425
    mxf_write_local_tag(pb, 16, 0x3C0A);
426
    mxf_write_uuid(pb, Identification, 0);
427
    PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
428

    
429
    // write generation uid
430
    mxf_write_local_tag(pb, 16, 0x3C09);
431
    mxf_write_uuid(pb, Identification, 1);
432

    
433
    mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
434
    mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
435
    mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
436

    
437
    // write product uid
438
    mxf_write_local_tag(pb, 16, 0x3C05);
439
    mxf_write_uuid(pb, Identification, 2);
440

    
441
    // modification date
442
    mxf_write_local_tag(pb, 8, 0x3C06);
443
    put_be64(pb, mxf->timestamp);
444
}
445

    
446
static void mxf_write_content_storage(AVFormatContext *s)
447
{
448
    ByteIOContext *pb = s->pb;
449

    
450
    mxf_write_metadata_key(pb, 0x011800);
451
    PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
452
    klv_encode_ber_length(pb, 92);
453

    
454
    // write uid
455
    mxf_write_local_tag(pb, 16, 0x3C0A);
456
    mxf_write_uuid(pb, ContentStorage, 0);
457
    PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
458

    
459
    // write package reference
460
    mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
461
    mxf_write_refs_count(pb, 2);
462
    mxf_write_uuid(pb, MaterialPackage, 0);
463
    mxf_write_uuid(pb, SourcePackage, 0);
464

    
465
    // write essence container data
466
    mxf_write_local_tag(pb, 8 + 16, 0x1902);
467
    mxf_write_refs_count(pb, 1);
468
    mxf_write_uuid(pb, EssenceContainerData, 0);
469
}
470

    
471
static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
472
{
473
    MXFContext *mxf = s->priv_data;
474
    ByteIOContext *pb = s->pb;
475
    MXFStreamContext *sc = st->priv_data;
476

    
477
    mxf_write_metadata_key(pb, 0x013b00);
478
    PRINT_KEY(s, "track key", pb->buf_ptr - 16);
479
    klv_encode_ber_length(pb, 80);
480

    
481
    // write track uid
482
    mxf_write_local_tag(pb, 16, 0x3C0A);
483
    mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
484
    PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
485

    
486
    // write track id
487
    mxf_write_local_tag(pb, 4, 0x4801);
488
    put_be32(pb, st->index);
489

    
490
    // write track number
491
    mxf_write_local_tag(pb, 4, 0x4804);
492
    if (type == MaterialPackage)
493
        put_be32(pb, 0); // track number of material package is 0
494
    else
495
        put_buffer(pb, sc->track_essence_element_key + 12, 4);
496

    
497
    mxf_write_local_tag(pb, 8, 0x4B01);
498
    put_be32(pb, mxf->time_base.den);
499
    put_be32(pb, mxf->time_base.num);
500

    
501
    // write origin
502
    mxf_write_local_tag(pb, 8, 0x4B02);
503
    put_be64(pb, 0);
504

    
505
    // write sequence refs
506
    mxf_write_local_tag(pb, 16, 0x4803);
507
    mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
508
}
509

    
510
static void mxf_write_common_fields(ByteIOContext *pb, AVStream *st)
511
{
512
    const MXFCodecUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
513
    MXFStreamContext *sc = st->priv_data;
514

    
515
    // find data define uls
516
    mxf_write_local_tag(pb, 16, 0x0201);
517
    put_buffer(pb, data_def_ul->uid, 16);
518

    
519
    // write duration
520
    mxf_write_local_tag(pb, 8, 0x0202);
521
    put_be64(pb, sc->duration);
522
}
523

    
524
static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
525
{
526
    ByteIOContext *pb = s->pb;
527

    
528
    mxf_write_metadata_key(pb, 0x010f00);
529
    PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
530
    klv_encode_ber_length(pb, 80);
531

    
532
    mxf_write_local_tag(pb, 16, 0x3C0A);
533
    mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
534

    
535
    PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
536
    mxf_write_common_fields(pb, st);
537

    
538
    // write structural component
539
    mxf_write_local_tag(pb, 16 + 8, 0x1001);
540
    mxf_write_refs_count(pb, 1);
541
    mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
542
}
543

    
544
static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
545
{
546
    ByteIOContext *pb = s->pb;
547
    int i;
548

    
549
    mxf_write_metadata_key(pb, 0x011100);
550
    PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
551
    klv_encode_ber_length(pb, 108);
552

    
553
    // write uid
554
    mxf_write_local_tag(pb, 16, 0x3C0A);
555
    mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
556

    
557
    PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
558
    mxf_write_common_fields(pb, st);
559

    
560
    // write start_position
561
    mxf_write_local_tag(pb, 8, 0x1201);
562
    put_be64(pb, 0);
563

    
564
    // write source package uid, end of the reference
565
    mxf_write_local_tag(pb, 32, 0x1101);
566
    if (type == SourcePackage) {
567
        for (i = 0; i < 4; i++)
568
            put_be64(pb, 0);
569
    } else
570
        mxf_write_umid(pb, SourcePackage, 0);
571

    
572
    // write source track id
573
    mxf_write_local_tag(pb, 4, 0x1102);
574
    if (type == SourcePackage)
575
        put_be32(pb, 0);
576
    else
577
        put_be32(pb, st->index);
578
}
579

    
580
static void mxf_write_multi_descriptor(AVFormatContext *s)
581
{
582
    MXFContext *mxf = s->priv_data;
583
    ByteIOContext *pb = s->pb;
584
    int i;
585

    
586
    mxf_write_metadata_key(pb, 0x014400);
587
    PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
588
    klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
589

    
590
    mxf_write_local_tag(pb, 16, 0x3C0A);
591
    mxf_write_uuid(pb, MultipleDescriptor, 0);
592
    PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
593

    
594
    // write sample rate
595
    mxf_write_local_tag(pb, 8, 0x3001);
596
    put_be32(pb, mxf->time_base.den);
597
    put_be32(pb, mxf->time_base.num);
598

    
599
    // write essence container ul
600
    mxf_write_local_tag(pb, 16, 0x3004);
601
    put_buffer(pb, multiple_desc_ul, 16);
602

    
603
    // write sub descriptor refs
604
    mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
605
    mxf_write_refs_count(pb, s->nb_streams);
606
    for (i = 0; i < s->nb_streams; i++)
607
        mxf_write_uuid(pb, SubDescriptor, i);
608
}
609

    
610
static void mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
611
{
612
    MXFContext *mxf = s->priv_data;
613
    MXFStreamContext *sc = st->priv_data;
614
    ByteIOContext *pb = s->pb;
615

    
616
    put_buffer(pb, key, 16);
617
    klv_encode_ber_length(pb, size);
618

    
619
    mxf_write_local_tag(pb, 16, 0x3C0A);
620
    mxf_write_uuid(pb, SubDescriptor, st->index);
621

    
622
    mxf_write_local_tag(pb, 4, 0x3006);
623
    put_be32(pb, st->index);
624

    
625
    mxf_write_local_tag(pb, 8, 0x3001);
626
    put_be32(pb, mxf->time_base.den);
627
    put_be32(pb, mxf->time_base.num);
628

    
629
    mxf_write_local_tag(pb, 16, 0x3004);
630
    put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
631
}
632

    
633
static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
634
static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
635
static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
636

    
637
static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
638
{
639
    MXFStreamContext *sc = st->priv_data;
640
    ByteIOContext *pb = s->pb;
641
    int stored_height = (st->codec->height+15)/16*16;
642
    AVRational dar;
643
    int f1, f2;
644

    
645
    mxf_write_generic_desc(s, st, mxf_mpegvideo_descriptor_key, 153+sc->interlaced*4);
646

    
647
    mxf_write_local_tag(pb, 4, 0x3203);
648
    put_be32(pb, st->codec->width);
649

    
650
    mxf_write_local_tag(pb, 4, 0x3202);
651
    put_be32(pb, stored_height>>sc->interlaced);
652

    
653
    mxf_write_local_tag(pb, 4, 0x3209);
654
    put_be32(pb, st->codec->width);
655

    
656
    mxf_write_local_tag(pb, 4, 0x3208);
657
    put_be32(pb, st->codec->height>>sc->interlaced);
658

    
659
    // bit rate
660
    mxf_write_local_tag(pb, 4, 0x8000);
661
    put_be32(pb, st->codec->bit_rate);
662

    
663
    // frame layout
664
    mxf_write_local_tag(pb, 1, 0x320C);
665
    put_byte(pb, sc->interlaced);
666

    
667
    // video line map
668
    switch (st->codec->height) {
669
    case  576: f1 = 23; f2 = 336; break;
670
    case  608: f1 =  7; f2 = 320; break;
671
    case  480: f1 = 20; f2 = 283; break;
672
    case  512: f1 =  7; f2 = 270; break;
673
    case  720: f1 = 26; f2 =   0; break; // progressive
674
    case 1080: f1 = 21; f2 = 584; break;
675
    default:   f1 =  0; f2 =   0; break;
676
    }
677

    
678
    if (!sc->interlaced) {
679
        f2  = 0;
680
        f1 *= 2;
681
    }
682

    
683
    mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
684
    put_be32(pb, sc->interlaced ? 2 : 1);
685
    put_be32(pb, 4);
686
    put_be32(pb, f1);
687
    if (sc->interlaced)
688
        put_be32(pb, f2);
689

    
690
    av_reduce(&dar.num, &dar.den,
691
              st->codec->width*st->codec->sample_aspect_ratio.num,
692
              st->codec->height*st->codec->sample_aspect_ratio.den,
693
              1024*1024);
694

    
695
    mxf_write_local_tag(pb, 8, 0x320E);
696
    put_be32(pb, dar.num);
697
    put_be32(pb, dar.den);
698

    
699
    mxf_write_local_tag(pb, 16, 0x3201);
700
    put_buffer(pb, *sc->codec_ul, 16);
701
}
702

    
703
static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
704
{
705
    ByteIOContext *pb = s->pb;
706

    
707
    mxf_write_generic_desc(s, st, key, size);
708

    
709
    // audio locked
710
    mxf_write_local_tag(pb, 1, 0x3D02);
711
    put_byte(pb, 1);
712

    
713
    // write audio sampling rate
714
    mxf_write_local_tag(pb, 8, 0x3D03);
715
    put_be32(pb, st->codec->sample_rate);
716
    put_be32(pb, 1);
717

    
718
    mxf_write_local_tag(pb, 4, 0x3D07);
719
    put_be32(pb, st->codec->channels);
720

    
721
    mxf_write_local_tag(pb, 4, 0x3D01);
722
    put_be32(pb, av_get_bits_per_sample(st->codec->codec_id));
723
}
724

    
725
static void mxf_write_wav_common_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
726
{
727
    ByteIOContext *pb = s->pb;
728

    
729
    mxf_write_generic_sound_desc(s, st, key, size);
730

    
731
    mxf_write_local_tag(pb, 2, 0x3D0A);
732
    put_be16(pb, st->codec->block_align);
733

    
734
    // avg bytes per sec
735
    mxf_write_local_tag(pb, 4, 0x3D09);
736
    put_be32(pb, st->codec->block_align*st->codec->sample_rate);
737
}
738

    
739
static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
740
{
741
    mxf_write_wav_common_desc(s, st, mxf_wav_descriptor_key, 107);
742
}
743

    
744
static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
745
{
746
    mxf_write_wav_common_desc(s, st, mxf_aes3_descriptor_key, 107);
747
}
748

    
749
static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
750
{
751
    MXFContext *mxf = s->priv_data;
752
    ByteIOContext *pb = s->pb;
753
    int i;
754

    
755
    if (type == MaterialPackage) {
756
        mxf_write_metadata_key(pb, 0x013600);
757
        PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
758
        klv_encode_ber_length(pb, 92 + 16 * s->nb_streams);
759
    } else {
760
        mxf_write_metadata_key(pb, 0x013700);
761
        PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
762
        klv_encode_ber_length(pb, 112 + 16 * s->nb_streams); // 20 bytes length for descriptor reference
763
    }
764

    
765
    // write uid
766
    mxf_write_local_tag(pb, 16, 0x3C0A);
767
    mxf_write_uuid(pb, type, 0);
768
    av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
769
    PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
770

    
771
    // write package umid
772
    mxf_write_local_tag(pb, 32, 0x4401);
773
    mxf_write_umid(pb, type, 0);
774
    PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
775

    
776
    // package creation date
777
    mxf_write_local_tag(pb, 8, 0x4405);
778
    put_be64(pb, mxf->timestamp);
779

    
780
    // package modified date
781
    mxf_write_local_tag(pb, 8, 0x4404);
782
    put_be64(pb, mxf->timestamp);
783

    
784
    // write track refs
785
    mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x4403);
786
    mxf_write_refs_count(pb, s->nb_streams);
787
    for (i = 0; i < s->nb_streams; i++)
788
        mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
789

    
790
    // write multiple descriptor reference
791
    if (type == SourcePackage) {
792
        mxf_write_local_tag(pb, 16, 0x4701);
793
        if (s->nb_streams > 1) {
794
            mxf_write_uuid(pb, MultipleDescriptor, 0);
795
            mxf_write_multi_descriptor(s);
796
        } else
797
            mxf_write_uuid(pb, SubDescriptor, 0);
798
    }
799

    
800
    for (i = 0; i < s->nb_streams; i++) {
801
        AVStream *st = s->streams[i];
802
        mxf_write_track(s, st, type);
803
        mxf_write_sequence(s, st, type);
804
        mxf_write_structural_component(s, st, type);
805

    
806
        if (type == SourcePackage) {
807
            MXFStreamContext *sc = st->priv_data;
808
            mxf_essence_container_uls[sc->index].write_desc(s, st);
809
        }
810
    }
811
}
812

    
813
static int mxf_write_essence_container_data(AVFormatContext *s)
814
{
815
    ByteIOContext *pb = s->pb;
816

    
817
    mxf_write_metadata_key(pb, 0x012300);
818
    klv_encode_ber_length(pb, 72);
819

    
820
    mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
821
    mxf_write_uuid(pb, EssenceContainerData, 0);
822

    
823
    mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
824
    mxf_write_umid(pb, SourcePackage, 0);
825

    
826
    mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
827
    put_be32(pb, 1);
828

    
829
    mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
830
    put_be32(pb, 2);
831

    
832
    return 0;
833
}
834

    
835
static int mxf_write_header_metadata_sets(AVFormatContext *s)
836
{
837
    mxf_write_preface(s);
838
    mxf_write_identification(s);
839
    mxf_write_content_storage(s);
840
    mxf_write_package(s, MaterialPackage);
841
    mxf_write_package(s, SourcePackage);
842
    mxf_write_essence_container_data(s);
843
    return 0;
844
}
845

    
846
static unsigned klv_fill_size(uint64_t size)
847
{
848
    unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
849
    if (pad < 17) // smallest fill item possible
850
        return pad + KAG_SIZE;
851
    else
852
        return pad & (KAG_SIZE-1);
853
}
854

    
855
static int mxf_write_index_table_segment(AVFormatContext *s)
856
{
857
    MXFContext *mxf = s->priv_data;
858
    ByteIOContext *pb = s->pb;
859
    int i, j, ret;
860
    int temporal_reordering = 0;
861
    int last_key_index = 0, key_index = 0;
862

    
863
    av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
864

    
865
    put_buffer(pb, index_table_segment_key, 16);
866
    ret = klv_encode_ber_length(pb, 109 + (s->nb_streams+1)*6 +
867
                                mxf->edit_units_count*(11+mxf->slice_count*4));
868

    
869
    // instance id
870
    mxf_write_local_tag(pb, 16, 0x3C0A);
871
    mxf_write_uuid(pb, IndexTableSegment, 0);
872

    
873
    // index edit rate
874
    mxf_write_local_tag(pb, 8, 0x3F0B);
875
    put_be32(pb, mxf->time_base.num);
876
    put_be32(pb, mxf->time_base.den);
877

    
878
    // index start position
879
    mxf_write_local_tag(pb, 8, 0x3F0C);
880
    put_be64(pb, 0);
881

    
882
    // index duration
883
    mxf_write_local_tag(pb, 8, 0x3F0D);
884
    put_be64(pb, mxf->edit_units_count);
885

    
886
    // edit unit byte count
887
    mxf_write_local_tag(pb, 4, 0x3F05);
888
    put_be32(pb, 0);
889

    
890
    // index sid
891
    mxf_write_local_tag(pb, 4, 0x3F06);
892
    put_be32(pb, 2);
893

    
894
    // body sid
895
    mxf_write_local_tag(pb, 4, 0x3F07);
896
    put_be32(pb, 1);
897

    
898
    // real slice count - 1
899
    mxf_write_local_tag(pb, 1, 0x3F08);
900
    put_byte(pb, mxf->slice_count);
901

    
902
    // delta entry array
903
    mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);
904
    put_be32(pb, s->nb_streams+1); // num of entries
905
    put_be32(pb, 6);             // size of one entry
906
    // write system item delta entry
907
    put_byte(pb, 0);
908
    put_byte(pb, 0); // slice entry
909
    put_be32(pb, 0); // element delta
910
    for (i = 0; i < s->nb_streams; i++) {
911
        AVStream *st = s->streams[i];
912
        MXFStreamContext *sc = st->priv_data;
913
        put_byte(pb, sc->temporal_reordering);
914
        if (sc->temporal_reordering)
915
            temporal_reordering = 1;
916
        // slice number
917
        if (i == 0) { // video track
918
            put_byte(pb, 0); // slice number
919
            put_be32(pb, KAG_SIZE); // system item size including klv fill
920
        } else { // audio track
921
            unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;
922
            audio_frame_size += klv_fill_size(audio_frame_size);
923
            put_byte(pb, 1);
924
            put_be32(pb, (i-1)*audio_frame_size); // element delta
925
        }
926
    }
927

    
928
    mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A);
929
    put_be32(pb, mxf->edit_units_count);  // num of entries
930
    put_be32(pb, 11+mxf->slice_count*4);  // size of one entry
931
    for (i = 0; i < mxf->edit_units_count; i++) {
932
        if (temporal_reordering) {
933
            int temporal_offset = 0;
934
            for (j = i+1; j < mxf->edit_units_count; j++) {
935
                temporal_offset++;
936
                if (mxf->index_entries[j].flags & 0x10) { // backward prediction
937
                    // next is not b, so is reordered
938
                    if (!(mxf->index_entries[i+1].flags & 0x10)) {
939
                        if ((mxf->index_entries[i].flags & 0x11) == 0) // i frame
940
                            temporal_offset = 0;
941
                        else
942
                            temporal_offset = -temporal_offset;
943
                    }
944
                    break;
945
                }
946
            }
947
            put_byte(pb, temporal_offset);
948
        } else
949
            put_byte(pb, 0);
950
        if (!(mxf->index_entries[i].flags & 0x33)) { // I frame
951
            last_key_index = key_index;
952
            key_index = i;
953
        }
954
        if (mxf->index_entries[i].flags & 0x10 && // backward prediction
955
            !(mxf->index_entries[key_index].flags & 0x80)) { // open gop
956
            put_byte(pb, last_key_index - i);
957
        } else {
958
            put_byte(pb, key_index - i); // key frame offset
959
            if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
960
                last_key_index = key_index;
961
        }
962
        put_byte(pb, mxf->index_entries[i].flags);
963
        // stream offset
964
        put_be64(pb, mxf->index_entries[i].offset - mxf->index_entries[0].offset);
965
        if (s->nb_streams > 1)
966
            put_be32(pb, mxf->index_entries[i].slice_offset);
967
    }
968

    
969
    return ret;
970
}
971

    
972
static void mxf_write_partition(AVFormatContext *s, int bodysid,
973
                                int indexsid, unsigned index_byte_count,
974
                                const uint8_t *key, int write_metadata)
975
{
976
    MXFContext *mxf = s->priv_data;
977
    ByteIOContext *pb = s->pb;
978
    int64_t header_byte_count_offset;
979

    
980
    // write klv
981
    put_buffer(pb, key, 16);
982

    
983
    klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
984

    
985
    // write partition value
986
    put_be16(pb, 1); // majorVersion
987
    put_be16(pb, 2); // minorVersion
988
    put_be32(pb, KAG_SIZE); // KAGSize
989

    
990
    put_be64(pb, url_ftell(pb) - 25); // thisPartition
991
    put_be64(pb, 0); // previousPartition
992

    
993
    put_be64(pb, mxf->footer_partition_offset); // footerPartition
994

    
995
    // set offset
996
    header_byte_count_offset = url_ftell(pb);
997
    put_be64(pb, 0); // headerByteCount, update later
998

    
999
    // indexTable
1000
    put_be64(pb, index_byte_count); // indexByteCount
1001
    put_be32(pb, indexsid); // indexSID
1002
    put_be64(pb, 0); // bodyOffset
1003

    
1004
    put_be32(pb, bodysid); // bodySID
1005
    put_buffer(pb, op1a_ul, 16); // operational pattern
1006

    
1007
    // essence container
1008
    mxf_write_essence_container_refs(s);
1009

    
1010
    if (write_metadata) {
1011
        // mark the start of the headermetadata and calculate metadata size
1012
        int64_t pos, start = url_ftell(s->pb);
1013
        unsigned header_byte_count;
1014

    
1015
        mxf_write_primer_pack(s);
1016
        mxf_write_header_metadata_sets(s);
1017
        pos = url_ftell(s->pb);
1018
        header_byte_count = pos - start + klv_fill_size(pos);
1019

    
1020
        // update header_byte_count
1021
        url_fseek(pb, header_byte_count_offset, SEEK_SET);
1022
        put_be64(pb, header_byte_count);
1023
        url_fseek(pb, pos, SEEK_SET);
1024
    }
1025

    
1026
    put_flush_packet(pb);
1027
}
1028

    
1029
static const UID mxf_mpeg2_codec_uls[] = {
1030
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
1031
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
1032
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
1033
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
1034
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
1035
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
1036
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
1037
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
1038
};
1039

    
1040
static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
1041
{
1042
    if (avctx->profile == 4) { // Main
1043
        if (avctx->level == 8) // Main
1044
            return avctx->gop_size ?
1045
                &mxf_mpeg2_codec_uls[1] :
1046
                &mxf_mpeg2_codec_uls[0];
1047
        else if (avctx->level == 4) // High
1048
            return avctx->gop_size ?
1049
                &mxf_mpeg2_codec_uls[5] :
1050
                &mxf_mpeg2_codec_uls[4];
1051
    } else if (avctx->profile == 0) { // 422
1052
        if (avctx->level == 5) // Main
1053
            return avctx->gop_size ?
1054
                &mxf_mpeg2_codec_uls[3] :
1055
                &mxf_mpeg2_codec_uls[2];
1056
        else if (avctx->level == 2) // High
1057
            return avctx->gop_size ?
1058
                &mxf_mpeg2_codec_uls[7] :
1059
                &mxf_mpeg2_codec_uls[6];
1060
    }
1061
    return NULL;
1062
}
1063

    
1064
static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1065
{
1066
    MXFContext *mxf = s->priv_data;
1067
    MXFStreamContext *sc = st->priv_data;
1068
    uint32_t c = -1;
1069
    int i;
1070

    
1071
    mxf->index_entries[mxf->edit_units_count].flags = 0;
1072

    
1073
    for(i = 0; i < pkt->size - 4; i++) {
1074
        c = (c<<8) + pkt->data[i];
1075
        if (c == 0x1B5) {
1076
            if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1077
                st->codec->profile = pkt->data[i+1] & 0x07;
1078
                st->codec->level   = pkt->data[i+2] >> 4;
1079
            } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1080
                sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1081
                break;
1082
            }
1083
        } else if (c == 0x1b8) { // gop
1084
            if (i + 4 < pkt->size && pkt->data[i+4]>>6 & 0x01) // closed
1085
                mxf->index_entries[mxf->edit_units_count].flags |= 0x80; // random access
1086
        } else if (c == 0x1b3) { // seq
1087
            mxf->index_entries[mxf->edit_units_count].flags |= 0x40;
1088
        } else if (c == 0x100) { // pic
1089
            int pict_type = (pkt->data[i+2]>>3) & 0x07;
1090
            if (pict_type == 2) { // P frame
1091
                mxf->index_entries[mxf->edit_units_count].flags |= 0x22;
1092
                st->codec->gop_size = 1;
1093
            } else if (pict_type == 3) { // B frame
1094
                mxf->index_entries[mxf->edit_units_count].flags |= 0x33;
1095
                sc->temporal_reordering = -1;
1096
            } else if (!pict_type) {
1097
                av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1098
                return 0;
1099
            }
1100
        }
1101
    }
1102
    sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1103
    return !!sc->codec_ul;
1104
}
1105

    
1106
static uint64_t mxf_parse_timestamp(time_t timestamp)
1107
{
1108
    struct tm *time = localtime(&timestamp);
1109
    return (uint64_t)(time->tm_year+1900) << 48 |
1110
           (uint64_t)(time->tm_mon+1)     << 40 |
1111
           (uint64_t) time->tm_mday       << 32 |
1112
                      time->tm_hour       << 24 |
1113
                      time->tm_min        << 16 |
1114
                      time->tm_sec        << 8;
1115
}
1116

    
1117
static int mxf_write_header(AVFormatContext *s)
1118
{
1119
    MXFContext *mxf = s->priv_data;
1120
    int i;
1121
    uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
1122
    const int *samples_per_frame = NULL;
1123

    
1124
    if (s->nb_streams > 17) {
1125
        av_log(s, AV_LOG_ERROR, "error, mxf muxer supports 17 tracks maximum\n");
1126
        return -1;
1127
    }
1128

    
1129
    for (i = 0; i < s->nb_streams; i++) {
1130
        AVStream *st = s->streams[i];
1131
        MXFStreamContext *sc = av_mallocz(sizeof(*sc));
1132
        if (!sc)
1133
            return AVERROR(ENOMEM);
1134
        st->priv_data = sc;
1135

    
1136
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1137
            if (i != 0) {
1138
                av_log(s, AV_LOG_ERROR, "video stream must be first track\n");
1139
                return -1;
1140
            }
1141
            if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1142
                samples_per_frame = PAL_samples_per_frame;
1143
                mxf->time_base = (AVRational){ 1, 25 };
1144
            } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1145
                samples_per_frame = NTSC_samples_per_frame;
1146
                mxf->time_base = (AVRational){ 1001, 30000 };
1147
            } else {
1148
                av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1149
                return -1;
1150
            }
1151
            av_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
1152
        } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1153
            if (st->codec->sample_rate != 48000) {
1154
                av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1155
                return -1;
1156
            }
1157
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1158
            mxf->slice_count = 1;
1159
        }
1160
        sc->duration = -1;
1161

    
1162
        sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
1163
        if (sc->index == -1) {
1164
            av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
1165
                   "codec not currently supported in container\n", i);
1166
            return -1;
1167
        }
1168

    
1169
        sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1170

    
1171
        if (!present[sc->index]) {
1172
            mxf->essence_containers_indices[mxf->essence_container_count++] = sc->index;
1173
            present[sc->index] = 1;
1174
        } else
1175
            present[sc->index]++;
1176
        memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
1177
        sc->track_essence_element_key[15] = present[sc->index];
1178
        PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
1179
    }
1180

    
1181
    for (i = 0; i < s->nb_streams; i++) {
1182
        MXFStreamContext *sc = s->streams[i]->priv_data;
1183
        // update element count
1184
        sc->track_essence_element_key[13] = present[sc->index];
1185
        sc->order = AV_RB32(sc->track_essence_element_key+12);
1186
    }
1187

    
1188
    mxf->timestamp = mxf_parse_timestamp(s->timestamp);
1189

    
1190
    if (!samples_per_frame)
1191
        samples_per_frame = PAL_samples_per_frame;
1192

    
1193
    if (ff_audio_interleave_init(s, samples_per_frame, mxf->time_base) < 0)
1194
        return -1;
1195

    
1196
    return 0;
1197
}
1198

    
1199
static void mxf_write_klv_fill(AVFormatContext *s)
1200
{
1201
    unsigned pad = klv_fill_size(url_ftell(s->pb));
1202
    if (pad) {
1203
        put_buffer(s->pb, klv_fill_key, 16);
1204
        pad -= 16;
1205
        pad -= klv_ber_length(pad);
1206
        klv_encode_ber_length(s->pb, pad);
1207
        for (; pad > 7; pad -= 8)
1208
            put_be64(s->pb, 0);
1209
        for (; pad; pad--)
1210
            put_byte(s->pb, 0);
1211
        assert(!(url_ftell(s->pb) & (KAG_SIZE-1)));
1212
    }
1213
}
1214

    
1215
static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
1216
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 };
1217

    
1218
static uint32_t ff_framenum_to_12m_time_code(unsigned frame, int drop, int fps)
1219
{
1220
    return (0                                    << 31) | // color frame flag
1221
           (0                                    << 30) | // drop  frame flag
1222
           ( ((frame % fps) / 10)                << 28) | // tens  of frames
1223
           ( ((frame % fps) % 10)                << 24) | // units of frames
1224
           (0                                    << 23) | // field phase (NTSC), b0 (PAL)
1225
           ((((frame / fps) % 60) / 10)          << 20) | // tens  of seconds
1226
           ((((frame / fps) % 60) % 10)          << 16) | // units of seconds
1227
           (0                                    << 15) | // b0 (NTSC), b2 (PAL)
1228
           ((((frame / (fps * 60)) % 60) / 10)   << 12) | // tens  of minutes
1229
           ((((frame / (fps * 60)) % 60) % 10)   <<  8) | // units of minutes
1230
           (0                                    <<  7) | // b1
1231
           (0                                    <<  6) | // b2 (NSC), field phase (PAL)
1232
           ((((frame / (fps * 3600) % 24)) / 10) <<  4) | // tens  of hours
1233
           (  (frame / (fps * 3600) % 24)) % 10;          // units of hours
1234
}
1235

    
1236
static void mxf_write_system_item(AVFormatContext *s)
1237
{
1238
    MXFContext *mxf = s->priv_data;
1239
    ByteIOContext *pb = s->pb;
1240
    unsigned fps, frame;
1241
    uint32_t time_code;
1242

    
1243
    frame = mxf->edit_units_count;
1244

    
1245
    // write system metadata pack
1246
    put_buffer(pb, system_metadata_pack_key, 16);
1247
    klv_encode_ber_length(pb, 57);
1248
    put_byte(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
1249
    put_byte(pb, 0x04); // content package rate
1250
    put_byte(pb, 0x00); // content package type
1251
    put_be16(pb, 0x00); // channel handle
1252
    put_be16(pb, frame); // continuity count
1253
    if (mxf->essence_container_count > 1)
1254
        put_buffer(pb, multiple_desc_ul, 16);
1255
    else
1256
        put_buffer(pb, mxf_essence_container_uls[mxf->essence_containers_indices[0]].container_ul, 16);
1257
    put_byte(pb, 0);
1258
    put_be64(pb, 0);
1259
    put_be64(pb, 0); // creation date/time stamp
1260

    
1261
    // XXX drop frame
1262
    if (mxf->time_base.den == 30000) fps = 30;
1263
    else                             fps = 25;
1264

    
1265
    put_byte(pb, 0x81); // SMPTE 12M time code
1266
    time_code = ff_framenum_to_12m_time_code(frame, 0, fps);
1267
    put_be32(pb, time_code);
1268
    put_be32(pb, 0); // binary group data
1269
    put_be64(pb, 0);
1270

    
1271
    // write system metadata package set
1272
    put_buffer(pb, system_metadata_package_set_key, 16);
1273
    klv_encode_ber_length(pb, 35);
1274
    put_byte(pb, 0x83); // UMID
1275
    put_be16(pb, 0x20);
1276
    mxf_write_umid(pb, SourcePackage, 0);
1277
}
1278

    
1279
static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1280
{
1281
    MXFContext *mxf = s->priv_data;
1282
    ByteIOContext *pb = s->pb;
1283
    AVStream *st = s->streams[pkt->stream_index];
1284
    MXFStreamContext *sc = st->priv_data;
1285

    
1286
    if (!(mxf->edit_units_count % MXF_INDEX_CLUSTER_SIZE)) {
1287
        mxf->index_entries = av_realloc(mxf->index_entries,
1288
            (mxf->edit_units_count + MXF_INDEX_CLUSTER_SIZE)*
1289
             sizeof(*mxf->index_entries));
1290
        if (!mxf->index_entries) {
1291
            av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1292
            return -1;
1293
        }
1294
    }
1295

    
1296
    if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1297
        if (!mxf_parse_mpeg2_frame(s, st, pkt)) {
1298
            av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1299
            return -1;
1300
        }
1301
    }
1302

    
1303
    if (!mxf->header_written) {
1304
        mxf_write_partition(s, 1, 0, 0, header_open_partition_key, 1);
1305
        mxf->header_written = 1;
1306
    }
1307

    
1308
    mxf_write_klv_fill(s);
1309

    
1310
    if (st->index == 0) {
1311
        mxf->index_entries[mxf->edit_units_count].offset = url_ftell(pb);
1312

    
1313
        mxf_write_system_item(s);
1314
        mxf_write_klv_fill(s);
1315

    
1316
        mxf->edit_units_count++;
1317
    } else if (st->index == 1) {
1318
        mxf->index_entries[mxf->edit_units_count-1].slice_offset =
1319
            url_ftell(pb) - mxf->index_entries[mxf->edit_units_count-1].offset;
1320
    }
1321

    
1322
    put_buffer(pb, sc->track_essence_element_key, 16); // write key
1323
    klv_encode_ber_length(pb, pkt->size); // write length
1324
    put_buffer(pb, pkt->data, pkt->size); // write value
1325

    
1326
    sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
1327

    
1328
    put_flush_packet(pb);
1329
    return 0;
1330
}
1331

    
1332
static void mxf_write_random_index_pack(AVFormatContext *s)
1333
{
1334
    MXFContext *mxf = s->priv_data;
1335
    ByteIOContext *pb = s->pb;
1336
    uint64_t pos = url_ftell(pb);
1337

    
1338
    put_buffer(pb, random_index_pack_key, 16);
1339
    klv_encode_ber_length(pb, 28);
1340

    
1341
    put_be32(pb, 1); // BodySID of header partition
1342
    put_be64(pb, 0); // offset of header partition
1343

    
1344
    put_be32(pb, 0); // BodySID of footer partition
1345
    put_be64(pb, mxf->footer_partition_offset);
1346

    
1347
    put_be32(pb, url_ftell(pb) - pos + 4);
1348
}
1349

    
1350
static int mxf_write_footer(AVFormatContext *s)
1351
{
1352
    MXFContext *mxf = s->priv_data;
1353
    ByteIOContext *pb = s->pb;
1354
    unsigned index_byte_count =
1355
        109 + (s->nb_streams+1)*6 +
1356
        mxf->edit_units_count*(11+mxf->slice_count*4);
1357

    
1358
    // add encoded ber length
1359
    index_byte_count += 16 + klv_ber_length(index_byte_count);
1360

    
1361
    mxf_write_klv_fill(s);
1362

    
1363
    mxf->footer_partition_offset = url_ftell(pb);
1364
    mxf_write_partition(s, 0, 2, index_byte_count, footer_partition_key, 0);
1365

    
1366
    mxf_write_index_table_segment(s);
1367

    
1368
    mxf_write_random_index_pack(s);
1369

    
1370
    if (!url_is_streamed(s->pb)) {
1371
        url_fseek(pb, 0, SEEK_SET);
1372
        mxf_write_partition(s, 1, 0, 0, header_closed_partition_key, 1);
1373
    }
1374

    
1375
    ff_audio_interleave_close(s);
1376

    
1377
    av_freep(&mxf->index_entries);
1378

    
1379
    mxf_free(s);
1380
    return 0;
1381
}
1382

    
1383
static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1384
{
1385
    AVPacketList *pktl;
1386
    int stream_count = 0;
1387
    int streams[MAX_STREAMS];
1388

    
1389
    memset(streams, 0, sizeof(streams));
1390
    pktl = s->packet_buffer;
1391
    while (pktl) {
1392
        //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
1393
        if (!streams[pktl->pkt.stream_index])
1394
            stream_count++;
1395
        streams[pktl->pkt.stream_index]++;
1396
        pktl = pktl->next;
1397
    }
1398

    
1399
    if (stream_count && (s->nb_streams == stream_count || flush)) {
1400
        pktl = s->packet_buffer;
1401
        if (s->nb_streams != stream_count) {
1402
            AVPacketList *first = NULL;
1403
            // find first packet in edit unit
1404
            while (pktl) {
1405
                AVStream *st = s->streams[pktl->pkt.stream_index];
1406
                if (st->index == 0)
1407
                    break;
1408
                else if (!first)
1409
                    first = pktl;
1410
                pktl = pktl->next;
1411
            }
1412
            // purge packet queue
1413
            while (pktl) {
1414
                AVPacketList *next = pktl->next;
1415
                av_free_packet(&pktl->pkt);
1416
                av_freep(&pktl);
1417
                pktl = next;
1418
            }
1419
            if (!first)
1420
                goto out;
1421
            pktl = first;
1422
        }
1423

    
1424
        *out = pktl->pkt;
1425
        //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1426
        s->packet_buffer = pktl->next;
1427
        av_freep(&pktl);
1428
        return 1;
1429
    } else {
1430
    out:
1431
        av_init_packet(out);
1432
        return 0;
1433
    }
1434
}
1435

    
1436
static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1437
{
1438
    MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
1439
    MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
1440

    
1441
    return next->dts > pkt->dts ||
1442
        (next->dts == pkt->dts && sc->order < sc2->order);
1443
}
1444

    
1445
static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1446
{
1447
    return ff_audio_interleave(s, out, pkt, flush,
1448
                               mxf_interleave_get_packet, mxf_compare_timestamps);
1449
}
1450

    
1451
AVOutputFormat mxf_muxer = {
1452
    "mxf",
1453
    NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1454
    NULL,
1455
    "mxf",
1456
    sizeof(MXFContext),
1457
    CODEC_ID_PCM_S16LE,
1458
    CODEC_ID_MPEG2VIDEO,
1459
    mxf_write_header,
1460
    mxf_write_packet,
1461
    mxf_write_footer,
1462
    AVFMT_NOTIMESTAMPS,
1463
    NULL,
1464
    mxf_interleave,
1465
};