OSDN Git Service

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