OSDN Git Service

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