OSDN Git Service

WinGui:
[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_deca52 ); 
220         hb_register( &hb_decdca ); 
221         hb_register( &hb_decavcodec ); 
222         hb_register( &hb_declpcm ); 
223         hb_register( &hb_encfaac ); 
224         hb_register( &hb_enclame ); 
225         hb_register( &hb_encvorbis ); 
226         
227         return h;
228 }
229
230
231 /**
232  * Returns current version of libhb.
233  * @param h Handle to hb_handle_t.
234  * @return character array of version number.
235  */
236 char * hb_get_version( hb_handle_t * h )
237 {
238     return HB_VERSION;
239 }
240
241 /**
242  * Returns current build of libhb.
243  * @param h Handle to hb_handle_t.
244  * @return character array of build number.
245  */
246 int hb_get_build( hb_handle_t * h )
247 {
248     return HB_BUILD;
249 }
250
251 /**
252  * Checks for needed update.
253  * @param h Handle to hb_handle_t.
254  * @param version Pointer to handle where version will be copied.
255  * @return update indicator.
256  */
257 int hb_check_update( hb_handle_t * h, char ** version )
258 {
259     *version = ( h->build < 0 ) ? NULL : h->version;
260     return h->build;
261 }
262
263 /**
264  * Sets the cpu count to the desired value.
265  * @param h Handle to hb_handle_t
266  * @param cpu_count Number of CPUs to use.
267  */
268 void hb_set_cpu_count( hb_handle_t * h, int cpu_count )
269 {
270     cpu_count    = MAX( 1, cpu_count );
271     cpu_count    = MIN( cpu_count, 8 );
272     h->cpu_count = cpu_count;
273 }
274
275 /**
276  * Initializes a scan of the by calling hb_scan_init
277  * @param h Handle to hb_handle_t
278  * @param path location of VIDEO_TS folder.
279  * @param title_index Desired title to scan.  0 for all titles.
280  */
281 void hb_scan( hb_handle_t * h, const char * path, int title_index )
282 {
283     hb_title_t * title;
284
285     /* Clean up from previous scan */
286     while( ( title = hb_list_item( h->list_title, 0 ) ) )
287     {
288         hb_list_rem( h->list_title, title );
289         hb_title_close( &title );
290     }
291     
292     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
293     h->scan_thread = hb_scan_init( h, path, title_index, h->list_title );
294 }
295
296 /**
297  * Returns the list of titles found.
298  * @param h Handle to hb_handle_t
299  * @return Handle to hb_list_t of the title list.
300  */
301 hb_list_t * hb_get_titles( hb_handle_t * h )
302 {
303     return h->list_title;
304 }
305
306 /**
307  * Create preview image of desired title a index of picture.
308  * @param h Handle to hb_handle_t.
309  * @param title Handle to hb_title_t of desired title.
310  * @param picture Index in title.
311  * @param buffer Handle to buufer were inage will be drawn.
312  */
313 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
314                      uint8_t * buffer )
315 {
316     hb_job_t           * job = title->job;
317     char                 filename[1024];
318     FILE               * file;
319     uint8_t            * buf1, * buf2, * buf3, * buf4, * pen;
320     uint32_t           * p32;
321     AVPicture            pic_in, pic_preview, pic_deint, pic_crop, pic_scale;
322     struct SwsContext  * context;
323     int                  i;
324
325     buf1 = malloc( title->width * title->height * 3 / 2 );
326     buf2 = malloc( title->width * title->height * 3 / 2 );
327     buf3 = malloc( title->width * title->height * 3 / 2 );
328     buf4 = malloc( title->width * title->height * 4 );
329     avpicture_fill( &pic_in, buf1, PIX_FMT_YUV420P,
330                     title->width, title->height );
331     avpicture_fill( &pic_deint, buf2, PIX_FMT_YUV420P,
332                     title->width, title->height );
333     avpicture_fill( &pic_scale, buf3, PIX_FMT_YUV420P,
334                     job->width, job->height );
335     avpicture_fill( &pic_preview, buf4, PIX_FMT_RGBA32,
336                     job->width, job->height );
337
338     // Allocate the AVPicture frames and fill in
339
340     memset( filename, 0, 1024 );
341
342     hb_get_tempory_filename( h, filename, "%x%d",
343                              (intptr_t) title, picture );
344
345     file = fopen( filename, "r" );
346     if( !file )
347     {
348         hb_log( "hb_get_preview: fopen failed" );
349         return;
350     }
351
352     fread( buf1, title->width * title->height * 3 / 2, 1, file );
353     fclose( file );
354
355     if( job->deinterlace )
356     {
357         // Deinterlace and crop
358         avpicture_deinterlace( &pic_deint, &pic_in, PIX_FMT_YUV420P, title->width, title->height );
359         av_picture_crop( &pic_crop, &pic_deint, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
360     }
361     else
362     {
363         // Crop
364         av_picture_crop( &pic_crop, &pic_in, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
365     }
366
367     // Get scaling context
368     context = sws_getContext(title->width  - (job->crop[2] + job->crop[3]),
369                              title->height - (job->crop[0] + job->crop[1]),
370                              PIX_FMT_YUV420P,
371                              job->width, job->height, PIX_FMT_YUV420P,
372                              (uint16_t)(SWS_LANCZOS|SWS_ACCURATE_RND), NULL, NULL, NULL);
373
374     // Scale
375     sws_scale(context,
376               pic_crop.data, pic_crop.linesize,
377               0, title->height - (job->crop[0] + job->crop[1]),
378               pic_scale.data, pic_scale.linesize);
379
380     // Free context
381     sws_freeContext( context );
382
383     // Get preview context
384     context = sws_getContext(job->width, job->height, PIX_FMT_YUV420P,
385                              job->width, job->height, PIX_FMT_RGBA32,
386                              (uint16_t)(SWS_LANCZOS|SWS_ACCURATE_RND), NULL, NULL, NULL);
387
388     // Create preview
389     sws_scale(context,
390               pic_scale.data, pic_scale.linesize,
391               0, job->height,
392               pic_preview.data, pic_preview.linesize);
393
394     // Free context
395     sws_freeContext( context );
396
397     /* Gray background */
398     p32 = (uint32_t *) buffer;
399     for( i = 0; i < ( title->width + 2 ) * ( title->height + 2 ); i++ )
400     {
401         p32[i] = 0xFF808080;
402     }
403
404     /* Draw the picture, centered, and draw the cropping zone */
405     pen = buffer + ( title->height - job->height ) *
406         ( title->width + 2 ) * 2 + ( title->width - job->width ) * 2;
407     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
408     pen += 4 * ( title->width + 2 );
409     for( i = 0; i < job->height; i++ )
410     {
411         uint8_t * nextLine;
412         nextLine = pen + 4 * ( title->width + 2 );
413         memset( pen, 0xFF, 4 );
414         pen += 4;
415         memcpy( pen, buf4 + 4 * job->width * i, 4 * job->width );
416         pen += 4 * job->width;
417         memset( pen, 0xFF, 4 );
418         pen = nextLine;
419     }
420     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
421
422     // Clean up
423     avpicture_free( &pic_preview );
424     avpicture_free( &pic_scale );
425     avpicture_free( &pic_deint );
426     avpicture_free( &pic_in );
427 }
428
429 /**
430  * Calculates job width and height for anamorphic content.
431  * @param job Handle to hb_job_t.
432  */
433 void hb_set_anamorphic_size( hb_job_t * job)
434 {
435     hb_title_t * title = job->title;
436
437     /* "Loose" anamorphic.
438         - Uses mod16-compliant dimensions,
439         - Allows users to set the width
440         - Handles ITU pixel aspects
441     */
442     
443     /* Set up some variables to make the math easier to follow. */
444     int cropped_width = title->width - job->crop[2] - job->crop[3] ;
445     int cropped_height = title->height - job->crop[0] - job->crop[1] ;
446     int storage_aspect = cropped_width * 10000 / cropped_height;        
447
448     /* Gotta handle bounding dimensions differently
449        than for non-anamorphic encodes:
450        If the width is too big, just reset it with no rescaling.
451        Instead of using the aspect-scaled job height,
452        we need to see if the job width divided by the storage aspect
453        is bigger than the max. If so, set it to the max (this is sloppy).
454        If not, set job height to job width divided by storage aspect.
455     */
456     if ( job->maxWidth && (job->maxWidth < job->width) )
457         job->width = job->maxWidth;
458         
459     if ( job->maxHeight && (job->maxHeight < (job->width / storage_aspect * 10000)) )
460     {
461         job->height = job->maxHeight;
462     }
463     else
464     {
465         job->height = job->width * 10000 / storage_aspect;
466     }
467         
468     /* Time to get picture dimensions that divide cleanly.
469        These variables will store temporary dimensions as we iterate. */
470     int i, w, h, mod;
471
472     /* In case the user specified a modulus, use it */
473     if (job->modulus)
474         mod = job->modulus;
475     else
476         mod = 16;
477         
478     /* Iterate through multiples of mod to find one close to job->width. */
479     for( i = 1;; i++ )
480     {
481         w = mod * i;
482         
483         if (w < job->width)
484         {
485             if ( ( job->width - w ) <= ( mod / 2 ) )
486                 /* We'll take a width that's
487                    smaller, but close enough. */
488                 break;
489         }
490         if (w == job->width)
491             /* Mod 16 dimensions, how nice! */
492             break;
493         if( w > job->width )
494         {
495             if ( ( w - job->width ) < (mod/2) )
496                 /* We'll take a width that's bigger, if we have to. */
497                 break;
498         }
499     }
500     job->width  = mod * (i);
501     
502     /* Now do the same for a mod-friendly value near job->height. */
503     for( i = 1;; i++)
504     {
505         h = i * mod;
506         
507         if (h < job->height)
508             {
509                 if ( ( job->height - h ) <= ( mod / 2 ))
510                     /* Go with a smaller height,
511                        if it's close enough.    */
512                     break;
513             }
514         if (h == job->height)
515             /* Mod 16 dimensions, how nice! */
516             break;
517             
518         if ( h > job->height)
519         {
520             if ( ( h - job->height ) < ( mod / 2 ))
521                 /* Use a taller height if necessary */
522                 break;
523         }
524     }
525     job->height = mod  * (i);
526     
527     if (cropped_width <= 706)
528     {
529         /* Handle ITU PARs */
530         if (title->height == 480)
531         {
532             /* It's NTSC */
533             if (title->aspect == 16)
534             {
535                 /* It's widescreen */
536                 job->pixel_aspect_width = 40;
537                 job->pixel_aspect_height = 33;
538             }
539             else
540             {
541                 /* It's 4:3 */
542                 job->pixel_aspect_width = 10;
543                 job->pixel_aspect_height = 11;
544             }
545         }
546         else if (title->height == 576)
547         {
548             /* It's PAL */
549             if(title->aspect == 16)
550             {
551                 /* It's widescreen */
552                 job->pixel_aspect_width = 16;
553                 job->pixel_aspect_height = 11;
554             }
555             else
556             {
557                 /* It's 4:3 */
558                 job->pixel_aspect_width = 12;
559                 job->pixel_aspect_height = 11;
560             }
561         }
562     }
563
564     /* Figure out what dimensions the source would display at. */
565     int source_display_width = cropped_width * ((float)job->pixel_aspect_width / (float)job->pixel_aspect_height) ;
566    
567     /* The film AR is the source's display width / cropped source height.
568        The output display width is the output height * film AR.
569        The output PAR is the output display width / output storage width. */
570     job->pixel_aspect_width = job->height * source_display_width / cropped_height;
571     job->pixel_aspect_height = job->width;
572     
573     /* While x264 is smart enough to reduce fractions on its own, libavcodec
574        needs some help with the math, so lose superfluous factors.            */
575     hb_reduce( &job->pixel_aspect_width, &job->pixel_aspect_height,
576                job->pixel_aspect_width, job->pixel_aspect_height );
577 }
578
579 /**
580  * Calculates job width, height, and cropping parameters.
581  * @param job Handle to hb_job_t.
582  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
583  * @param pixels Maximum desired pixel count.
584  */
585 void hb_set_size( hb_job_t * job, int aspect, int pixels )
586 {
587     hb_title_t * title = job->title;
588
589     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
590     int croppedHeight = title->height - title->crop[0] - title->crop[1];
591     int croppedAspect = title->aspect * title->height * croppedWidth /
592                             croppedHeight / title->width;
593     int addCrop;
594     int i, w, h;
595
596     if( aspect <= 0 )
597     {
598         /* Keep the best possible aspect ratio */
599         aspect = croppedAspect;
600     }
601
602     /* Crop if necessary to obtain the desired ratio */
603     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
604     if( aspect < croppedAspect )
605     {
606         /* Need to crop on the left and right */
607         addCrop = croppedWidth - aspect * croppedHeight * title->width /
608                     title->aspect / title->height;
609         if( addCrop & 3 )
610         {
611             addCrop = ( addCrop + 1 ) / 2;
612             job->crop[2] += addCrop;
613             job->crop[3] += addCrop;
614         }
615         else if( addCrop & 2 )
616         {
617             addCrop /= 2;
618             job->crop[2] += addCrop - 1;
619             job->crop[3] += addCrop + 1;
620         }
621         else
622         {
623             addCrop /= 2;
624             job->crop[2] += addCrop;
625             job->crop[3] += addCrop;
626         }
627     }
628     else if( aspect > croppedAspect )
629     {
630         /* Need to crop on the top and bottom */
631         addCrop = croppedHeight - croppedWidth * title->aspect *
632             title->height / aspect / title->width;
633         if( addCrop & 3 )
634         {
635             addCrop = ( addCrop + 1 ) / 2;
636             job->crop[0] += addCrop;
637             job->crop[1] += addCrop;
638         }
639         else if( addCrop & 2 )
640         {
641             addCrop /= 2;
642             job->crop[0] += addCrop - 1;
643             job->crop[1] += addCrop + 1;
644         }
645         else
646         {
647             addCrop /= 2;
648             job->crop[0] += addCrop;
649             job->crop[1] += addCrop;
650         }
651     }
652
653     /* Compute a resolution from the number of pixels and aspect */
654     for( i = 0;; i++ )
655     {
656         w = 16 * i;
657         h = MULTIPLE_16( w * HB_ASPECT_BASE / aspect );
658         if( w * h > pixels )
659         {
660             break;
661         }
662     }
663     i--;
664     job->width  = 16 * i;
665     job->height = MULTIPLE_16( 16 * i * HB_ASPECT_BASE / aspect );
666 }
667
668 /**
669  * Returns the number of jobs in the queue.
670  * @param h Handle to hb_handle_t.
671  * @return Number of jobs.
672  */
673 int hb_count( hb_handle_t * h )
674 {
675     return hb_list_count( h->jobs );
676 }
677
678 /**
679  * Returns handle to job at index i within the job list.
680  * @param h Handle to hb_handle_t.
681  * @param i Index of job.
682  * @returns Handle to hb_job_t of desired job.
683  */
684 hb_job_t * hb_job( hb_handle_t * h, int i )
685 {
686     return hb_list_item( h->jobs, i );
687 }
688
689 hb_job_t * hb_current_job( hb_handle_t * h )
690 {
691     return( h->current_job );
692 }
693
694 /**
695  * Adds a job to the job list.
696  * @param h Handle to hb_handle_t.
697  * @param job Handle to hb_job_t.
698  */
699 void hb_add( hb_handle_t * h, hb_job_t * job )
700 {
701     hb_job_t      * job_copy;
702     hb_title_t    * title,    * title_copy;
703     hb_chapter_t  * chapter,  * chapter_copy;
704     hb_audio_t    * audio,    * audio_copy;
705     hb_subtitle_t * subtitle, * subtitle_copy;
706     int             i;
707     char            audio_lang[4];
708
709     /* Copy the title */
710     title      = job->title;
711     title_copy = malloc( sizeof( hb_title_t ) );
712     memcpy( title_copy, title, sizeof( hb_title_t ) );
713
714     title_copy->list_chapter = hb_list_init();
715     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
716     {
717         chapter      = hb_list_item( title->list_chapter, i );
718         chapter_copy = malloc( sizeof( hb_chapter_t ) );
719         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
720         hb_list_add( title_copy->list_chapter, chapter_copy );
721     }
722
723     /* Copy the audio track(s) we want */
724     title_copy->list_audio = hb_list_init();
725
726     /* Do nothing about audio during first pass */
727     if( job->pass == 0 || job->pass == 2 )
728     {
729         for( i = 0; i < 8; i++ )
730         {
731             if( job->audios[i] < 0 )
732             {
733                 break;
734             }
735             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
736             {
737                 audio_copy = malloc( sizeof( hb_audio_t ) );
738                 memcpy( audio_copy, audio, sizeof( hb_audio_t ) );
739                 hb_list_add( title_copy->list_audio, audio_copy );
740             }
741         }
742     }
743
744     title_copy->list_subtitle = hb_list_init();
745
746     /*
747      * The following code is confusing, there are three ways in which
748      * we select subtitles and it depends on whether this is single or
749      * two pass mode.
750      *
751      * subtitle_scan may be enabled, in which case the first pass
752      * scans all subtitles of that language. The second pass does not
753      * select any because they are set at the end of the first pass.
754      *
755      * native_language may have a preferred language, in which case we
756      * may be switching the language we want for the subtitles in the
757      * first pass of a single pass, or the second pass of a two pass.
758      *
759      * We may have manually selected a subtitle, in which case that is
760      * selected in the first pass of a single pass, or the second of a
761      * two pass.
762      */
763     memset( audio_lang, 0, sizeof( audio_lang ) );
764
765     if ( job->indepth_scan || job->native_language ) {
766       
767         /*
768          * Find the first audio language that is being encoded
769          */
770         for( i = 0; i < 8; i++ )
771         {
772             if( job->audios[i] < 0 )
773             {
774                 break;
775             }
776             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
777             {
778                 strncpy(audio_lang, audio->iso639_2, sizeof(audio_lang));
779                 break;
780             }
781         }
782
783         /*
784          * In all cases switch the language if we need to to our native
785          * language.
786          */
787         if( job->native_language ) 
788         {
789             if( strncasecmp( job->native_language, audio_lang, 
790                              sizeof( audio_lang ) ) != 0 )
791             {             
792                 
793                 if( job->pass != 2 )
794                 {
795                     hb_log( "Enabled subtitles in native language '%s', audio is in '%s'",
796                             job->native_language, audio_lang);
797                 }
798                 /*
799                  * The main audio track is not in our native language, so switch
800                  * the subtitles to use our native language instead.
801                  */
802                 strncpy( audio_lang, job->native_language, sizeof( audio_lang ) );
803             } else {
804                 /*
805                  * native language is irrelevent, free it.
806                  */
807                 free( job->native_language );
808                 job->native_language = NULL;
809             }
810         }
811     }
812
813     /*
814      * If doing a subtitle scan then add all the matching subtitles for this
815      * language.
816      */
817     if ( job->indepth_scan ) 
818     {
819         for( i=0; i < hb_list_count( title->list_subtitle ); i++ ) 
820         {
821             subtitle = hb_list_item( title->list_subtitle, i );
822             if( strcmp( subtitle->iso639_2, audio_lang ) == 0 ) 
823             {
824                 /*
825                  * Matched subtitle language with audio language, so
826                  * add this to our list to scan.
827                  *
828                  * We will update the subtitle list on the second pass
829                  * later after the first pass has completed.
830                  */
831                 subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
832                 memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
833                 hb_list_add( title_copy->list_subtitle, subtitle_copy );
834                 if ( job->native_language ) {
835                     /*
836                      * With native language just select the
837                      * first match in our langiage, not all of
838                      * them. Subsequent ones are likely to be commentary
839                      */
840                     break;
841                 }
842             }
843         }
844     } else {
845         /*
846          * Not doing a subtitle scan in this pass, but maybe we are in the
847          * first pass?
848          */
849         if( job->select_subtitle )
850         {
851             /*
852              * Don't add subtitles here, we'll add them via select_subtitle
853              * at the end of the subtitle_scan.
854              */
855         } else {
856             /*
857              * Definitely not doing a subtitle scan.
858              */
859             if( job->pass != 1 && job->native_language ) 
860             {
861                 /*
862                  * We are not doing a subtitle scan but do want the
863                  * native langauge subtitle selected, so select it 
864                  * for pass 0 or pass 2 of a two pass.
865                  */
866                 for( i=0; i < hb_list_count( title->list_subtitle ); i++ ) 
867                 {
868                     subtitle = hb_list_item( title->list_subtitle, i );
869                     if( strcmp( subtitle->iso639_2, audio_lang ) == 0 ) 
870                     {
871                         /*
872                          * Matched subtitle language with audio language, so
873                          * add this to our list to scan.
874                          */
875                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
876                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
877                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
878                         break;
879                     }
880                 }
881             } else {
882                 /*
883                  * Manually selected subtitle, in which case only
884                  * bother adding them for pass 0 or pass 2 of a two
885                  * pass.
886                  */
887                 if( job->pass != 1 ) 
888                 {
889                     if( ( subtitle = hb_list_item( title->list_subtitle, job->subtitle ) ) )
890                     {
891                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
892                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
893                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
894                     }
895                 }
896             }
897         }
898     }
899
900     /* Copy the job */
901     job_copy        = calloc( sizeof( hb_job_t ), 1 );
902     memcpy( job_copy, job, sizeof( hb_job_t ) );
903     title_copy->job = job_copy;
904     job_copy->title = title_copy;
905     job_copy->file  = strdup( job->file );
906     job_copy->h     = h;
907     job_copy->pause = h->pause_lock;
908
909     /* Copy the job filter list */
910     if( job->filters )
911     {
912         int i;
913         int filter_count = hb_list_count( job->filters );
914         job_copy->filters = hb_list_init();        
915         for( i = 0; i < filter_count; i++ )
916         {
917             hb_filter_object_t * filter = hb_list_item( job->filters, i );
918             hb_list_add( job_copy->filters, filter );
919         }        
920     }
921     
922     /* Add the job to the list */
923     hb_list_add( h->jobs, job_copy );
924     h->job_count = hb_count(h);
925     h->job_count_permanent++;
926 }
927
928 /**
929  * Removes a job from the job list.
930  * @param h Handle to hb_handle_t.
931  * @param job Handle to hb_job_t.
932  */
933 void hb_rem( hb_handle_t * h, hb_job_t * job )
934 {
935     hb_list_rem( h->jobs, job );
936     
937     h->job_count = hb_count(h);
938     if (h->job_count_permanent)
939         h->job_count_permanent--;
940
941     /* XXX free everything XXX */
942 }
943
944 /**
945  * Starts the conversion process.
946  * Sets state to HB_STATE_WORKING.
947  * calls hb_work_init, to launch work thread. Stores handle to work thread.
948  * @param h Handle to hb_handle_t.
949  */
950 void hb_start( hb_handle_t * h )
951 {
952     /* XXX Hack */
953     h->job_count = hb_list_count( h->jobs );
954     h->job_count_permanent = h->job_count;
955
956     hb_lock( h->state_lock );
957     h->state.state = HB_STATE_WORKING;
958 #define p h->state.param.working
959     p.progress  = 0.0;
960     p.job_cur   = 1;
961     p.job_count = h->job_count;
962     p.rate_cur  = 0.0;
963     p.rate_avg  = 0.0;
964     p.hours     = -1;
965     p.minutes   = -1;
966     p.seconds   = -1;
967     p.sequence_id = 0;
968 #undef p
969     hb_unlock( h->state_lock );
970
971     h->paused = 0;
972
973     h->work_die    = 0;
974     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
975                                    &h->work_die, &h->work_error, &h->current_job );
976 }
977
978 /**
979  * Pauses the conversion process.
980  * @param h Handle to hb_handle_t.
981  */
982 void hb_pause( hb_handle_t * h )
983 {
984     if( !h->paused )
985     {
986         hb_lock( h->pause_lock );
987         h->paused = 1;
988
989         hb_lock( h->state_lock );
990         h->state.state = HB_STATE_PAUSED;
991         hb_unlock( h->state_lock );
992     }
993 }
994
995 /**
996  * Resumes the conversion process.
997  * @param h Handle to hb_handle_t.
998  */
999 void hb_resume( hb_handle_t * h )
1000 {
1001     if( h->paused )
1002     {
1003         hb_unlock( h->pause_lock );
1004         h->paused = 0;
1005     }
1006 }
1007
1008 /**
1009  * Stops the conversion process.
1010  * @param h Handle to hb_handle_t.
1011  */
1012 void hb_stop( hb_handle_t * h )
1013 {
1014     h->work_die = 1;
1015
1016     h->job_count = hb_count(h);
1017     h->job_count_permanent = 0;
1018
1019     hb_resume( h );
1020 }
1021
1022 /**
1023  * Returns the state of the conversion process.
1024  * @param h Handle to hb_handle_t.
1025  * @param s Handle to hb_state_t which to copy the state data.
1026  */
1027 void hb_get_state( hb_handle_t * h, hb_state_t * s )
1028 {
1029     hb_lock( h->state_lock );
1030
1031     memcpy( s, &h->state, sizeof( hb_state_t ) );
1032     if ( h->state.state == HB_STATE_SCANDONE || h->state.state == HB_STATE_WORKDONE )
1033         h->state.state = HB_STATE_IDLE;
1034
1035     hb_unlock( h->state_lock );
1036 }
1037
1038 void hb_get_state2( hb_handle_t * h, hb_state_t * s )
1039 {
1040     hb_lock( h->state_lock );
1041
1042     memcpy( s, &h->state, sizeof( hb_state_t ) );
1043
1044     hb_unlock( h->state_lock );
1045 }
1046
1047 /**
1048  * Called in MacGui in UpdateUI to check
1049  *  for a new scan being completed to set a new source
1050  */
1051 int hb_get_scancount( hb_handle_t * h)
1052  {
1053      return h->scanCount;
1054  }
1055
1056 /**
1057  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init_real.
1058  * @param _h Pointer to handle to hb_handle_t.
1059  */
1060 void hb_close( hb_handle_t ** _h )
1061 {
1062     hb_handle_t * h = *_h;
1063     hb_title_t * title;
1064
1065     h->die = 1;
1066     hb_thread_close( &h->main_thread );
1067
1068     while( ( title = hb_list_item( h->list_title, 0 ) ) )
1069     {
1070         hb_list_rem( h->list_title, title );
1071         if( title->job && title->job->filters )
1072         {
1073             hb_list_close( &title->job->filters );
1074         }
1075         free( title->job );
1076         hb_title_close( &title );
1077     }
1078     hb_list_close( &h->list_title );
1079
1080     hb_list_close( &h->jobs );
1081     hb_lock_close( &h->state_lock );
1082     hb_lock_close( &h->pause_lock );
1083     free( h );
1084     *_h = NULL;
1085
1086 }
1087
1088 /**
1089  * Monitors the state of the update, scan, and work threads.
1090  * Sets scan done state when scan thread exits.
1091  * Sets work done state when work thread exits.
1092  * @param _h Handle to hb_handle_t
1093  */
1094 static void thread_func( void * _h )
1095 {
1096     hb_handle_t * h = (hb_handle_t *) _h;
1097     char dirname[1024];
1098     DIR * dir;
1099     struct dirent * entry;
1100
1101     h->pid = getpid();
1102
1103     /* Create folder for temporary files */
1104     memset( dirname, 0, 1024 );
1105     hb_get_tempory_directory( h, dirname );
1106
1107     hb_mkdir( dirname );
1108
1109     while( !h->die )
1110     {
1111         /* In case the check_update thread hangs, it'll die sooner or
1112            later. Then, we join it here */
1113         if( h->update_thread &&
1114             hb_thread_has_exited( h->update_thread ) )
1115         {
1116             hb_thread_close( &h->update_thread );
1117         }
1118
1119         /* Check if the scan thread is done */
1120         if( h->scan_thread &&
1121             hb_thread_has_exited( h->scan_thread ) )
1122         {
1123             hb_thread_close( &h->scan_thread );
1124
1125             hb_log( "libhb: scan thread found %d valid title(s)",
1126                     hb_list_count( h->list_title ) );
1127             hb_lock( h->state_lock );
1128             h->state.state = HB_STATE_SCANDONE; //originally state.state
1129                         hb_unlock( h->state_lock );
1130                         /*we increment this sessions scan count by one for the MacGui
1131                         to trigger a new source being set */
1132             h->scanCount++;
1133         }
1134
1135         /* Check if the work thread is done */
1136         if( h->work_thread &&
1137             hb_thread_has_exited( h->work_thread ) )
1138         {
1139             hb_thread_close( &h->work_thread );
1140
1141             hb_log( "libhb: work result = %d",
1142                     h->work_error );
1143             hb_lock( h->state_lock );
1144             h->state.state                = HB_STATE_WORKDONE;
1145             h->state.param.workdone.error = h->work_error;
1146             
1147             h->job_count = hb_count(h);
1148             if (h->job_count < 1)
1149                 h->job_count_permanent = 0;
1150             hb_unlock( h->state_lock );
1151         }
1152
1153         hb_snooze( 50 );
1154     }
1155
1156     if( h->work_thread )
1157     {
1158         hb_stop( h );
1159         hb_thread_close( &h->work_thread );
1160     }
1161
1162     /* Remove temp folder */
1163     dir = opendir( dirname );
1164     while( ( entry = readdir( dir ) ) )
1165     {
1166         char filename[1024];
1167         if( entry->d_name[0] == '.' )
1168         {
1169             continue;
1170         }
1171         memset( filename, 0, 1024 );
1172         snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
1173         unlink( filename );
1174     }
1175     closedir( dir );
1176     rmdir( dirname );
1177 }
1178
1179 /**
1180  * Returns the PID.
1181  * @param h Handle to hb_handle_t
1182  */
1183 int hb_get_pid( hb_handle_t * h )
1184 {
1185     return h->pid;
1186 }
1187
1188 /**
1189  * Sets the current state.
1190  * @param h Handle to hb_handle_t
1191  * @param s Handle to new hb_state_t
1192  */
1193 void hb_set_state( hb_handle_t * h, hb_state_t * s )
1194 {
1195     hb_lock( h->pause_lock );
1196     hb_lock( h->state_lock );
1197     memcpy( &h->state, s, sizeof( hb_state_t ) );
1198     if( h->state.state == HB_STATE_WORKING )
1199     {
1200         /* XXX Hack */
1201         if (h->job_count < 1)
1202             h->job_count_permanent = 1;
1203         
1204         h->state.param.working.job_cur =
1205             h->job_count_permanent - hb_list_count( h->jobs );
1206         h->state.param.working.job_count = h->job_count_permanent;
1207         
1208         // Set which job is being worked on
1209         if (h->current_job)
1210             h->state.param.working.sequence_id = h->current_job->sequence_id;
1211         else
1212             h->state.param.working.sequence_id = 0;
1213     }
1214     hb_unlock( h->state_lock );
1215     hb_unlock( h->pause_lock );
1216 }