OSDN Git Service

Fixes encx264.c from rev 994 to avoid crasing with 2pass and auto select / forced...
[handbrake-jp/handbrake-jp-git.git] / libhb / encx264.c
1 /* $Id: encx264.c,v 1.21 2005/11/04 13:09:41 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.m0k.org/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include <stdarg.h>
8
9 #include "hb.h"
10
11 #include "x264.h"
12
13 int  encx264Init( hb_work_object_t *, hb_job_t * );
14 int  encx264Work( hb_work_object_t *, hb_buffer_t **, hb_buffer_t ** );
15 void encx264Close( hb_work_object_t * );
16
17 hb_work_object_t hb_encx264 =
18 {
19     WORK_ENCX264,
20     "H.264/AVC encoder (libx264)",
21     encx264Init,
22     encx264Work,
23     encx264Close
24 };
25
26 // 16 is probably overkill but it's also the maximum for h.264 reference frames
27 #define MAX_INFLIGHT_FRAMES 16
28
29 struct hb_work_private_s
30 {
31     hb_job_t       * job;
32     x264_t         * x264;
33     x264_picture_t   pic_in;
34
35     // Internal queue of DTS start/stop values.
36     int64_t        dts_start[MAX_INFLIGHT_FRAMES];
37     int64_t        dts_stop[MAX_INFLIGHT_FRAMES];
38
39     int64_t        dts_write_index;
40     int64_t        dts_read_index;
41     int64_t        next_chap;
42
43     char             filename[1024];
44 };
45
46 /***********************************************************************
47  * hb_work_encx264_init
48  ***********************************************************************
49  *
50  **********************************************************************/
51 int encx264Init( hb_work_object_t * w, hb_job_t * job )
52 {
53     x264_param_t       param;
54     x264_nal_t       * nal;
55     int                nal_count;
56
57     hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) );
58     w->private_data = pv;
59
60     pv->job = job;
61
62     memset( pv->filename, 0, 1024 );
63     hb_get_tempory_filename( job->h, pv->filename, "x264.log" );
64
65     x264_param_default( &param );
66
67     param.i_threads    = ( hb_get_cpu_count() * 3 / 2 );
68     param.i_width      = job->width;
69     param.i_height     = job->height;
70     param.i_fps_num    = job->vrate;
71     param.i_fps_den    = job->vrate_base;
72     param.i_keyint_max = 20 * job->vrate / job->vrate_base;
73     param.i_log_level  = X264_LOG_INFO;
74     if( job->h264_level )
75     {
76         param.b_cabac     = 0;
77         param.i_level_idc = job->h264_level;
78         hb_log( "encx264: encoding at level %i",
79                 param.i_level_idc );
80     }
81
82     /* Slightly faster with minimal quality lost */
83     param.analyse.i_subpel_refine = 4;
84
85     /*
86         This section passes the string x264opts to libx264 for parsing into 
87         parameter names and values.
88
89         The string is set up like this:
90         option1=value1:option2=value 2
91
92         So, you have to iterate through based on the colons, and then put 
93         the left side of the equals sign in "name" and the right side into
94         "value." Then you hand those strings off to x264 for interpretation.
95
96         This is all based on the universal x264 option handling Loren
97         Merritt implemented in the Mplayer/Mencoder project.
98      */
99
100     if( job->x264opts != NULL && *job->x264opts != '\0' )
101     {
102         char *x264opts = strdup(job->x264opts);
103         while( *x264opts )
104         {
105             char *name = x264opts;
106             char *value;
107             int ret;
108
109             x264opts += strcspn( x264opts, ":" );
110             if( *x264opts )
111             {
112                 *x264opts = 0;
113                 x264opts++;
114             }
115
116             value = strchr( name, '=' );
117             if( value )
118             {
119                 *value = 0;
120                 value++;
121             }
122
123             /*
124                When B-frames are enabled, the max frame count increments
125                by 1 (regardless of the number of B-frames). If you don't
126                change the duration of the video track when you mux, libmp4
127                barfs.  So, check if the x264opts are using B-frames, and
128                when they are, set the boolean job->areBframes as true.
129              */
130
131             if( !( strcmp( name, "bframes" ) ) )
132             {
133                 if( atoi( value ) > 0 )
134                 {
135                     job->areBframes = 1;
136                 }
137             }
138
139             /* Note b-pyramid here, so the initial delay can be doubled */
140             if( !( strcmp( name, "b-pyramid" ) ) )
141             {
142                 if( value != NULL )
143                 {
144                     if( atoi( value ) > 0 )
145                     {
146                         job->areBframes = 2;
147                     }
148                 }
149                 else
150                 {
151                     job->areBframes = 2;
152                 }
153             }
154
155             /* Here's where the strings are passed to libx264 for parsing. */
156             ret = x264_param_parse( &param, name, value );
157
158             /*  Let x264 sanity check the options for us*/
159             if( ret == X264_PARAM_BAD_NAME )
160                 hb_log( "x264 options: Unknown suboption %s", name );
161             if( ret == X264_PARAM_BAD_VALUE )
162                 hb_log( "x264 options: Bad argument %s=%s", name, value ? value : "(null)" );
163         }
164         free(x264opts);
165     }
166
167
168     if( job->pixel_ratio )
169     {
170         param.vui.i_sar_width = job->pixel_aspect_width;
171         param.vui.i_sar_height = job->pixel_aspect_height;
172
173         hb_log( "encx264: encoding with stored aspect %d/%d",
174                 param.vui.i_sar_width, param.vui.i_sar_height );
175     }
176
177
178     if( job->vquality >= 0.0 && job->vquality <= 1.0 )
179     {
180         switch( job->crf )
181         {
182             case 1:
183                 /*Constant RF*/
184                 param.rc.i_rc_method = X264_RC_CRF;
185                 param.rc.f_rf_constant = 51 - job->vquality * 51;
186                 hb_log( "encx264: Encoding at constant RF %f",
187                         param.rc.f_rf_constant );
188                 break;
189
190             case 0:
191                 /*Constant QP*/
192                 param.rc.i_rc_method = X264_RC_CQP;
193                 param.rc.i_qp_constant = 51 - job->vquality * 51;
194                 hb_log( "encx264: encoding at constant QP %d",
195                         param.rc.i_qp_constant );
196                 break;
197         }
198     }
199     else
200     {
201         /* Rate control */
202         param.rc.i_rc_method = X264_RC_ABR;
203         param.rc.i_bitrate = job->vbitrate;
204         switch( job->pass )
205         {
206             case 1:
207                 param.rc.b_stat_write  = 1;
208                 param.rc.psz_stat_out = pv->filename;
209                 break;
210             case 2:
211                 param.rc.b_stat_read = 1;
212                 param.rc.psz_stat_in = pv->filename;
213                 break;
214         }
215     }
216
217     hb_log( "encx264: opening libx264 (pass %d)", job->pass );
218     pv->x264 = x264_encoder_open( &param );
219
220     x264_encoder_headers( pv->x264, &nal, &nal_count );
221
222     /* Sequence Parameter Set */
223     w->config->h264.sps_length = 1 + nal[1].i_payload;
224     w->config->h264.sps[0] = 0x67;
225     memcpy( &w->config->h264.sps[1], nal[1].p_payload, nal[1].i_payload );
226
227     /* Picture Parameter Set */
228     w->config->h264.pps_length = 1 + nal[2].i_payload;
229     w->config->h264.pps[0] = 0x68;
230     memcpy( &w->config->h264.pps[1], nal[2].p_payload, nal[2].i_payload );
231
232     x264_picture_alloc( &pv->pic_in, X264_CSP_I420,
233             job->width, job->height );
234
235     pv->dts_write_index = 0;
236     pv->dts_read_index = 0;
237     pv->next_chap = 0;
238
239     return 0;
240 }
241
242 void encx264Close( hb_work_object_t * w )
243 {
244     hb_work_private_t * pv = w->private_data;
245     x264_picture_clean( &pv->pic_in );
246     x264_encoder_close( pv->x264 );
247     free( pv );
248     w->private_data = NULL;
249
250     /* TODO */
251 }
252
253 int encx264Work( hb_work_object_t * w, hb_buffer_t ** buf_in,
254                   hb_buffer_t ** buf_out )
255 {
256     hb_work_private_t * pv = w->private_data;
257     hb_job_t    * job = pv->job;
258     hb_buffer_t * in = *buf_in, * buf;
259     x264_picture_t   pic_out;
260     int           i_nal;
261     x264_nal_t  * nal;
262     int i;
263
264     if( in->data )
265     {
266         /* XXX avoid this memcpy ? */
267         memcpy( pv->pic_in.img.plane[0], in->data, job->width * job->height );
268         if( job->grayscale )
269         {
270             /* XXX x264 has currently no option for grayscale encoding */
271             memset( pv->pic_in.img.plane[1], 0x80, job->width * job->height / 4 );
272             memset( pv->pic_in.img.plane[2], 0x80, job->width * job->height / 4 );
273         }
274         else
275         {
276             memcpy( pv->pic_in.img.plane[1], in->data + job->width * job->height,
277                     job->width * job->height / 4 );
278             memcpy( pv->pic_in.img.plane[2], in->data + 5 * job->width *
279                     job->height / 4, job->width * job->height / 4 );
280         }
281
282         if( in->new_chap && job->chapter_markers )
283         {
284             /* chapters have to start with an IDR frame so request that this
285                frame be coded as IDR. Since there may be up to 16 frames
286                currently buffered in the encoder remember the timestamp so
287                when this frame finally pops out of the encoder we'll mark
288                its buffer as the start of a chapter. */
289             pv->pic_in.i_type = X264_TYPE_IDR;
290             if( pv->next_chap == 0 )
291             {
292                 pv->next_chap = in->start;
293             }
294             /* don't let 'work_loop' put a chapter mark on the wrong buffer */
295             in->new_chap = 0;
296         }
297         else
298         {
299             pv->pic_in.i_type = X264_TYPE_AUTO;
300         }
301         pv->pic_in.i_qpplus1 = 0;
302
303         // Remember current PTS value, use as DTS later
304         pv->dts_start[pv->dts_write_index & (MAX_INFLIGHT_FRAMES-1)] = in->start;
305         pv->dts_stop[pv->dts_write_index & (MAX_INFLIGHT_FRAMES-1)]  = in->stop;
306         pv->dts_write_index++;
307
308         /* Feed the input DTS to x264 so it can figure out proper output PTS */
309         pv->pic_in.i_pts = in->start;
310
311         x264_encoder_encode( pv->x264, &nal, &i_nal,
312                              &pv->pic_in, &pic_out );        
313     }
314     else
315     {
316         x264_encoder_encode( pv->x264, &nal, &i_nal,
317                              NULL, &pic_out );
318         /* No more delayed B frames */
319         if( i_nal == 0 )
320         {
321             *buf_out = NULL;
322             return HB_WORK_DONE;
323         }
324         else
325         {
326         /*  Since we output at least one more frame, drop another empty
327             one onto our input fifo.  We'll keep doing this automatically
328             until we stop getting frames out of the encoder. */
329             hb_fifo_push(w->fifo_in, hb_buffer_init(0));
330         }
331     }
332
333     if( i_nal )
334     {
335         /* Should be way too large */
336         buf        = hb_buffer_init( 3 * job->width * job->height / 2 );
337         buf->size  = 0;
338         buf->start = in->start;
339         buf->stop  = in->stop;
340         buf->frametype   = 0;
341
342         int64_t dts_start, dts_stop;
343
344         /* Get next DTS value to use */
345         dts_start = pv->dts_start[pv->dts_read_index & (MAX_INFLIGHT_FRAMES-1)];
346         dts_stop  = pv->dts_stop[pv->dts_read_index & (MAX_INFLIGHT_FRAMES-1)];
347         pv->dts_read_index++;
348
349         for( i = 0; i < i_nal; i++ )
350         {
351             int size, data;
352
353             data = buf->alloc - buf->size;
354             if( ( size = x264_nal_encode( buf->data + buf->size, &data,
355                                           1, &nal[i] ) ) < 1 )
356             {
357                 continue;
358             }
359
360             if( job->mux & HB_MUX_AVI )
361             {
362                 if( nal[i].i_ref_idc == NAL_PRIORITY_HIGHEST )
363                 {
364                     buf->frametype = HB_FRAME_KEY;
365                 }
366                 buf->size += size;
367                 continue;
368             }
369
370             /* H.264 in .mp4 */
371             switch( buf->data[buf->size+4] & 0x1f )
372             {
373                 case 0x7:
374                 case 0x8:
375                     /* SPS, PPS */
376                     break;
377
378                 default:
379                     /* H.264 in mp4 (stolen from mp4creator) */
380                     buf->data[buf->size+0] = ( ( size - 4 ) >> 24 ) & 0xFF;
381                     buf->data[buf->size+1] = ( ( size - 4 ) >> 16 ) & 0xFF;
382                     buf->data[buf->size+2] = ( ( size - 4 ) >>  8 ) & 0xFF;
383                     buf->data[buf->size+3] = ( ( size - 4 ) >>  0 ) & 0xFF;
384                     switch( pic_out.i_type )
385                     {
386                     /*  Decide what type of frame we have. */
387                         case X264_TYPE_IDR:
388                             buf->frametype = HB_FRAME_IDR;
389                             /* if we have a chapter marker pending and this
390                                frame's presentation time stamp is at or after
391                                the marker's time stamp, use this as the
392                                chapter start. */
393                             if( pv->next_chap != 0 && pv->next_chap <= pic_out.i_pts )
394                             {
395                                 pv->next_chap = 0;
396                                 buf->new_chap = 1;
397                             }
398                             break;
399                         case X264_TYPE_I:
400                             buf->frametype = HB_FRAME_I;
401                             break;
402                         case X264_TYPE_P:
403                             buf->frametype = HB_FRAME_P;
404                             break;
405                         case X264_TYPE_B:
406                             buf->frametype = HB_FRAME_B;
407                             break;
408                     /*  This is for b-pyramid, which has reference b-frames
409                         However, it doesn't seem to ever be used... */
410                         case X264_TYPE_BREF:
411                             buf->frametype = HB_FRAME_BREF;
412                             break;
413                     /*  If it isn't the above, what type of frame is it?? */
414                         default:
415                             buf->frametype = 0;
416                     }
417
418
419                     /* Store the output presentation time stamp
420                        from x264 for use by muxmp4 in off-setting
421                        b-frames with the CTTS atom.
422                        For now, just add 1000000 to the offset so that the
423                        value is pretty much guaranteed to be positive.  The
424                        muxing code will minimize the renderOffset at the end. */
425
426                     buf->renderOffset = pic_out.i_pts - dts_start + 1000000;
427
428                     /* Send out the next dts values */
429                     buf->start = dts_start;
430                     buf->stop  = dts_stop;
431
432                     buf->size += size;
433             }
434         }
435     }
436
437     else
438         buf = NULL;
439
440     *buf_out = buf;
441
442     return HB_WORK_OK;
443 }
444
445