OSDN Git Service

0bc1546ffb84a2cdfdb9197bb2ab34843736685a
[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 8 allows
34  * any frame rate slower than 352fps.) 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 17 which is 2^(17-8+1) = 1024 slots guarantees
39  * no collisions down to a rate of .7 fps).
40  */
41 #define FRAME_INFO_MAX2 (8)     // 2^8 = 256; 90000/256 = 352 frames/sec
42 #define FRAME_INFO_MIN2 (17)    // 2^17 = 128K; 90000/131072 = 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        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     int                nal_size;
76
77     hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) );
78     w->private_data = pv;
79
80     pv->job = job;
81
82     memset( pv->filename, 0, 1024 );
83     hb_get_tempory_filename( job->h, pv->filename, "x264.log" );
84
85     x264_param_default( &param );
86
87     param.i_threads    = ( hb_get_cpu_count() * 3 / 2 );
88     param.i_width      = job->width;
89     param.i_height     = job->height;
90     param.i_fps_num    = job->vrate;
91     param.i_fps_den    = job->vrate_base;
92
93     /* Set min:max key intervals ratio to 1:10 of fps.
94      * This section is skipped if fps=25 (default).
95      */
96     if (job->vrate_base != 1080000)
97     {
98         int fps = job->vrate / job->vrate_base;
99
100         /* adjust +1 when fps has remainder to bump { 23.976, 29.976, 59.94 } to { 24, 30, 60 } */
101         if (job->vrate % job->vrate_base)
102             fps += 1;
103
104         param.i_keyint_min = fps;
105         param.i_keyint_max = fps * 10;
106
107         hb_log("encx264: keyint-min: %i, keyint-max: %i", param.i_keyint_min, param.i_keyint_max);
108     }
109
110     param.i_log_level  = X264_LOG_INFO;
111     if( job->h264_level )
112     {
113         param.b_cabac     = 0;
114         param.i_level_idc = job->h264_level;
115         hb_log( "encx264: encoding at level %i",
116                 param.i_level_idc );
117     }
118
119     /*
120         This section passes the string x264opts to libx264 for parsing into
121         parameter names and values.
122
123         The string is set up like this:
124         option1=value1:option2=value 2
125
126         So, you have to iterate through based on the colons, and then put
127         the left side of the equals sign in "name" and the right side into
128         "value." Then you hand those strings off to x264 for interpretation.
129
130         This is all based on the universal x264 option handling Loren
131         Merritt implemented in the Mplayer/Mencoder project.
132      */
133
134     if( job->x264opts != NULL && *job->x264opts != '\0' )
135     {
136         char *x264opts, *x264opts_start;
137
138         x264opts = x264opts_start = strdup(job->x264opts);
139
140         while( x264opts_start && *x264opts )
141         {
142             char *name = x264opts;
143             char *value;
144             int ret;
145
146             x264opts += strcspn( x264opts, ":" );
147             if( *x264opts )
148             {
149                 *x264opts = 0;
150                 x264opts++;
151             }
152
153             value = strchr( name, '=' );
154             if( value )
155             {
156                 *value = 0;
157                 value++;
158             }
159
160             /*
161                When B-frames are enabled, the max frame count increments
162                by 1 (regardless of the number of B-frames). If you don't
163                change the duration of the video track when you mux, libmp4
164                barfs.  So, check if the x264opts are using B-frames, and
165                when they are, set the boolean job->areBframes as true.
166              */
167
168             if( !( strcmp( name, "bframes" ) ) )
169             {
170                 if( atoi( value ) > 0 )
171                 {
172                     job->areBframes = 1;
173                 }
174             }
175
176             /* Note b-pyramid here, so the initial delay can be doubled */
177             if( !( strcmp( name, "b-pyramid" ) ) )
178             {
179                 if( value != NULL )
180                 {
181                     if( atoi( value ) > 0 )
182                     {
183                         job->areBframes = 2;
184                     }
185                 }
186                 else
187                 {
188                     job->areBframes = 2;
189                 }
190             }
191
192             /* Here's where the strings are passed to libx264 for parsing. */
193             ret = x264_param_parse( &param, name, value );
194
195             /*  Let x264 sanity check the options for us*/
196             if( ret == X264_PARAM_BAD_NAME )
197                 hb_log( "x264 options: Unknown suboption %s", name );
198             if( ret == X264_PARAM_BAD_VALUE )
199                 hb_log( "x264 options: Bad argument %s=%s", name, value ? value : "(null)" );
200         }
201         free(x264opts_start);
202     }
203
204     /* set up the VUI color model & gamma to match what the COLR atom
205      * set in muxmp4.c says. See libhb/muxmp4.c for notes. */
206     if( job->color_matrix == 1 )
207     {
208         // ITU BT.601 DVD or SD TV content
209         param.vui.i_colorprim = 6;
210         param.vui.i_transfer = 1;
211         param.vui.i_colmatrix = 6;
212     }
213     else if( job->color_matrix == 2 )
214     {
215         // ITU BT.709 HD content
216         param.vui.i_colorprim = 1;
217         param.vui.i_transfer = 1;
218         param.vui.i_colmatrix = 1;
219     }
220     else if ( job->title->width >= 1280 || job->title->height >= 720 )
221     {
222         // we guess that 720p or above is ITU BT.709 HD content
223         param.vui.i_colorprim = 1;
224         param.vui.i_transfer = 1;
225         param.vui.i_colmatrix = 1;
226     }
227     else
228     {
229         // ITU BT.601 DVD or SD TV content
230         param.vui.i_colorprim = 6;
231         param.vui.i_transfer = 1;
232         param.vui.i_colmatrix = 6;
233     }
234
235     if( job->anamorphic.mode )
236     {
237         param.vui.i_sar_width  = job->anamorphic.par_width;
238         param.vui.i_sar_height = job->anamorphic.par_height;
239
240         hb_log( "encx264: encoding with stored aspect %d/%d",
241                 param.vui.i_sar_width, param.vui.i_sar_height );
242     }
243
244
245     if( job->vquality > 0.0 && job->vquality < 1.0 )
246     {
247         switch( job->crf )
248         {
249             case 1:
250                 /*Constant RF*/
251                 param.rc.i_rc_method = X264_RC_CRF;
252                 param.rc.f_rf_constant = 51 - job->vquality * 51;
253                 hb_log( "encx264: Encoding at constant RF %f",
254                         param.rc.f_rf_constant );
255                 break;
256
257             case 0:
258                 /*Constant QP*/
259                 param.rc.i_rc_method = X264_RC_CQP;
260                 param.rc.i_qp_constant = 51 - job->vquality * 51;
261                 hb_log( "encx264: encoding at constant QP %d",
262                         param.rc.i_qp_constant );
263                 break;
264         }
265     }
266     else if( job->vquality == 0 || job->vquality >= 1.0 )
267     {
268         /* Use the vquality as a raw RF or QP
269           instead of treating it like a percentage. */
270         switch( job->crf )
271         {
272             case 1:
273                 /*Constant RF*/
274                 param.rc.i_rc_method = X264_RC_CRF;
275                 param.rc.f_rf_constant = job->vquality;
276                 hb_log( "encx264: Encoding at constant RF %f",
277                         param.rc.f_rf_constant );
278                 break;
279
280             case 0:
281                 /*Constant QP*/
282                 param.rc.i_rc_method = X264_RC_CQP;
283                 param.rc.i_qp_constant = job->vquality;
284                 hb_log( "encx264: encoding at constant QP %d",
285                         param.rc.i_qp_constant );
286                 break;
287         }        
288     }
289     else
290     {
291         /* Rate control */
292         param.rc.i_rc_method = X264_RC_ABR;
293         param.rc.i_bitrate = job->vbitrate;
294         switch( job->pass )
295         {
296             case 1:
297                 param.rc.b_stat_write  = 1;
298                 param.rc.psz_stat_out = pv->filename;
299                 break;
300             case 2:
301                 param.rc.b_stat_read = 1;
302                 param.rc.psz_stat_in = pv->filename;
303                 break;
304         }
305     }
306
307     hb_deep_log( 2, "encx264: opening libx264 (pass %d)", job->pass );
308     pv->x264 = x264_encoder_open( &param );
309
310     x264_encoder_headers( pv->x264, &nal, &nal_count );
311
312     /* Sequence Parameter Set */
313     x264_nal_encode( w->config->h264.sps, &nal_size, 0, &nal[1] );
314     w->config->h264.sps_length = nal_size;
315
316     /* Picture Parameter Set */
317     x264_nal_encode( w->config->h264.pps, &nal_size, 0, &nal[2] );
318     w->config->h264.pps_length = nal_size;
319
320     x264_picture_alloc( &pv->pic_in, X264_CSP_I420,
321                         job->width, job->height );
322
323     pv->pic_in.img.i_stride[2] = pv->pic_in.img.i_stride[1] = ( ( job->width + 1 ) >> 1 );
324     pv->x264_allocated_pic = pv->pic_in.img.plane[0];
325
326     if (job->areBframes)
327     {
328         /* Basic initDelay value is the clockrate divided by the FPS
329            -- the length of one frame in clockticks.                  */
330         pv->init_delay = 90000. / ((double)job->vrate / (double)job->vrate_base);
331
332         /* 23.976-length frames are 3753.75 ticks long on average but the DVD
333            creates that average rate by repeating 59.95 fields so the max
334            frame size is actually 4504.5 (3 field times). The field durations
335            are computed based on quantized times (see below) so we need an extra
336            two ticks to account for the rounding. */
337         if (pv->init_delay == 3753)
338             pv->init_delay = 4507;
339
340         /* frame rates are not exact in the DVD 90KHz PTS clock (they are
341            exact in the DVD 27MHz system clock but we never see that) so the
342            rates computed above are all +-1 due to quantization. Worst case
343            is when a clock-rounded-down frame is adjacent to a rounded-up frame
344            which makes one of the frames 2 ticks longer than the nominal
345            frame time. */
346         pv->init_delay += 2;
347
348         /* For VFR, libhb sees the FPS as 29.97, but the longest frames
349            will use the duration of frames running at 23.976fps instead.. */
350         if (job->vfr)
351         {
352             pv->init_delay = 7506;
353         }
354
355         /* The delay is 1 frames for regular b-frames, 2 for b-pyramid. */
356         pv->init_delay *= job->areBframes;
357     }
358     w->config->h264.init_delay = pv->init_delay;
359
360     return 0;
361 }
362
363 void encx264Close( hb_work_object_t * w )
364 {
365     hb_work_private_t * pv = w->private_data;
366     /*
367      * Patch the x264 allocated data back in so that x264 can free it
368      * we have been using our own buffers during the encode to avoid copying.
369      */
370     pv->pic_in.img.plane[0] = pv->x264_allocated_pic;
371     x264_picture_clean( &pv->pic_in );
372     x264_encoder_close( pv->x264 );
373     free( pv );
374     w->private_data = NULL;
375
376     /* TODO */
377 }
378
379 /*
380  * see comments in definition of 'frame_info' in pv struct for description
381  * of what these routines are doing.
382  */
383 static void save_frame_info( hb_work_private_t * pv, hb_buffer_t * in )
384 {
385     int i = (in->start >> FRAME_INFO_MAX2) & FRAME_INFO_MASK;
386     pv->frame_info[i].duration = in->stop - in->start;
387 }
388
389 static int64_t get_frame_duration( hb_work_private_t * pv, int64_t pts )
390 {
391     int i = (pts >> FRAME_INFO_MAX2) & FRAME_INFO_MASK;
392     return pv->frame_info[i].duration;
393 }
394
395 static hb_buffer_t *nal_encode( hb_work_object_t *w, x264_picture_t *pic_out,
396                                 int i_nal, x264_nal_t *nal )
397 {
398     hb_buffer_t *buf = NULL;
399     hb_work_private_t *pv = w->private_data;
400     hb_job_t *job = pv->job;
401
402     /* Should be way too large */
403     buf = hb_video_buffer_init( job->width, job->height );
404     buf->size = 0;
405     buf->frametype = 0;
406
407     // use the pts to get the original frame's duration.
408     int64_t duration  = get_frame_duration( pv, pic_out->i_pts );
409     buf->start = pic_out->i_pts;
410     buf->stop  = pic_out->i_pts + duration;
411
412     /* Encode all the NALs we were given into buf.
413        NOTE: This code assumes one video frame per NAL (but there can
414              be other stuff like SPS and/or PPS). If there are multiple
415              frames we only get the duration of the first which will
416              eventually screw up the muxer & decoder. */
417     int i;
418     for( i = 0; i < i_nal; i++ )
419     {
420         int data = buf->alloc - buf->size;
421         int size = x264_nal_encode( buf->data + buf->size, &data, 1, &nal[i] );
422         if( size < 1 )
423         {
424             continue;
425         }
426
427         if( job->mux & HB_MUX_AVI )
428         {
429             if( nal[i].i_ref_idc == NAL_PRIORITY_HIGHEST )
430             {
431                 buf->frametype = HB_FRAME_KEY;
432             }
433             buf->size += size;
434             continue;
435         }
436
437         /* H.264 in .mp4 or .mkv */
438         int naltype = buf->data[buf->size+4] & 0x1f;
439         if ( naltype == 0x7 || naltype == 0x8 )
440         {
441             // Sequence Parameter Set & Program Parameter Set go in the
442             // mp4 header so skip them here
443             continue;
444         }
445
446         /* H.264 in mp4 (stolen from mp4creator) */
447         buf->data[buf->size+0] = ( ( size - 4 ) >> 24 ) & 0xFF;
448         buf->data[buf->size+1] = ( ( size - 4 ) >> 16 ) & 0xFF;
449         buf->data[buf->size+2] = ( ( size - 4 ) >>  8 ) & 0xFF;
450         buf->data[buf->size+3] = ( ( size - 4 ) >>  0 ) & 0xFF;
451
452         /* Decide what type of frame we have. */
453         switch( pic_out->i_type )
454         {
455             case X264_TYPE_IDR:
456                 buf->frametype = HB_FRAME_IDR;
457                 /* if we have a chapter marker pending and this
458                    frame's presentation time stamp is at or after
459                    the marker's time stamp, use this as the
460                    chapter start. */
461                 if( pv->next_chap != 0 && pv->next_chap <= pic_out->i_pts )
462                 {
463                     pv->next_chap = 0;
464                     buf->new_chap = pv->chap_mark;
465                 }
466                 break;
467
468             case X264_TYPE_I:
469                 buf->frametype = HB_FRAME_I;
470                 break;
471
472             case X264_TYPE_P:
473                 buf->frametype = HB_FRAME_P;
474                 break;
475
476             case X264_TYPE_B:
477                 buf->frametype = HB_FRAME_B;
478                 break;
479
480         /*  This is for b-pyramid, which has reference b-frames
481             However, it doesn't seem to ever be used... */
482             case X264_TYPE_BREF:
483                 buf->frametype = HB_FRAME_BREF;
484                 break;
485
486             // If it isn't the above, what type of frame is it??
487             default:
488                 buf->frametype = 0;
489                 break;
490         }
491
492         /* Since libx264 doesn't tell us when b-frames are
493            themselves reference frames, figure it out on our own. */
494         if( (buf->frametype == HB_FRAME_B) &&
495             (nal[i].i_ref_idc != NAL_PRIORITY_DISPOSABLE) )
496             buf->frametype = HB_FRAME_BREF;
497
498         buf->size += size;
499     }
500     // make sure we found at least one video frame
501     if ( buf->size <= 0 )
502     {
503         // no video - discard the buf
504         hb_buffer_close( &buf );
505     }
506     return buf;
507 }
508
509 static hb_buffer_t *x264_encode( hb_work_object_t *w, hb_buffer_t *in )
510 {
511     hb_work_private_t *pv = w->private_data;
512     hb_job_t *job = pv->job;
513
514     /* Point x264 at our current buffers Y(UV) data.  */
515     pv->pic_in.img.plane[0] = in->data;
516
517     int uvsize = ( (job->width + 1) >> 1 ) * ( (job->height + 1) >> 1 );
518     if( job->grayscale )
519     {
520         /* XXX x264 has currently no option for grayscale encoding */
521         memset( pv->pic_in.img.plane[1], 0x80, uvsize );
522         memset( pv->pic_in.img.plane[2], 0x80, uvsize );
523     }
524     else
525     {
526         /* Point x264 at our buffers (Y)UV data */
527         pv->pic_in.img.plane[1] = in->data + job->width * job->height;
528         pv->pic_in.img.plane[2] = pv->pic_in.img.plane[1] + uvsize;
529     }
530     if( in->new_chap && job->chapter_markers )
531     {
532         /* chapters have to start with an IDR frame so request that this
533            frame be coded as IDR. Since there may be up to 16 frames
534            currently buffered in the encoder remember the timestamp so
535            when this frame finally pops out of the encoder we'll mark
536            its buffer as the start of a chapter. */
537         pv->pic_in.i_type = X264_TYPE_IDR;
538         if( pv->next_chap == 0 )
539         {
540             pv->next_chap = in->start;
541             pv->chap_mark = in->new_chap;
542         }
543         /* don't let 'work_loop' put a chapter mark on the wrong buffer */
544         in->new_chap = 0;
545     }
546     else
547     {
548         pv->pic_in.i_type = X264_TYPE_AUTO;
549     }
550     pv->pic_in.i_qpplus1 = 0;
551
552     /* XXX this is temporary debugging code to check that the upstream
553      * modules (render & sync) have generated a continuous, self-consistent
554      * frame stream with the current frame's start time equal to the
555      * previous frame's stop time.
556      */
557     if( pv->last_stop != in->start )
558     {
559         hb_log("encx264 input continuity err: last stop %lld  start %lld",
560                 pv->last_stop, in->start);
561     }
562     pv->last_stop = in->stop;
563
564     // Remember info about this frame that we need to pass across
565     // the x264_encoder_encode call (since it reorders frames).
566     save_frame_info( pv, in );
567
568     /* Feed the input PTS to x264 so it can figure out proper output PTS */
569     pv->pic_in.i_pts = in->start;
570
571     x264_picture_t pic_out;
572     int i_nal;
573     x264_nal_t *nal;
574
575     x264_encoder_encode( pv->x264, &nal, &i_nal, &pv->pic_in, &pic_out );
576     if ( i_nal > 0 )
577     {
578         return nal_encode( w, &pic_out, i_nal, nal );
579     }
580     return NULL;
581 }
582
583 int encx264Work( hb_work_object_t * w, hb_buffer_t ** buf_in,
584                   hb_buffer_t ** buf_out )
585 {
586     hb_work_private_t *pv = w->private_data;
587     hb_buffer_t *in = *buf_in;
588
589     *buf_out = NULL;
590
591     if( in->size <= 0 )
592     {
593         // EOF on input. Flush any frames still in the decoder then
594         // send the eof downstream to tell the muxer we're done.
595         x264_picture_t pic_out;
596         int i_nal;
597         x264_nal_t *nal;
598         hb_buffer_t *last_buf = NULL;
599
600         while (1)
601         {
602             x264_encoder_encode( pv->x264, &nal, &i_nal, NULL, &pic_out );
603             if ( i_nal <= 0 )
604                 break;
605
606             hb_buffer_t *buf = nal_encode( w, &pic_out, i_nal, nal );
607             if ( buf )
608             {
609                 if ( last_buf == NULL )
610                     *buf_out = buf;
611                 else
612                     last_buf->next = buf;
613                 last_buf = buf;
614             }
615         }
616         // Flushed everything - add the eof to the end of the chain.
617         if ( last_buf == NULL )
618             *buf_out = in;
619         else
620             last_buf->next = in;
621
622         *buf_in = NULL;
623         return HB_WORK_DONE;
624     }
625
626     // Not EOF - encode the packet & wrap it in a NAL
627
628     // if we're re-ordering frames, check if this frame is too large to reorder
629     if ( pv->init_delay && in->stop - in->start > pv->init_delay )
630     {
631         // This frame's duration is larger than the time allotted for b-frame
632         // reordering. That means that if it's used as a reference the decoder
633         // won't be able to move it early enough to render it in correct
634         // sequence & the playback will have odd jumps & twitches. To make
635         // sure this doesn't happen we pretend this frame is multiple
636         // frames, each with duration <= init_delay. Since each of these
637         // new frames contains the same image the visual effect is identical
638         // to the original but the resulting stream can now be coded without
639         // error. We take advantage of the fact that x264 buffers frame
640         // data internally to feed the same image into the encoder multiple
641         // times, just changing its start & stop times each time.
642         int64_t orig_stop = in->stop;
643         int64_t new_stop = in->start;
644         hb_buffer_t *last_buf = NULL;
645
646         // We want to spread the new frames uniformly over the total time
647         // so that we don't end up with a very short frame at the end.
648         // In the number of pieces calculation we add in init_delay-1 to
649         // round up but not add an extra piece if the frame duration is
650         // a multiple of init_delay. The final increment of frame_dur is
651         // to restore the bits that got truncated by the divide on the
652         // previous line. If we don't do this we end up with an extra tiny
653         // frame at the end whose duration is npieces-1.
654         int64_t frame_dur = orig_stop - new_stop;
655         int64_t npieces = ( frame_dur + pv->init_delay - 1 ) / pv->init_delay;
656         frame_dur /= npieces;
657         ++frame_dur;
658
659         while ( in->start < orig_stop )
660         {
661             new_stop += frame_dur;
662             if ( new_stop > orig_stop )
663                 new_stop = orig_stop;
664             in->stop = new_stop;
665             hb_buffer_t *buf = x264_encode( w, in );
666             if ( buf )
667             {
668                 if ( last_buf == NULL )
669                     *buf_out = buf;
670                 else
671                     last_buf->next = buf;
672                 last_buf = buf;
673             }
674             in->start = new_stop;
675         }
676     }
677     else
678     {
679         *buf_out = x264_encode( w, in );
680     }
681     return HB_WORK_OK;
682 }