OSDN Git Service

8b6c22d07e1aeb867590919a702319a2ec405687
[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 #define DTS_BUFFER_SIZE 32 
27
28 /*
29  * The frame info struct remembers information about each frame across calls
30  * to x264_encoder_encode. Since frames are uniquely identified by their
31  * timestamp, we use some bits of the timestamp as an index. The LSB is
32  * chosen so that two successive frames will have different values in the
33  * bits over any plausible range of frame rates. (Starting with bit 9 allows
34  * any frame rate slower than 175fps.) The MSB determines the size of the array.
35  * It is chosen so that two frames can't use the same slot during the 
36  * encoder's max frame delay (set by the standard as 16 frames) and so
37  * that, up to some minimum frame rate, frames are guaranteed to map to
38  * different slots. (An MSB of 16 which is 2^(16-9+1) = 256 slots guarantees
39  * no collisions down to a rate of 1.4 fps).
40  */
41 #define FRAME_INFO_MAX2 (9)     // 2^9 = 512; 90000/512 = 175 frames/sec
42 #define FRAME_INFO_MIN2 (16)    // 2^16 = 65536; 90000/65536 = 1.4 frames/sec
43 #define FRAME_INFO_SIZE (1 << (FRAME_INFO_MIN2 - FRAME_INFO_MAX2 + 1))
44 #define FRAME_INFO_MASK (FRAME_INFO_SIZE - 1)
45
46 struct hb_work_private_s
47 {
48     hb_job_t       * job;
49     x264_t         * x264;
50     x264_picture_t   pic_in;
51     uint8_t         *x264_allocated_pic;
52
53     int64_t        dts_next;    // DTS start time value for next output frame
54     int64_t        last_stop;   // Debugging - stop time of previous input frame
55     int64_t        init_delay;
56     int64_t        next_chap;
57
58     struct {
59         int64_t duration;
60     } frame_info[FRAME_INFO_SIZE];
61
62     char             filename[1024];
63 };
64
65 /***********************************************************************
66  * hb_work_encx264_init
67  ***********************************************************************
68  *
69  **********************************************************************/
70 int encx264Init( hb_work_object_t * w, hb_job_t * job )
71 {
72     x264_param_t       param;
73     x264_nal_t       * nal;
74     int                nal_count;
75
76     hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) );
77     w->private_data = pv;
78
79     pv->job = job;
80
81     memset( pv->filename, 0, 1024 );
82     hb_get_tempory_filename( job->h, pv->filename, "x264.log" );
83
84     x264_param_default( &param );
85
86     param.i_threads    = ( hb_get_cpu_count() * 3 / 2 );
87     param.i_width      = job->width;
88     param.i_height     = job->height;
89     param.i_fps_num    = job->vrate;
90     param.i_fps_den    = job->vrate_base;
91     
92     if (job->vrate_base != 1080000)
93     {
94         /* If the fps isn't 25, adjust the key intervals. Add 1 because
95            we want 24, not 23 with a truncated remainder.               */
96         param.i_keyint_min     = (job->vrate / job->vrate_base) + 1;
97         param.i_keyint_max = (10 * job->vrate / job->vrate_base) + 1;
98         hb_log("encx264: keyint-min: %i, keyint-max: %i", param.i_keyint_min, param.i_keyint_max);        
99     }
100     
101     param.i_log_level  = X264_LOG_INFO;
102     if( job->h264_level )
103     {
104         param.b_cabac     = 0;
105         param.i_level_idc = job->h264_level;
106         hb_log( "encx264: encoding at level %i",
107                 param.i_level_idc );
108     }
109
110     /* Slightly faster with minimal quality lost */
111     param.analyse.i_subpel_refine = 4;
112
113     /*
114         This section passes the string x264opts to libx264 for parsing into 
115         parameter names and values.
116
117         The string is set up like this:
118         option1=value1:option2=value 2
119
120         So, you have to iterate through based on the colons, and then put 
121         the left side of the equals sign in "name" and the right side into
122         "value." Then you hand those strings off to x264 for interpretation.
123
124         This is all based on the universal x264 option handling Loren
125         Merritt implemented in the Mplayer/Mencoder project.
126      */
127
128     if( job->x264opts != NULL && *job->x264opts != '\0' )
129     {
130         char *x264opts, *x264opts_start;
131
132         x264opts = x264opts_start = strdup(job->x264opts);
133
134         while( x264opts_start && *x264opts )
135         {
136             char *name = x264opts;
137             char *value;
138             int ret;
139
140             x264opts += strcspn( x264opts, ":" );
141             if( *x264opts )
142             {
143                 *x264opts = 0;
144                 x264opts++;
145             }
146
147             value = strchr( name, '=' );
148             if( value )
149             {
150                 *value = 0;
151                 value++;
152             }
153
154             /*
155                When B-frames are enabled, the max frame count increments
156                by 1 (regardless of the number of B-frames). If you don't
157                change the duration of the video track when you mux, libmp4
158                barfs.  So, check if the x264opts are using B-frames, and
159                when they are, set the boolean job->areBframes as true.
160              */
161
162             if( !( strcmp( name, "bframes" ) ) )
163             {
164                 if( atoi( value ) > 0 )
165                 {
166                     job->areBframes = 1;
167                 }
168             }
169
170             /* Note b-pyramid here, so the initial delay can be doubled */
171             if( !( strcmp( name, "b-pyramid" ) ) )
172             {
173                 if( value != NULL )
174                 {
175                     if( atoi( value ) > 0 )
176                     {
177                         job->areBframes = 2;
178                     }
179                 }
180                 else
181                 {
182                     job->areBframes = 2;
183                 }
184             }
185
186             /* Here's where the strings are passed to libx264 for parsing. */
187             ret = x264_param_parse( &param, name, value );
188
189             /*  Let x264 sanity check the options for us*/
190             if( ret == X264_PARAM_BAD_NAME )
191                 hb_log( "x264 options: Unknown suboption %s", name );
192             if( ret == X264_PARAM_BAD_VALUE )
193                 hb_log( "x264 options: Bad argument %s=%s", name, value ? value : "(null)" );
194         }
195         free(x264opts_start);
196     }
197
198
199     if( job->pixel_ratio )
200     {
201         param.vui.i_sar_width = job->pixel_aspect_width;
202         param.vui.i_sar_height = job->pixel_aspect_height;
203
204         hb_log( "encx264: encoding with stored aspect %d/%d",
205                 param.vui.i_sar_width, param.vui.i_sar_height );
206     }
207
208
209     if( job->vquality >= 0.0 && job->vquality <= 1.0 )
210     {
211         switch( job->crf )
212         {
213             case 1:
214                 /*Constant RF*/
215                 param.rc.i_rc_method = X264_RC_CRF;
216                 param.rc.f_rf_constant = 51 - job->vquality * 51;
217                 hb_log( "encx264: Encoding at constant RF %f",
218                         param.rc.f_rf_constant );
219                 break;
220
221             case 0:
222                 /*Constant QP*/
223                 param.rc.i_rc_method = X264_RC_CQP;
224                 param.rc.i_qp_constant = 51 - job->vquality * 51;
225                 hb_log( "encx264: encoding at constant QP %d",
226                         param.rc.i_qp_constant );
227                 break;
228         }
229     }
230     else
231     {
232         /* Rate control */
233         param.rc.i_rc_method = X264_RC_ABR;
234         param.rc.i_bitrate = job->vbitrate;
235         switch( job->pass )
236         {
237             case 1:
238                 param.rc.b_stat_write  = 1;
239                 param.rc.psz_stat_out = pv->filename;
240                 break;
241             case 2:
242                 param.rc.b_stat_read = 1;
243                 param.rc.psz_stat_in = pv->filename;
244                 break;
245         }
246     }
247
248     hb_log( "encx264: opening libx264 (pass %d)", job->pass );
249     pv->x264 = x264_encoder_open( &param );
250
251     x264_encoder_headers( pv->x264, &nal, &nal_count );
252
253     /* Sequence Parameter Set */
254     w->config->h264.sps_length = 1 + nal[1].i_payload;
255     w->config->h264.sps[0] = 0x67;
256     memcpy( &w->config->h264.sps[1], nal[1].p_payload, nal[1].i_payload );
257
258     /* Picture Parameter Set */
259     w->config->h264.pps_length = 1 + nal[2].i_payload;
260     w->config->h264.pps[0] = 0x68;
261     memcpy( &w->config->h264.pps[1], nal[2].p_payload, nal[2].i_payload );
262
263     x264_picture_alloc( &pv->pic_in, X264_CSP_I420,
264                         job->width, job->height );
265
266     pv->x264_allocated_pic = pv->pic_in.img.plane[0];
267
268     pv->dts_next = -1;
269     pv->next_chap = 0;
270
271     if (job->areBframes)
272     {
273         /* Basic initDelay value is the clockrate divided by the FPS
274            -- the length of one frame in clockticks.                  */
275         pv->init_delay = (float)90000 / (float)((float)job->vrate / (float)job->vrate_base);
276        
277         /* 23.976-length frames are 3753.75 ticks long. That means 25%
278            will come out as 3753, 75% will be 3754. The delay has to be
279            the longest possible frame duration, 3754. However, 3753.75
280            gets truncated to 3753, so if that's what it is, ++ it.     */
281         if (pv->init_delay == 3753)
282             pv->init_delay++;
283        
284         /* For VFR, libhb sees the FPS as 29.97, but the longest frames
285            will use the duration of frames running at 23.976fps instead.. */
286         if (job->vfr)
287         {
288             pv->init_delay = 7506;
289         }
290    
291         /* The delay is 2 frames for regular b-frames, 3 for b-pyramid.
292            Since job->areBframes is 1 for b-frames and 2 for b-pyramid,
293            add one to it and use it as a multiplier.                    */
294         pv->init_delay *= ( job->areBframes + 1);
295     }
296
297     return 0;
298 }
299
300 void encx264Close( hb_work_object_t * w )
301 {
302     hb_work_private_t * pv = w->private_data;
303     /*
304      * Patch the x264 allocated data back in so that x264 can free it
305      * we have been using our own buffers during the encode to avoid copying.
306      */
307     pv->pic_in.img.plane[0] = pv->x264_allocated_pic;
308     x264_picture_clean( &pv->pic_in );
309     x264_encoder_close( pv->x264 );
310     free( pv );
311     w->private_data = NULL;
312
313     /* TODO */
314 }
315
316 /*
317  * see comments in definition of 'frame_info' in pv struct for description
318  * of what these routines are doing.
319  */
320 static void save_frame_info( hb_work_private_t * pv, hb_buffer_t * in )
321 {
322     int i = (in->start >> FRAME_INFO_MAX2) & FRAME_INFO_MASK;
323     pv->frame_info[i].duration = in->stop - in->start;
324 }
325
326 static int64_t get_frame_duration( hb_work_private_t * pv, int64_t pts )
327 {
328     int i = (pts >> FRAME_INFO_MAX2) & FRAME_INFO_MASK;
329     return pv->frame_info[i].duration;
330 }
331
332 int encx264Work( hb_work_object_t * w, hb_buffer_t ** buf_in,
333                   hb_buffer_t ** buf_out )
334 {
335     hb_work_private_t * pv = w->private_data;
336     hb_job_t    * job = pv->job;
337     hb_buffer_t * in = *buf_in, * buf;
338     x264_picture_t   pic_out;
339     int           i_nal;
340     x264_nal_t  * nal;
341     int i;
342
343     if( in->data )
344     {
345         /*
346          * Point x264 at our current buffers Y(UV) data.
347          */
348         pv->pic_in.img.plane[0] = in->data;
349
350         if( job->grayscale )
351         {
352             /* XXX x264 has currently no option for grayscale encoding */
353             memset( pv->pic_in.img.plane[1], 0x80, job->width * job->height / 4 );
354             memset( pv->pic_in.img.plane[2], 0x80, job->width * job->height / 4 );
355         }
356         else
357         {
358             /*
359              * Point x264 at our buffers (Y)UV data
360              */
361             pv->pic_in.img.plane[1] = in->data + job->width * job->height;
362             pv->pic_in.img.plane[2] = in->data + 5 * job->width *
363                 job->height / 4;
364         }
365
366         if( pv->dts_next == -1 )
367         {
368             /* we don't have a start time yet so use the first frame's 
369              * start. All other frame times will be determined by the
370              * sum of the prior output frame durations in *DTS* order
371              * (not by the order they arrive here). This timing change is
372              * essential for VFR with b-frames but a complete nop otherwise.
373              */
374             pv->dts_next = in->start;
375         }
376         if( in->new_chap && job->chapter_markers )
377         {
378             /* chapters have to start with an IDR frame so request that this
379                frame be coded as IDR. Since there may be up to 16 frames
380                currently buffered in the encoder remember the timestamp so
381                when this frame finally pops out of the encoder we'll mark
382                its buffer as the start of a chapter. */
383             pv->pic_in.i_type = X264_TYPE_IDR;
384             if( pv->next_chap == 0 )
385             {
386                 pv->next_chap = in->start;
387             }
388             /* don't let 'work_loop' put a chapter mark on the wrong buffer */
389             in->new_chap = 0;
390         }
391         else
392         {
393             pv->pic_in.i_type = X264_TYPE_AUTO;
394         }
395         pv->pic_in.i_qpplus1 = 0;
396
397         /* XXX this is temporary debugging code to check that the upstream
398          * modules (render & sync) have generated a continuous, self-consistent
399          * frame stream with the current frame's start time equal to the
400          * previous frame's stop time.
401          */
402         if( pv->last_stop != in->start )
403         {
404             hb_log("encx264 input continuity err: last stop %lld  start %lld",
405                     pv->last_stop, in->start);
406         }
407         pv->last_stop = in->stop;
408
409         // Remember info about this frame that we need to pass across 
410         // the x264_encoder_encode call (since it reorders frames).
411         save_frame_info( pv, in );
412
413         /* Feed the input DTS to x264 so it can figure out proper output PTS */
414         pv->pic_in.i_pts = in->start;
415
416         x264_encoder_encode( pv->x264, &nal, &i_nal,
417                              &pv->pic_in, &pic_out );        
418     }
419     else
420     {
421         x264_encoder_encode( pv->x264, &nal, &i_nal,
422                              NULL, &pic_out );
423         /* No more delayed B frames */
424         if( i_nal == 0 )
425         {
426             *buf_out = NULL;
427             return HB_WORK_DONE;
428         }
429         else
430         {
431         /*  Since we output at least one more frame, drop another empty
432             one onto our input fifo.  We'll keep doing this automatically
433             until we stop getting frames out of the encoder. */
434             hb_fifo_push(w->fifo_in, hb_buffer_init(0));
435         }
436     }
437
438     if( i_nal )
439     {
440         /* Should be way too large */
441         buf        = hb_buffer_init( 3 * job->width * job->height / 2 );
442         buf->size  = 0;
443         buf->frametype   = 0;
444
445         /* Get next DTS value to use */
446         int64_t dts_start = pv->dts_next;
447
448         /* compute the stop time based on the original frame's duration */
449         int64_t dts_stop  = dts_start + get_frame_duration( pv, pic_out.i_pts );
450         pv->dts_next = dts_stop;
451
452         for( i = 0; i < i_nal; i++ )
453         {
454             int size, data;
455
456             data = buf->alloc - buf->size;
457             if( ( size = x264_nal_encode( buf->data + buf->size, &data,
458                                           1, &nal[i] ) ) < 1 )
459             {
460                 continue;
461             }
462
463             if( job->mux & HB_MUX_AVI )
464             {
465                 if( nal[i].i_ref_idc == NAL_PRIORITY_HIGHEST )
466                 {
467                     buf->frametype = HB_FRAME_KEY;
468                 }
469                 buf->size += size;
470                 continue;
471             }
472
473             /* H.264 in .mp4 */
474             switch( buf->data[buf->size+4] & 0x1f )
475             {
476                 case 0x7:
477                 case 0x8:
478                     /* SPS, PPS */
479                     break;
480
481                 default:
482                     /* H.264 in mp4 (stolen from mp4creator) */
483                     buf->data[buf->size+0] = ( ( size - 4 ) >> 24 ) & 0xFF;
484                     buf->data[buf->size+1] = ( ( size - 4 ) >> 16 ) & 0xFF;
485                     buf->data[buf->size+2] = ( ( size - 4 ) >>  8 ) & 0xFF;
486                     buf->data[buf->size+3] = ( ( size - 4 ) >>  0 ) & 0xFF;
487                     switch( pic_out.i_type )
488                     {
489                     /*  Decide what type of frame we have. */
490                         case X264_TYPE_IDR:
491                             buf->frametype = HB_FRAME_IDR;
492                             /* if we have a chapter marker pending and this
493                                frame's presentation time stamp is at or after
494                                the marker's time stamp, use this as the
495                                chapter start. */
496                             if( pv->next_chap != 0 && pv->next_chap <= pic_out.i_pts )
497                             {
498                                 pv->next_chap = 0;
499                                 buf->new_chap = 1;
500                             }
501                             break;
502                         case X264_TYPE_I:
503                             buf->frametype = HB_FRAME_I;
504                             break;
505                         case X264_TYPE_P:
506                             buf->frametype = HB_FRAME_P;
507                             break;
508                         case X264_TYPE_B:
509                             buf->frametype = HB_FRAME_B;
510                             break;
511                     /*  This is for b-pyramid, which has reference b-frames
512                         However, it doesn't seem to ever be used... */
513                         case X264_TYPE_BREF:
514                             buf->frametype = HB_FRAME_BREF;
515                             break;
516                     /*  If it isn't the above, what type of frame is it?? */
517                         default:
518                             buf->frametype = 0;
519                     }
520
521
522                     /* Store the output presentation time stamp
523                        from x264 for use by muxmp4 in off-setting
524                        b-frames with the CTTS atom. */
525                     buf->renderOffset = pic_out.i_pts - dts_start + pv->init_delay;
526
527                     /* Send out the next dts values */
528                     buf->start = dts_start;
529                     buf->stop  = dts_stop;
530
531                     buf->size += size;
532             }
533         }
534     }
535
536     else
537         buf = NULL;
538
539     *buf_out = buf;
540
541     return HB_WORK_OK;
542 }