]> git.sesse.net Git - x264/blob - output/mp4.c
Fix possible buffer overflow in mp4 muxer
[x264] / output / mp4.c
1 /*****************************************************************************
2  * mp4.c: mp4 muxer
3  *****************************************************************************
4  * Copyright (C) 2003-2011 x264 project
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *          Loren Merritt <lorenm@u.washington.edu>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
22  *
23  * This program is also available under a commercial proprietary license.
24  * For more information, contact us at licensing@x264.com.
25  *****************************************************************************/
26
27 #include "output.h"
28 #include <gpac/isomedia.h>
29
30 #if HAVE_GF_MALLOC
31 #undef malloc
32 #undef free
33 #undef realloc
34 #define malloc gf_malloc
35 #define free gf_free
36 #define realloc gf_realloc
37 #endif
38
39 typedef struct
40 {
41     GF_ISOFile *p_file;
42     GF_AVCConfig *p_config;
43     GF_ISOSample *p_sample;
44     int i_track;
45     uint32_t i_descidx;
46     uint64_t i_time_res;
47     int64_t i_time_inc;
48     int64_t i_delay_time;
49     int64_t i_init_delta;
50     int i_numframe;
51     int i_delay_frames;
52     int b_dts_compress;
53     int i_dts_compress_multiplier;
54     int i_data_size;
55 } mp4_hnd_t;
56
57 static void recompute_bitrate_mp4( GF_ISOFile *p_file, int i_track )
58 {
59     u32 count, di, timescale, time_wnd, rate;
60     u64 offset;
61     Double br;
62     GF_ESD *esd;
63
64     esd = gf_isom_get_esd( p_file, i_track, 1 );
65     if( !esd )
66         return;
67
68     esd->decoderConfig->avgBitrate = 0;
69     esd->decoderConfig->maxBitrate = 0;
70     rate = time_wnd = 0;
71
72     timescale = gf_isom_get_media_timescale( p_file, i_track );
73     count = gf_isom_get_sample_count( p_file, i_track );
74     for( u32 i = 0; i < count; i++ )
75     {
76         GF_ISOSample *samp = gf_isom_get_sample_info( p_file, i_track, i+1, &di, &offset );
77         if( !samp )
78         {
79             x264_cli_log( "mp4", X264_LOG_ERROR, "failure reading back frame %u\n", i );
80             break;
81         }
82
83         if( esd->decoderConfig->bufferSizeDB < samp->dataLength )
84             esd->decoderConfig->bufferSizeDB = samp->dataLength;
85
86         esd->decoderConfig->avgBitrate += samp->dataLength;
87         rate += samp->dataLength;
88         if( samp->DTS > time_wnd + timescale )
89         {
90             if( rate > esd->decoderConfig->maxBitrate )
91                 esd->decoderConfig->maxBitrate = rate;
92             time_wnd = samp->DTS;
93             rate = 0;
94         }
95
96         gf_isom_sample_del( &samp );
97     }
98
99     br = (Double)(s64)gf_isom_get_media_duration( p_file, i_track );
100     br /= timescale;
101     esd->decoderConfig->avgBitrate = (u32)(esd->decoderConfig->avgBitrate / br);
102     /*move to bps*/
103     esd->decoderConfig->avgBitrate *= 8;
104     esd->decoderConfig->maxBitrate *= 8;
105
106     gf_isom_change_mpeg4_description( p_file, i_track, 1, esd );
107     gf_odf_desc_del( (GF_Descriptor*)esd );
108 }
109
110 static int close_file( hnd_t handle, int64_t largest_pts, int64_t second_largest_pts )
111 {
112     mp4_hnd_t *p_mp4 = handle;
113
114     if( !p_mp4 )
115         return 0;
116
117     if( p_mp4->p_config )
118         gf_odf_avc_cfg_del( p_mp4->p_config );
119
120     if( p_mp4->p_sample )
121     {
122         if( p_mp4->p_sample->data )
123             free( p_mp4->p_sample->data );
124
125         p_mp4->p_sample->dataLength = 0;
126         gf_isom_sample_del( &p_mp4->p_sample );
127     }
128
129     if( p_mp4->p_file )
130     {
131         if( p_mp4->i_track )
132         {
133             /* The mdhd duration is defined as CTS[final] - CTS[0] + duration of last frame.
134              * The mdhd duration (in seconds) should be able to be longer than the tkhd duration since the track is managed by edts.
135              * So, if mdhd duration is equal to the last DTS or less, we give the last composition time delta to the last sample duration.
136              * And then, the mdhd duration is updated, but it time-wise doesn't give the actual duration.
137              * The tkhd duration is the actual track duration. */
138             uint64_t mdhd_duration = (2 * largest_pts - second_largest_pts) * p_mp4->i_time_inc;
139             if( mdhd_duration != gf_isom_get_media_duration( p_mp4->p_file, p_mp4->i_track ) )
140             {
141                 uint64_t last_dts = gf_isom_get_sample_dts( p_mp4->p_file, p_mp4->i_track, p_mp4->i_numframe );
142                 uint32_t last_duration = (uint32_t)( mdhd_duration > last_dts ? mdhd_duration - last_dts : (largest_pts - second_largest_pts) * p_mp4->i_time_inc );
143                 gf_isom_set_last_sample_duration( p_mp4->p_file, p_mp4->i_track, last_duration );
144             }
145
146             /* Write an Edit Box if the first CTS offset is positive.
147              * A media_time is given by not the mvhd timescale but rather the mdhd timescale.
148              * The reason is that an Edit Box maps the presentation time-line to the media time-line.
149              * Any demuxers should follow the Edit Box if it exists. */
150             GF_ISOSample *sample = gf_isom_get_sample_info( p_mp4->p_file, p_mp4->i_track, 1, NULL, NULL );
151             if( sample && sample->CTS_Offset > 0 )
152             {
153                 uint32_t mvhd_timescale = gf_isom_get_timescale( p_mp4->p_file );
154                 uint64_t tkhd_duration = (uint64_t)( mdhd_duration * ( (double)mvhd_timescale / p_mp4->i_time_res ) );
155                 gf_isom_append_edit_segment( p_mp4->p_file, p_mp4->i_track, tkhd_duration, sample->CTS_Offset, GF_ISOM_EDIT_NORMAL );
156             }
157             gf_isom_sample_del( &sample );
158
159             recompute_bitrate_mp4( p_mp4->p_file, p_mp4->i_track );
160         }
161         gf_isom_set_pl_indication( p_mp4->p_file, GF_ISOM_PL_VISUAL, 0x15 );
162         gf_isom_set_storage_mode( p_mp4->p_file, GF_ISOM_STORE_FLAT );
163         gf_isom_close( p_mp4->p_file );
164     }
165
166     free( p_mp4 );
167
168     return 0;
169 }
170
171 static int open_file( char *psz_filename, hnd_t *p_handle, cli_output_opt_t *opt )
172 {
173     mp4_hnd_t *p_mp4;
174
175     *p_handle = NULL;
176     FILE *fh = fopen( psz_filename, "w" );
177     if( !fh )
178         return -1;
179     FAIL_IF_ERR( !x264_is_regular_file( fh ), "mp4", "MP4 output is incompatible with non-regular file `%s'\n", psz_filename )
180     fclose( fh );
181
182     if( !(p_mp4 = malloc( sizeof(mp4_hnd_t) )) )
183         return -1;
184
185     memset( p_mp4, 0, sizeof(mp4_hnd_t) );
186     p_mp4->p_file = gf_isom_open( psz_filename, GF_ISOM_OPEN_WRITE, NULL );
187
188     p_mp4->b_dts_compress = opt->use_dts_compress;
189
190     if( !(p_mp4->p_sample = gf_isom_sample_new()) )
191     {
192         close_file( p_mp4, 0, 0 );
193         return -1;
194     }
195
196     gf_isom_set_brand_info( p_mp4->p_file, GF_ISOM_BRAND_AVC1, 0 );
197
198     *p_handle = p_mp4;
199
200     return 0;
201 }
202
203 static int set_param( hnd_t handle, x264_param_t *p_param )
204 {
205     mp4_hnd_t *p_mp4 = handle;
206
207     p_mp4->i_delay_frames = p_param->i_bframe ? (p_param->i_bframe_pyramid ? 2 : 1) : 0;
208     p_mp4->i_dts_compress_multiplier = p_mp4->b_dts_compress * p_mp4->i_delay_frames + 1;
209
210     p_mp4->i_time_res = p_param->i_timebase_den * p_mp4->i_dts_compress_multiplier;
211     p_mp4->i_time_inc = p_param->i_timebase_num * p_mp4->i_dts_compress_multiplier;
212     FAIL_IF_ERR( p_mp4->i_time_res > UINT32_MAX, "mp4", "MP4 media timescale %"PRIu64" exceeds maximum\n", p_mp4->i_time_res )
213
214     p_mp4->i_track = gf_isom_new_track( p_mp4->p_file, 0, GF_ISOM_MEDIA_VISUAL,
215                                         p_mp4->i_time_res );
216
217     p_mp4->p_config = gf_odf_avc_cfg_new();
218     gf_isom_avc_config_new( p_mp4->p_file, p_mp4->i_track, p_mp4->p_config,
219                             NULL, NULL, &p_mp4->i_descidx );
220
221     gf_isom_set_track_enabled( p_mp4->p_file, p_mp4->i_track, 1 );
222
223     gf_isom_set_visual_info( p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx,
224                              p_param->i_width, p_param->i_height );
225
226     if( p_param->vui.i_sar_width && p_param->vui.i_sar_height )
227     {
228         uint64_t dw = p_param->i_width << 16;
229         uint64_t dh = p_param->i_height << 16;
230         double sar = (double)p_param->vui.i_sar_width / p_param->vui.i_sar_height;
231         if( sar > 1.0 )
232             dw *= sar ;
233         else
234             dh /= sar;
235         gf_isom_set_pixel_aspect_ratio( p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, p_param->vui.i_sar_width, p_param->vui.i_sar_height );
236         gf_isom_set_track_layout_info( p_mp4->p_file, p_mp4->i_track, dw, dh, 0, 0, 0 );
237     }
238
239     p_mp4->i_data_size = p_param->i_width * p_param->i_height * 3 / 2;
240     p_mp4->p_sample->data = malloc( p_mp4->i_data_size );
241     if( !p_mp4->p_sample->data )
242     {
243         p_mp4->i_data_size = 0;
244         return -1;
245     }
246
247     return 0;
248 }
249
250 static int check_buffer( mp4_hnd_t *p_mp4, int needed_size )
251 {
252     if( needed_size > p_mp4->i_data_size )
253     {
254         void *ptr = realloc( p_mp4->p_sample->data, needed_size );
255         if( !ptr )
256             return -1;
257         p_mp4->p_sample->data = ptr;
258         p_mp4->i_data_size = needed_size;
259     }
260     return 0;
261 }
262
263 static int write_headers( hnd_t handle, x264_nal_t *p_nal )
264 {
265     mp4_hnd_t *p_mp4 = handle;
266     GF_AVCConfigSlot *p_slot;
267
268     int sps_size = p_nal[0].i_payload - 4;
269     int pps_size = p_nal[1].i_payload - 4;
270     int sei_size = p_nal[2].i_payload;
271
272     uint8_t *sps = p_nal[0].p_payload + 4;
273     uint8_t *pps = p_nal[1].p_payload + 4;
274     uint8_t *sei = p_nal[2].p_payload;
275
276     // SPS
277
278     p_mp4->p_config->configurationVersion = 1;
279     p_mp4->p_config->AVCProfileIndication = sps[1];
280     p_mp4->p_config->profile_compatibility = sps[2];
281     p_mp4->p_config->AVCLevelIndication = sps[3];
282     p_slot = malloc( sizeof(GF_AVCConfigSlot) );
283     if( !p_slot )
284         return -1;
285     p_slot->size = sps_size;
286     p_slot->data = malloc( p_slot->size );
287     if( !p_slot->data )
288         return -1;
289     memcpy( p_slot->data, sps, sps_size );
290     gf_list_add( p_mp4->p_config->sequenceParameterSets, p_slot );
291
292     // PPS
293
294     p_slot = malloc( sizeof(GF_AVCConfigSlot) );
295     if( !p_slot )
296         return -1;
297     p_slot->size = pps_size;
298     p_slot->data = malloc( p_slot->size );
299     if( !p_slot->data )
300         return -1;
301     memcpy( p_slot->data, pps, pps_size );
302     gf_list_add( p_mp4->p_config->pictureParameterSets, p_slot );
303     gf_isom_avc_config_update( p_mp4->p_file, p_mp4->i_track, 1, p_mp4->p_config );
304
305     // SEI
306
307     if( check_buffer( p_mp4, p_mp4->p_sample->dataLength + sei_size ) )
308         return -1;
309     memcpy( p_mp4->p_sample->data + p_mp4->p_sample->dataLength, sei, sei_size );
310     p_mp4->p_sample->dataLength += sei_size;
311
312     return sei_size + sps_size + pps_size;
313 }
314
315 static int write_frame( hnd_t handle, uint8_t *p_nalu, int i_size, x264_picture_t *p_picture )
316 {
317     mp4_hnd_t *p_mp4 = handle;
318     int64_t dts;
319     int64_t cts;
320
321     if( check_buffer( p_mp4, p_mp4->p_sample->dataLength + i_size ) )
322         return -1;
323     memcpy( p_mp4->p_sample->data + p_mp4->p_sample->dataLength, p_nalu, i_size );
324     p_mp4->p_sample->dataLength += i_size;
325
326     if( !p_mp4->i_numframe )
327         p_mp4->i_delay_time = p_picture->i_dts * -1;
328
329     if( p_mp4->b_dts_compress )
330     {
331         if( p_mp4->i_numframe == 1 )
332             p_mp4->i_init_delta = (p_picture->i_dts + p_mp4->i_delay_time) * p_mp4->i_time_inc;
333         dts = p_mp4->i_numframe > p_mp4->i_delay_frames
334             ? p_picture->i_dts * p_mp4->i_time_inc
335             : p_mp4->i_numframe * (p_mp4->i_init_delta / p_mp4->i_dts_compress_multiplier);
336         cts = p_picture->i_pts * p_mp4->i_time_inc;
337     }
338     else
339     {
340         dts = (p_picture->i_dts + p_mp4->i_delay_time) * p_mp4->i_time_inc;
341         cts = (p_picture->i_pts + p_mp4->i_delay_time) * p_mp4->i_time_inc;
342     }
343
344     p_mp4->p_sample->IsRAP = p_picture->b_keyframe;
345     p_mp4->p_sample->DTS = dts;
346     p_mp4->p_sample->CTS_Offset = (uint32_t)(cts - dts);
347     gf_isom_add_sample( p_mp4->p_file, p_mp4->i_track, p_mp4->i_descidx, p_mp4->p_sample );
348
349     p_mp4->p_sample->dataLength = 0;
350     p_mp4->i_numframe++;
351
352     return i_size;
353 }
354
355 const cli_output_t mp4_output = { open_file, set_param, write_headers, write_frame, close_file };