OSDN Git Service

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