OSDN Git Service

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