OSDN Git Service

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