OSDN Git Service

Native language subtitle scan improvements. Thanks, eddyg!
[handbrake-jp/handbrake-jp-git.git] / libhb / hb.c
1 #include "hb.h"
2
3 #include "ffmpeg/avcodec.h"
4
5 struct hb_handle_s
6 {
7     /* The "Check for update" thread */
8     int            build;
9     char           version[16];
10     hb_thread_t  * update_thread;
11
12     /* This thread's only purpose is to check other threads'
13        states */
14     volatile int   die;
15     hb_thread_t  * main_thread;
16     int            pid;
17
18     /* DVD/file scan thread */
19     hb_list_t    * list_title;
20     hb_thread_t  * scan_thread;
21
22     /* The thread which processes the jobs. Others threads are launched
23        from this one (see work.c) */
24     hb_list_t    * jobs;
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_work_object_t * hb_objects = NULL;
45
46 static void thread_func( void * );
47
48 /**
49  * Registers work objects, by adding the work object to a liked list.
50  * @param w Handle to hb_work_object_t to register.
51  */
52 void hb_register( hb_work_object_t * w )
53 {
54     w->next    = hb_objects;
55     hb_objects = w;
56 }
57
58 /**
59  * libhb initialization routine.
60  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
61  * @param update_check signals libhb to check for updated version from HandBrake website.
62  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
63  */
64 hb_handle_t * hb_init_real( int verbose, int update_check )
65 {
66     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
67     uint64_t      date;
68
69     /* See hb_log() in common.c */
70     if( verbose > HB_DEBUG_NONE )
71     {
72         putenv( "HB_DEBUG=1" );
73                 av_log_set_level(AV_LOG_DEBUG);
74     }
75
76     /* Check for an update on the website if asked to */
77     h->build = -1;
78
79     if( update_check )
80     {
81         hb_log( "hb_init: checking for updates" );
82         date             = hb_get_date();
83         h->update_thread = hb_update_init( &h->build, h->version );
84
85         for( ;; )
86         {
87             if( hb_thread_has_exited( h->update_thread ) )
88             {
89                 /* Immediate success or failure */
90                 hb_thread_close( &h->update_thread );
91                 break;
92             }
93             if( hb_get_date() > date + 1000 )
94             {
95                 /* Still nothing after one second. Connection problem,
96                    let the thread die */
97                 hb_log( "hb_init: connection problem, not waiting for "
98                         "update_thread" );
99                 break;
100             }
101             hb_snooze( 500 );
102         }
103     }
104
105     /* CPU count detection */
106     hb_log( "hb_init: checking cpu count" );
107     h->cpu_count = hb_get_cpu_count();
108
109     h->list_title = hb_list_init();
110     h->jobs       = hb_list_init();
111
112     h->state_lock  = hb_lock_init();
113     h->state.state = HB_STATE_IDLE;
114
115     h->pause_lock = hb_lock_init();
116
117     /* libavcodec */
118     avcodec_init();
119     register_avcodec( &mpeg4_encoder );
120     register_avcodec( &mp2_decoder );
121     register_avcodec( &ac3_encoder );
122     av_register_codec_parser( &mpegaudio_parser);
123     
124     /* Start library thread */
125     hb_log( "hb_init: starting libhb thread" );
126     h->die         = 0;
127     h->main_thread = hb_thread_init( "libhb", thread_func, h,
128                                      HB_NORMAL_PRIORITY );
129
130     return h;
131         
132         /* Set the scan count to start at 0 */
133         //scan_count = 0;
134 }
135
136 /**
137  * libhb initialization routine.
138  * This version is to use when calling the dylib, the macro hb_init isn't available from a dylib call!
139  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
140  * @param update_check signals libhb to check for updated version from HandBrake website.
141  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
142  */
143 hb_handle_t * hb_init_dl( int verbose, int update_check )
144 {
145     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
146     uint64_t      date;
147
148     /* See hb_log() in common.c */
149     if( verbose > HB_DEBUG_NONE )
150     {
151         putenv( "HB_DEBUG=1" );
152                 av_log_set_level(AV_LOG_DEBUG);
153     }
154
155     /* Check for an update on the website if asked to */
156     h->build = -1;
157
158     if( update_check )
159     {
160         hb_log( "hb_init: checking for updates" );
161         date             = hb_get_date();
162         h->update_thread = hb_update_init( &h->build, h->version );
163
164         for( ;; )
165         {
166             if( hb_thread_has_exited( h->update_thread ) )
167             {
168                 /* Immediate success or failure */
169                 hb_thread_close( &h->update_thread );
170                 break;
171             }
172             if( hb_get_date() > date + 1000 )
173             {
174                 /* Still nothing after one second. Connection problem,
175                    let the thread die */
176                 hb_log( "hb_init: connection problem, not waiting for "
177                         "update_thread" );
178                 break;
179             }
180             hb_snooze( 500 );
181         }
182     }
183
184     /* CPU count detection */
185     hb_log( "hb_init: checking cpu count" );
186     h->cpu_count = hb_get_cpu_count();
187
188     h->list_title = hb_list_init();
189     h->jobs       = hb_list_init();
190
191     h->state_lock  = hb_lock_init();
192     h->state.state = HB_STATE_IDLE;
193
194     h->pause_lock = hb_lock_init();
195
196     /* libavcodec */
197     avcodec_init();
198     register_avcodec( &mpeg4_encoder );
199     register_avcodec( &mp2_decoder );
200     register_avcodec( &ac3_encoder );
201
202     /* Start library thread */
203     hb_log( "hb_init: starting libhb thread" );
204     h->die         = 0;
205     h->main_thread = hb_thread_init( "libhb", thread_func, h,
206                                      HB_NORMAL_PRIORITY );
207
208     hb_register( &hb_sync ); 
209         hb_register( &hb_decmpeg2 ); 
210         hb_register( &hb_decsub ); 
211         hb_register( &hb_render ); 
212         hb_register( &hb_encavcodec ); 
213         hb_register( &hb_encxvid ); 
214         hb_register( &hb_encx264 ); 
215         hb_register( &hb_deca52 ); 
216         hb_register( &hb_decdca ); 
217         hb_register( &hb_decavcodec ); 
218         hb_register( &hb_declpcm ); 
219         hb_register( &hb_encfaac ); 
220         hb_register( &hb_enclame ); 
221         hb_register( &hb_encvorbis ); 
222         
223         return h;
224 }
225
226
227 /**
228  * Returns current version of libhb.
229  * @param h Handle to hb_handle_t.
230  * @return character array of version number.
231  */
232 char * hb_get_version( hb_handle_t * h )
233 {
234     return HB_VERSION;
235 }
236
237 /**
238  * Returns current build of libhb.
239  * @param h Handle to hb_handle_t.
240  * @return character array of build number.
241  */
242 int hb_get_build( hb_handle_t * h )
243 {
244     return HB_BUILD;
245 }
246
247 /**
248  * Checks for needed update.
249  * @param h Handle to hb_handle_t.
250  * @param version Pointer to handle where version will be copied.
251  * @return update indicator.
252  */
253 int hb_check_update( hb_handle_t * h, char ** version )
254 {
255     *version = ( h->build < 0 ) ? NULL : h->version;
256     return h->build;
257 }
258
259 /**
260  * Sets the cpu count to the desired value.
261  * @param h Handle to hb_handle_t
262  * @param cpu_count Number of CPUs to use.
263  */
264 void hb_set_cpu_count( hb_handle_t * h, int cpu_count )
265 {
266     cpu_count    = MAX( 1, cpu_count );
267     cpu_count    = MIN( cpu_count, 8 );
268     h->cpu_count = cpu_count;
269 }
270
271 /**
272  * Initializes a scan of the by calling hb_scan_init
273  * @param h Handle to hb_handle_t
274  * @param path location of VIDEO_TS folder.
275  * @param title_index Desired title to scan.  0 for all titles.
276  */
277 void hb_scan( hb_handle_t * h, const char * path, int title_index )
278 {
279     hb_title_t * title;
280
281     /* Clean up from previous scan */
282     while( ( title = hb_list_item( h->list_title, 0 ) ) )
283     {
284         hb_list_rem( h->list_title, title );
285         hb_title_close( &title );
286     }
287     
288     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
289     h->scan_thread = hb_scan_init( h, path, title_index, h->list_title );
290 }
291
292 /**
293  * Returns the list of titles found.
294  * @param h Handle to hb_handle_t
295  * @return Handle to hb_list_t of the title list.
296  */
297 hb_list_t * hb_get_titles( hb_handle_t * h )
298 {
299     return h->list_title;
300 }
301
302 /**
303  * Create preview image of desired title a index of picture.
304  * @param h Handle to hb_handle_t.
305  * @param title Handle to hb_title_t of desired title.
306  * @param picture Index in title.
307  * @param buffer Handle to buufer were inage will be drawn.
308  */
309 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
310                      uint8_t * buffer )
311 {
312     hb_job_t           * job = title->job;
313     char                 filename[1024];
314     FILE               * file;
315     uint8_t            * buf1, * buf2, * buf3, * buf4, * pen;
316     uint32_t           * p32;
317     AVPicture            pic1, pic2, pic3, pic4;
318     ImgReSampleContext * context;
319     int                  i;
320
321     buf1 = malloc( title->width * title->height * 3 / 2 );
322     buf2 = malloc( title->width * title->height * 3 / 2 );
323     buf3 = malloc( title->width * title->height * 3 / 2 );
324     buf4 = malloc( title->width * title->height * 4 );
325     avpicture_fill( &pic1, buf1, PIX_FMT_YUV420P,
326                     title->width, title->height );
327     avpicture_fill( &pic2, buf2, PIX_FMT_YUV420P,
328                     title->width, title->height );
329     avpicture_fill( &pic3, buf3, PIX_FMT_YUV420P,
330                     job->width, job->height );
331     avpicture_fill( &pic4, buf4, PIX_FMT_RGBA32,
332                     job->width, job->height );
333     
334     memset( filename, 0, 1024 );
335
336     hb_get_tempory_filename( h, filename, "%x%d",
337                              (intptr_t) title, picture );
338
339     file = fopen( filename, "r" );
340     if( !file )
341     {
342         hb_log( "hb_get_preview: fopen failed" );
343         return;
344     }
345
346     fread( buf1, title->width * title->height * 3 / 2, 1, file );
347     fclose( file );
348
349     context = img_resample_full_init(
350             job->width, job->height, title->width, title->height,
351             job->crop[0], job->crop[1], job->crop[2], job->crop[3],
352             0, 0, 0, 0 );
353
354     if( job->deinterlace )
355     {
356         avpicture_deinterlace( &pic2, &pic1, PIX_FMT_YUV420P,
357                                title->width, title->height );
358         img_resample( context, &pic3, &pic2 );
359     }
360     else
361     {
362         img_resample( context, &pic3, &pic1 );
363     }
364     img_convert( &pic4, PIX_FMT_RGBA32, &pic3, PIX_FMT_YUV420P,
365                  job->width, job->height );
366
367     /* Gray background */
368     p32 = (uint32_t *) buffer;
369     for( i = 0; i < ( title->width + 2 ) * ( title->height + 2 ); i++ )
370     {
371         p32[i] = 0xFF808080;
372     }
373
374     /* Draw the picture, centered, and draw the cropping zone */
375     pen = buffer + ( title->height - job->height ) *
376         ( title->width + 2 ) * 2 + ( title->width - job->width ) * 2;
377     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
378     pen += 4 * ( title->width + 2 );
379     for( i = 0; i < job->height; i++ )
380     {
381         uint8_t * nextLine;
382         nextLine = pen + 4 * ( title->width + 2 );
383         memset( pen, 0xFF, 4 );
384         pen += 4;
385         memcpy( pen, buf4 + 4 * job->width * i, 4 * job->width );
386         pen += 4 * job->width;
387         memset( pen, 0xFF, 4 );
388         pen = nextLine;
389     }
390     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
391
392     free( buf1 );
393     free( buf2 );
394     free( buf3 );
395     free( buf4 );
396 }
397
398 /**
399  * Calculates job width, height, and cropping parameters.
400  * @param job Handle to hb_job_t.
401  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
402  * @param pixels Maximum desired pixel count.
403  */
404 void hb_set_size( hb_job_t * job, int aspect, int pixels )
405 {
406     hb_title_t * title = job->title;
407
408     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
409     int croppedHeight = title->height - title->crop[0] - title->crop[1];
410     int croppedAspect = title->aspect * title->height * croppedWidth /
411                             croppedHeight / title->width;
412     int addCrop;
413     int i, w, h;
414
415     if( aspect <= 0 )
416     {
417         /* Keep the best possible aspect ratio */
418         aspect = croppedAspect;
419     }
420
421     /* Crop if necessary to obtain the desired ratio */
422     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
423     if( aspect < croppedAspect )
424     {
425         /* Need to crop on the left and right */
426         addCrop = croppedWidth - aspect * croppedHeight * title->width /
427                     title->aspect / title->height;
428         if( addCrop & 3 )
429         {
430             addCrop = ( addCrop + 1 ) / 2;
431             job->crop[2] += addCrop;
432             job->crop[3] += addCrop;
433         }
434         else if( addCrop & 2 )
435         {
436             addCrop /= 2;
437             job->crop[2] += addCrop - 1;
438             job->crop[3] += addCrop + 1;
439         }
440         else
441         {
442             addCrop /= 2;
443             job->crop[2] += addCrop;
444             job->crop[3] += addCrop;
445         }
446     }
447     else if( aspect > croppedAspect )
448     {
449         /* Need to crop on the top and bottom */
450         addCrop = croppedHeight - croppedWidth * title->aspect *
451             title->height / aspect / title->width;
452         if( addCrop & 3 )
453         {
454             addCrop = ( addCrop + 1 ) / 2;
455             job->crop[0] += addCrop;
456             job->crop[1] += addCrop;
457         }
458         else if( addCrop & 2 )
459         {
460             addCrop /= 2;
461             job->crop[0] += addCrop - 1;
462             job->crop[1] += addCrop + 1;
463         }
464         else
465         {
466             addCrop /= 2;
467             job->crop[0] += addCrop;
468             job->crop[1] += addCrop;
469         }
470     }
471
472     /* Compute a resolution from the number of pixels and aspect */
473     for( i = 0;; i++ )
474     {
475         w = 16 * i;
476         h = MULTIPLE_16( w * HB_ASPECT_BASE / aspect );
477         if( w * h > pixels )
478         {
479             break;
480         }
481     }
482     i--;
483     job->width  = 16 * i;
484     job->height = MULTIPLE_16( 16 * i * HB_ASPECT_BASE / aspect );
485 }
486
487 /**
488  * Returns the number of jobs in the queue.
489  * @param h Handle to hb_handle_t.
490  * @return Number of jobs.
491  */
492 int hb_count( hb_handle_t * h )
493 {
494     return hb_list_count( h->jobs );
495 }
496
497 /**
498  * Returns handle to job at index i within the job list.
499  * @param h Handle to hb_handle_t.
500  * @param i Index of job.
501  * @returns Handle to hb_job_t of desired job.
502  */
503 hb_job_t * hb_job( hb_handle_t * h, int i )
504 {
505     return hb_list_item( h->jobs, i );
506 }
507
508 /**
509  * Adds a job to the job list.
510  * @param h Handle to hb_handle_t.
511  * @param job Handle to hb_job_t.
512  */
513 void hb_add( hb_handle_t * h, hb_job_t * job )
514 {
515     hb_job_t      * job_copy;
516     hb_title_t    * title,    * title_copy;
517     hb_chapter_t  * chapter,  * chapter_copy;
518     hb_audio_t    * audio,    * audio_copy;
519     hb_subtitle_t * subtitle, * subtitle_copy;
520     int             i;
521     char            audio_lang[4];
522
523     /* Copy the title */
524     title      = job->title;
525     title_copy = malloc( sizeof( hb_title_t ) );
526     memcpy( title_copy, title, sizeof( hb_title_t ) );
527
528     title_copy->list_chapter = hb_list_init();
529     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
530     {
531         chapter      = hb_list_item( title->list_chapter, i );
532         chapter_copy = malloc( sizeof( hb_chapter_t ) );
533         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
534         hb_list_add( title_copy->list_chapter, chapter_copy );
535     }
536
537     /* Copy the audio track(s) we want */
538     title_copy->list_audio = hb_list_init();
539
540     /* Do nothing about audio during first pass */
541     if( job->pass != 1 )
542     {
543         for( i = 0; i < 8; i++ )
544         {
545             if( job->audios[i] < 0 )
546             {
547                 break;
548             }
549             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
550             {
551                 audio_copy = malloc( sizeof( hb_audio_t ) );
552                 memcpy( audio_copy, audio, sizeof( hb_audio_t ) );
553                 hb_list_add( title_copy->list_audio, audio_copy );
554             }
555         }
556     }
557
558     title_copy->list_subtitle = hb_list_init();
559
560     /*
561      * The following code is confusing, there are three ways in which we select subtitles
562      * and it depends on whether this is single or two pass mode.
563      *
564      * subtitle_scan may be enabled, in which case the first pass scans all subtitles
565      * of that language. The second pass does not select any because they are set at the
566      * end of the first pass.
567      *
568      * native_language may have a preferred language, in which case we may be switching
569      * the language we want for the subtitles in the first pass of a single pass, or the
570      * second pass of a two pass.
571      *
572      * We may have manually selected a subtitle, in which case that is selected in the
573      * first pass of a single pass, or the second of a two pass.
574      */
575     memset( audio_lang, 0, sizeof( audio_lang ) );
576
577     if ( job->subtitle_scan || job->native_language ) {
578       
579         /*
580          * Find the first audio language that is being encoded
581          */
582         for( i = 0; i < 8; i++ )
583         {
584             if( job->audios[i] < 0 )
585             {
586                 break;
587             }
588             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
589             {
590                 strncpy(audio_lang, audio->iso639_2, sizeof(audio_lang));
591                 break;
592             }
593         }
594
595         /*
596          * In all cases switch the language if we need to to our native
597          * language.
598          */
599         if( job->native_language ) 
600         {
601             if( strncasecmp( job->native_language, audio_lang, 
602                              sizeof( audio_lang ) ) != 0 )
603             {             
604                 
605                 if( job->pass != 2 )
606                 {
607                     hb_log( "Enabled subtitles in native language '%s', audio is in '%s'",
608                             job->native_language, audio_lang);
609                 }
610                 /*
611                  * The main audio track is not in our native language, so switch
612                  * the subtitles to use our native language instead.
613                  */
614                 strncpy( audio_lang, job->native_language, sizeof( audio_lang ) );
615             } else {
616                 /*
617                  * native language is irrelevent, free it.
618                  */
619                 free( job->native_language );
620                 job->native_language = NULL;
621             }
622         }
623     }
624
625     /*
626      * If doing a subtitle scan then add all the matching subtitles for this
627      * language.
628      */
629     if ( job->subtitle_scan ) 
630     {
631         for( i=0; i < hb_list_count( title->list_subtitle ); i++ ) 
632         {
633             subtitle = hb_list_item( title->list_subtitle, i );
634             if( strcmp( subtitle->iso639_2, audio_lang ) == 0 ) 
635             {
636                 /*
637                  * Matched subtitle language with audio language, so
638                  * add this to our list to scan.
639                  *
640                  * We will update the subtitle list on the second pass
641                  * later after the first pass has completed.
642                  */
643                 subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
644                 memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
645                 hb_list_add( title_copy->list_subtitle, subtitle_copy );
646                 if ( job->native_language ) {
647                     /*
648                      * With native language just select the
649                      * first match in our langiage, not all of
650                      * them. Subsequent ones are likely to be commentary
651                      */
652                     break;
653                 }
654             }
655         }
656     } else {
657         /*
658          * Not doing a subtitle scan in this pass, but maybe we are in the
659          * first pass?
660          */
661         if( job->select_subtitle )
662         {
663             /*
664              * Don't add subtitles here, we'll add them via select_subtitle
665              * at the end of pass 1
666              */
667         } else {
668             /*
669              * Definitely not doing a subtitle scan.
670              */
671             if( job->pass != 1 && job->native_language ) 
672             {
673                 /*
674                  * We are not doing a subtitle scan but do want the
675                  * native langauge subtitle selected, so select it 
676                  * for pass 0 or pass 2 of a two pass.
677                  */
678                 for( i=0; i < hb_list_count( title->list_subtitle ); i++ ) 
679                 {
680                     subtitle = hb_list_item( title->list_subtitle, i );
681                     if( strcmp( subtitle->iso639_2, audio_lang ) == 0 ) 
682                     {
683                         /*
684                          * Matched subtitle language with audio language, so
685                          * add this to our list to scan.
686                          */
687                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
688                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
689                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
690                         break;
691                     }
692                 }
693             } else {
694                 /*
695                  * Manually selected subtitle, in which case only
696                  * bother adding them for pass 0 or pass 2 of a two
697                  * pass.
698                  */
699                 if( job->pass != 1 ) 
700                 {
701                     if( ( subtitle = hb_list_item( title->list_subtitle, job->subtitle ) ) )
702                     {
703                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
704                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
705                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
706                     }
707                 }
708             }
709         }
710     }
711
712     /* Copy the job */
713     job_copy        = calloc( sizeof( hb_job_t ), 1 );
714     memcpy( job_copy, job, sizeof( hb_job_t ) );
715     title_copy->job = job_copy;
716     job_copy->title = title_copy;
717     job_copy->file  = strdup( job->file );
718     job_copy->h     = h;
719     job_copy->pause = h->pause_lock;
720
721     /* Add the job to the list */
722     hb_list_add( h->jobs, job_copy );
723     h->job_count = hb_count(h);
724     h->job_count_permanent++;
725 }
726
727 /**
728  * Removes a job from the job list.
729  * @param h Handle to hb_handle_t.
730  * @param job Handle to hb_job_t.
731  */
732 void hb_rem( hb_handle_t * h, hb_job_t * job )
733 {
734     hb_list_rem( h->jobs, job );
735     
736     h->job_count = hb_count(h);
737     if (h->job_count_permanent)
738         h->job_count_permanent--;
739
740     /* XXX free everything XXX */
741 }
742
743 /**
744  * Starts the conversion process.
745  * Sets state to HB_STATE_WORKING.
746  * calls hb_work_init, to launch work thread. Stores handle to work thread.
747  * @param h Handle to hb_handle_t.
748  */
749 void hb_start( hb_handle_t * h )
750 {
751     /* XXX Hack */
752     h->job_count = hb_list_count( h->jobs );
753
754     hb_lock( h->state_lock );
755     h->state.state = HB_STATE_WORKING;
756 #define p h->state.param.working
757     p.progress  = 0.0;
758     p.job_cur   = 1;
759     p.job_count = h->job_count;
760     p.rate_cur  = 0.0;
761     p.rate_avg  = 0.0;
762     p.hours     = -1;
763     p.minutes   = -1;
764     p.seconds   = -1;
765 #undef p
766     hb_unlock( h->state_lock );
767
768     h->paused = 0;
769
770     h->work_die    = 0;
771     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
772                                    &h->work_die, &h->work_error );
773 }
774
775 /**
776  * Pauses the conversion process.
777  * @param h Handle to hb_handle_t.
778  */
779 void hb_pause( hb_handle_t * h )
780 {
781     if( !h->paused )
782     {
783         hb_lock( h->pause_lock );
784         h->paused = 1;
785
786         hb_lock( h->state_lock );
787         h->state.state = HB_STATE_PAUSED;
788         hb_unlock( h->state_lock );
789     }
790 }
791
792 /**
793  * Resumes the conversion process.
794  * @param h Handle to hb_handle_t.
795  */
796 void hb_resume( hb_handle_t * h )
797 {
798     if( h->paused )
799     {
800         hb_unlock( h->pause_lock );
801         h->paused = 0;
802     }
803 }
804
805 /**
806  * Stops the conversion process.
807  * @param h Handle to hb_handle_t.
808  */
809 void hb_stop( hb_handle_t * h )
810 {
811     h->work_die = 1;
812
813     h->job_count = hb_count(h);
814     h->job_count_permanent = 0;
815
816     hb_resume( h );
817 }
818
819 /**
820  * Returns the state of the conversion process.
821  * @param h Handle to hb_handle_t.
822  * @param s Handle to hb_state_t which to copy the state data.
823  */
824 void hb_get_state( hb_handle_t * h, hb_state_t * s )
825 {
826     hb_lock( h->state_lock );
827
828     memcpy( s, &h->state, sizeof( hb_state_t ) );
829     h->state.state = HB_STATE_IDLE;
830
831     hb_unlock( h->state_lock );
832 }
833
834 /**
835  * Called in MacGui in UpdateUI to check
836  *  for a new scan being completed to set a new source
837  */
838 int hb_get_scancount( hb_handle_t * h)
839  {
840      return h->scanCount;
841  }
842
843 /**
844  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init_real.
845  * @param _h Pointer to handle to hb_handle_t.
846  */
847 void hb_close( hb_handle_t ** _h )
848 {
849     hb_handle_t * h = *_h;
850     hb_title_t * title;
851
852     h->die = 1;
853     hb_thread_close( &h->main_thread );
854
855     while( ( title = hb_list_item( h->list_title, 0 ) ) )
856     {
857         hb_list_rem( h->list_title, title );
858         free( title->job );
859         hb_title_close( &title );
860     }
861     hb_list_close( &h->list_title );
862
863     hb_list_close( &h->jobs );
864     hb_lock_close( &h->state_lock );
865     hb_lock_close( &h->pause_lock );
866     free( h );
867     *_h = NULL;
868 }
869
870 /**
871  * Monitors the state of the update, scan, and work threads.
872  * Sets scan done state when scan thread exits.
873  * Sets work done state when work thread exits.
874  * @param _h Handle to hb_handle_t
875  */
876 static void thread_func( void * _h )
877 {
878     hb_handle_t * h = (hb_handle_t *) _h;
879     char dirname[1024];
880     DIR * dir;
881     struct dirent * entry;
882
883     h->pid = getpid();
884
885     /* Create folder for temporary files */
886     memset( dirname, 0, 1024 );
887     hb_get_tempory_directory( h, dirname );
888
889     hb_mkdir( dirname );
890
891     while( !h->die )
892     {
893         /* In case the check_update thread hangs, it'll die sooner or
894            later. Then, we join it here */
895         if( h->update_thread &&
896             hb_thread_has_exited( h->update_thread ) )
897         {
898             hb_thread_close( &h->update_thread );
899         }
900
901         /* Check if the scan thread is done */
902         if( h->scan_thread &&
903             hb_thread_has_exited( h->scan_thread ) )
904         {
905             hb_thread_close( &h->scan_thread );
906
907             hb_log( "libhb: scan thread found %d valid title(s)",
908                     hb_list_count( h->list_title ) );
909             hb_lock( h->state_lock );
910             h->state.state = HB_STATE_SCANDONE; //originally state.state
911                         hb_unlock( h->state_lock );
912                         /*we increment this sessions scan count by one for the MacGui
913                         to trigger a new source being set */
914             h->scanCount++;
915         }
916
917         /* Check if the work thread is done */
918         if( h->work_thread &&
919             hb_thread_has_exited( h->work_thread ) )
920         {
921             hb_thread_close( &h->work_thread );
922
923             hb_log( "libhb: work result = %d",
924                     h->work_error );
925             hb_lock( h->state_lock );
926             h->state.state                = HB_STATE_WORKDONE;
927             h->state.param.workdone.error = h->work_error;
928             
929             h->job_count = hb_count(h);
930             if (h->job_count < 1)
931                 h->job_count_permanent = 0;
932             hb_unlock( h->state_lock );
933         }
934
935         hb_snooze( 50 );
936     }
937
938     if( h->work_thread )
939     {
940         hb_stop( h );
941         hb_thread_close( &h->work_thread );
942     }
943
944     /* Remove temp folder */
945     dir = opendir( dirname );
946     while( ( entry = readdir( dir ) ) )
947     {
948         char filename[1024];
949         if( entry->d_name[0] == '.' )
950         {
951             continue;
952         }
953         memset( filename, 0, 1024 );
954         snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
955         unlink( filename );
956     }
957     closedir( dir );
958     rmdir( dirname );
959 }
960
961 /**
962  * Returns the PID.
963  * @param h Handle to hb_handle_t
964  */
965 int hb_get_pid( hb_handle_t * h )
966 {
967     return h->pid;
968 }
969
970 /**
971  * Sets the current state.
972  * @param h Handle to hb_handle_t
973  * @param s Handle to new hb_state_t
974  */
975 void hb_set_state( hb_handle_t * h, hb_state_t * s )
976 {
977     hb_lock( h->pause_lock );
978     hb_lock( h->state_lock );
979     memcpy( &h->state, s, sizeof( hb_state_t ) );
980     if( h->state.state == HB_STATE_WORKING )
981     {
982         /* XXX Hack */
983         if (h->job_count < 1)
984             h->job_count_permanent = 1;
985         
986         h->state.param.working.job_cur =
987             h->job_count_permanent - hb_list_count( h->jobs );
988         h->state.param.working.job_count = h->job_count_permanent;
989     }
990     hb_unlock( h->state_lock );
991     hb_unlock( h->pause_lock );
992 }