OSDN Git Service

= Adds an hb_detect_comb() function that indicates whether or not a frame shows inter...
[handbrake-jp/handbrake-jp-git.git] / libhb / hb.c
1 #include "hb.h"
2
3 #include "ffmpeg/avcodec.h"
4 #include "ffmpeg/swscale.h"
5
6 struct hb_handle_s
7 {
8     /* The "Check for update" thread */
9     int            build;
10     char           version[16];
11     hb_thread_t  * update_thread;
12
13     /* This thread's only purpose is to check other threads'
14        states */
15     volatile int   die;
16     hb_thread_t  * main_thread;
17     int            pid;
18
19     /* DVD/file scan thread */
20     hb_list_t    * list_title;
21     hb_thread_t  * scan_thread;
22
23     /* The thread which processes the jobs. Others threads are launched
24        from this one (see work.c) */
25     hb_list_t    * jobs;
26     hb_job_t     * current_job;
27     int            job_count;
28     int            job_count_permanent;
29     volatile int   work_die;
30     int            work_error;
31     hb_thread_t  * work_thread;
32
33     int            cpu_count;
34
35     hb_lock_t    * state_lock;
36     hb_state_t     state;
37
38     int            paused;
39     hb_lock_t    * pause_lock;
40     /* For MacGui active queue
41        increments each time the scan thread completes*/
42     int            scanCount;
43
44 };
45
46 hb_work_object_t * hb_objects = NULL;
47
48 static void thread_func( void * );
49
50 /**
51  * Registers work objects, by adding the work object to a liked list.
52  * @param w Handle to hb_work_object_t to register.
53  */
54 void hb_register( hb_work_object_t * w )
55 {
56     w->next    = hb_objects;
57     hb_objects = w;
58 }
59
60 /**
61  * libhb initialization routine.
62  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
63  * @param update_check signals libhb to check for updated version from HandBrake website.
64  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
65  */
66 hb_handle_t * hb_init_real( int verbose, int update_check )
67 {
68     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
69     uint64_t      date;
70
71     /* See hb_log() in common.c */
72     if( verbose > HB_DEBUG_NONE )
73     {
74         putenv( "HB_DEBUG=1" );
75                 av_log_set_level(AV_LOG_DEBUG);
76     }
77
78     /* Check for an update on the website if asked to */
79     h->build = -1;
80
81     if( update_check )
82     {
83         hb_log( "hb_init: checking for updates" );
84         date             = hb_get_date();
85         h->update_thread = hb_update_init( &h->build, h->version );
86
87         for( ;; )
88         {
89             if( hb_thread_has_exited( h->update_thread ) )
90             {
91                 /* Immediate success or failure */
92                 hb_thread_close( &h->update_thread );
93                 break;
94             }
95             if( hb_get_date() > date + 1000 )
96             {
97                 /* Still nothing after one second. Connection problem,
98                    let the thread die */
99                 hb_log( "hb_init: connection problem, not waiting for "
100                         "update_thread" );
101                 break;
102             }
103             hb_snooze( 500 );
104         }
105     }
106
107     /*
108      * Initialise buffer pool
109      */
110     hb_buffer_pool_init();
111
112     /* CPU count detection */
113     hb_log( "hb_init: checking cpu count" );
114     h->cpu_count = hb_get_cpu_count();
115
116     h->list_title = hb_list_init();
117     h->jobs       = hb_list_init();
118
119     h->state_lock  = hb_lock_init();
120     h->state.state = HB_STATE_IDLE;
121
122     h->pause_lock = hb_lock_init();
123
124     /* libavcodec */
125     avcodec_init();
126     avcodec_register_all();
127     av_register_codec_parser( &mpegaudio_parser);
128
129     /* Start library thread */
130     hb_log( "hb_init: starting libhb thread" );
131     h->die         = 0;
132     h->main_thread = hb_thread_init( "libhb", thread_func, h,
133                                      HB_NORMAL_PRIORITY );
134
135     return h;
136
137         /* Set the scan count to start at 0 */
138         //scan_count = 0;
139 }
140
141 /**
142  * libhb initialization routine.
143  * This version is to use when calling the dylib, the macro hb_init isn't available from a dylib call!
144  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
145  * @param update_check signals libhb to check for updated version from HandBrake website.
146  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
147  */
148 hb_handle_t * hb_init_dl( int verbose, int update_check )
149 {
150     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
151     uint64_t      date;
152
153     /* See hb_log() in common.c */
154     if( verbose > HB_DEBUG_NONE )
155     {
156         putenv( "HB_DEBUG=1" );
157                 av_log_set_level(AV_LOG_DEBUG);
158     }
159
160     /* Check for an update on the website if asked to */
161     h->build = -1;
162
163     if( update_check )
164     {
165         hb_log( "hb_init: checking for updates" );
166         date             = hb_get_date();
167         h->update_thread = hb_update_init( &h->build, h->version );
168
169         for( ;; )
170         {
171             if( hb_thread_has_exited( h->update_thread ) )
172             {
173                 /* Immediate success or failure */
174                 hb_thread_close( &h->update_thread );
175                 break;
176             }
177             if( hb_get_date() > date + 1000 )
178             {
179                 /* Still nothing after one second. Connection problem,
180                    let the thread die */
181                 hb_log( "hb_init: connection problem, not waiting for "
182                         "update_thread" );
183                 break;
184             }
185             hb_snooze( 500 );
186         }
187     }
188
189     /* CPU count detection */
190     hb_log( "hb_init: checking cpu count" );
191     h->cpu_count = hb_get_cpu_count();
192
193     h->list_title = hb_list_init();
194     h->jobs       = hb_list_init();
195     h->current_job = NULL;
196
197     h->state_lock  = hb_lock_init();
198     h->state.state = HB_STATE_IDLE;
199
200     h->pause_lock = hb_lock_init();
201
202     /* libavcodec */
203     avcodec_init();
204     avcodec_register_all();
205
206     /* Start library thread */
207     hb_log( "hb_init: starting libhb thread" );
208     h->die         = 0;
209     h->main_thread = hb_thread_init( "libhb", thread_func, h,
210                                      HB_NORMAL_PRIORITY );
211
212     hb_register( &hb_sync );
213         hb_register( &hb_decmpeg2 );
214         hb_register( &hb_decsub );
215         hb_register( &hb_render );
216         hb_register( &hb_encavcodec );
217         hb_register( &hb_encxvid );
218         hb_register( &hb_encx264 );
219     hb_register( &hb_enctheora );
220         hb_register( &hb_deca52 );
221         hb_register( &hb_decdca );
222         hb_register( &hb_decavcodec );
223         hb_register( &hb_declpcm );
224         hb_register( &hb_encfaac );
225         hb_register( &hb_enclame );
226         hb_register( &hb_encvorbis );
227
228         return h;
229 }
230
231
232 /**
233  * Returns current version of libhb.
234  * @param h Handle to hb_handle_t.
235  * @return character array of version number.
236  */
237 char * hb_get_version( hb_handle_t * h )
238 {
239     return HB_VERSION;
240 }
241
242 /**
243  * Returns current build of libhb.
244  * @param h Handle to hb_handle_t.
245  * @return character array of build number.
246  */
247 int hb_get_build( hb_handle_t * h )
248 {
249     return HB_BUILD;
250 }
251
252 /**
253  * Checks for needed update.
254  * @param h Handle to hb_handle_t.
255  * @param version Pointer to handle where version will be copied.
256  * @return update indicator.
257  */
258 int hb_check_update( hb_handle_t * h, char ** version )
259 {
260     *version = ( h->build < 0 ) ? NULL : h->version;
261     return h->build;
262 }
263
264 /**
265  * Sets the cpu count to the desired value.
266  * @param h Handle to hb_handle_t
267  * @param cpu_count Number of CPUs to use.
268  */
269 void hb_set_cpu_count( hb_handle_t * h, int cpu_count )
270 {
271     cpu_count    = MAX( 1, cpu_count );
272     cpu_count    = MIN( cpu_count, 8 );
273     h->cpu_count = cpu_count;
274 }
275
276 /**
277  * Initializes a scan of the by calling hb_scan_init
278  * @param h Handle to hb_handle_t
279  * @param path location of VIDEO_TS folder.
280  * @param title_index Desired title to scan.  0 for all titles.
281  */
282 void hb_scan( hb_handle_t * h, const char * path, int title_index )
283 {
284     hb_title_t * title;
285
286     /* Clean up from previous scan */
287     while( ( title = hb_list_item( h->list_title, 0 ) ) )
288     {
289         hb_list_rem( h->list_title, title );
290         hb_title_close( &title );
291     }
292
293     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
294     h->scan_thread = hb_scan_init( h, path, title_index, h->list_title );
295 }
296
297 /**
298  * Returns the list of titles found.
299  * @param h Handle to hb_handle_t
300  * @return Handle to hb_list_t of the title list.
301  */
302 hb_list_t * hb_get_titles( hb_handle_t * h )
303 {
304     return h->list_title;
305 }
306
307 /**
308  * Create preview image of desired title a index of picture.
309  * @param h Handle to hb_handle_t.
310  * @param title Handle to hb_title_t of desired title.
311  * @param picture Index in title.
312  * @param buffer Handle to buufer were inage will be drawn.
313  */
314 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
315                      uint8_t * buffer )
316 {
317     hb_job_t           * job = title->job;
318     char                 filename[1024];
319     FILE               * file;
320     uint8_t            * buf1, * buf2, * buf3, * buf4, * pen;
321     uint32_t           * p32, swsflags;
322     AVPicture            pic_in, pic_preview, pic_deint, pic_crop, pic_scale;
323     struct SwsContext  * context;
324     int                  i;
325
326     swsflags = SWS_LANCZOS;
327 #ifndef __x86_64__
328     swsflags |= SWS_ACCURATE_RND;
329 #endif  /* __x86_64__ */
330
331     buf1 = malloc( title->width * title->height * 3 / 2 );
332     buf2 = malloc( title->width * title->height * 3 / 2 );
333     buf3 = malloc( title->width * title->height * 3 / 2 );
334     buf4 = malloc( title->width * title->height * 4 );
335     avpicture_fill( &pic_in, buf1, PIX_FMT_YUV420P,
336                     title->width, title->height );
337     avpicture_fill( &pic_deint, buf2, PIX_FMT_YUV420P,
338                     title->width, title->height );
339     avpicture_fill( &pic_scale, buf3, PIX_FMT_YUV420P,
340                     job->width, job->height );
341     avpicture_fill( &pic_preview, buf4, PIX_FMT_RGBA32,
342                     job->width, job->height );
343
344     // Allocate the AVPicture frames and fill in
345
346     memset( filename, 0, 1024 );
347
348     hb_get_tempory_filename( h, filename, "%x%d",
349                              (intptr_t) title, picture );
350
351     file = fopen( filename, "r" );
352     if( !file )
353     {
354         hb_log( "hb_get_preview: fopen failed" );
355         return;
356     }
357
358     fread( buf1, title->width * title->height * 3 / 2, 1, file );
359     fclose( file );
360
361     if( job->deinterlace )
362     {
363         // Deinterlace and crop
364         avpicture_deinterlace( &pic_deint, &pic_in, PIX_FMT_YUV420P, title->width, title->height );
365         av_picture_crop( &pic_crop, &pic_deint, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
366     }
367     else
368     {
369         // Crop
370         av_picture_crop( &pic_crop, &pic_in, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
371     }
372
373     // Get scaling context
374     context = sws_getContext(title->width  - (job->crop[2] + job->crop[3]),
375                              title->height - (job->crop[0] + job->crop[1]),
376                              PIX_FMT_YUV420P,
377                              job->width, job->height, PIX_FMT_YUV420P,
378                              swsflags, NULL, NULL, NULL);
379
380     // Scale
381     sws_scale(context,
382               pic_crop.data, pic_crop.linesize,
383               0, title->height - (job->crop[0] + job->crop[1]),
384               pic_scale.data, pic_scale.linesize);
385
386     // Free context
387     sws_freeContext( context );
388
389     // Get preview context
390     context = sws_getContext(job->width, job->height, PIX_FMT_YUV420P,
391                               job->width, job->height, PIX_FMT_RGBA32,
392                               swsflags, NULL, NULL, NULL);
393
394     // Create preview
395     sws_scale(context,
396               pic_scale.data, pic_scale.linesize,
397               0, job->height,
398               pic_preview.data, pic_preview.linesize);
399
400     // Free context
401     sws_freeContext( context );
402
403     /* Gray background */
404     p32 = (uint32_t *) buffer;
405     for( i = 0; i < ( title->width + 2 ) * ( title->height + 2 ); i++ )
406     {
407         p32[i] = 0xFF808080;
408     }
409
410     /* Draw the picture, centered, and draw the cropping zone */
411     pen = buffer + ( title->height - job->height ) *
412         ( title->width + 2 ) * 2 + ( title->width - job->width ) * 2;
413     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
414     pen += 4 * ( title->width + 2 );
415     for( i = 0; i < job->height; i++ )
416     {
417         uint8_t * nextLine;
418         nextLine = pen + 4 * ( title->width + 2 );
419         memset( pen, 0xFF, 4 );
420         pen += 4;
421         memcpy( pen, buf4 + 4 * job->width * i, 4 * job->width );
422         pen += 4 * job->width;
423         memset( pen, 0xFF, 4 );
424         pen = nextLine;
425     }
426     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
427
428     // Clean up
429     avpicture_free( &pic_preview );
430     avpicture_free( &pic_scale );
431     avpicture_free( &pic_deint );
432     avpicture_free( &pic_in );
433 }
434
435  /**
436  * Analyzes a frame to detect interlacing artifacts
437  * and returns true if interlacing (combing) is found.
438  *
439  * Code taken from Thomas Oestreich's 32detect filter
440  * in the Transcode project, with minor formatting changes.
441  *
442  * @param buf         An hb_buffer structure holding valid frame data
443  * @param width       The frame's width in pixels
444  * @param height      The frame's height in pixels
445  * @param color_equal Sensitivity for detecting similar colors
446  * @param color_diff  Sensitivity for detecting different colors
447  * @param threshold   Sensitivity for flagging planes as combed
448  */
449 int hb_detect_comb( hb_buffer_t * buf, int width, int height, int color_equal, int color_diff, int threshold )
450 {
451     int j, k, n, off, block, cc_1, cc_2, cc[3], flag[3];
452     uint16_t s1, s2, s3, s4;
453     cc_1 = 0; cc_2 = 0;
454
455     int offset = 0;
456     
457     for( k = 0; k < 3; k++ )
458     {
459         /* One pas for Y, one pass for Cb, one pass for Cr */
460
461         if( k == 1 )
462         {
463             /* Y has already been checked, now offset by Y's dimensions
464                and divide all the other values by 2, since Cr and Cb
465                are half-size compared to Y.                               */
466             offset = width * height;
467             width >>= 1;
468             height >>= 1;
469             threshold >>= 1;
470             color_equal >>= 1;
471             color_diff >>= 1;
472         }
473         else if ( k == 2 )
474         {
475             /* Y and Cb are done, so the offset needs to be bumped
476                so it's width*height + (width / 2) * (height / 2)  */
477             offset *= 5/4;
478         }
479         
480         /* Look at one horizontal line at a time */
481         block = width;
482         
483         for( j = 0; j < block; ++j )
484         {
485             off = 0;
486             
487             for( n = 0; n < ( height - 4 ); n = n + 2 )
488             {
489                 /* Look at groups of 4 sequential horizontal lines */
490                 s1 = ( ( buf->data + offset )[ off + j             ] & 0xff );
491                 s2 = ( ( buf->data + offset )[ off + j + block     ] & 0xff );
492                 s3 = ( ( buf->data + offset )[ off + j + 2 * block ] & 0xff );
493                 s4 = ( ( buf->data + offset )[ off + j + 3 * block ] & 0xff );
494                 
495                 /* Note if the 1st and 2nd lines are more different in
496                    color than the 1st and 3rd lines are similar in color.*/
497                 if ( ( abs( s1 - s3 ) < color_equal ) && 
498                      ( abs( s1 - s2 ) > color_diff ) )
499                         ++cc_1;
500     
501                 /* Note if the 2nd and 3rd lines are more different in
502                    color than the 2nd and 4th lines are similar in color.*/
503                 if ( ( abs( s2 - s4 ) < color_equal ) &&
504                      ( abs( s2 - s3 ) > color_diff) )
505                         ++cc_2;
506                 
507                 /* Now move down 2 horizontal lines before starting over.*/
508                 off += 2 * block;
509             }
510         }
511         
512         // compare results
513         /* The final metric seems to be doing some kind of bits per pixel style calculation
514            to decide whether or not enough lines showed alternating colors for the frame size. */
515         cc[k] = (int)( ( cc_1 + cc_2 ) * 1000.0 / ( width * height ) );
516         
517         /* If the plane's cc score meets the threshold, flag it as combed. */
518         flag[k] = 0;
519         if ( cc[k] > threshold )
520         {
521             flag[k] = 1;
522         }
523     }
524     
525 #if 0
526 /* Debugging info */
527 //    if(flag)
528         hb_log("flags: %i/%i/%i | cc0: %i | cc1: %i | cc2: %i", flag[0], flag[1], flag[2], cc[0], cc[1], cc[2]);
529 #endif
530     
531     /* When more than one plane shows combing, tell the caller. */
532     if (flag[0] || flag[1] || flag[2] )
533     {
534         return 1;
535     }
536
537     return 0;
538 }
539
540
541 /**
542  * Calculates job width and height for anamorphic content,
543  *
544  * @param job Handle to hb_job_t
545  * @param output_width Pointer to returned storage width
546  * @param output_height Pointer to returned storage height
547  * @param output_par_width Pointer to returned pixel width
548  @ param output_par_height Pointer to returned pixel height
549  */
550 void hb_set_anamorphic_size( hb_job_t * job,
551         int *output_width, int *output_height,
552         int *output_par_width, int *output_par_height )
553 {
554     /* "Loose" anamorphic.
555         - Uses mod16-compliant dimensions,
556         - Allows users to set the width
557         - Handles ITU pixel aspects
558     */
559
560     /* Set up some variables to make the math easier to follow. */
561     hb_title_t * title = job->title;
562     int cropped_width = title->width - job->crop[2] - job->crop[3] ;
563     int cropped_height = title->height - job->crop[0] - job->crop[1] ;
564     int storage_aspect = cropped_width * 10000 / cropped_height;
565     int width = job->width;
566     int height; // Gets set later, ignore user value
567     int mod = job->modulus;
568     int aspect = title->aspect;
569
570     /* Gotta handle bounding dimensions differently
571        than for non-anamorphic encodes:
572        If the width is too big, just reset it with no rescaling.
573        Instead of using the aspect-scaled job height,
574        we need to see if the job width divided by the storage aspect
575        is bigger than the max. If so, set it to the max (this is sloppy).
576        If not, set job height to job width divided by storage aspect.
577     */
578
579     if ( job->maxWidth && (job->maxWidth < job->width) )
580             width = job->maxWidth;
581
582     if ( job->maxHeight && (job->maxHeight < (width / storage_aspect * 10000)) )
583     {
584         height = job->maxHeight;
585     }
586     else
587     {
588         height = width * 10000 / storage_aspect;
589     }
590
591
592     /* Time to get picture dimensions that divide cleanly.
593        These variables will store temporary dimensions as we iterate. */
594     int i, w, h;
595
596     /* In case the user specified a modulus, use it */
597     if (job->modulus)
598         mod = job->modulus;
599     else
600         mod = 16;
601
602     /* Iterate through multiples of mod to find one close to job->width. */
603     for( i = 1;; i++ )
604     {
605         w = mod * i;
606
607         if (w < width)
608         {
609             if ( ( width - w ) <= ( mod / 2 ) )
610                 /* We'll take a width that's
611                    smaller, but close enough. */
612                 break;
613         }
614         if (w == width)
615             /* Mod 16 dimensions, how nice! */
616             break;
617         if( w > width )
618         {
619             if ( ( w - width ) < (mod/2) )
620                 /* We'll take a width that's bigger, if we have to. */
621                 break;
622         }
623     }
624     width  = mod * (i);
625
626     /* Now do the same for a mod-friendly value near job->height. */
627     for( i = 1;; i++)
628     {
629         h = i * mod;
630
631         if (h < height)
632             {
633                 if ( ( height - h ) <= ( mod / 2 ))
634                     /* Go with a smaller height,
635                        if it's close enough.    */
636                     break;
637             }
638         if (h == height)
639             /* Mod 16 dimensions, how nice! */
640             break;
641
642         if ( h > height)
643         {
644             if ( ( h - height ) < ( mod / 2 ))
645                 /* Use a taller height if necessary */
646                 break;
647         }
648     }
649     height = mod  * (i);
650
651     int pixel_aspect_width = job->pixel_aspect_width;
652     int pixel_aspect_height = job->pixel_aspect_height;
653
654     if (cropped_width <= 706)
655     {
656         /* Handle ITU PARs */
657         if (title->height == 480)
658         {
659             /* It's NTSC */
660             if (aspect == 16)
661             {
662                 /* It's widescreen */
663                 pixel_aspect_width = 40;
664                 pixel_aspect_height = 33;
665             }
666             else
667             {
668                 /* It's 4:3 */
669                 pixel_aspect_width = 10;
670                 pixel_aspect_height = 11;
671             }
672         }
673         else if (title->height == 576)
674         {
675             /* It's PAL */
676             if(aspect == 16)
677             {
678                 /* It's widescreen */
679                 pixel_aspect_width = 16;
680                 pixel_aspect_height = 11;
681             }
682             else
683             {
684                 /* It's 4:3 */
685                 pixel_aspect_width = 12;
686                 pixel_aspect_height = 11;
687             }
688         }
689     }
690
691     /* Figure out what dimensions the source would display at. */
692     int source_display_width = cropped_width * ((float)pixel_aspect_width / (float)pixel_aspect_height) ;
693
694     /* The film AR is the source's display width / cropped source height.
695        The output display width is the output height * film AR.
696        The output PAR is the output display width / output storage width. */
697     pixel_aspect_width = height * source_display_width / cropped_height;
698     pixel_aspect_height = width;
699
700     /* While x264 is smart enough to reduce fractions on its own, libavcodec
701        needs some help with the math, so lose superfluous factors.            */
702     hb_reduce( &pixel_aspect_width, &pixel_aspect_height,
703                pixel_aspect_width, pixel_aspect_height );
704
705     /* Pass the results back to the caller */
706     *output_width = width;
707     *output_height = height;
708     *output_par_width = pixel_aspect_width;
709     *output_par_height = pixel_aspect_height;
710 }
711
712 /**
713  * Calculates job width, height, and cropping parameters.
714  * @param job Handle to hb_job_t.
715  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
716  * @param pixels Maximum desired pixel count.
717  */
718 void hb_set_size( hb_job_t * job, int aspect, int pixels )
719 {
720     hb_title_t * title = job->title;
721
722     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
723     int croppedHeight = title->height - title->crop[0] - title->crop[1];
724     int croppedAspect = title->aspect * title->height * croppedWidth /
725                             croppedHeight / title->width;
726     int addCrop;
727     int i, w, h;
728
729     if( aspect <= 0 )
730     {
731         /* Keep the best possible aspect ratio */
732         aspect = croppedAspect;
733     }
734
735     /* Crop if necessary to obtain the desired ratio */
736     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
737     if( aspect < croppedAspect )
738     {
739         /* Need to crop on the left and right */
740         addCrop = croppedWidth - aspect * croppedHeight * title->width /
741                     title->aspect / title->height;
742         if( addCrop & 3 )
743         {
744             addCrop = ( addCrop + 1 ) / 2;
745             job->crop[2] += addCrop;
746             job->crop[3] += addCrop;
747         }
748         else if( addCrop & 2 )
749         {
750             addCrop /= 2;
751             job->crop[2] += addCrop - 1;
752             job->crop[3] += addCrop + 1;
753         }
754         else
755         {
756             addCrop /= 2;
757             job->crop[2] += addCrop;
758             job->crop[3] += addCrop;
759         }
760     }
761     else if( aspect > croppedAspect )
762     {
763         /* Need to crop on the top and bottom */
764         addCrop = croppedHeight - croppedWidth * title->aspect *
765             title->height / aspect / title->width;
766         if( addCrop & 3 )
767         {
768             addCrop = ( addCrop + 1 ) / 2;
769             job->crop[0] += addCrop;
770             job->crop[1] += addCrop;
771         }
772         else if( addCrop & 2 )
773         {
774             addCrop /= 2;
775             job->crop[0] += addCrop - 1;
776             job->crop[1] += addCrop + 1;
777         }
778         else
779         {
780             addCrop /= 2;
781             job->crop[0] += addCrop;
782             job->crop[1] += addCrop;
783         }
784     }
785
786     /* Compute a resolution from the number of pixels and aspect */
787     for( i = 0;; i++ )
788     {
789         w = 16 * i;
790         h = MULTIPLE_16( w * HB_ASPECT_BASE / aspect );
791         if( w * h > pixels )
792         {
793             break;
794         }
795     }
796     i--;
797     job->width  = 16 * i;
798     job->height = MULTIPLE_16( 16 * i * HB_ASPECT_BASE / aspect );
799 }
800
801 /**
802  * Returns the number of jobs in the queue.
803  * @param h Handle to hb_handle_t.
804  * @return Number of jobs.
805  */
806 int hb_count( hb_handle_t * h )
807 {
808     return hb_list_count( h->jobs );
809 }
810
811 /**
812  * Returns handle to job at index i within the job list.
813  * @param h Handle to hb_handle_t.
814  * @param i Index of job.
815  * @returns Handle to hb_job_t of desired job.
816  */
817 hb_job_t * hb_job( hb_handle_t * h, int i )
818 {
819     return hb_list_item( h->jobs, i );
820 }
821
822 hb_job_t * hb_current_job( hb_handle_t * h )
823 {
824     return( h->current_job );
825 }
826
827 /**
828  * Adds a job to the job list.
829  * @param h Handle to hb_handle_t.
830  * @param job Handle to hb_job_t.
831  */
832 void hb_add( hb_handle_t * h, hb_job_t * job )
833 {
834     hb_job_t      * job_copy;
835     hb_title_t    * title,    * title_copy;
836     hb_chapter_t  * chapter,  * chapter_copy;
837     hb_audio_t    * audio,    * audio_copy;
838     hb_subtitle_t * subtitle, * subtitle_copy;
839     int             i;
840     char            audio_lang[4];
841
842     /* Copy the title */
843     title      = job->title;
844     title_copy = malloc( sizeof( hb_title_t ) );
845     memcpy( title_copy, title, sizeof( hb_title_t ) );
846
847     title_copy->list_chapter = hb_list_init();
848     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
849     {
850         chapter      = hb_list_item( title->list_chapter, i );
851         chapter_copy = malloc( sizeof( hb_chapter_t ) );
852         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
853         hb_list_add( title_copy->list_chapter, chapter_copy );
854     }
855
856     /* Copy the audio track(s) we want */
857     title_copy->list_audio = hb_list_init();
858
859     /* Do nothing about audio during first pass */
860     if( job->pass == 0 || job->pass == 2 )
861     {
862         for( i = 0; i < 8; i++ )
863         {
864             if( job->audios[i] < 0 )
865             {
866                 break;
867             }
868             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
869             {
870                 audio_copy = malloc( sizeof( hb_audio_t ) );
871                 memcpy( audio_copy, audio, sizeof( hb_audio_t ) );
872                 hb_list_add( title_copy->list_audio, audio_copy );
873             }
874         }
875     }
876
877     title_copy->list_subtitle = hb_list_init();
878
879     /*
880      * The following code is confusing, there are three ways in which
881      * we select subtitles and it depends on whether this is single or
882      * two pass mode.
883      *
884      * subtitle_scan may be enabled, in which case the first pass
885      * scans all subtitles of that language. The second pass does not
886      * select any because they are set at the end of the first pass.
887      *
888      * native_language may have a preferred language, in which case we
889      * may be switching the language we want for the subtitles in the
890      * first pass of a single pass, or the second pass of a two pass.
891      *
892      * We may have manually selected a subtitle, in which case that is
893      * selected in the first pass of a single pass, or the second of a
894      * two pass.
895      */
896     memset( audio_lang, 0, sizeof( audio_lang ) );
897
898     if ( job->indepth_scan || job->native_language ) {
899
900         /*
901          * Find the first audio language that is being encoded
902          */
903         for( i = 0; i < 8; i++ )
904         {
905             if( job->audios[i] < 0 )
906             {
907                 break;
908             }
909             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
910             {
911                 strncpy(audio_lang, audio->iso639_2, sizeof(audio_lang));
912                 break;
913             }
914         }
915
916         /*
917          * In all cases switch the language if we need to to our native
918          * language.
919          */
920         if( job->native_language )
921         {
922             if( strncasecmp( job->native_language, audio_lang,
923                              sizeof( audio_lang ) ) != 0 )
924             {
925
926                 if( job->pass != 2 )
927                 {
928                     hb_log( "Enabled subtitles in native language '%s', audio is in '%s'",
929                             job->native_language, audio_lang);
930                 }
931                 /*
932                  * The main audio track is not in our native language, so switch
933                  * the subtitles to use our native language instead.
934                  */
935                 strncpy( audio_lang, job->native_language, sizeof( audio_lang ) );
936             } else {
937                 /*
938                  * native language is irrelevent, free it.
939                  */
940                 free( job->native_language );
941                 job->native_language = NULL;
942             }
943         }
944     }
945
946     /*
947      * If doing a subtitle scan then add all the matching subtitles for this
948      * language.
949      */
950     if ( job->indepth_scan )
951     {
952         for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
953         {
954             subtitle = hb_list_item( title->list_subtitle, i );
955             if( strcmp( subtitle->iso639_2, audio_lang ) == 0 )
956             {
957                 /*
958                  * Matched subtitle language with audio language, so
959                  * add this to our list to scan.
960                  *
961                  * We will update the subtitle list on the second pass
962                  * later after the first pass has completed.
963                  */
964                 subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
965                 memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
966                 hb_list_add( title_copy->list_subtitle, subtitle_copy );
967                 if ( job->native_language ) {
968                     /*
969                      * With native language just select the
970                      * first match in our langiage, not all of
971                      * them. Subsequent ones are likely to be commentary
972                      */
973                     break;
974                 }
975             }
976         }
977     } else {
978         /*
979          * Not doing a subtitle scan in this pass, but maybe we are in the
980          * first pass?
981          */
982         if( job->select_subtitle )
983         {
984             /*
985              * Don't add subtitles here, we'll add them via select_subtitle
986              * at the end of the subtitle_scan.
987              */
988         } else {
989             /*
990              * Definitely not doing a subtitle scan.
991              */
992             if( job->pass != 1 && job->native_language )
993             {
994                 /*
995                  * We are not doing a subtitle scan but do want the
996                  * native langauge subtitle selected, so select it
997                  * for pass 0 or pass 2 of a two pass.
998                  */
999                 for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
1000                 {
1001                     subtitle = hb_list_item( title->list_subtitle, i );
1002                     if( strcmp( subtitle->iso639_2, audio_lang ) == 0 )
1003                     {
1004                         /*
1005                          * Matched subtitle language with audio language, so
1006                          * add this to our list to scan.
1007                          */
1008                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1009                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1010                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
1011                         break;
1012                     }
1013                 }
1014             } else {
1015                 /*
1016                  * Manually selected subtitle, in which case only
1017                  * bother adding them for pass 0 or pass 2 of a two
1018                  * pass.
1019                  */
1020                 if( job->pass != 1 )
1021                 {
1022                     if( ( subtitle = hb_list_item( title->list_subtitle, job->subtitle ) ) )
1023                     {
1024                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1025                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1026                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
1027                     }
1028                 }
1029             }
1030         }
1031     }
1032
1033     /* Copy the job */
1034     job_copy        = calloc( sizeof( hb_job_t ), 1 );
1035     memcpy( job_copy, job, sizeof( hb_job_t ) );
1036     title_copy->job = job_copy;
1037     job_copy->title = title_copy;
1038     job_copy->file  = strdup( job->file );
1039     job_copy->h     = h;
1040     job_copy->pause = h->pause_lock;
1041
1042     /* Copy the job filter list */
1043     if( job->filters )
1044     {
1045         int i;
1046         int filter_count = hb_list_count( job->filters );
1047         job_copy->filters = hb_list_init();
1048         for( i = 0; i < filter_count; i++ )
1049         {
1050             /*
1051              * Copy the filters, since the MacGui reuses the global filter objects
1052              * meaning that queued up jobs overwrite the previous filter settings.
1053              * In reality, settings is probably the only field that needs duplicating
1054              * since it's the only value that is ever changed. But name is duplicated
1055              * as well for completeness. Not copying private_data since it gets
1056              * created for each job in renderInit.
1057              */
1058             hb_filter_object_t * filter = hb_list_item( job->filters, i );
1059             hb_filter_object_t * filter_copy = malloc( sizeof( hb_filter_object_t ) );
1060             memcpy( filter_copy, filter, sizeof( hb_filter_object_t ) );
1061             if( filter->name )
1062                 filter_copy->name = strdup( filter->name );
1063             if( filter->settings )
1064                 filter_copy->settings = strdup( filter->settings );
1065             hb_list_add( job_copy->filters, filter_copy );
1066         }
1067     }
1068
1069     /* Add the job to the list */
1070     hb_list_add( h->jobs, job_copy );
1071     h->job_count = hb_count(h);
1072     h->job_count_permanent++;
1073 }
1074
1075 /**
1076  * Removes a job from the job list.
1077  * @param h Handle to hb_handle_t.
1078  * @param job Handle to hb_job_t.
1079  */
1080 void hb_rem( hb_handle_t * h, hb_job_t * job )
1081 {
1082     hb_list_rem( h->jobs, job );
1083
1084     h->job_count = hb_count(h);
1085     if (h->job_count_permanent)
1086         h->job_count_permanent--;
1087
1088     /* XXX free everything XXX */
1089 }
1090
1091 /**
1092  * Starts the conversion process.
1093  * Sets state to HB_STATE_WORKING.
1094  * calls hb_work_init, to launch work thread. Stores handle to work thread.
1095  * @param h Handle to hb_handle_t.
1096  */
1097 void hb_start( hb_handle_t * h )
1098 {
1099     /* XXX Hack */
1100     h->job_count = hb_list_count( h->jobs );
1101     h->job_count_permanent = h->job_count;
1102
1103     hb_lock( h->state_lock );
1104     h->state.state = HB_STATE_WORKING;
1105 #define p h->state.param.working
1106     p.progress  = 0.0;
1107     p.job_cur   = 1;
1108     p.job_count = h->job_count;
1109     p.rate_cur  = 0.0;
1110     p.rate_avg  = 0.0;
1111     p.hours     = -1;
1112     p.minutes   = -1;
1113     p.seconds   = -1;
1114     p.sequence_id = 0;
1115 #undef p
1116     hb_unlock( h->state_lock );
1117
1118     h->paused = 0;
1119
1120     h->work_die    = 0;
1121     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
1122                                    &h->work_die, &h->work_error, &h->current_job );
1123 }
1124
1125 /**
1126  * Pauses the conversion process.
1127  * @param h Handle to hb_handle_t.
1128  */
1129 void hb_pause( hb_handle_t * h )
1130 {
1131     if( !h->paused )
1132     {
1133         hb_lock( h->pause_lock );
1134         h->paused = 1;
1135
1136         hb_lock( h->state_lock );
1137         h->state.state = HB_STATE_PAUSED;
1138         hb_unlock( h->state_lock );
1139     }
1140 }
1141
1142 /**
1143  * Resumes the conversion process.
1144  * @param h Handle to hb_handle_t.
1145  */
1146 void hb_resume( hb_handle_t * h )
1147 {
1148     if( h->paused )
1149     {
1150         hb_unlock( h->pause_lock );
1151         h->paused = 0;
1152     }
1153 }
1154
1155 /**
1156  * Stops the conversion process.
1157  * @param h Handle to hb_handle_t.
1158  */
1159 void hb_stop( hb_handle_t * h )
1160 {
1161     h->work_die = 1;
1162
1163     h->job_count = hb_count(h);
1164     h->job_count_permanent = 0;
1165
1166     hb_resume( h );
1167 }
1168
1169 /**
1170  * Returns the state of the conversion process.
1171  * @param h Handle to hb_handle_t.
1172  * @param s Handle to hb_state_t which to copy the state data.
1173  */
1174 void hb_get_state( hb_handle_t * h, hb_state_t * s )
1175 {
1176     hb_lock( h->state_lock );
1177
1178     memcpy( s, &h->state, sizeof( hb_state_t ) );
1179     if ( h->state.state == HB_STATE_SCANDONE || h->state.state == HB_STATE_WORKDONE )
1180         h->state.state = HB_STATE_IDLE;
1181
1182     hb_unlock( h->state_lock );
1183 }
1184
1185 void hb_get_state2( hb_handle_t * h, hb_state_t * s )
1186 {
1187     hb_lock( h->state_lock );
1188
1189     memcpy( s, &h->state, sizeof( hb_state_t ) );
1190
1191     hb_unlock( h->state_lock );
1192 }
1193
1194 /**
1195  * Called in MacGui in UpdateUI to check
1196  *  for a new scan being completed to set a new source
1197  */
1198 int hb_get_scancount( hb_handle_t * h)
1199  {
1200      return h->scanCount;
1201  }
1202
1203 /**
1204  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init_real.
1205  * @param _h Pointer to handle to hb_handle_t.
1206  */
1207 void hb_close( hb_handle_t ** _h )
1208 {
1209     hb_handle_t * h = *_h;
1210     hb_title_t * title;
1211
1212     h->die = 1;
1213     hb_thread_close( &h->main_thread );
1214
1215     while( ( title = hb_list_item( h->list_title, 0 ) ) )
1216     {
1217         hb_list_rem( h->list_title, title );
1218         if( title->job && title->job->filters )
1219         {
1220             hb_list_close( &title->job->filters );
1221         }
1222         free( title->job );
1223         hb_title_close( &title );
1224     }
1225     hb_list_close( &h->list_title );
1226
1227     hb_list_close( &h->jobs );
1228     hb_lock_close( &h->state_lock );
1229     hb_lock_close( &h->pause_lock );
1230     free( h );
1231     *_h = NULL;
1232
1233 }
1234
1235 /**
1236  * Monitors the state of the update, scan, and work threads.
1237  * Sets scan done state when scan thread exits.
1238  * Sets work done state when work thread exits.
1239  * @param _h Handle to hb_handle_t
1240  */
1241 static void thread_func( void * _h )
1242 {
1243     hb_handle_t * h = (hb_handle_t *) _h;
1244     char dirname[1024];
1245     DIR * dir;
1246     struct dirent * entry;
1247
1248     h->pid = getpid();
1249
1250     /* Create folder for temporary files */
1251     memset( dirname, 0, 1024 );
1252     hb_get_tempory_directory( h, dirname );
1253
1254     hb_mkdir( dirname );
1255
1256     while( !h->die )
1257     {
1258         /* In case the check_update thread hangs, it'll die sooner or
1259            later. Then, we join it here */
1260         if( h->update_thread &&
1261             hb_thread_has_exited( h->update_thread ) )
1262         {
1263             hb_thread_close( &h->update_thread );
1264         }
1265
1266         /* Check if the scan thread is done */
1267         if( h->scan_thread &&
1268             hb_thread_has_exited( h->scan_thread ) )
1269         {
1270             hb_thread_close( &h->scan_thread );
1271
1272             hb_log( "libhb: scan thread found %d valid title(s)",
1273                     hb_list_count( h->list_title ) );
1274             hb_lock( h->state_lock );
1275             h->state.state = HB_STATE_SCANDONE; //originally state.state
1276                         hb_unlock( h->state_lock );
1277                         /*we increment this sessions scan count by one for the MacGui
1278                         to trigger a new source being set */
1279             h->scanCount++;
1280         }
1281
1282         /* Check if the work thread is done */
1283         if( h->work_thread &&
1284             hb_thread_has_exited( h->work_thread ) )
1285         {
1286             hb_thread_close( &h->work_thread );
1287
1288             hb_log( "libhb: work result = %d",
1289                     h->work_error );
1290             hb_lock( h->state_lock );
1291             h->state.state                = HB_STATE_WORKDONE;
1292             h->state.param.workdone.error = h->work_error;
1293
1294             h->job_count = hb_count(h);
1295             if (h->job_count < 1)
1296                 h->job_count_permanent = 0;
1297             hb_unlock( h->state_lock );
1298         }
1299
1300         hb_snooze( 50 );
1301     }
1302
1303     if( h->work_thread )
1304     {
1305         hb_stop( h );
1306         hb_thread_close( &h->work_thread );
1307     }
1308
1309     /* Remove temp folder */
1310     dir = opendir( dirname );
1311     while( ( entry = readdir( dir ) ) )
1312     {
1313         char filename[1024];
1314         if( entry->d_name[0] == '.' )
1315         {
1316             continue;
1317         }
1318         memset( filename, 0, 1024 );
1319         snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
1320         unlink( filename );
1321     }
1322     closedir( dir );
1323     rmdir( dirname );
1324 }
1325
1326 /**
1327  * Returns the PID.
1328  * @param h Handle to hb_handle_t
1329  */
1330 int hb_get_pid( hb_handle_t * h )
1331 {
1332     return h->pid;
1333 }
1334
1335 /**
1336  * Sets the current state.
1337  * @param h Handle to hb_handle_t
1338  * @param s Handle to new hb_state_t
1339  */
1340 void hb_set_state( hb_handle_t * h, hb_state_t * s )
1341 {
1342     hb_lock( h->pause_lock );
1343     hb_lock( h->state_lock );
1344     memcpy( &h->state, s, sizeof( hb_state_t ) );
1345     if( h->state.state == HB_STATE_WORKING )
1346     {
1347         /* XXX Hack */
1348         if (h->job_count < 1)
1349             h->job_count_permanent = 1;
1350
1351         h->state.param.working.job_cur =
1352             h->job_count_permanent - hb_list_count( h->jobs );
1353         h->state.param.working.job_count = h->job_count_permanent;
1354
1355         // Set which job is being worked on
1356         if (h->current_job)
1357             h->state.param.working.sequence_id = h->current_job->sequence_id;
1358         else
1359             h->state.param.working.sequence_id = 0;
1360     }
1361     hb_unlock( h->state_lock );
1362     hb_unlock( h->pause_lock );
1363 }