OSDN Git Service

36fcd75c93be67cf52ea2441a94d65728f62e358
[handbrake-jp/handbrake-jp-git.git] / libhb / hb.c
1 #include "hb.h"
2 #include "hbffmpeg.h"
3 #include <stdio.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6
7 #if defined( SYS_MINGW )
8 #include <io.h>
9 #if defined( PTW32_STATIC_LIB )
10 #include <pthread.h>
11 #endif
12 #endif
13
14 struct hb_handle_s
15 {
16     int            id;
17     
18     /* The "Check for update" thread */
19     int            build;
20     char           version[32];
21     hb_thread_t  * update_thread;
22
23     /* This thread's only purpose is to check other threads'
24        states */
25     volatile int   die;
26     hb_thread_t  * main_thread;
27     int            pid;
28
29     /* DVD/file scan thread */
30     hb_list_t    * list_title;
31     hb_thread_t  * scan_thread;
32
33     /* The thread which processes the jobs. Others threads are launched
34        from this one (see work.c) */
35     hb_list_t    * jobs;
36     hb_job_t     * current_job;
37     int            job_count;
38     int            job_count_permanent;
39     volatile int   work_die;
40     int            work_error;
41     hb_thread_t  * work_thread;
42
43     int            cpu_count;
44
45     hb_lock_t    * state_lock;
46     hb_state_t     state;
47
48     int            paused;
49     hb_lock_t    * pause_lock;
50     /* For MacGui active queue
51        increments each time the scan thread completes*/
52     int            scanCount;
53     volatile int   scan_die;
54     
55     /* Stash of persistent data between jobs, for stuff
56        like correcting frame count and framerate estimates
57        on multi-pass encodes where frames get dropped.     */
58     hb_interjob_t * interjob;
59
60 };
61
62 hb_lock_t *hb_avcodec_lock;
63 hb_work_object_t * hb_objects = NULL;
64 int hb_instance_counter = 0;
65 int hb_process_initialized = 0;
66
67 static void thread_func( void * );
68 hb_title_t * hb_get_title_by_index( hb_handle_t *, int );
69
70 void hb_avcodec_init()
71 {
72     hb_avcodec_lock  = hb_lock_init();
73     av_register_all();
74 }
75
76 int hb_avcodec_open(AVCodecContext *avctx, AVCodec *codec)
77 {
78     int ret;
79     hb_lock( hb_avcodec_lock );
80     ret = avcodec_open(avctx, codec);
81     hb_unlock( hb_avcodec_lock );
82     return ret;
83 }
84
85 int hb_avcodec_close(AVCodecContext *avctx)
86 {
87     int ret;
88     hb_lock( hb_avcodec_lock );
89     ret = avcodec_close(avctx);
90     hb_unlock( hb_avcodec_lock );
91     return ret;
92 }
93
94 int hb_ff_layout_xlat(int64_t ff_channel_layout, int channels)
95 {
96     int hb_layout;
97
98     switch (ff_channel_layout)
99     {
100         case CH_LAYOUT_MONO:
101             hb_layout = HB_INPUT_CH_LAYOUT_MONO;
102             break;
103         case CH_LAYOUT_STEREO:
104             hb_layout = HB_INPUT_CH_LAYOUT_STEREO;
105             break;
106         case CH_LAYOUT_SURROUND:
107             hb_layout = HB_INPUT_CH_LAYOUT_3F;
108             break;
109         case CH_LAYOUT_4POINT0:
110             hb_layout = HB_INPUT_CH_LAYOUT_3F1R;
111             break;
112         case CH_LAYOUT_2_2:
113             hb_layout = HB_INPUT_CH_LAYOUT_2F2R;
114             break;
115         case CH_LAYOUT_QUAD:
116             hb_layout = HB_INPUT_CH_LAYOUT_2F2R;
117             break;
118         case CH_LAYOUT_5POINT0:
119             hb_layout = HB_INPUT_CH_LAYOUT_3F2R;
120             break;
121         case CH_LAYOUT_5POINT1:
122             hb_layout = HB_INPUT_CH_LAYOUT_3F2R|HB_INPUT_CH_LAYOUT_HAS_LFE;
123             break;
124         case CH_LAYOUT_5POINT0_BACK:
125             hb_layout = HB_INPUT_CH_LAYOUT_3F2R;
126             break;
127         case CH_LAYOUT_5POINT1_BACK:
128             hb_layout = HB_INPUT_CH_LAYOUT_3F2R|HB_INPUT_CH_LAYOUT_HAS_LFE;
129             break;
130         case CH_LAYOUT_7POINT0:
131             hb_layout = HB_INPUT_CH_LAYOUT_3F4R;
132             break;
133         case CH_LAYOUT_7POINT1:
134             hb_layout = HB_INPUT_CH_LAYOUT_3F4R|HB_INPUT_CH_LAYOUT_HAS_LFE;
135             break;
136         case CH_LAYOUT_STEREO_DOWNMIX:
137             hb_layout = HB_INPUT_CH_LAYOUT_STEREO;
138             break;
139         default:
140             hb_layout = HB_INPUT_CH_LAYOUT_STEREO;
141             break;
142     }
143     // Now make sure the chosen layout agrees with the number of channels
144     // ffmpeg tells us there are.  It seems ffmpeg is sometimes confused
145     // about this. So we will make a best guess based on the number
146     // of channels.
147     int chans = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT( hb_layout );
148     if ( chans == channels )
149     {
150         return hb_layout;
151     }
152     hb_log( "Channels reported by ffmpeg (%d) != computed layout channels (%d).", channels, chans );
153     switch (channels)
154     {
155         case 1:
156             hb_layout = HB_INPUT_CH_LAYOUT_MONO;
157             break;
158         case 2:
159             hb_layout = HB_INPUT_CH_LAYOUT_STEREO;
160             break;
161         case 3:
162             hb_layout = HB_INPUT_CH_LAYOUT_3F;
163             break;
164         case 4:
165             hb_layout = HB_INPUT_CH_LAYOUT_3F1R;
166             break;
167         case 5:
168             hb_layout = HB_INPUT_CH_LAYOUT_3F2R;
169             break;
170         case 6:
171             hb_layout = HB_INPUT_CH_LAYOUT_3F2R|HB_INPUT_CH_LAYOUT_HAS_LFE;
172             break;
173         case 7:
174             hb_layout = HB_INPUT_CH_LAYOUT_3F4R;
175             break;
176         case 8:
177             hb_layout = HB_INPUT_CH_LAYOUT_3F4R|HB_INPUT_CH_LAYOUT_HAS_LFE;
178             break;
179         default:
180             hb_log("Unsupported number of audio channels (%d).\n", channels);
181             hb_layout = 0;
182             break;
183     }
184     return hb_layout;
185 }
186
187 /**
188  * Registers work objects, by adding the work object to a liked list.
189  * @param w Handle to hb_work_object_t to register.
190  */
191 void hb_register( hb_work_object_t * w )
192 {
193     w->next    = hb_objects;
194     hb_objects = w;
195 }
196
197 /**
198  * Ensures that the process has been initialized.
199  */
200 static void process_init()
201 {
202     if (!hb_process_initialized)
203     {
204 #if defined( SYS_MINGW ) && defined( PTW32_STATIC_LIB )
205         pthread_win32_process_attach_np();
206 #endif
207
208 #if defined( _WIN32 ) || defined( __MINGW32__ )
209         setvbuf( stdout, NULL, _IONBF, 0 );
210         setvbuf( stderr, NULL, _IONBF, 0 );
211 #endif
212         hb_process_initialized = 1;
213     }
214     
215 }
216
217 void (*hb_log_callback)(const char* message);
218 static void redirect_thread_func(void *);
219
220 #if defined( SYS_MINGW )
221 #define pipe(phandles)  _pipe (phandles, 4096, _O_BINARY)
222 #endif
223
224 /**
225  * Registers the given function as a logger. All logs will be passed to it.
226  * @param log_cb The function to register as a logger.
227  */
228 void hb_register_logger( void (*log_cb)(const char* message) )
229 {
230     process_init();
231
232     hb_log_callback = log_cb;
233     hb_thread_init("ioredirect", redirect_thread_func, NULL, HB_NORMAL_PRIORITY);
234 }
235
236 /**
237  * libhb initialization routine.
238  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
239  * @param update_check signals libhb to check for updated version from HandBrake website.
240  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
241  */
242 hb_handle_t * hb_init( int verbose, int update_check )
243 {
244     process_init();
245
246     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
247     uint64_t      date;
248
249     /* See hb_deep_log() and hb_log() in common.c */
250     global_verbosity_level = verbose;
251     if( verbose )
252         putenv( "HB_DEBUG=1" );
253     
254     h->id = hb_instance_counter++;
255     
256     /* Check for an update on the website if asked to */
257     h->build = -1;
258
259     if( update_check )
260     {
261         hb_log( "hb_init: checking for updates" );
262         date             = hb_get_date();
263         h->update_thread = hb_update_init( &h->build, h->version );
264
265         for( ;; )
266         {
267             if( hb_thread_has_exited( h->update_thread ) )
268             {
269                 /* Immediate success or failure */
270                 hb_thread_close( &h->update_thread );
271                 break;
272             }
273             if( hb_get_date() > date + 1000 )
274             {
275                 /* Still nothing after one second. Connection problem,
276                    let the thread die */
277                 hb_log( "hb_init: connection problem, not waiting for "
278                         "update_thread" );
279                 break;
280             }
281             hb_snooze( 500 );
282         }
283     }
284
285     /*
286      * Initialise buffer pool
287      */
288     hb_buffer_pool_init();
289
290     /* CPU count detection */
291     hb_log( "hb_init: checking cpu count" );
292     h->cpu_count = hb_get_cpu_count();
293
294     h->list_title = hb_list_init();
295     h->jobs       = hb_list_init();
296
297     h->state_lock  = hb_lock_init();
298     h->state.state = HB_STATE_IDLE;
299
300     h->pause_lock = hb_lock_init();
301
302     h->interjob = calloc( sizeof( hb_interjob_t ), 1 );
303
304     /* libavcodec */
305     hb_avcodec_init();
306
307     /* Start library thread */
308     hb_log( "hb_init: starting libhb thread" );
309     h->die         = 0;
310     h->main_thread = hb_thread_init( "libhb", thread_func, h,
311                                      HB_NORMAL_PRIORITY );
312     hb_register( &hb_sync_video );
313     hb_register( &hb_sync_audio );
314         hb_register( &hb_decmpeg2 );
315         hb_register( &hb_decvobsub );
316     hb_register( &hb_encvobsub );
317     hb_register( &hb_deccc608 );
318     hb_register( &hb_decsrtsub );
319     hb_register( &hb_decutf8sub );
320     hb_register( &hb_dectx3gsub );
321     hb_register( &hb_decssasub );
322         hb_register( &hb_render );
323         hb_register( &hb_encavcodec );
324         hb_register( &hb_encx264 );
325     hb_register( &hb_enctheora );
326         hb_register( &hb_deca52 );
327         hb_register( &hb_decdca );
328         hb_register( &hb_decavcodec );
329         hb_register( &hb_decavcodecv );
330         hb_register( &hb_decavcodecvi );
331         hb_register( &hb_decavcodecai );
332         hb_register( &hb_declpcm );
333         hb_register( &hb_encfaac );
334         hb_register( &hb_enclame );
335         hb_register( &hb_encvorbis );
336         hb_register( &hb_muxer );
337 #ifdef __APPLE__
338         hb_register( &hb_encca_aac );
339 #endif
340     
341     return h;
342 }
343
344 /**
345  * libhb initialization routine.
346  * This version is to use when calling the dylib, the macro hb_init isn't available from a dylib call!
347  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
348  * @param update_check signals libhb to check for updated version from HandBrake website.
349  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
350  */
351 hb_handle_t * hb_init_dl( int verbose, int update_check )
352 {
353     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
354     uint64_t      date;
355
356     /* See hb_log() in common.c */
357     if( verbose > HB_DEBUG_NONE )
358     {
359         putenv( "HB_DEBUG=1" );
360     }
361
362     h->id = hb_instance_counter++;
363
364     /* Check for an update on the website if asked to */
365     h->build = -1;
366
367     if( update_check )
368     {
369         hb_log( "hb_init: checking for updates" );
370         date             = hb_get_date();
371         h->update_thread = hb_update_init( &h->build, h->version );
372
373         for( ;; )
374         {
375             if( hb_thread_has_exited( h->update_thread ) )
376             {
377                 /* Immediate success or failure */
378                 hb_thread_close( &h->update_thread );
379                 break;
380             }
381             if( hb_get_date() > date + 1000 )
382             {
383                 /* Still nothing after one second. Connection problem,
384                    let the thread die */
385                 hb_log( "hb_init: connection problem, not waiting for "
386                         "update_thread" );
387                 break;
388             }
389             hb_snooze( 500 );
390         }
391     }
392
393     /* CPU count detection */
394     hb_log( "hb_init: checking cpu count" );
395     h->cpu_count = hb_get_cpu_count();
396
397     h->list_title = hb_list_init();
398     h->jobs       = hb_list_init();
399     h->current_job = NULL;
400
401     h->state_lock  = hb_lock_init();
402     h->state.state = HB_STATE_IDLE;
403
404     h->pause_lock = hb_lock_init();
405
406     /* libavcodec */
407     avcodec_init();
408     avcodec_register_all();
409
410     /* Start library thread */
411     hb_log( "hb_init: starting libhb thread" );
412     h->die         = 0;
413     h->main_thread = hb_thread_init( "libhb", thread_func, h,
414                                      HB_NORMAL_PRIORITY );
415
416     hb_register( &hb_sync_video );
417     hb_register( &hb_sync_audio );
418         hb_register( &hb_decmpeg2 );
419         hb_register( &hb_decvobsub );
420     hb_register( &hb_encvobsub );
421     hb_register( &hb_deccc608 );
422     hb_register( &hb_decsrtsub );
423     hb_register( &hb_decutf8sub );
424     hb_register( &hb_dectx3gsub );
425     hb_register( &hb_decssasub );
426         hb_register( &hb_render );
427         hb_register( &hb_encavcodec );
428         hb_register( &hb_encx264 );
429     hb_register( &hb_enctheora );
430         hb_register( &hb_deca52 );
431         hb_register( &hb_decdca );
432         hb_register( &hb_decavcodec );
433         hb_register( &hb_decavcodecv );
434         hb_register( &hb_decavcodecvi );
435         hb_register( &hb_decavcodecai );
436         hb_register( &hb_declpcm );
437         hb_register( &hb_encfaac );
438         hb_register( &hb_enclame );
439         hb_register( &hb_encvorbis );
440         hb_register( &hb_muxer );
441 #ifdef __APPLE__
442         hb_register( &hb_encca_aac );
443 #endif
444
445         return h;
446 }
447
448
449 /**
450  * Returns current version of libhb.
451  * @param h Handle to hb_handle_t.
452  * @return character array of version number.
453  */
454 char * hb_get_version( hb_handle_t * h )
455 {
456     return HB_PROJECT_VERSION;
457 }
458
459 /**
460  * Returns current build of libhb.
461  * @param h Handle to hb_handle_t.
462  * @return character array of build number.
463  */
464 int hb_get_build( hb_handle_t * h )
465 {
466     return HB_PROJECT_BUILD;
467 }
468
469 /**
470  * Checks for needed update.
471  * @param h Handle to hb_handle_t.
472  * @param version Pointer to handle where version will be copied.
473  * @return update indicator.
474  */
475 int hb_check_update( hb_handle_t * h, char ** version )
476 {
477     *version = ( h->build < 0 ) ? NULL : h->version;
478     return h->build;
479 }
480
481 /**
482  * Sets the cpu count to the desired value.
483  * @param h Handle to hb_handle_t
484  * @param cpu_count Number of CPUs to use.
485  */
486 void hb_set_cpu_count( hb_handle_t * h, int cpu_count )
487 {
488     cpu_count    = MAX( 1, cpu_count );
489     cpu_count    = MIN( cpu_count, 8 );
490     h->cpu_count = cpu_count;
491 }
492
493 /**
494  * Deletes current previews associated with titles
495  * @param h Handle to hb_handle_t
496  */
497 void hb_remove_previews( hb_handle_t * h )
498 {
499     char            filename[1024];
500     char            dirname[1024];
501     hb_title_t    * title;
502     int             i, count, len;
503     DIR           * dir;
504     struct dirent * entry;
505
506     memset( dirname, 0, 1024 );
507     hb_get_temporary_directory( dirname );
508     dir = opendir( dirname );
509     if (dir == NULL) return;
510
511     count = hb_list_count( h->list_title );
512     while( ( entry = readdir( dir ) ) )
513     {
514         if( entry->d_name[0] == '.' )
515         {
516             continue;
517         }
518         for( i = 0; i < count; i++ )
519         {
520             title = hb_list_item( h->list_title, i );
521             len = snprintf( filename, 1024, "%d_%d", h->id, title->index );
522             if (strncmp(entry->d_name, filename, len) == 0)
523             {
524                 snprintf( filename, 1024, "%s/%s", dirname, entry->d_name );
525                 unlink( filename );
526                 break;
527             }
528         }
529     }
530     closedir( dir );
531 }
532
533 /**
534  * Initializes a scan of the by calling hb_scan_init
535  * @param h Handle to hb_handle_t
536  * @param path location of VIDEO_TS folder.
537  * @param title_index Desired title to scan.  0 for all titles.
538  * @param preview_count Number of preview images to generate.
539  * @param store_previews Whether or not to write previews to disk.
540  */
541 void hb_scan( hb_handle_t * h, const char * path, int title_index,
542               int preview_count, int store_previews, uint64_t min_duration )
543 {
544     hb_title_t * title;
545
546     h->scan_die = 0;
547
548     /* Clean up from previous scan */
549     hb_remove_previews( h );
550     while( ( title = hb_list_item( h->list_title, 0 ) ) )
551     {
552         hb_list_rem( h->list_title, title );
553         hb_title_close( &title );
554     }
555
556     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
557     h->scan_thread = hb_scan_init( h, &h->scan_die, path, title_index, 
558                                    h->list_title, preview_count, 
559                                    store_previews, min_duration );
560 }
561
562 /**
563  * Returns the list of titles found.
564  * @param h Handle to hb_handle_t
565  * @return Handle to hb_list_t of the title list.
566  */
567 hb_list_t * hb_get_titles( hb_handle_t * h )
568 {
569     return h->list_title;
570 }
571
572 /**
573  * Create preview image of desired title a index of picture.
574  * @param h Handle to hb_handle_t.
575  * @param title_index Index of the title to get the preview for (1-based).
576  * @param picture Index in title.
577  * @param buffer Handle to buffer were image will be drawn.
578  */
579 void hb_get_preview_by_index( hb_handle_t * h, int title_index, int picture, uint8_t * buffer )
580 {
581     hb_title_t * title;
582
583     title = hb_get_title_by_index( h, title_index );
584     if ( title != NULL )
585     {
586         hb_get_preview( h, title, picture, buffer );
587     } 
588 }
589
590 /**
591  * Create preview image of desired title a index of picture.
592  * @param h Handle to hb_handle_t.
593  * @param title Handle to hb_title_t of desired title.
594  * @param picture Index in title.
595  * @param buffer Handle to buffer were image will be drawn.
596  */
597 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
598                      uint8_t * buffer )
599 {
600     hb_job_t           * job = title->job;
601     char                 filename[1024];
602     FILE               * file;
603     uint8_t            * buf1, * buf2, * buf3, * buf4, * pen;
604     uint32_t             swsflags;
605     AVPicture            pic_in, pic_preview, pic_deint, pic_crop, pic_scale;
606     struct SwsContext  * context;
607     int                  i;
608     int                  rgb_width = ((job->width + 7) >> 3) << 3;
609     int                  preview_size;
610
611     swsflags = SWS_LANCZOS | SWS_ACCURATE_RND;
612
613     buf1 = av_malloc( avpicture_get_size( PIX_FMT_YUV420P, title->width, title->height ) );
614     buf2 = av_malloc( avpicture_get_size( PIX_FMT_YUV420P, title->width, title->height ) );
615     buf3 = av_malloc( avpicture_get_size( PIX_FMT_YUV420P, rgb_width, job->height ) );
616     buf4 = av_malloc( avpicture_get_size( PIX_FMT_RGB32, rgb_width, job->height ) );
617     avpicture_fill( &pic_in, buf1, PIX_FMT_YUV420P,
618                     title->width, title->height );
619     avpicture_fill( &pic_deint, buf2, PIX_FMT_YUV420P,
620                     title->width, title->height );
621     avpicture_fill( &pic_scale, buf3, PIX_FMT_YUV420P,
622                     rgb_width, job->height );
623     avpicture_fill( &pic_preview, buf4, PIX_FMT_RGB32,
624                     rgb_width, job->height );
625
626     // Allocate the AVPicture frames and fill in
627
628     memset( filename, 0, 1024 );
629
630     hb_get_tempory_filename( h, filename, "%d_%d_%d",
631                              h->id, title->index, picture );
632
633     file = fopen( filename, "rb" );
634     if( !file )
635     {
636         hb_log( "hb_get_preview: fopen failed" );
637         return;
638     }
639
640     fread( buf1, avpicture_get_size( PIX_FMT_YUV420P, title->width, title->height), 1, file );
641     fclose( file );
642
643     if( job->deinterlace )
644     {
645         // Deinterlace and crop
646         avpicture_deinterlace( &pic_deint, &pic_in, PIX_FMT_YUV420P, title->width, title->height );
647         av_picture_crop( &pic_crop, &pic_deint, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
648     }
649     else
650     {
651         // Crop
652         av_picture_crop( &pic_crop, &pic_in, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
653     }
654
655     // Get scaling context
656     context = sws_getContext(title->width  - (job->crop[2] + job->crop[3]),
657                              title->height - (job->crop[0] + job->crop[1]),
658                              PIX_FMT_YUV420P,
659                              job->width, job->height, PIX_FMT_YUV420P,
660                              swsflags, NULL, NULL, NULL);
661
662     // Scale
663     sws_scale(context,
664               pic_crop.data, pic_crop.linesize,
665               0, title->height - (job->crop[0] + job->crop[1]),
666               pic_scale.data, pic_scale.linesize);
667
668     // Free context
669     sws_freeContext( context );
670
671     // Get preview context
672     context = sws_getContext(rgb_width, job->height, PIX_FMT_YUV420P,
673                               rgb_width, job->height, PIX_FMT_RGB32,
674                               swsflags, NULL, NULL, NULL);
675
676     // Create preview
677     sws_scale(context,
678               pic_scale.data, pic_scale.linesize,
679               0, job->height,
680               pic_preview.data, pic_preview.linesize);
681
682     // Free context
683     sws_freeContext( context );
684
685     preview_size = pic_preview.linesize[0];
686     pen = buffer;
687     for( i = 0; i < job->height; i++ )
688     {
689         memcpy( pen, buf4 + preview_size * i, 4 * job->width );
690         pen += 4 * job->width;
691     }
692
693     // Clean up
694     avpicture_free( &pic_preview );
695     avpicture_free( &pic_scale );
696     avpicture_free( &pic_deint );
697     avpicture_free( &pic_in );
698 }
699
700  /**
701  * Analyzes a frame to detect interlacing artifacts
702  * and returns true if interlacing (combing) is found.
703  *
704  * Code taken from Thomas Oestreich's 32detect filter
705  * in the Transcode project, with minor formatting changes.
706  *
707  * @param buf         An hb_buffer structure holding valid frame data
708  * @param width       The frame's width in pixels
709  * @param height      The frame's height in pixels
710  * @param color_equal Sensitivity for detecting similar colors
711  * @param color_diff  Sensitivity for detecting different colors
712  * @param threshold   Sensitivity for flagging planes as combed
713  * @param prog_equal  Sensitivity for detecting similar colors on progressive frames
714  * @param prog_diff   Sensitivity for detecting different colors on progressive frames
715  * @param prog_threshold Sensitivity for flagging progressive frames as combed
716  */
717 int hb_detect_comb( hb_buffer_t * buf, int width, int height, int color_equal, int color_diff, int threshold, int prog_equal, int prog_diff, int prog_threshold )
718 {
719     int j, k, n, off, cc_1, cc_2, cc[3];
720         // int flag[3] ; // debugging flag
721     uint16_t s1, s2, s3, s4;
722     cc_1 = 0; cc_2 = 0;
723
724     int offset = 0;
725     
726     if ( buf->flags & 16 )
727     {
728         /* Frame is progressive, be more discerning. */
729         color_diff = prog_diff;
730         color_equal = prog_equal;
731         threshold = prog_threshold;
732     }
733
734     /* One pas for Y, one pass for Cb, one pass for Cr */    
735     for( k = 0; k < 3; k++ )
736     {
737         if( k == 1 )
738         {
739             /* Y has already been checked, now offset by Y's dimensions
740                and divide all the other values by 2, since Cr and Cb
741                are half-size compared to Y.                               */
742             offset = width * height;
743             width >>= 1;
744             height >>= 1;
745         }
746         else if ( k == 2 )
747         {
748             /* Y and Cb are done, so the offset needs to be bumped
749                so it's width*height + (width / 2) * (height / 2)  */
750             offset *= 5/4;
751         }
752
753         for( j = 0; j < width; ++j )
754         {
755             off = 0;
756
757             for( n = 0; n < ( height - 4 ); n = n + 2 )
758             {
759                 /* Look at groups of 4 sequential horizontal lines */
760                 s1 = ( ( buf->data + offset )[ off + j             ] & 0xff );
761                 s2 = ( ( buf->data + offset )[ off + j + width     ] & 0xff );
762                 s3 = ( ( buf->data + offset )[ off + j + 2 * width ] & 0xff );
763                 s4 = ( ( buf->data + offset )[ off + j + 3 * width ] & 0xff );
764
765                 /* Note if the 1st and 2nd lines are more different in
766                    color than the 1st and 3rd lines are similar in color.*/
767                 if ( ( abs( s1 - s3 ) < color_equal ) &&
768                      ( abs( s1 - s2 ) > color_diff ) )
769                         ++cc_1;
770
771                 /* Note if the 2nd and 3rd lines are more different in
772                    color than the 2nd and 4th lines are similar in color.*/
773                 if ( ( abs( s2 - s4 ) < color_equal ) &&
774                      ( abs( s2 - s3 ) > color_diff) )
775                         ++cc_2;
776
777                 /* Now move down 2 horizontal lines before starting over.*/
778                 off += 2 * width;
779             }
780         }
781
782         // compare results
783         /*  The final cc score for a plane is the percentage of combed pixels it contains.
784             Because sensitivity goes down to hundreths of a percent, multiply by 1000
785             so it will be easy to compare against the threhold value which is an integer. */
786         cc[k] = (int)( ( cc_1 + cc_2 ) * 1000.0 / ( width * height ) );
787     }
788
789
790     /* HandBrake is all yuv420, so weight the average percentage of all 3 planes accordingly.*/
791     int average_cc = ( 2 * cc[0] + ( cc[1] / 2 ) + ( cc[2] / 2 ) ) / 3;
792     
793     /* Now see if that average percentage of combed pixels surpasses the threshold percentage given by the user.*/
794     if( average_cc > threshold )
795     {
796 #if 0
797             hb_log("Average %i combed (Threshold %i) %i/%i/%i | PTS: %"PRId64" (%fs) %s", average_cc, threshold, cc[0], cc[1], cc[2], buf->start, (float)buf->start / 90000, (buf->flags & 16) ? "Film" : "Video" );
798 #endif
799         return 1;
800     }
801
802 #if 0
803     hb_log("SKIPPED Average %i combed (Threshold %i) %i/%i/%i | PTS: %"PRId64" (%fs) %s", average_cc, threshold, cc[0], cc[1], cc[2], buf->start, (float)buf->start / 90000, (buf->flags & 16) ? "Film" : "Video" );
804 #endif
805
806     /* Reaching this point means no combing detected. */
807     return 0;
808
809 }
810
811 /**
812  * Calculates job width and height for anamorphic content,
813  *
814  * @param h Instance handle
815  * @param title_index Index of the title/job to inspect (1-based).
816  * @param output_width Pointer to returned storage width
817  * @param output_height Pointer to returned storage height
818  * @param output_par_width Pointer to returned pixel width
819  * @param output_par_height Pointer to returned pixel height
820  */
821 void hb_set_anamorphic_size_by_index( hb_handle_t * h, int title_index,
822         int *output_width, int *output_height,
823         int *output_par_width, int *output_par_height )
824 {
825     hb_title_t * title;
826     title = hb_get_title_by_index( h, title_index );
827     
828     hb_set_anamorphic_size( title->job, output_width, output_height, output_par_width, output_par_height );
829 }
830
831 /**
832  * Calculates job width and height for anamorphic content,
833  *
834  * @param job Handle to hb_job_t
835  * @param output_width Pointer to returned storage width
836  * @param output_height Pointer to returned storage height
837  * @param output_par_width Pointer to returned pixel width
838  * @param output_par_height Pointer to returned pixel height
839  */
840 void hb_set_anamorphic_size( hb_job_t * job,
841         int *output_width, int *output_height,
842         int *output_par_width, int *output_par_height )
843 {
844     /* Set up some variables to make the math easier to follow. */
845     hb_title_t * title = job->title;
846     int cropped_width = title->width - job->crop[2] - job->crop[3] ;
847     int cropped_height = title->height - job->crop[0] - job->crop[1] ;
848     double storage_aspect = (double)cropped_width / (double)cropped_height;
849     int mod = job->modulus ? job->modulus : 16;
850     double aspect = title->aspect;
851     
852     int pixel_aspect_width  = job->anamorphic.par_width;
853     int pixel_aspect_height = job->anamorphic.par_height;
854
855     /* If a source was really NTSC or PAL and the user specified ITU PAR
856        values, replace the standard PAR values with the ITU broadcast ones. */
857     if( title->width == 720 && job->anamorphic.itu_par )
858     {
859         // convert aspect to a scaled integer so we can test for 16:9 & 4:3
860         // aspect ratios ignoring insignificant differences in the LSBs of
861         // the floating point representation.
862         int iaspect = aspect * 9.;
863
864         /* Handle ITU PARs */
865         if (title->height == 480)
866         {
867             /* It's NTSC */
868             if (iaspect == 16)
869             {
870                 /* It's widescreen */
871                 pixel_aspect_width = 40;
872                 pixel_aspect_height = 33;
873             }
874             else if (iaspect == 12)
875             {
876                 /* It's 4:3 */
877                 pixel_aspect_width = 10;
878                 pixel_aspect_height = 11;
879             }
880         }
881         else if (title->height == 576)
882         {
883             /* It's PAL */
884             if(iaspect == 16)
885             {
886                 /* It's widescreen */
887                 pixel_aspect_width = 16;
888                 pixel_aspect_height = 11;
889             }
890             else if (iaspect == 12)
891             {
892                 /* It's 4:3 */
893                 pixel_aspect_width = 12;
894                 pixel_aspect_height = 11;
895             }
896         }
897     }
898
899     /* Figure out what width the source would display at. */
900     int source_display_width = cropped_width * (double)pixel_aspect_width /
901                                (double)pixel_aspect_height ;
902
903     /*
904        3 different ways of deciding output dimensions:
905         - 1: Strict anamorphic, preserve source dimensions
906         - 2: Loose anamorphic, round to mod16 and preserve storage aspect ratio
907         - 3: Power user anamorphic, specify everything
908     */
909     int width, height;
910     int maxWidth, maxHeight;
911
912     maxWidth = MULTIPLE_MOD_DOWN( job->maxWidth, mod );
913     maxHeight = MULTIPLE_MOD_DOWN( job->maxHeight, mod );
914
915     switch( job->anamorphic.mode )
916     {
917         case 1:
918             /* Strict anamorphic */
919             *output_width = cropped_width;
920             *output_height = cropped_height;
921             *output_par_width = title->pixel_aspect_width;
922             *output_par_height = title->pixel_aspect_height;
923         break;
924
925         case 2:
926             /* "Loose" anamorphic.
927                 - Uses mod16-compliant dimensions,
928                 - Allows users to set the width
929             */
930             width = job->width;
931             // height: Gets set later, ignore user job->height value
932
933             /* Gotta handle bounding dimensions.
934                If the width is too big, just reset it with no rescaling.
935                Instead of using the aspect-scaled job height,
936                we need to see if the job width divided by the storage aspect
937                is bigger than the max. If so, set it to the max (this is sloppy).
938                If not, set job height to job width divided by storage aspect.
939             */
940
941             /* Time to get picture width that divide cleanly.*/
942             width  = MULTIPLE_MOD( width, mod);
943
944             if ( maxWidth && (maxWidth < job->width) )
945                 width = maxWidth;
946
947             /* Verify these new dimensions don't violate max height and width settings */
948             height = ((double)width / storage_aspect) + 0.5;
949
950             /* Time to get picture height that divide cleanly.*/
951             height = MULTIPLE_MOD( height, mod);
952             
953             if ( maxHeight && (maxHeight < height) )
954             {
955                 height = maxHeight;
956                 width = ((double)height * storage_aspect) + 0.5;
957                 width  = MULTIPLE_MOD( width, mod);
958             }
959
960             /* The film AR is the source's display width / cropped source height.
961                The output display width is the output height * film AR.
962                The output PAR is the output display width / output storage width. */
963             pixel_aspect_width = height * source_display_width / cropped_height;
964             pixel_aspect_height = width;
965
966             /* Pass the results back to the caller */
967             *output_width = width;
968             *output_height = height;
969         break;
970             
971         case 3:
972             /* Anamorphic 3: Power User Jamboree
973                - Set everything based on specified values */
974             
975             /* Use specified storage dimensions */
976             storage_aspect = (double)job->width / (double)job->height;
977             width = job->width;
978             height = job->height;
979             
980             /* Time to get picture dimensions that divide cleanly.*/
981             width  = MULTIPLE_MOD( width, mod);
982             height = MULTIPLE_MOD( height, mod);
983             
984             /* Bind to max dimensions */
985             if( maxWidth && width > maxWidth )
986             {
987                 width = maxWidth;
988                 // If we are keeping the display aspect, then we are going
989                 // to be modifying the PAR anyway.  So it's preferred
990                 // to let the width/height stray some from the original
991                 // requested storage aspect.
992                 //
993                 // But otherwise, PAR and DAR will change the least
994                 // if we stay as close as possible to the requested
995                 // storage aspect.
996                 if ( !job->anamorphic.keep_display_aspect )
997                 {
998                     height = ((double)width / storage_aspect) + 0.5;
999                     height = MULTIPLE_MOD( height, mod);
1000                 }
1001             }
1002             if( maxHeight && height > maxHeight )
1003             {
1004                 height = maxHeight;
1005                 // Ditto, see comment above
1006                 if ( !job->anamorphic.keep_display_aspect )
1007                 {
1008                     width = ((double)height * storage_aspect) + 0.5;
1009                     width  = MULTIPLE_MOD( width, mod);
1010                 }
1011             }
1012             
1013             /* That finishes the storage dimensions. On to display. */            
1014             if( job->anamorphic.dar_width && job->anamorphic.dar_height )
1015             {
1016                 /* We need to adjust the PAR to produce this aspect. */
1017                 pixel_aspect_width = height * job->anamorphic.dar_width / job->anamorphic.dar_height;
1018                 pixel_aspect_height = width;
1019             }
1020             else
1021             {
1022                 /* If we're doing ana 3 and not specifying a DAR, care needs to be taken.
1023                    This indicates a PAR is potentially being set by the interface. But
1024                    this is an output PAR, to correct a source, and it should not be assumed
1025                    that it properly creates a display aspect ratio when applied to the source,
1026                    which could easily be stored in a different resolution. */
1027                 if( job->anamorphic.keep_display_aspect )
1028                 {
1029                     /* We can ignore the possibility of a PAR change */
1030                     pixel_aspect_width = height * ( (double)source_display_width / (double)cropped_height );
1031                     pixel_aspect_height = width;
1032                 }
1033                 else
1034                 {
1035                     int output_display_width = width * (double)pixel_aspect_width /
1036                         (double)pixel_aspect_height;
1037                     pixel_aspect_width = output_display_width;
1038                     pixel_aspect_height = width;
1039                 }
1040             }
1041             
1042             /* Back to caller */
1043             *output_width = width;
1044             *output_height = height;
1045         break;
1046     }
1047     
1048     /* While x264 is smart enough to reduce fractions on its own, libavcodec
1049        needs some help with the math, so lose superfluous factors.            */
1050     hb_reduce( output_par_width, output_par_height,
1051                pixel_aspect_width, pixel_aspect_height );
1052 }
1053
1054 /**
1055  * Calculates job width, height, and cropping parameters.
1056  * @param job Handle to hb_job_t.
1057  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
1058  * @param pixels Maximum desired pixel count.
1059  */
1060 void hb_set_size( hb_job_t * job, double aspect, int pixels )
1061 {
1062     hb_title_t * title = job->title;
1063
1064     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
1065     int croppedHeight = title->height - title->crop[0] - title->crop[1];
1066     double croppedAspect = title->aspect * title->height * croppedWidth /
1067                            croppedHeight / title->width;
1068     int addCrop;
1069     int i, w, h;
1070
1071     if( aspect <= 0 )
1072     {
1073         /* Keep the best possible aspect ratio */
1074         aspect = croppedAspect;
1075     }
1076
1077     /* Crop if necessary to obtain the desired ratio */
1078     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
1079     if( aspect < croppedAspect )
1080     {
1081         /* Need to crop on the left and right */
1082         addCrop = croppedWidth - aspect * croppedHeight * title->width /
1083                     title->aspect / title->height;
1084         if( addCrop & 3 )
1085         {
1086             addCrop = ( addCrop + 1 ) / 2;
1087             job->crop[2] += addCrop;
1088             job->crop[3] += addCrop;
1089         }
1090         else if( addCrop & 2 )
1091         {
1092             addCrop /= 2;
1093             job->crop[2] += addCrop - 1;
1094             job->crop[3] += addCrop + 1;
1095         }
1096         else
1097         {
1098             addCrop /= 2;
1099             job->crop[2] += addCrop;
1100             job->crop[3] += addCrop;
1101         }
1102     }
1103     else if( aspect > croppedAspect )
1104     {
1105         /* Need to crop on the top and bottom */
1106         addCrop = croppedHeight - croppedWidth * title->aspect *
1107             title->height / aspect / title->width;
1108         if( addCrop & 3 )
1109         {
1110             addCrop = ( addCrop + 1 ) / 2;
1111             job->crop[0] += addCrop;
1112             job->crop[1] += addCrop;
1113         }
1114         else if( addCrop & 2 )
1115         {
1116             addCrop /= 2;
1117             job->crop[0] += addCrop - 1;
1118             job->crop[1] += addCrop + 1;
1119         }
1120         else
1121         {
1122             addCrop /= 2;
1123             job->crop[0] += addCrop;
1124             job->crop[1] += addCrop;
1125         }
1126     }
1127
1128     /* Compute a resolution from the number of pixels and aspect */
1129     for( i = 0;; i++ )
1130     {
1131         w = 16 * i;
1132         h = MULTIPLE_16( (int)( (double)w / aspect ) );
1133         if( w * h > pixels )
1134         {
1135             break;
1136         }
1137     }
1138     i--;
1139     job->width  = 16 * i;
1140     job->height = MULTIPLE_16( (int)( (double)job->width / aspect ) );
1141 }
1142
1143 /**
1144  * Returns the number of jobs in the queue.
1145  * @param h Handle to hb_handle_t.
1146  * @return Number of jobs.
1147  */
1148 int hb_count( hb_handle_t * h )
1149 {
1150     return hb_list_count( h->jobs );
1151 }
1152
1153 /**
1154  * Returns handle to job at index i within the job list.
1155  * @param h Handle to hb_handle_t.
1156  * @param i Index of job.
1157  * @returns Handle to hb_job_t of desired job.
1158  */
1159 hb_job_t * hb_job( hb_handle_t * h, int i )
1160 {
1161     return hb_list_item( h->jobs, i );
1162 }
1163
1164 hb_job_t * hb_current_job( hb_handle_t * h )
1165 {
1166     return( h->current_job );
1167 }
1168
1169 /**
1170  * Applies information from the given job to the official job instance.
1171  * @param h Handle to hb_handle_t.
1172  * @param title_index Index of the title to apply the chapter name to (1-based).
1173  * @param chapter The chapter to apply the name to (1-based).
1174  * @param job Job information to apply.
1175  */
1176 void hb_set_chapter_name( hb_handle_t * h, int title_index, int chapter_index, const char * chapter_name )
1177 {
1178     hb_title_t * title;
1179     title = hb_get_title_by_index( h, title_index );
1180     
1181     hb_chapter_t * chapter = hb_list_item( title->list_chapter, chapter_index - 1 );
1182     
1183     strncpy(chapter->title, chapter_name, 1023);
1184     chapter->title[1023] = '\0';
1185 }
1186
1187 /**
1188  * Applies information from the given job to the official job instance.
1189  * Currently only applies information needed for anamorphic size calculation and previews.
1190  * @param h Handle to hb_handle_t.
1191  * @param title_index Index of the title to apply the job information to (1-based).
1192  * @param job Job information to apply.
1193  */
1194 void hb_set_job( hb_handle_t * h, int title_index, hb_job_t * job )
1195 {
1196         int i;
1197
1198     hb_title_t * title;
1199     title = hb_get_title_by_index( h, title_index );
1200     
1201     hb_job_t * job_target = title->job;
1202     
1203     job_target->deinterlace = job->deinterlace;
1204     job_target->width = job->width;
1205     job_target->height = job->height;
1206     job_target->maxWidth = job->maxWidth;
1207     job_target->maxHeight = job->maxHeight;
1208     for (i = 0; i < 4; i++)
1209     {
1210         job_target->crop[i] = job->crop[i];
1211     }
1212         
1213     job_target->anamorphic = job->anamorphic;
1214 }
1215
1216 /**
1217  * Adds a job to the job list.
1218  * @param h Handle to hb_handle_t.
1219  * @param job Handle to hb_job_t.
1220  */
1221 void hb_add( hb_handle_t * h, hb_job_t * job )
1222 {
1223     hb_job_t      * job_copy;
1224     hb_title_t    * title,    * title_copy;
1225     hb_chapter_t  * chapter,  * chapter_copy;
1226     hb_audio_t    * audio;
1227     hb_subtitle_t * subtitle, * subtitle_copy;
1228     hb_attachment_t * attachment;
1229     int             i;
1230     char            audio_lang[4];
1231
1232     /* Copy the title */
1233     title      = job->title;
1234     title_copy = malloc( sizeof( hb_title_t ) );
1235     memcpy( title_copy, title, sizeof( hb_title_t ) );
1236
1237     title_copy->list_chapter = hb_list_init();
1238     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
1239     {
1240         chapter      = hb_list_item( title->list_chapter, i );
1241         chapter_copy = malloc( sizeof( hb_chapter_t ) );
1242         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
1243         hb_list_add( title_copy->list_chapter, chapter_copy );
1244     }
1245
1246     /*
1247      * Copy the metadata
1248      */
1249     if( title->metadata )
1250     {
1251         title_copy->metadata = malloc( sizeof( hb_metadata_t ) );
1252         
1253         if( title_copy->metadata ) 
1254         {
1255             memcpy( title_copy->metadata, title->metadata, sizeof( hb_metadata_t ) );
1256
1257             /*
1258              * Need to copy the artwork seperatly (TODO).
1259              */
1260             if( title->metadata->coverart )
1261             {
1262                 title_copy->metadata->coverart = malloc( title->metadata->coverart_size );
1263                 if( title_copy->metadata->coverart )
1264                 {
1265                     memcpy( title_copy->metadata->coverart, title->metadata->coverart,
1266                             title->metadata->coverart_size );
1267                 } else {
1268                     title_copy->metadata->coverart_size = 0; 
1269                 }
1270             }
1271         }
1272     }
1273
1274     /* Copy the audio track(s) we want */
1275     title_copy->list_audio = hb_list_init();
1276     for( i = 0; i < hb_list_count(job->list_audio); i++ )
1277     {
1278         if( ( audio = hb_list_item( job->list_audio, i ) ) )
1279         {
1280             hb_list_add( title_copy->list_audio, hb_audio_copy(audio) );
1281         }
1282     }
1283
1284     /* Initialize subtitle list - filled out further below */
1285     title_copy->list_subtitle = hb_list_init();
1286     
1287     /* Copy all the attachments */
1288     title_copy->list_attachment = hb_list_init();
1289     for( i = 0; i < hb_list_count(title->list_attachment); i++ )
1290     {
1291         if( ( attachment = hb_list_item( title->list_attachment, i ) ) )
1292         {
1293             hb_list_add( title_copy->list_attachment, hb_attachment_copy(attachment) );
1294         }
1295     }
1296
1297     /*
1298      * The following code is confusing, there are two ways in which
1299      * we select subtitles and it depends on whether this is single or
1300      * two pass mode.
1301      *
1302      * subtitle_scan may be enabled, in which case the first pass
1303      * scans all subtitles of that language. The second pass does not
1304      * select any because they are set at the end of the first pass.
1305      *
1306      * We may have manually selected a subtitle, in which case that is
1307      * selected in the first pass of a single pass, or the second of a
1308      * two pass.
1309      */
1310     memset( audio_lang, 0, sizeof( audio_lang ) );
1311
1312     if ( job->indepth_scan ) {
1313
1314         /*
1315          * Find the first audio language that is being encoded
1316          */
1317         for( i = 0; i < hb_list_count(job->list_audio); i++ )
1318         {
1319             if( ( audio = hb_list_item( job->list_audio, i ) ) )
1320             {
1321                 strncpy(audio_lang, audio->config.lang.iso639_2, sizeof(audio_lang));
1322                 break;
1323             }
1324         }
1325     }
1326
1327     /*
1328      * If doing a subtitle scan then add all the matching subtitles for this
1329      * language.
1330      */
1331     if ( job->indepth_scan )
1332     {
1333         for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
1334         {
1335             subtitle = hb_list_item( title->list_subtitle, i );
1336             if( strcmp( subtitle->iso639_2, audio_lang ) == 0 &&
1337                 subtitle->source == VOBSUB )
1338             {
1339                 /*
1340                  * Matched subtitle language with audio language, so
1341                  * add this to our list to scan.
1342                  *
1343                  * We will update the subtitle list on the second pass
1344                  * later after the first pass has completed.
1345                  */
1346                 subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1347                 memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1348                 hb_list_add( title_copy->list_subtitle, subtitle_copy );
1349             }
1350         }
1351     } else {
1352         /*
1353          * Not doing a subtitle scan in this pass, but maybe we are in the
1354          * first pass?
1355          */
1356         if( job->pass != 1 )
1357         {
1358             /*
1359              * Copy all of them from the input job, to the title_copy/job_copy.
1360              */
1361             for(  i = 0; i < hb_list_count(job->list_subtitle); i++ ) {
1362                 if( ( subtitle = hb_list_item( job->list_subtitle, i ) ) )
1363                 {
1364                     subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1365                     memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1366                     hb_list_add( title_copy->list_subtitle, subtitle_copy );
1367                 }
1368             }
1369         }
1370     }
1371
1372     /* Copy the job */
1373     job_copy        = calloc( sizeof( hb_job_t ), 1 );
1374     memcpy( job_copy, job, sizeof( hb_job_t ) );
1375     title_copy->job = job_copy;
1376     job_copy->title = title_copy;
1377     job_copy->list_audio = title_copy->list_audio;
1378     job_copy->list_subtitle = title_copy->list_subtitle;   // sharing list between title and job
1379     job_copy->file  = strdup( job->file );
1380     job_copy->h     = h;
1381     job_copy->pause = h->pause_lock;
1382
1383     /* Copy the job filter list */
1384     if( job->filters )
1385     {
1386         int i;
1387         int filter_count = hb_list_count( job->filters );
1388         job_copy->filters = hb_list_init();
1389         for( i = 0; i < filter_count; i++ )
1390         {
1391             /*
1392              * Copy the filters, since the MacGui reuses the global filter objects
1393              * meaning that queued up jobs overwrite the previous filter settings.
1394              * In reality, settings is probably the only field that needs duplicating
1395              * since it's the only value that is ever changed. But name is duplicated
1396              * as well for completeness. Not copying private_data since it gets
1397              * created for each job in renderInit.
1398              */
1399             hb_filter_object_t * filter = hb_list_item( job->filters, i );
1400             hb_filter_object_t * filter_copy = malloc( sizeof( hb_filter_object_t ) );
1401             memcpy( filter_copy, filter, sizeof( hb_filter_object_t ) );
1402             if( filter->name )
1403                 filter_copy->name = strdup( filter->name );
1404             if( filter->settings )
1405                 filter_copy->settings = strdup( filter->settings );
1406             hb_list_add( job_copy->filters, filter_copy );
1407         }
1408     }
1409
1410     /* Add the job to the list */
1411     hb_list_add( h->jobs, job_copy );
1412     h->job_count = hb_count(h);
1413     h->job_count_permanent++;
1414 }
1415
1416 /**
1417  * Removes a job from the job list.
1418  * @param h Handle to hb_handle_t.
1419  * @param job Handle to hb_job_t.
1420  */
1421 void hb_rem( hb_handle_t * h, hb_job_t * job )
1422 {
1423     hb_list_rem( h->jobs, job );
1424
1425     h->job_count = hb_count(h);
1426     if (h->job_count_permanent)
1427         h->job_count_permanent--;
1428
1429     /* XXX free everything XXX */
1430 }
1431
1432 /**
1433  * Starts the conversion process.
1434  * Sets state to HB_STATE_WORKING.
1435  * calls hb_work_init, to launch work thread. Stores handle to work thread.
1436  * @param h Handle to hb_handle_t.
1437  */
1438 void hb_start( hb_handle_t * h )
1439 {
1440     /* XXX Hack */
1441     h->job_count = hb_list_count( h->jobs );
1442     h->job_count_permanent = h->job_count;
1443
1444     hb_lock( h->state_lock );
1445     h->state.state = HB_STATE_WORKING;
1446 #define p h->state.param.working
1447     p.progress  = 0.0;
1448     p.job_cur   = 1;
1449     p.job_count = h->job_count;
1450     p.rate_cur  = 0.0;
1451     p.rate_avg  = 0.0;
1452     p.hours     = -1;
1453     p.minutes   = -1;
1454     p.seconds   = -1;
1455     p.sequence_id = 0;
1456 #undef p
1457     hb_unlock( h->state_lock );
1458
1459     h->paused = 0;
1460
1461     h->work_die    = 0;
1462     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
1463                                    &h->work_die, &h->work_error, &h->current_job );
1464 }
1465
1466 /**
1467  * Pauses the conversion process.
1468  * @param h Handle to hb_handle_t.
1469  */
1470 void hb_pause( hb_handle_t * h )
1471 {
1472     if( !h->paused )
1473     {
1474         hb_lock( h->pause_lock );
1475         h->paused = 1;
1476
1477         hb_current_job( h )->st_pause_date = hb_get_date();
1478
1479         hb_lock( h->state_lock );
1480         h->state.state = HB_STATE_PAUSED;
1481         hb_unlock( h->state_lock );
1482     }
1483 }
1484
1485 /**
1486  * Resumes the conversion process.
1487  * @param h Handle to hb_handle_t.
1488  */
1489 void hb_resume( hb_handle_t * h )
1490 {
1491     if( h->paused )
1492     {
1493 #define job hb_current_job( h )
1494         if( job->st_pause_date != -1 )
1495         {
1496            job->st_paused += hb_get_date() - job->st_pause_date;
1497         }
1498 #undef job
1499
1500         hb_unlock( h->pause_lock );
1501         h->paused = 0;
1502     }
1503 }
1504
1505 /**
1506  * Stops the conversion process.
1507  * @param h Handle to hb_handle_t.
1508  */
1509 void hb_stop( hb_handle_t * h )
1510 {
1511     h->work_die = 1;
1512
1513     h->job_count = hb_count(h);
1514     h->job_count_permanent = 0;
1515
1516     hb_resume( h );
1517 }
1518
1519 /**
1520  * Stops the conversion process.
1521  * @param h Handle to hb_handle_t.
1522  */
1523 void hb_scan_stop( hb_handle_t * h )
1524 {
1525     h->scan_die = 1;
1526
1527     h->job_count = hb_count(h);
1528     h->job_count_permanent = 0;
1529
1530     hb_resume( h );
1531 }
1532
1533 /**
1534  * Gets a filter object with the given type and settings.
1535  * @param filter_id The type of filter to get.
1536  * @param settings The filter settings to use.
1537  * @returns The requested filter object.
1538  */
1539 hb_filter_object_t * hb_get_filter_object(int filter_id, const char * settings)
1540 {
1541     if (filter_id == HB_FILTER_ROTATE)
1542     {
1543         hb_filter_rotate.settings = (char*)settings;
1544         return &hb_filter_rotate;
1545     }
1546
1547     if (filter_id == HB_FILTER_DETELECINE)
1548     {
1549         hb_filter_detelecine.settings = (char*)settings;
1550         return &hb_filter_detelecine;
1551     }
1552
1553     if (filter_id == HB_FILTER_DECOMB)
1554     {
1555         hb_filter_decomb.settings = (char*)settings;
1556         return &hb_filter_decomb;
1557     }
1558
1559     if (filter_id == HB_FILTER_DEINTERLACE)
1560     {
1561         hb_filter_deinterlace.settings = (char*)settings;
1562         return &hb_filter_deinterlace;
1563     }
1564
1565     if (filter_id == HB_FILTER_DEBLOCK)
1566     {
1567         hb_filter_deblock.settings = (char*)settings;
1568         return &hb_filter_deblock;
1569     }
1570
1571     if (filter_id == HB_FILTER_DENOISE)
1572     {
1573         hb_filter_denoise.settings = (char*)settings;
1574         return &hb_filter_denoise;
1575     }
1576     return NULL;
1577 }
1578
1579 /**
1580  * Returns the state of the conversion process.
1581  * @param h Handle to hb_handle_t.
1582  * @param s Handle to hb_state_t which to copy the state data.
1583  */
1584 void hb_get_state( hb_handle_t * h, hb_state_t * s )
1585 {
1586     hb_lock( h->state_lock );
1587
1588     memcpy( s, &h->state, sizeof( hb_state_t ) );
1589     if ( h->state.state == HB_STATE_SCANDONE || h->state.state == HB_STATE_WORKDONE )
1590         h->state.state = HB_STATE_IDLE;
1591
1592     hb_unlock( h->state_lock );
1593 }
1594
1595 void hb_get_state2( hb_handle_t * h, hb_state_t * s )
1596 {
1597     hb_lock( h->state_lock );
1598
1599     memcpy( s, &h->state, sizeof( hb_state_t ) );
1600
1601     hb_unlock( h->state_lock );
1602 }
1603
1604 /**
1605  * Called in MacGui in UpdateUI to check
1606  *  for a new scan being completed to set a new source
1607  */
1608 int hb_get_scancount( hb_handle_t * h)
1609  {
1610      return h->scanCount;
1611  }
1612
1613 /**
1614  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init.
1615  * @param _h Pointer to handle to hb_handle_t.
1616  */
1617 void hb_close( hb_handle_t ** _h )
1618 {
1619     hb_handle_t * h = *_h;
1620     hb_title_t * title;
1621
1622     h->die = 1;
1623     
1624     hb_thread_close( &h->main_thread );
1625
1626     while( ( title = hb_list_item( h->list_title, 0 ) ) )
1627     {
1628         hb_list_rem( h->list_title, title );
1629         if( title->job && title->job->filters )
1630         {
1631             hb_list_close( &title->job->filters );
1632         }
1633         free( title->job );
1634         hb_title_close( &title );
1635     }
1636     hb_list_close( &h->list_title );
1637
1638     hb_list_close( &h->jobs );
1639     hb_lock_close( &h->state_lock );
1640     hb_lock_close( &h->pause_lock );
1641
1642     free( h );
1643     *_h = NULL;
1644 }
1645
1646 /**
1647  * Cleans up libhb at a process level. Call before the app closes. Removes preview directory.
1648  */
1649 void hb_global_close()
1650 {
1651     char dirname[1024];
1652     DIR * dir;
1653     struct dirent * entry;
1654     
1655     /* Find and remove temp folder */
1656     memset( dirname, 0, 1024 );
1657     hb_get_temporary_directory( dirname );
1658
1659     dir = opendir( dirname );
1660     if (dir)
1661     {
1662         while( ( entry = readdir( dir ) ) )
1663         {
1664             char filename[1024];
1665             if( entry->d_name[0] == '.' )
1666             {
1667                 continue;
1668             }
1669             memset( filename, 0, 1024 );
1670             snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
1671             unlink( filename );
1672         }
1673         closedir( dir );
1674         rmdir( dirname );
1675     }
1676 }
1677
1678 /**
1679  * Monitors the state of the update, scan, and work threads.
1680  * Sets scan done state when scan thread exits.
1681  * Sets work done state when work thread exits.
1682  * @param _h Handle to hb_handle_t
1683  */
1684 static void thread_func( void * _h )
1685 {
1686     hb_handle_t * h = (hb_handle_t *) _h;
1687     char dirname[1024];
1688
1689     h->pid = getpid();
1690
1691     /* Create folder for temporary files */
1692     memset( dirname, 0, 1024 );
1693     hb_get_temporary_directory( dirname );
1694
1695     hb_mkdir( dirname );
1696
1697     while( !h->die )
1698     {
1699         /* In case the check_update thread hangs, it'll die sooner or
1700            later. Then, we join it here */
1701         if( h->update_thread &&
1702             hb_thread_has_exited( h->update_thread ) )
1703         {
1704             hb_thread_close( &h->update_thread );
1705         }
1706
1707         /* Check if the scan thread is done */
1708         if( h->scan_thread &&
1709             hb_thread_has_exited( h->scan_thread ) )
1710         {
1711             hb_thread_close( &h->scan_thread );
1712
1713             if ( h->scan_die )
1714             {
1715                 hb_title_t * title;
1716
1717                 hb_remove_previews( h );
1718                 while( ( title = hb_list_item( h->list_title, 0 ) ) )
1719                 {
1720                     hb_list_rem( h->list_title, title );
1721                     hb_title_close( &title );
1722                 }
1723
1724                 hb_log( "hb_scan: canceled" );
1725             }
1726             else
1727             {
1728                 hb_log( "libhb: scan thread found %d valid title(s)",
1729                         hb_list_count( h->list_title ) );
1730             }
1731             hb_lock( h->state_lock );
1732             h->state.state = HB_STATE_SCANDONE; //originally state.state
1733                         hb_unlock( h->state_lock );
1734                         /*we increment this sessions scan count by one for the MacGui
1735                         to trigger a new source being set */
1736             h->scanCount++;
1737         }
1738
1739         /* Check if the work thread is done */
1740         if( h->work_thread &&
1741             hb_thread_has_exited( h->work_thread ) )
1742         {
1743             hb_thread_close( &h->work_thread );
1744
1745             hb_log( "libhb: work result = %d",
1746                     h->work_error );
1747             hb_lock( h->state_lock );
1748             h->state.state                = HB_STATE_WORKDONE;
1749             h->state.param.workdone.error = h->work_error;
1750
1751             h->job_count = hb_count(h);
1752             if (h->job_count < 1)
1753                 h->job_count_permanent = 0;
1754             hb_unlock( h->state_lock );
1755         }
1756
1757         hb_snooze( 50 );
1758     }
1759
1760     if( h->scan_thread )
1761     {
1762         hb_scan_stop( h );
1763         hb_thread_close( &h->scan_thread );
1764     }
1765     if( h->work_thread )
1766     {
1767         hb_stop( h );
1768         hb_thread_close( &h->work_thread );
1769     }
1770     hb_remove_previews( h );
1771 }
1772
1773 /**
1774  * Redirects stderr to the registered callback
1775  * function.
1776  * @param _data Unused.
1777  */
1778 static void redirect_thread_func(void * _data)
1779 {
1780     int pfd[2];
1781     pipe(pfd);
1782 #if defined( SYS_MINGW )
1783     // dup2 doesn't work on windows for some stupid reason
1784     stderr->_file = pfd[1];
1785 #else
1786     dup2(pfd[1], /*stderr*/ 2);
1787 #endif
1788     FILE * log_f = fdopen(pfd[0], "rb");
1789     
1790     char line_buffer[500];
1791     while(fgets(line_buffer, 500, log_f) != NULL)
1792     {
1793         hb_log_callback(line_buffer);
1794     }
1795 }
1796
1797 /**
1798  * Returns the PID.
1799  * @param h Handle to hb_handle_t
1800  */
1801 int hb_get_pid( hb_handle_t * h )
1802 {
1803     return h->pid;
1804 }
1805
1806 /**
1807  * Returns the id for the given instance.
1808  * @param h Handle to hb_handle_t
1809  * @returns The ID for the given instance
1810  */
1811 int hb_get_instance_id( hb_handle_t * h )
1812 {
1813     return h->id;
1814 }
1815
1816 /**
1817  * Returns the title with the given title index.
1818  * @param h Handle to hb_handle_t
1819  * @param title_index the index of the title to get
1820  * @returns The requested title
1821  */
1822 hb_title_t * hb_get_title_by_index( hb_handle_t * h, int title_index )
1823 {
1824     hb_title_t * title;
1825     int i;
1826         int count = hb_list_count( h->list_title );
1827     for (i = 0; i < count; i++)
1828     {
1829         title = hb_list_item( h->list_title, i );
1830         if (title->index == title_index)
1831         {
1832             return title;
1833         }
1834     }
1835     
1836     return NULL;
1837 }
1838
1839 /**
1840  * Sets the current state.
1841  * @param h Handle to hb_handle_t
1842  * @param s Handle to new hb_state_t
1843  */
1844 void hb_set_state( hb_handle_t * h, hb_state_t * s )
1845 {
1846     hb_lock( h->pause_lock );
1847     hb_lock( h->state_lock );
1848     memcpy( &h->state, s, sizeof( hb_state_t ) );
1849     if( h->state.state == HB_STATE_WORKING ||
1850         h->state.state == HB_STATE_SEARCHING )
1851     {
1852         /* XXX Hack */
1853         if (h->job_count < 1)
1854             h->job_count_permanent = 1;
1855
1856         h->state.param.working.job_cur =
1857             h->job_count_permanent - hb_list_count( h->jobs );
1858         h->state.param.working.job_count = h->job_count_permanent;
1859
1860         // Set which job is being worked on
1861         if (h->current_job)
1862             h->state.param.working.sequence_id = h->current_job->sequence_id;
1863         else
1864             h->state.param.working.sequence_id = 0;
1865     }
1866     hb_unlock( h->state_lock );
1867     hb_unlock( h->pause_lock );
1868 }
1869
1870 /* Passes a pointer to persistent data */
1871 hb_interjob_t * hb_interjob_get( hb_handle_t * h )
1872 {
1873     return h->interjob;
1874 }