OSDN Git Service

LinGui: several ui improvements
[handbrake-jp/handbrake-jp-git.git] / gtk / src / hb-backend.c
1 /***************************************************************************
2  *            hb-backend.c
3  *
4  *  Fri Mar 28 10:38:44 2008
5  *  Copyright  2008  John Stebbins
6  *  <john at stebbins dot name>
7  ****************************************************************************/
8
9 /*
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  * 
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Library General Public License for more details.
19  * 
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301,  USA
23  */
24 #define _GNU_SOURCE
25 #include <limits.h>
26 #include <math.h>
27 #include "hb.h"
28 #include <gtk/gtk.h>
29 #include <glib/gstdio.h>
30 #include "hb-backend.h"
31 #include "settings.h"
32 #include "callbacks.h"
33 #include "subtitlehandler.h"
34 #include "x264handler.h"
35 #include "preview.h"
36 #include "values.h"
37 #include "lang.h"
38
39 typedef struct
40 {
41         const gchar *option;
42         const gchar *shortOpt;
43         gdouble ivalue;
44         const gchar *svalue;
45 } options_map_t;
46
47 typedef struct
48 {
49         gint count;
50         options_map_t *map;
51 } combo_opts_t;
52
53 static gchar **index_str = NULL;
54 static gint index_str_size = 0;
55
56 static void 
57 index_str_init(gint max_index)
58 {
59         int ii;
60
61         if (max_index+1 > index_str_size)
62         {
63                 index_str = realloc(index_str, (max_index+1) * sizeof(char*));
64                 for (ii = index_str_size; ii <= max_index; ii++)
65                 {
66                         index_str[ii] = g_strdup_printf("%d", ii);
67                 }
68                 index_str_size = max_index + 1;
69         }
70 }
71
72 static options_map_t d_when_complete_opts[] =
73 {
74         {"Do Nothing",            "nothing",  0, "0"},
75         {"Show Notification",     "notify",   1, "1"},
76         {"Put Computer To Sleep", "sleep",    2, "2"},
77         {"Shutdown Computer",     "shutdown", 3, "3"},
78 };
79 combo_opts_t when_complete_opts =
80 {
81         sizeof(d_when_complete_opts)/sizeof(options_map_t),
82         d_when_complete_opts
83 };
84
85 static options_map_t d_par_opts[] =
86 {
87         {"Off", "0", 0, "0"},
88         {"Strict", "1", 1, "1"},
89         {"Loose", "2", 2, "2"},
90         {"Custom", "3", 3, "3"},
91 };
92 combo_opts_t par_opts =
93 {
94         sizeof(d_par_opts)/sizeof(options_map_t),
95         d_par_opts
96 };
97
98 static options_map_t d_alignment_opts[] =
99 {
100         {"2", "2", 2, "2"},
101         {"4", "4", 4, "4"},
102         {"8", "8", 8, "8"},
103         {"16", "16", 16, "16"},
104 };
105 combo_opts_t alignment_opts =
106 {
107         sizeof(d_alignment_opts)/sizeof(options_map_t),
108         d_alignment_opts
109 };
110
111 static options_map_t d_logging_opts[] =
112 {
113         {"0", "0", 0, "0"},
114         {"1", "1", 1, "1"},
115         {"2", "2", 2, "2"},
116 };
117 combo_opts_t logging_opts =
118 {
119         sizeof(d_logging_opts)/sizeof(options_map_t),
120         d_logging_opts
121 };
122
123 static options_map_t d_log_longevity_opts[] =
124 {
125         {"Week",     "week",     7, "7"},
126         {"Month",    "month",    30, "30"},
127         {"Year",     "year",     365, "365"},
128         {"Immortal", "immortal", 366, "366"},
129 };
130 combo_opts_t log_longevity_opts =
131 {
132         sizeof(d_log_longevity_opts)/sizeof(options_map_t),
133         d_log_longevity_opts
134 };
135
136 static options_map_t d_appcast_update_opts[] =
137 {
138         {"Never", "never", 0, "never"},
139         {"Daily", "daily", 1, "daily"},
140         {"Weekly", "weekly", 2, "weekly"},
141         {"Monthly", "monthly", 3, "monthly"},
142 };
143 combo_opts_t appcast_update_opts =
144 {
145         sizeof(d_appcast_update_opts)/sizeof(options_map_t),
146         d_appcast_update_opts
147 };
148
149 static options_map_t d_vqual_granularity_opts[] =
150 {
151         {"0.2",  "0.2",  0.2,  "0.2"},
152         {"0.25", "0.25", 0.25, "0.25"},
153         {"0.5",  "0.5",  0.5,  "0.5"},
154         {"1",    "1",    1,    "1"},
155 };
156 combo_opts_t vqual_granularity_opts =
157 {
158         sizeof(d_vqual_granularity_opts)/sizeof(options_map_t),
159         d_vqual_granularity_opts
160 };
161
162 static options_map_t d_container_opts[] =
163 {
164         {"MKV", "mkv", HB_MUX_MKV, "mkv"},
165         {"MP4", "mp4", HB_MUX_MP4, "mp4"},
166 };
167 combo_opts_t container_opts =
168 {
169         sizeof(d_container_opts)/sizeof(options_map_t),
170         d_container_opts
171 };
172
173 static options_map_t d_detel_opts[] =
174 {
175         {"None",   "none",   0, ""},
176         {"Custom", "custom", 1, ""},
177         {"Default","default",2, NULL},
178 };
179 combo_opts_t detel_opts =
180 {
181         sizeof(d_detel_opts)/sizeof(options_map_t),
182         d_detel_opts
183 };
184
185 static options_map_t d_decomb_opts[] =
186 {
187         {"None",   "none",   0, ""},
188         {"Custom", "custom", 1, ""},
189         {"Default","default",2, NULL},
190 };
191 combo_opts_t decomb_opts =
192 {
193         sizeof(d_decomb_opts)/sizeof(options_map_t),
194         d_decomb_opts
195 };
196
197 static options_map_t d_deint_opts[] =
198 {
199         {"None",   "none",   0, ""},
200         {"Custom", "custom", 1, ""},
201         {"Fast",   "fast",   2, "-1:-1:-1:0:1"},
202         {"Slow",   "slow",   3, "2:-1:-1:0:1"},
203         {"Slower", "slower", 4, "0:-1:-1:0:1"},
204 };
205 combo_opts_t deint_opts =
206 {
207         sizeof(d_deint_opts)/sizeof(options_map_t),
208         d_deint_opts
209 };
210
211 static options_map_t d_denoise_opts[] =
212 {
213         {"None",   "none",   0, ""},
214         {"Custom", "custom", 1, ""},
215         {"Weak",   "weak",   2, "2:1:2:3"},
216         {"Medium", "medium", 3, "3:2:2:3"},
217         {"Strong", "strong", 4, "7:7:5:5"},
218 };
219 combo_opts_t denoise_opts =
220 {
221         sizeof(d_denoise_opts)/sizeof(options_map_t),
222         d_denoise_opts
223 };
224
225 static options_map_t d_vcodec_opts[] =
226 {
227         {"H.264 (x264)",    "x264",   HB_VCODEC_X264, ""},
228         {"MPEG-4 (FFMPEG)", "ffmpeg", HB_VCODEC_FFMPEG, ""},
229         {"Theora",          "theora", HB_VCODEC_THEORA, ""},
230 };
231 combo_opts_t vcodec_opts =
232 {
233         sizeof(d_vcodec_opts)/sizeof(options_map_t),
234         d_vcodec_opts
235 };
236
237 static options_map_t d_acodec_opts[] =
238 {
239         {"AAC (faac)",      "faac",   HB_ACODEC_FAAC, "faac"},
240         {"MP3 (lame)",      "lame",   HB_ACODEC_LAME, "lame"},
241         {"Vorbis",          "vorbis", HB_ACODEC_VORBIS, "vorbis"},
242         {"AC3 (pass-thru)", "ac3",    HB_ACODEC_AC3, "ac3"},
243         {"DTS (pass-thru)", "dts",    HB_ACODEC_DCA, "dts"},
244         {"Auto Pass-Thru", "auto",    HB_ACODEC_DCA|HB_ACODEC_AC3, "auto"},
245 };
246 combo_opts_t acodec_opts =
247 {
248         sizeof(d_acodec_opts)/sizeof(options_map_t),
249         d_acodec_opts
250 };
251
252 static options_map_t d_direct_opts[] =
253 {
254         {"None",      "none",     0, "none"},
255         {"Spatial",   "spatial",  1, "spatial"},
256         {"Temporal",  "temporal", 2, "temporal"},
257         {"Automatic", "auto",     3, "auto"},
258 };
259 combo_opts_t direct_opts =
260 {
261         sizeof(d_direct_opts)/sizeof(options_map_t),
262         d_direct_opts
263 };
264
265 static options_map_t d_badapt_opts[] =
266 {
267         {"Off",             "0", 0, "0"},
268         {"Fast",            "1", 1, "1"},
269         {"Optimal",         "2", 2, "2"},
270 };
271 combo_opts_t badapt_opts =
272 {
273         sizeof(d_badapt_opts)/sizeof(options_map_t),
274         d_badapt_opts
275 };
276
277 static options_map_t d_me_opts[] =
278 {
279         {"Diamond",              "dia",  0, "dia"},
280         {"Hexagon",              "hex",  1, "hex"},
281         {"Uneven Multi-Hexagon", "umh",  2, "umh"},
282         {"Exhaustive",           "esa",  3, "esa"},
283         {"Hadamard Exhaustive",  "tesa", 4, "tesa"},
284 };
285 combo_opts_t me_opts =
286 {
287         sizeof(d_me_opts)/sizeof(options_map_t),
288         d_me_opts
289 };
290
291 static options_map_t d_subme_opts[] =
292 {
293         {"1", "1", 1, "1"},
294         {"2", "2", 2, "2"},
295         {"3", "3", 3, "3"},
296         {"4", "4", 4, "4"},
297         {"5", "5", 5, "5"},
298         {"6", "6", 6, "6"},
299         {"7", "7", 7, "7"},
300         {"8", "8", 8, "8"},
301         {"9", "9", 9, "9"},
302 };
303 combo_opts_t subme_opts =
304 {
305         sizeof(d_subme_opts)/sizeof(options_map_t),
306         d_subme_opts
307 };
308
309 static options_map_t d_analyse_opts[] =
310 {
311         {"Some", "some", 0, "some"},
312         {"None", "none", 1, "none"},
313         {"All",  "all",  2, "all"},
314         {"Custom",  "custom",  3, "all"},
315 };
316 combo_opts_t analyse_opts =
317 {
318         sizeof(d_analyse_opts)/sizeof(options_map_t),
319         d_analyse_opts
320 };
321
322 static options_map_t d_trellis_opts[] =
323 {
324         {"Disabled",          "0", 0, "0"},
325         {"Final Macro Block", "1", 1, "1"},
326         {"Always",            "2", 2, "2"},
327 };
328 combo_opts_t trellis_opts =
329 {
330         sizeof(d_trellis_opts)/sizeof(options_map_t),
331         d_trellis_opts
332 };
333
334 combo_opts_t subtitle_opts =
335 {
336         0,
337         NULL
338 };
339
340 combo_opts_t title_opts =
341 {
342         0,
343         NULL
344 };
345
346 combo_opts_t audio_track_opts =
347 {
348         0,
349         NULL
350 };
351
352 typedef struct
353 {
354         const gchar *name;
355         combo_opts_t *opts;
356 } combo_name_map_t;
357
358 combo_name_map_t combo_name_map[] =
359 {
360         {"WhenComplete", &when_complete_opts},
361         {"PicturePAR", &par_opts},
362         {"PictureModulus", &alignment_opts},
363         {"LoggingLevel", &logging_opts},
364         {"LogLongevity", &log_longevity_opts},
365         {"check_updates", &appcast_update_opts},
366         {"VideoQualityGranularity", &vqual_granularity_opts},
367         {"FileFormat", &container_opts},
368         {"PictureDeinterlace", &deint_opts},
369         {"PictureDecomb", &decomb_opts},
370         {"PictureDetelecine", &detel_opts},
371         {"PictureDenoise", &denoise_opts},
372         {"VideoEncoder", &vcodec_opts},
373         {"AudioEncoder", &acodec_opts},
374         {"x264_direct", &direct_opts},
375         {"x264_b_adapt", &badapt_opts},
376         {"x264_me", &me_opts},
377         {"x264_subme", &subme_opts},
378         {"x264_analyse", &analyse_opts},
379         {"x264_trellis", &trellis_opts},
380         {"SubtitleTrack", &subtitle_opts},
381         {"title", &title_opts},
382         {"AudioTrack", &audio_track_opts},
383         {NULL, NULL}
384 };
385
386 const gchar *srt_codeset_table[] =
387 {
388         "ANSI_X3.4-1968",
389         "ANSI_X3.4-1986",
390         "ANSI_X3.4",
391         "ANSI_X3.110-1983",
392         "ANSI_X3.110",
393         "ASCII",
394         "ECMA-114",
395         "ECMA-118",
396         "ECMA-128",
397         "ECMA-CYRILLIC",
398         "IEC_P27-1",
399         "ISO-8859-1",
400         "ISO-8859-2",
401         "ISO-8859-3",
402         "ISO-8859-4",
403         "ISO-8859-5",
404         "ISO-8859-6",
405         "ISO-8859-7",
406         "ISO-8859-8",
407         "ISO-8859-9",
408         "ISO-8859-9E",
409         "ISO-8859-10",
410         "ISO-8859-11",
411         "ISO-8859-13",
412         "ISO-8859-14",
413         "ISO-8859-15",
414         "ISO-8859-16",
415         "UTF-7",
416         "UTF-8",
417         "UTF-16",
418         "UTF-32",
419         NULL
420 };
421 #define SRT_TABLE_SIZE (sizeof(srt_codeset_table)/ sizeof(char*)-1)
422
423 #if 0
424 typedef struct iso639_lang_t
425 {
426     char * eng_name;        /* Description in English */
427     char * native_name;     /* Description in native language */
428     char * iso639_1;       /* ISO-639-1 (2 characters) code */
429     char * iso639_2;        /* ISO-639-2/t (3 character) code */
430     char * iso639_2b;       /* ISO-639-2/b code (if different from above) */
431 } iso639_lang_t;
432 #endif
433
434 const iso639_lang_t ghb_language_table[] =
435
436         { "Any", "", "zz", "und" },
437         { "Afar", "", "aa", "aar" },
438         { "Abkhazian", "", "ab", "abk" },
439         { "Afrikaans", "", "af", "afr" },
440         { "Akan", "", "ak", "aka" },
441         { "Albanian", "", "sq", "sqi", "alb" },
442         { "Amharic", "", "am", "amh" },
443         { "Arabic", "", "ar", "ara" },
444         { "Aragonese", "", "an", "arg" },
445         { "Armenian", "", "hy", "hye", "arm" },
446         { "Assamese", "", "as", "asm" },
447         { "Avaric", "", "av", "ava" },
448         { "Avestan", "", "ae", "ave" },
449         { "Aymara", "", "ay", "aym" },
450         { "Azerbaijani", "", "az", "aze" },
451         { "Bashkir", "", "ba", "bak" },
452         { "Bambara", "", "bm", "bam" },
453         { "Basque", "", "eu", "eus", "baq" },
454         { "Belarusian", "", "be", "bel" },
455         { "Bengali", "", "bn", "ben" },
456         { "Bihari", "", "bh", "bih" },
457         { "Bislama", "", "bi", "bis" },
458         { "Bosnian", "", "bs", "bos" },
459         { "Breton", "", "br", "bre" },
460         { "Bulgarian", "", "bg", "bul" },
461         { "Burmese", "", "my", "mya", "bur" },
462         { "Catalan", "", "ca", "cat" },
463         { "Chamorro", "", "ch", "cha" },
464         { "Chechen", "", "ce", "che" },
465         { "Chinese", "", "zh", "zho", "chi" },
466         { "Church Slavic", "", "cu", "chu" },
467         { "Chuvash", "", "cv", "chv" },
468         { "Cornish", "", "kw", "cor" },
469         { "Corsican", "", "co", "cos" },
470         { "Cree", "", "cr", "cre" },
471         { "Czech", "", "cs", "ces", "cze" },
472         { "Danish", "Dansk", "da", "dan" },
473         { "Divehi", "", "dv", "div" },
474         { "Dutch", "Nederlands", "nl", "nld", "dut" },
475         { "Dzongkha", "", "dz", "dzo" },
476         { "English", "English", "en", "eng" },
477         { "Esperanto", "", "eo", "epo" },
478         { "Estonian", "", "et", "est" },
479         { "Ewe", "", "ee", "ewe" },
480         { "Faroese", "", "fo", "fao" },
481         { "Fijian", "", "fj", "fij" },
482         { "Finnish", "Suomi", "fi", "fin" },
483         { "French", "Francais", "fr", "fra", "fre" },
484         { "Western Frisian", "", "fy", "fry" },
485         { "Fulah", "", "ff", "ful" },
486         { "Georgian", "", "ka", "kat", "geo" },
487         { "German", "Deutsch", "de", "deu", "ger" },
488         { "Gaelic (Scots)", "", "gd", "gla" },
489         { "Irish", "", "ga", "gle" },
490         { "Galician", "", "gl", "glg" },
491         { "Manx", "", "gv", "glv" },
492         { "Greek, Modern", "", "el", "ell", "gre" },
493         { "Guarani", "", "gn", "grn" },
494         { "Gujarati", "", "gu", "guj" },
495         { "Haitian", "", "ht", "hat" },
496         { "Hausa", "", "ha", "hau" },
497         { "Hebrew", "", "he", "heb" },
498         { "Herero", "", "hz", "her" },
499         { "Hindi", "", "hi", "hin" },
500         { "Hiri Motu", "", "ho", "hmo" },
501         { "Hungarian", "Magyar", "hu", "hun" },
502         { "Igbo", "", "ig", "ibo" },
503         { "Icelandic", "Islenska", "is", "isl", "ice" },
504         { "Ido", "", "io", "ido" },
505         { "Sichuan Yi", "", "ii", "iii" },
506         { "Inuktitut", "", "iu", "iku" },
507         { "Interlingue", "", "ie", "ile" },
508         { "Interlingua", "", "ia", "ina" },
509         { "Indonesian", "", "id", "ind" },
510         { "Inupiaq", "", "ik", "ipk" },
511         { "Italian", "Italiano", "it", "ita" },
512         { "Javanese", "", "jv", "jav" },
513         { "Japanese", "", "ja", "jpn" },
514         { "Kalaallisut", "", "kl", "kal" },
515         { "Kannada", "", "kn", "kan" },
516         { "Kashmiri", "", "ks", "kas" },
517         { "Kanuri", "", "kr", "kau" },
518         { "Kazakh", "", "kk", "kaz" },
519         { "Central Khmer", "", "km", "khm" },
520         { "Kikuyu", "", "ki", "kik" },
521         { "Kinyarwanda", "", "rw", "kin" },
522         { "Kirghiz", "", "ky", "kir" },
523         { "Komi", "", "kv", "kom" },
524         { "Kongo", "", "kg", "kon" },
525         { "Korean", "", "ko", "kor" },
526         { "Kuanyama", "", "kj", "kua" },
527         { "Kurdish", "", "ku", "kur" },
528         { "Lao", "", "lo", "lao" },
529         { "Latin", "", "la", "lat" },
530         { "Latvian", "", "lv", "lav" },
531         { "Limburgan", "", "li", "lim" },
532         { "Lingala", "", "ln", "lin" },
533         { "Lithuanian", "", "lt", "lit" },
534         { "Luxembourgish", "", "lb", "ltz" },
535         { "Luba-Katanga", "", "lu", "lub" },
536         { "Ganda", "", "lg", "lug" },
537         { "Macedonian", "", "mk", "mkd", "mac" },
538         { "Marshallese", "", "mh", "mah" },
539         { "Malayalam", "", "ml", "mal" },
540         { "Maori", "", "mi", "mri", "mao" },
541         { "Marathi", "", "mr", "mar" },
542         { "Malay", "", "ms", "msa", "msa" },
543         { "Malagasy", "", "mg", "mlg" },
544         { "Maltese", "", "mt", "mlt" },
545         { "Moldavian", "", "mo", "mol" },
546         { "Mongolian", "", "mn", "mon" },
547         { "Nauru", "", "na", "nau" },
548         { "Navajo", "", "nv", "nav" },
549         { "Ndebele, South", "", "nr", "nbl" },
550         { "Ndebele, North", "", "nd", "nde" },
551         { "Ndonga", "", "ng", "ndo" },
552         { "Nepali", "", "ne", "nep" },
553         { "Norwegian Nynorsk", "", "nn", "nno" },
554         { "Norwegian Bokmål", "", "nb", "nob" },
555         { "Norwegian", "Norsk", "no", "nor" },
556         { "Chichewa; Nyanja", "", "ny", "nya" },
557         { "Occitan", "", "oc", "oci" },
558         { "Ojibwa", "", "oj", "oji" },
559         { "Oriya", "", "or", "ori" },
560         { "Oromo", "", "om", "orm" },
561         { "Ossetian", "", "os", "oss" },
562         { "Panjabi", "", "pa", "pan" },
563         { "Persian", "", "fa", "fas", "per" },
564         { "Pali", "", "pi", "pli" },
565         { "Polish", "", "pl", "pol" },
566         { "Portuguese", "Portugues", "pt", "por" },
567         { "Pushto", "", "ps", "pus" },
568         { "Quechua", "", "qu", "que" },
569         { "Romansh", "", "rm", "roh" },
570         { "Romanian", "", "ro", "ron", "rum" },
571         { "Rundi", "", "rn", "run" },
572         { "Russian", "", "ru", "rus" },
573         { "Sango", "", "sg", "sag" },
574         { "Sanskrit", "", "sa", "san" },
575         { "Serbian", "", "sr", "srp", "scc" },
576         { "Croatian", "Hrvatski", "hr", "hrv", "scr" },
577         { "Sinhala", "", "si", "sin" },
578         { "Slovak", "", "sk", "slk", "slo" },
579         { "Slovenian", "", "sl", "slv" },
580         { "Northern Sami", "", "se", "sme" },
581         { "Samoan", "", "sm", "smo" },
582         { "Shona", "", "sn", "sna" },
583         { "Sindhi", "", "sd", "snd" },
584         { "Somali", "", "so", "som" },
585         { "Sotho, Southern", "", "st", "sot" },
586         { "Spanish", "Espanol", "es", "spa" },
587         { "Sardinian", "", "sc", "srd" },
588         { "Swati", "", "ss", "ssw" },
589         { "Sundanese", "", "su", "sun" },
590         { "Swahili", "", "sw", "swa" },
591         { "Swedish", "Svenska", "sv", "swe" },
592         { "Tahitian", "", "ty", "tah" },
593         { "Tamil", "", "ta", "tam" },
594         { "Tatar", "", "tt", "tat" },
595         { "Telugu", "", "te", "tel" },
596         { "Tajik", "", "tg", "tgk" },
597         { "Tagalog", "", "tl", "tgl" },
598         { "Thai", "", "th", "tha" },
599         { "Tibetan", "", "bo", "bod", "tib" },
600         { "Tigrinya", "", "ti", "tir" },
601         { "Tonga", "", "to", "ton" },
602         { "Tswana", "", "tn", "tsn" },
603         { "Tsonga", "", "ts", "tso" },
604         { "Turkmen", "", "tk", "tuk" },
605         { "Turkish", "", "tr", "tur" },
606         { "Twi", "", "tw", "twi" },
607         { "Uighur", "", "ug", "uig" },
608         { "Ukrainian", "", "uk", "ukr" },
609         { "Urdu", "", "ur", "urd" },
610         { "Uzbek", "", "uz", "uzb" },
611         { "Venda", "", "ve", "ven" },
612         { "Vietnamese", "", "vi", "vie" },
613         { "Volapük", "", "vo", "vol" },
614         { "Welsh", "", "cy", "cym", "wel" },
615         { "Walloon", "", "wa", "wln" },
616         { "Wolof", "", "wo", "wol" },
617         { "Xhosa", "", "xh", "xho" },
618         { "Yiddish", "", "yi", "yid" },
619         { "Yoruba", "", "yo", "yor" },
620         { "Zhuang", "", "za", "zha" },
621         { "Zulu", "", "zu", "zul" },
622         {NULL, NULL, NULL, NULL}
623 };
624 #define LANG_TABLE_SIZE (sizeof(ghb_language_table)/ sizeof(iso639_lang_t)-1)
625
626 static void audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name);
627
628 static void
629 del_tree(const gchar *name, gboolean del_top)
630 {
631         const gchar *file;
632
633         if (g_file_test(name, G_FILE_TEST_IS_DIR))
634         {
635                 GDir *gdir = g_dir_open(name, 0, NULL);
636                 file = g_dir_read_name(gdir);
637                 while (file)
638                 {
639                         gchar *path;
640                         path = g_strdup_printf("%s/%s", name, file);
641                         del_tree(path, TRUE);
642                         g_free(path);
643                         file = g_dir_read_name(gdir);
644                 }
645                 if (del_top)
646                         g_rmdir(name);
647                 g_dir_close(gdir);
648         }
649         else
650         {
651                 g_unlink(name);
652         }
653 }
654
655 const gchar*
656 ghb_version()
657 {
658         return hb_get_version(NULL);
659 }
660
661 void
662 ghb_vquality_range(
663         signal_user_data_t *ud, 
664         gdouble *min, 
665         gdouble *max,
666         gdouble *step,
667         gdouble *page,
668         gint *digits,
669         gboolean *inverted)
670 {
671         gint vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
672         *page = 10;
673         *digits = 0;
674         switch (vcodec)
675         {
676                 case HB_VCODEC_X264:
677                 {
678                         *min = 0;
679                         *max = 51;
680                         *step = ghb_settings_combo_double(ud->settings, 
681                                                                                         "VideoQualityGranularity");
682                         if (*step == 0.2 || *step == 0.5)
683                                 *digits = 1;
684                         else if (*step == 0.25)
685                                 *digits = 2;
686                         *inverted = TRUE;
687                 } break;
688
689                 case HB_VCODEC_FFMPEG:
690                 {
691                         *min = 1;
692                         *max = 31;
693                         *step = 1;
694                         *inverted = TRUE;
695                 } break;
696
697                 case HB_VCODEC_THEORA:
698                 {
699                         *min = 0;
700                         *max = 63;
701                         *step = 1;
702                         *inverted = FALSE;
703                 } break;
704
705                 default:
706                 {
707                         *min = 0;
708                         *max = 100;
709                         *step = 1;
710                         *inverted = FALSE;
711                 } break;
712         }
713 }
714
715 static const gchar*
716 lookup_generic_string(combo_opts_t *opts, const GValue *gval)
717 {
718         gint ii;
719         gchar *str;
720         const gchar *result = "";
721
722         str = ghb_value_string(gval);
723         for (ii = 0; ii < opts->count; ii++)
724         {
725                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
726                 {
727                         result = opts->map[ii].svalue;
728                         break;
729                 }
730         }
731         g_free(str);
732         return result;
733 }
734
735 static gint
736 lookup_generic_int(combo_opts_t *opts, const GValue *gval)
737 {
738         gint ii;
739         gchar *str;
740         gint result = -1;
741
742         str = ghb_value_string(gval);
743         for (ii = 0; ii < opts->count; ii++)
744         {
745                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
746                 {
747                         result = opts->map[ii].ivalue;
748                         break;
749                 }
750         }
751         g_free(str);
752         return result;
753 }
754
755 static gdouble
756 lookup_generic_double(combo_opts_t *opts, const GValue *gval)
757 {
758         gint ii;
759         gchar *str;
760         gdouble result = -1;
761
762         str = ghb_value_string(gval);
763         for (ii = 0; ii < opts->count; ii++)
764         {
765                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
766                 {
767                         result = opts->map[ii].ivalue;
768                         break;
769                 }
770         }
771         g_free(str);
772         return result;
773 }
774
775 static const gchar*
776 lookup_generic_option(combo_opts_t *opts, const GValue *gval)
777 {
778         gint ii;
779         gchar *str;
780         const gchar *result = "";
781
782         str = ghb_value_string(gval);
783         for (ii = 0; ii < opts->count; ii++)
784         {
785                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
786                 {
787                         result = opts->map[ii].option;
788                         break;
789                 }
790         }
791         g_free(str);
792         return result;
793 }
794
795 static gint
796 lookup_mix_int(const GValue *mix)
797 {
798         gint ii;
799         gchar *str;
800         gint result = 0;
801
802
803         str = ghb_value_string(mix);
804         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
805         {
806                 if (strcmp(hb_audio_mixdowns[ii].short_name, str) == 0)
807                 {
808                         result = hb_audio_mixdowns[ii].amixdown;
809                         break;
810                 }
811         }
812         g_free(str);
813         return result;
814 }
815
816 static const gchar*
817 lookup_mix_option(const GValue *mix)
818 {
819         gint ii;
820         gchar *str;
821         gchar *result = "None";
822
823
824         str = ghb_value_string(mix);
825         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
826         {
827                 if (strcmp(hb_audio_mixdowns[ii].short_name, str) == 0)
828                 {
829                         result = hb_audio_mixdowns[ii].human_readable_name;
830                         break;
831                 }
832         }
833         g_free(str);
834         return result;
835 }
836
837 static gint
838 lookup_video_rate_int(const GValue *vrate)
839 {
840         gint ii;
841         gchar *str;
842         gint result = 0;
843
844         str = ghb_value_string(vrate);
845         for (ii = 0; ii < hb_video_rates_count; ii++)
846         {
847                 if (strcmp(hb_video_rates[ii].string, str) == 0)
848                 {
849                         result = hb_video_rates[ii].rate;
850                         break;
851                 }
852         }
853         g_free(str);
854         // Default to "same as source"
855         return result;
856 }
857
858 static const gchar*
859 lookup_video_rate_option(const GValue *vrate)
860 {
861         gint ii;
862         gchar *str;
863         const gchar *result = "Same as source";
864
865         str = ghb_value_string(vrate);
866         for (ii = 0; ii < hb_video_rates_count; ii++)
867         {
868                 if (strcmp(hb_video_rates[ii].string, str) == 0)
869                 {
870                         result = hb_video_rates[ii].string;
871                         break;
872                 }
873         }
874         g_free(str);
875         // Default to "same as source"
876         return result;
877 }
878
879 static gint
880 lookup_audio_rate_int(const GValue *rate)
881 {
882         gint ii;
883         gchar *str;
884         gint result = 0;
885
886         // Coincidentally, the string "source" will return 0
887         // which is our flag to use "same as source"
888         str = ghb_value_string(rate);
889         for (ii = 0; ii < hb_audio_rates_count; ii++)
890         {
891                 if (strcmp(hb_audio_rates[ii].string, str) == 0)
892                 {
893                         result = hb_audio_rates[ii].rate;
894                         break;
895                 }
896         }
897         g_free(str);
898         return result;
899 }
900
901 static const gchar*
902 lookup_audio_rate_option(const GValue *rate)
903 {
904         gint ii;
905         gchar *str;
906         const gchar *result = "Same as source";
907
908         // Coincidentally, the string "source" will return 0
909         // which is our flag to use "same as source"
910         str = ghb_value_string(rate);
911         for (ii = 0; ii < hb_audio_rates_count; ii++)
912         {
913                 if (strcmp(hb_audio_rates[ii].string, str) == 0)
914                 {
915                         result = hb_audio_rates[ii].string;
916                         break;
917                 }
918         }
919         g_free(str);
920         return result;
921 }
922
923 static gint
924 lookup_audio_bitrate_int(const GValue *rate)
925 {
926         gint ii;
927         gchar *str;
928         gint result = 0;
929
930         // Coincidentally, the string "source" will return 0
931         // which is our flag to use "same as source"
932         str = ghb_value_string(rate);
933         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
934         {
935                 if (strcmp(hb_audio_bitrates[ii].string, str) == 0)
936                 {
937                         result = hb_audio_bitrates[ii].rate;
938                         break;
939                 }
940         }
941         g_free(str);
942         return result;
943 }
944
945 static const gchar*
946 lookup_audio_bitrate_option(const GValue *rate)
947 {
948         gint ii;
949         gchar *str;
950         const gchar *result = "Same as source";
951
952         // Coincidentally, the string "source" will return 0
953         // which is our flag to use "same as source"
954         str = ghb_value_string(rate);
955         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
956         {
957                 if (strcmp(hb_audio_bitrates[ii].string, str) == 0)
958                 {
959                         result = hb_audio_bitrates[ii].string;
960                         break;
961                 }
962         }
963         g_free(str);
964         return result;
965 }
966
967 static gint
968 lookup_audio_lang_int(const GValue *rate)
969 {
970         gint ii;
971         gchar *str;
972         gint result = 0;
973
974         // Coincidentally, the string "source" will return 0
975         // which is our flag to use "same as source"
976         str = ghb_value_string(rate);
977         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
978         {
979                 if (strcmp(ghb_language_table[ii].iso639_2, str) == 0)
980                 {
981                         result = ii;
982                         break;
983                 }
984         }
985         g_free(str);
986         return result;
987 }
988
989 static const gchar*
990 lookup_audio_lang_option(const GValue *rate)
991 {
992         gint ii;
993         gchar *str;
994         const gchar *result = "Same as source";
995
996         // Coincidentally, the string "source" will return 0
997         // which is our flag to use "same as source"
998         str = ghb_value_string(rate);
999         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1000         {
1001                 if (strcmp(ghb_language_table[ii].iso639_2, str) == 0)
1002                 {
1003                         result = ghb_language_table[ii].eng_name;
1004                         break;
1005                 }
1006         }
1007         g_free(str);
1008         return result;
1009 }
1010
1011 static GValue*
1012 get_acodec_value(gint val)
1013 {
1014         GValue *value = NULL;
1015         gint ii;
1016
1017         for (ii = 0; ii < acodec_opts.count; ii++)
1018         {
1019                 if ((int)acodec_opts.map[ii].ivalue == val)
1020                 {
1021                         value = ghb_string_value_new(acodec_opts.map[ii].shortOpt);
1022                         break;
1023                 }
1024         }
1025         return value;
1026 }
1027
1028 static GValue*
1029 get_amix_value(gint val)
1030 {
1031         GValue *value = NULL;
1032         gint ii;
1033
1034         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1035         {
1036                 if (hb_audio_mixdowns[ii].amixdown == val)
1037                 {
1038                         value = ghb_string_value_new(hb_audio_mixdowns[ii].short_name);
1039                         break;
1040                 }
1041         }
1042         return value;
1043 }
1044
1045 // Handle for libhb.  Gets set by ghb_backend_init()
1046 static hb_handle_t * h_scan = NULL;
1047 static hb_handle_t * h_queue = NULL;
1048
1049 extern void hb_get_tempory_directory(hb_handle_t *h, char path[512]);
1050
1051 gchar*
1052 ghb_get_tmp_dir()
1053 {
1054         char dir[512];
1055
1056         hb_get_tempory_directory(h_scan, dir);
1057         return g_strdup(dir);
1058 }
1059
1060 void
1061 ghb_hb_cleanup(gboolean partial)
1062 {
1063         char dir[512];
1064
1065         hb_get_tempory_directory(h_scan, dir);
1066         del_tree(dir, !partial);
1067 }
1068
1069 gint
1070 ghb_subtitle_track_source(signal_user_data_t *ud, gint track)
1071 {
1072         gint titleindex;
1073
1074         if (track == -2)
1075                 return SRTSUB;
1076         if (track < 0)
1077                 return VOBSUB;
1078         titleindex = ghb_settings_combo_int(ud->settings, "title");
1079         if (titleindex < 0)
1080                 return VOBSUB;
1081
1082         hb_list_t  * list;
1083         hb_title_t * title;
1084         hb_subtitle_t * sub;
1085         
1086         if (h_scan == NULL) return VOBSUB;
1087         list = hb_get_titles( h_scan );
1088         if( !hb_list_count( list ) )
1089         {
1090                 /* No valid title, stop right there */
1091                 return VOBSUB;
1092         }
1093         title = hb_list_item( list, titleindex );
1094         if (title == NULL) return VOBSUB;       // Bad titleindex
1095         sub = hb_list_item( title->list_subtitle, track);
1096         if (sub != NULL)
1097                 return sub->source;
1098         else
1099                 return VOBSUB;
1100 }
1101
1102 const char*
1103 ghb_subtitle_track_source_name(signal_user_data_t *ud, gint track)
1104 {
1105         gint titleindex;
1106         const gchar * name = "Unknown";
1107
1108         if (track == -2)
1109         {
1110                 name = "SRT";
1111                 goto done;
1112         }
1113         if (track == -1)
1114         {
1115                 name = "Bitmap";
1116                 goto done;
1117         }
1118
1119         titleindex = ghb_settings_combo_int(ud->settings, "title");
1120         if (titleindex < 0)
1121                 goto done;
1122
1123         hb_list_t  * list;
1124         hb_title_t * title;
1125         hb_subtitle_t * sub;
1126         
1127         if (h_scan == NULL) 
1128                 goto done;
1129         list = hb_get_titles( h_scan );
1130         if( !hb_list_count( list ) )
1131                 goto done;
1132
1133         title = hb_list_item( list, titleindex );
1134         if (title == NULL)
1135                 goto done;
1136
1137         sub = hb_list_item( title->list_subtitle, track);
1138         if (sub != NULL)
1139         {
1140                 switch (sub->source)
1141                 {
1142                         case VOBSUB:
1143                                 name = "Bitmap";
1144                                 break;
1145                         case CC708SUB:
1146                         case CC608SUB:
1147                                 name = "Text";
1148                                 break;
1149                         case SRTSUB:
1150                                 name = "SRT";
1151                                 break;
1152                         default:
1153                                 break;
1154                 }
1155         }
1156
1157 done:
1158         return name;
1159 }
1160
1161
1162 gint
1163 ghb_get_title_number(gint titleindex)
1164 {
1165         hb_list_t  * list;
1166         hb_title_t * title;
1167         
1168         if (h_scan == NULL) return 1;
1169         list = hb_get_titles( h_scan );
1170         if( !hb_list_count( list ) )
1171         {
1172                 /* No valid title, stop right there */
1173                 return 1;
1174         }
1175         title = hb_list_item( list, titleindex );
1176         if (title == NULL) return 1;    // Bad titleindex
1177         return title->index;
1178 }
1179
1180 static hb_audio_config_t*
1181 get_hb_audio(gint titleindex, gint track)
1182 {
1183         hb_list_t  * list;
1184         hb_title_t * title;
1185     hb_audio_config_t *audio = NULL;
1186         
1187     if (h_scan == NULL) return NULL;
1188         list = hb_get_titles( h_scan );
1189         if( !hb_list_count( list ) )
1190         {
1191                 /* No valid title, stop right there */
1192                 return NULL;
1193         }
1194     title = hb_list_item( list, titleindex );
1195         if (title == NULL) return NULL; // Bad titleindex
1196         if (!hb_list_count(title->list_audio))
1197         {
1198                 return NULL;
1199         }
1200     audio = (hb_audio_config_t *)hb_list_audio_config_item(title->list_audio, track);
1201         return audio;
1202 }
1203
1204 static gint
1205 search_rates(hb_rate_t *rates, gint rate, gint count)
1206 {
1207         gint ii;
1208         for (ii = 0; ii < count; ii++)
1209         {
1210                 if (rates[ii].rate == rate)
1211                         return ii;
1212         }
1213         return -1;
1214 }
1215
1216 static gboolean find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter);
1217
1218 static GtkListStore*
1219 get_combo_box_store(GtkBuilder *builder, const gchar *name)
1220 {
1221         GtkComboBox *combo;
1222         GtkListStore *store;
1223
1224         g_debug("get_combo_box_store() %s\n", name);
1225         // First modify the combobox model to allow greying out of options
1226         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1227         store = GTK_LIST_STORE(gtk_combo_box_get_model (combo));
1228         return store;
1229 }
1230
1231 static void
1232 grey_combo_box_item(GtkBuilder *builder, const gchar *name, gint value, gboolean grey)
1233 {
1234         GtkListStore *store;
1235         GtkTreeIter iter;
1236         
1237         store = get_combo_box_store(builder, name);
1238         if (find_combo_item_by_int(GTK_TREE_MODEL(store), value, &iter))
1239         {
1240                 gtk_list_store_set(store, &iter, 
1241                                                    1, !grey, 
1242                                                    -1);
1243         }
1244 }
1245
1246 void
1247 ghb_grey_combo_options(GtkBuilder *builder)
1248 {
1249         GtkWidget *widget;
1250         gint container, track, titleindex, acodec;
1251     hb_audio_config_t *audio = NULL;
1252         GValue *gval;
1253         
1254         widget = GHB_WIDGET (builder, "title");
1255         gval = ghb_widget_value(widget);
1256         titleindex = ghb_lookup_combo_int("title", gval);
1257         ghb_value_free(gval);
1258         widget = GHB_WIDGET (builder, "AudioTrack");
1259         gval = ghb_widget_value(widget);
1260         track = ghb_lookup_combo_int("AudioTrack", gval);
1261         ghb_value_free(gval);
1262         audio = get_hb_audio(titleindex, track);
1263         widget = GHB_WIDGET (builder, "FileFormat");
1264         gval = ghb_widget_value(widget);
1265         container = ghb_lookup_combo_int("FileFormat", gval);
1266         ghb_value_free(gval);
1267
1268         grey_combo_box_item(builder, "x264_analyse", 3, TRUE);
1269         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, FALSE);
1270         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_LAME, FALSE);
1271         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, FALSE);
1272
1273         gboolean allow_dca = TRUE;
1274         allow_dca = (container != HB_MUX_MP4);
1275
1276         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, FALSE);
1277         if (allow_dca)
1278                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, FALSE);
1279         else
1280                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, TRUE);
1281
1282         if (audio && audio->in.codec != HB_ACODEC_AC3)
1283         {
1284                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, TRUE);
1285         }
1286         if (audio && audio->in.codec != HB_ACODEC_DCA)
1287         {
1288                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, TRUE);
1289         }
1290         grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, FALSE);
1291
1292         widget = GHB_WIDGET (builder, "AudioEncoder");
1293         gval = ghb_widget_value(widget);
1294         acodec = ghb_lookup_combo_int("AudioEncoder", gval);
1295         ghb_value_free(gval);
1296         if (acodec != HB_ACODEC_AC3)
1297         {
1298                 grey_combo_box_item(builder, "AudioMixdown", 0, TRUE);
1299         }
1300         if (container == HB_MUX_MP4)
1301         {
1302                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_LAME, TRUE);
1303                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
1304                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
1305         }
1306         else if (container == HB_MUX_AVI)
1307         {
1308                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1309                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
1310                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
1311         }
1312         else if (container == HB_MUX_OGM)
1313         {
1314                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1315         }
1316
1317         gboolean allow_mono = TRUE;
1318         gboolean allow_stereo = TRUE;
1319         gboolean allow_dolby = TRUE;
1320         gboolean allow_dpl2 = TRUE;
1321         gboolean allow_6ch = TRUE;
1322         if (audio)
1323         {
1324                 allow_mono =
1325                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1326                         (acodec != HB_ACODEC_LAME);
1327                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1328                 allow_stereo =
1329                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1330                 allow_dolby =
1331                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1332                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1333                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1334                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1335                 allow_6ch =
1336                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1337                         (acodec != HB_ACODEC_LAME) &&
1338                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1339                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1340         }
1341         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_MONO, !allow_mono);
1342         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_STEREO, !allow_stereo);
1343         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBY, !allow_dolby);
1344         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBYPLII, !allow_dpl2);
1345         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_6CH, !allow_6ch);
1346 }
1347
1348 gint
1349 ghb_get_best_mix(gint titleindex, gint track, gint acodec, gint mix)
1350 {
1351     hb_audio_config_t *audio = NULL;
1352         gboolean allow_mono = TRUE;
1353         gboolean allow_stereo = TRUE;
1354         gboolean allow_dolby = TRUE;
1355         gboolean allow_dpl2 = TRUE;
1356         gboolean allow_6ch = TRUE;
1357         
1358         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1359         {
1360                 // Audio codec pass-thru.  No mixdown
1361                 return 0;
1362         }
1363         audio = get_hb_audio(titleindex, track);
1364         if (audio)
1365         {
1366                 allow_mono =
1367                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1368                         (acodec != HB_ACODEC_LAME);
1369                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1370                 allow_stereo =
1371                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1372                 allow_dolby =
1373                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1374                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1375                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1376                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1377                 allow_6ch =
1378                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1379                         (acodec != HB_ACODEC_LAME) &&
1380                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1381                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1382         }
1383         gboolean greater = FALSE;
1384         if (mix == 0) 
1385         {
1386                 // If no mix is specified, select the best available.
1387                 mix = HB_AMIXDOWN_6CH;
1388         }
1389         if (mix == HB_AMIXDOWN_6CH)
1390         {
1391                 greater = TRUE;
1392                 if (allow_6ch) return HB_AMIXDOWN_6CH;
1393         }
1394         if (mix == HB_AMIXDOWN_DOLBYPLII || greater)
1395         {
1396                 greater = TRUE;
1397                 if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1398         }
1399         if (mix == HB_AMIXDOWN_DOLBY || greater)
1400         {
1401                 greater = TRUE;
1402                 if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1403         }
1404         if (mix == HB_AMIXDOWN_STEREO || greater)
1405         {
1406                 greater = TRUE;
1407                 if (allow_stereo) return HB_AMIXDOWN_STEREO;
1408         }
1409         if (mix == HB_AMIXDOWN_MONO || greater)
1410         {
1411                 greater = TRUE;
1412                 if (allow_mono) return HB_AMIXDOWN_MONO;
1413         }
1414         if (allow_stereo) return HB_AMIXDOWN_STEREO;
1415         if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1416         if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1417         if (allow_6ch) return HB_AMIXDOWN_6CH;
1418         return 0;
1419 }
1420
1421 // Set up the model for the combo box
1422 static void
1423 init_combo_box(GtkBuilder *builder, const gchar *name)
1424 {
1425         GtkComboBox *combo;
1426         GtkListStore *store;
1427         GtkCellRenderer *cell;
1428
1429         g_debug("init_combo_box() %s\n", name);
1430         // First modify the combobox model to allow greying out of options
1431         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1432         if (combo == NULL)
1433                 return;
1434         // Store contains:
1435         // 1 - String to display
1436         // 2 - bool indicating whether the entry is selectable (grey or not)
1437         // 3 - String that is used for presets
1438         // 4 - Int value determined by backend
1439         // 5 - String value determined by backend
1440         store = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_BOOLEAN, 
1441                                                            G_TYPE_STRING, G_TYPE_DOUBLE, G_TYPE_STRING);
1442         gtk_combo_box_set_model(combo, GTK_TREE_MODEL(store));
1443
1444         if (GTK_WIDGET_TYPE(combo) == GTK_TYPE_COMBO_BOX)
1445         {
1446                 gtk_cell_layout_clear(GTK_CELL_LAYOUT(combo));
1447         cell = GTK_CELL_RENDERER(gtk_cell_renderer_text_new());
1448         gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE);
1449         gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell,
1450                 "text", 0, "sensitive", 1, NULL);
1451         }
1452         else
1453         { // Combo box entry
1454                 gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(combo), 0);
1455         }
1456 }       
1457
1458 static void
1459 audio_samplerate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1460 {
1461         GtkTreeIter iter;
1462         GtkListStore *store;
1463         gint ii;
1464         
1465         g_debug("audio_samplerate_opts_set ()\n");
1466         store = get_combo_box_store(builder, name);
1467         gtk_list_store_clear(store);
1468         // Add an item for "Same As Source"
1469         gtk_list_store_append(store, &iter);
1470         gtk_list_store_set(store, &iter, 
1471                                            0, "Same as source", 
1472                                            1, TRUE, 
1473                                            2, "source", 
1474                                            3, 0.0, 
1475                                            4, "source", 
1476                                            -1);
1477         for (ii = 0; ii < count; ii++)
1478         {
1479                 gtk_list_store_append(store, &iter);
1480                 gtk_list_store_set(store, &iter, 
1481                                                    0, rates[ii].string, 
1482                                                    1, TRUE, 
1483                                                    2, rates[ii].string, 
1484                                                    3, (gdouble)rates[ii].rate, 
1485                                                    4, rates[ii].string, 
1486                                                    -1);
1487         }
1488 }
1489
1490 static void
1491 video_rate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1492 {
1493         GtkTreeIter iter;
1494         GtkListStore *store;
1495         gint ii;
1496         
1497         g_debug("video_rate_opts_set ()\n");
1498         store = get_combo_box_store(builder, name);
1499         gtk_list_store_clear(store);
1500         // Add an item for "Same As Source"
1501         gtk_list_store_append(store, &iter);
1502         gtk_list_store_set(store, &iter, 
1503                                            0, "Same as source", 
1504                                            1, TRUE, 
1505                                            2, "source", 
1506                                            3, 0.0, 
1507                                            4, "source", 
1508                                            -1);
1509         for (ii = 0; ii < count; ii++)
1510         {
1511                 gchar *desc = "";
1512                 gchar *option;
1513                 if (strcmp(rates[ii].string, "23.976") == 0)
1514                 {
1515                         desc = "(NTSC Film)";
1516                 }
1517                 else if (strcmp(rates[ii].string, "25") == 0)
1518                 {
1519                         desc = "(PAL Film/Video)";
1520                 }
1521                 else if (strcmp(rates[ii].string, "29.97") == 0)
1522                 {
1523                         desc = "(NTSC Video)";
1524                 }
1525                 option = g_strdup_printf ("%s %s", rates[ii].string, desc);
1526                 gtk_list_store_append(store, &iter);
1527                 gtk_list_store_set(store, &iter, 
1528                                                    0, option, 
1529                                                    1, TRUE, 
1530                                                    2, rates[ii].string, 
1531                                                    3, (gdouble)rates[ii].rate, 
1532                                                    4, rates[ii].string, 
1533                                                    -1);
1534                 g_free(option);
1535         }
1536 }
1537
1538 static void
1539 mix_opts_set(GtkBuilder *builder, const gchar *name)
1540 {
1541         GtkTreeIter iter;
1542         GtkListStore *store;
1543         gint ii;
1544         
1545         g_debug("mix_opts_set ()\n");
1546         store = get_combo_box_store(builder, name);
1547         gtk_list_store_clear(store);
1548         gtk_list_store_append(store, &iter);
1549         gtk_list_store_set(store, &iter, 
1550                                            0, "None", 
1551                                            1, TRUE, 
1552                                            2, "none", 
1553                                            3, 0.0, 
1554                                            4, "none", 
1555                                            -1);
1556         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1557         {
1558                 gtk_list_store_append(store, &iter);
1559                 gtk_list_store_set(store, &iter, 
1560                                                    0, hb_audio_mixdowns[ii].human_readable_name, 
1561                                                    1, TRUE, 
1562                                                    2, hb_audio_mixdowns[ii].short_name, 
1563                                                    3, (gdouble)hb_audio_mixdowns[ii].amixdown, 
1564                                                    4, hb_audio_mixdowns[ii].internal_name, 
1565                                                    -1);
1566         }
1567 }
1568
1569 static void
1570 srt_codeset_opts_set(GtkBuilder *builder, const gchar *name)
1571 {
1572         GtkTreeIter iter;
1573         GtkListStore *store;
1574         gint ii;
1575         
1576         g_debug("srt_codeset_opts_set ()\n");
1577         store = get_combo_box_store(builder, name);
1578         gtk_list_store_clear(store);
1579         for (ii = 0; ii < SRT_TABLE_SIZE; ii++)
1580         {
1581                 gtk_list_store_append(store, &iter);
1582                 gtk_list_store_set(store, &iter, 
1583                                                    0, srt_codeset_table[ii],
1584                                                    1, TRUE, 
1585                                                    2, srt_codeset_table[ii],
1586                                                    3, (gdouble)ii, 
1587                                                    4, srt_codeset_table[ii],
1588                                                    -1);
1589         }
1590         GtkComboBoxEntry *cbe;
1591
1592         cbe = GTK_COMBO_BOX_ENTRY(GHB_WIDGET(builder, name));
1593         //gtk_combo_box_entry_set_text_column(cbe, 0);
1594 }
1595
1596 static void
1597 language_opts_set(GtkBuilder *builder, const gchar *name)
1598 {
1599         GtkTreeIter iter;
1600         GtkListStore *store;
1601         gint ii;
1602         
1603         g_debug("language_opts_set ()\n");
1604         store = get_combo_box_store(builder, name);
1605         gtk_list_store_clear(store);
1606         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1607         {
1608                 gtk_list_store_append(store, &iter);
1609                 gtk_list_store_set(store, &iter, 
1610                                                    0, ghb_language_table[ii].eng_name, 
1611                                                    1, TRUE, 
1612                                                    2, ghb_language_table[ii].iso639_2, 
1613                                                    3, (gdouble)ii, 
1614                                                    4, ghb_language_table[ii].iso639_1, 
1615                                                    -1);
1616         }
1617 }
1618
1619 static gchar **titles = NULL;
1620
1621 void
1622 title_opts_set(GtkBuilder *builder, const gchar *name)
1623 {
1624         GtkTreeIter iter;
1625         GtkListStore *store;
1626         hb_list_t  * list = NULL;
1627         hb_title_t * title = NULL;
1628         gint ii;
1629         gint count = 0;
1630         
1631         g_debug("title_opts_set ()\n");
1632         store = get_combo_box_store(builder, name);
1633         gtk_list_store_clear(store);
1634         if (h_scan != NULL)
1635         {
1636                 list = hb_get_titles( h_scan );
1637                 count = hb_list_count( list );
1638                 if (count > 100) count = 100;
1639         }
1640         if (titles) g_strfreev(titles);
1641         if (title_opts.map) g_free(title_opts.map);
1642         if (count > 0)
1643         {
1644                 title_opts.count = count;
1645                 title_opts.map = g_malloc(count*sizeof(options_map_t));
1646                 titles = g_malloc((count+1) * sizeof(gchar*));
1647         }
1648         else
1649         {
1650                 title_opts.count = 1;
1651                 title_opts.map = g_malloc(sizeof(options_map_t));
1652                 titles = NULL;
1653         }
1654         if( count <= 0 )
1655         {
1656                 // No titles.  Fill in a default.
1657                 gtk_list_store_append(store, &iter);
1658                 gtk_list_store_set(store, &iter, 
1659                                                    0, "No Titles", 
1660                                                    1, TRUE, 
1661                                                    2, "none", 
1662                                                    3, -1.0, 
1663                                                    4, "none", 
1664                                                    -1);
1665                 title_opts.map[0].option = "No Titles";
1666                 title_opts.map[0].shortOpt = "none";
1667                 title_opts.map[0].ivalue = -1;
1668                 title_opts.map[0].svalue = "none";
1669                 return;
1670         }
1671         for (ii = 0; ii < count; ii++)
1672         {
1673                 title = (hb_title_t*)hb_list_item(list, ii);
1674                 if (title->duration != 0)
1675                 {
1676                         titles[ii]  = g_strdup_printf ("%d - %02dh%02dm%02ds",
1677                                 title->index, title->hours, title->minutes, title->seconds);
1678                 }
1679                 else
1680                 {
1681                         titles[ii]  = g_strdup_printf ("%d - Unknown Length", title->index);
1682                 }
1683                 gtk_list_store_append(store, &iter);
1684                 gtk_list_store_set(store, &iter, 
1685                                                    0, titles[ii], 
1686                                                    1, TRUE, 
1687                                                    2, titles[ii], 
1688                                                    3, (gdouble)ii, 
1689                                                    4, titles[ii], 
1690                                                    -1);
1691                 title_opts.map[ii].option = titles[ii];
1692                 title_opts.map[ii].shortOpt = titles[ii];
1693                 title_opts.map[ii].ivalue = ii;
1694                 title_opts.map[ii].svalue = titles[ii];
1695         }
1696         titles[ii] = NULL;
1697 }
1698
1699 static gboolean
1700 find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter)
1701 {
1702         gdouble ivalue;
1703         gboolean foundit = FALSE;
1704         
1705         if (gtk_tree_model_get_iter_first (store, iter))
1706         {
1707                 do
1708                 {
1709                         gtk_tree_model_get(store, iter, 3, &ivalue, -1);
1710                         if (value == (int)ivalue)
1711                         {
1712                                 foundit = TRUE;
1713                                 break;
1714                         }
1715                 } while (gtk_tree_model_iter_next (store, iter));
1716         }
1717         return foundit;
1718 }
1719
1720 void
1721 audio_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1722 {
1723         GtkTreeIter iter;
1724         GtkListStore *store;
1725         hb_list_t  * list = NULL;
1726         hb_title_t * title = NULL;
1727     hb_audio_config_t * audio;
1728         gint ii;
1729         gint count = 0;
1730         
1731         g_debug("audio_track_opts_set ()\n");
1732         store = get_combo_box_store(builder, name);
1733         gtk_list_store_clear(store);
1734         if (h_scan != NULL)
1735         {
1736                 list = hb_get_titles( h_scan );
1737             title = (hb_title_t*)hb_list_item( list, titleindex );
1738                 if (title != NULL)
1739                 {
1740                         count = hb_list_count( title->list_audio );
1741                 }
1742         }
1743         if (count > 100) count = 100;
1744         if (audio_track_opts.map) g_free(audio_track_opts.map);
1745         if (count > 0)
1746         {
1747                 audio_track_opts.count = count;
1748                 audio_track_opts.map = g_malloc(count*sizeof(options_map_t));
1749         }
1750         else
1751         {
1752                 audio_track_opts.count = 1;
1753                 audio_track_opts.map = g_malloc(sizeof(options_map_t));
1754         }
1755         if( count <= 0 )
1756         {
1757                 // No audio. set some default
1758                 gtk_list_store_append(store, &iter);
1759                 gtk_list_store_set(store, &iter, 
1760                                                    0, "No Audio", 
1761                                                    1, TRUE, 
1762                                                    2, "none", 
1763                                                    3, -1.0, 
1764                                                    4, "none", 
1765                                                    -1);
1766                 audio_track_opts.map[0].option = "No Audio";
1767                 audio_track_opts.map[0].shortOpt = "none";
1768                 audio_track_opts.map[0].ivalue = -1;
1769                 audio_track_opts.map[0].svalue = "none";
1770                 return;
1771         }
1772         index_str_init(count-1);
1773         for (ii = 0; ii < count; ii++)
1774         {
1775         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, ii );
1776                 gtk_list_store_append(store, &iter);
1777                 gtk_list_store_set(store, &iter, 
1778                                                    0, audio->lang.description, 
1779                                                    1, TRUE, 
1780                                                    2, index_str[ii], 
1781                                                    3, (gdouble)ii, 
1782                                                    4, index_str[ii], 
1783                                                    -1);
1784                 audio_track_opts.map[ii].option = audio->lang.description,
1785                 audio_track_opts.map[ii].shortOpt = index_str[ii];
1786                 audio_track_opts.map[ii].ivalue = ii;
1787                 audio_track_opts.map[ii].svalue = index_str[ii];
1788         }
1789 }
1790
1791 void
1792 subtitle_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1793 {
1794         GtkTreeIter iter;
1795         GtkListStore *store;
1796         hb_list_t  * list = NULL;
1797         hb_title_t * title = NULL;
1798         hb_subtitle_t * subtitle;
1799         gint ii, count = 0;
1800         static char ** options = NULL;
1801         
1802         g_debug("subtitle_track_opts_set ()\n");
1803         store = get_combo_box_store(builder, name);
1804         gtk_list_store_clear(store);
1805         if (h_scan != NULL)
1806         {
1807                 list = hb_get_titles( h_scan );
1808             title = (hb_title_t*)hb_list_item( list, titleindex );
1809                 if (title != NULL)
1810                 {
1811                         count = hb_list_count( title->list_subtitle );
1812                 }
1813         }
1814         if (count > 100) count = 100;
1815         if (subtitle_opts.map) g_free(subtitle_opts.map);
1816         if (count > 0)
1817         {
1818                 subtitle_opts.count = count+1;
1819                 subtitle_opts.map = g_malloc((count+1)*sizeof(options_map_t));
1820         }
1821         else
1822         {
1823                 subtitle_opts.count = LANG_TABLE_SIZE+1;
1824                 subtitle_opts.map = g_malloc((LANG_TABLE_SIZE+1)*sizeof(options_map_t));
1825         }
1826         gtk_list_store_append(store, &iter);
1827         gtk_list_store_set(store, &iter, 
1828                                            0, "Foreign Audio Search", 
1829                                            1, TRUE, 
1830                                            2, "-1", 
1831                                            3, -1.0, 
1832                                            4, "auto", 
1833                                            -1);
1834         subtitle_opts.map[0].option = "Foreign Audio Search";
1835         subtitle_opts.map[0].shortOpt = "-1";
1836         subtitle_opts.map[0].ivalue = -1;
1837         subtitle_opts.map[0].svalue = "auto";
1838         if (count > 0)
1839         {
1840                 if (options != NULL)
1841                         g_strfreev(options);
1842                 options = g_malloc((count+1)*sizeof(gchar*));
1843                 index_str_init(count-1);
1844                 for (ii = 0; ii < count; ii++)
1845                 {
1846                 subtitle = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
1847                         // Skip subtitles that must be burned if there is already
1848                         // a burned subtitle in the list
1849                         options[ii] = g_strdup_printf("%d - %s", ii+1, subtitle->lang);
1850                         subtitle_opts.map[ii+1].option = options[ii];
1851                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
1852                         subtitle_opts.map[ii+1].ivalue = ii;
1853                         subtitle_opts.map[ii+1].svalue = subtitle->iso639_2;
1854                         gtk_list_store_append(store, &iter);
1855                         gtk_list_store_set(store, &iter, 
1856                                                 0, options[ii], 
1857                                                 1, TRUE, 
1858                                                 2, index_str[ii], 
1859                                                 3, (gdouble)ii, 
1860                                                 4, subtitle->iso639_2, 
1861                                                 -1);
1862                 }
1863                 options[count] = NULL;
1864         }
1865         else
1866         {
1867                 index_str_init(LANG_TABLE_SIZE-1);
1868                 for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1869                 {
1870                         subtitle_opts.map[ii+1].option = ghb_language_table[ii].eng_name;
1871                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
1872                         subtitle_opts.map[ii+1].ivalue = ii;
1873                         subtitle_opts.map[ii+1].svalue = ghb_language_table[ii].iso639_2;
1874                         gtk_list_store_append(store, &iter);
1875                         gtk_list_store_set(store, &iter, 
1876                                         0, ghb_language_table[ii].eng_name, 
1877                                         1, TRUE, 
1878                                         2, index_str[ii],
1879                                         3, (gdouble)ii, 
1880                                         4, ghb_language_table[ii].iso639_2, 
1881                                         -1);
1882                 }
1883         }
1884 }
1885
1886 gint
1887 ghb_longest_title()
1888 {
1889         hb_list_t  * list;
1890         hb_title_t * title;
1891         gint ii;
1892         gint count = 0;
1893         guint64 longest = 0;
1894         gint titleindex = 0;
1895         
1896         g_debug("ghb_longest_title ()\n");
1897         if (h_scan == NULL) return 0;
1898         list = hb_get_titles( h_scan );
1899         count = hb_list_count( list );
1900         if (count > 100) count = 100;
1901         for (ii = 0; ii < count; ii++)
1902         {
1903                 title = (hb_title_t*)hb_list_item(list, ii);
1904                 if (title->duration > longest)
1905                 {
1906                         titleindex = ii;
1907                         longest = title->duration;
1908                 }
1909         }
1910         return titleindex;
1911 }
1912
1913 gchar*
1914 ghb_get_source_audio_lang(gint titleindex, gint track)
1915 {
1916         hb_list_t  * list;
1917         hb_title_t * title;
1918     hb_audio_config_t * audio;
1919         gchar *lang = NULL;
1920         
1921         g_debug("ghb_lookup_1st_audio_lang ()\n");
1922         if (h_scan == NULL) 
1923                 return NULL;
1924         list = hb_get_titles( h_scan );
1925     title = (hb_title_t*)hb_list_item( list, titleindex );
1926         if (title == NULL)
1927                 return NULL;
1928         if (hb_list_count( title->list_audio ) <= track)
1929                 return NULL;
1930
1931         audio = hb_list_audio_config_item(title->list_audio, track);
1932         if (audio == NULL)
1933                 return NULL;
1934
1935         lang = g_strdup(audio->lang.iso639_2);
1936         return lang;
1937 }
1938
1939 gint
1940 ghb_find_audio_track(
1941         gint titleindex, 
1942         const gchar *lang, 
1943         gint acodec,
1944         GHashTable *track_indices)
1945 {
1946         hb_list_t  * list;
1947         hb_title_t * title;
1948     hb_audio_config_t * audio;
1949         gint ii;
1950         gint count = 0;
1951         gint track = -1;
1952         gint max_chan = 0;
1953         gboolean *used;
1954         
1955         g_debug("find_audio_track ()\n");
1956         if (h_scan == NULL) return -1;
1957         list = hb_get_titles( h_scan );
1958     title = (hb_title_t*)hb_list_item( list, titleindex );
1959         if (title != NULL)
1960         {
1961                 count = hb_list_count( title->list_audio );
1962         }
1963         if (count > 10) count = 10;
1964         used = g_hash_table_lookup(track_indices, &acodec);
1965         if (used == NULL)
1966         {
1967                 used = g_malloc0(count * sizeof(gboolean));
1968                 g_hash_table_insert(track_indices, &acodec, used);
1969         }
1970         // Try to find an item that matches the preferred language and
1971         // the passthru codec type
1972         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1973         {
1974                 for (ii = 0; ii < count; ii++)
1975                 {
1976                         gint channels;
1977
1978                         if (used[ii])
1979                                 continue;
1980
1981                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
1982                                                                                                         title->list_audio, ii );
1983                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
1984                                                                                                         audio->in.channel_layout);
1985                         // Find a track that is not visually impaired or dirctor's
1986                         // commentary, and has the highest channel count.
1987                         if ((audio->in.codec & acodec) &&
1988                                 (audio->lang.type < 2) &&
1989                                 ((strcmp(lang, audio->lang.iso639_2) == 0) ||
1990                                 (strcmp(lang, "und") == 0)))
1991                         {
1992                                 if (channels > max_chan)
1993                                 {
1994                                         track = ii;
1995                                         max_chan = channels;
1996                                 }
1997                         }
1998                 }
1999         }
2000         if (track > -1)
2001         {
2002                 used[track] = TRUE;
2003                 return track;
2004         }
2005         // Try to find an item that matches the preferred language
2006         for (ii = 0; ii < count; ii++)
2007         {
2008                 if (used[ii])
2009                         continue;
2010         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2011                                                                                                         title->list_audio, ii );
2012                 // Find a track that is not visually impaired or dirctor's commentary
2013                 if ((audio->lang.type < 2) &&
2014                         ((strcmp(lang, audio->lang.iso639_2) == 0) ||
2015                         (strcmp(lang, "und") == 0)))
2016                 {
2017                         track = ii;
2018                         break;
2019                 }
2020         }
2021         if (track > -1)
2022         {
2023                 used[track] = TRUE;
2024                 return track;
2025         }
2026         // Try to fine an item that does not match the preferred language and
2027         // matches the passthru codec type
2028         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
2029         {
2030                 for (ii = 0; ii < count; ii++)
2031                 {
2032                         gint channels;
2033
2034                         if (used[ii])
2035                                 continue;
2036
2037                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2038                                                                                                         title->list_audio, ii );
2039                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2040                                                                                                         audio->in.channel_layout);
2041                         // Find a track that is not visually impaired or dirctor's
2042                         // commentary, and has the highest channel count.
2043                         if ((audio->in.codec & acodec) &&
2044                                 (audio->lang.type < 2))
2045                         {
2046                                 if (channels > max_chan)
2047                                 {
2048                                         track = ii;
2049                                         max_chan = channels;
2050                                 }
2051                         }
2052                 }
2053         }
2054         if (track > -1)
2055         {
2056                 used[track] = TRUE;
2057                 return track;
2058         }
2059         // Try to fine an item that does not match the preferred language
2060         for (ii = 0; ii < count; ii++)
2061         {
2062                 if (used[ii])
2063                         continue;
2064         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2065                                                                                                         title->list_audio, ii );
2066                 // Find a track that is not visually impaired or dirctor's commentary
2067                 if (audio->lang.type < 2)
2068                 {
2069                         track = ii;
2070                         break;
2071                 }
2072         }
2073         if (track > -1)
2074         {
2075                 used[track] = TRUE;
2076                 return track;
2077         }
2078         // Last ditch, anything goes
2079         for (ii = 0; ii < count; ii++)
2080         {
2081         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2082                                                                                                         title->list_audio, ii );
2083                 if (!used[ii])
2084                 {
2085                         track = ii;
2086                         break;
2087                 }
2088         }
2089         if (track > -1)
2090         {
2091                 used[track] = TRUE;
2092         }
2093         return track;
2094 }
2095
2096 gint
2097 ghb_find_pref_subtitle_track(const gchar *lang)
2098 {
2099         gint ii, count;
2100         count = subtitle_opts.count;
2101         for (ii = 0; ii < count; ii++)
2102         {
2103                 if (strcmp(lang, subtitle_opts.map[ii].svalue) == 0)
2104                 {
2105                         return subtitle_opts.map[ii].ivalue;
2106                 }
2107         }
2108         return -2;
2109 }
2110
2111 gint
2112 ghb_find_subtitle_track(
2113         gint titleindex, 
2114         const gchar *lang, 
2115         GHashTable *track_indices)
2116 {
2117         hb_list_t  * list;
2118         hb_title_t * title;
2119         hb_subtitle_t * subtitle;
2120         gint count, ii;
2121         gboolean *used;
2122         
2123         g_debug("find_subtitle_track ()\n");
2124         if (strcmp(lang, "auto") == 0)
2125                 return -1;
2126         if (h_scan == NULL) return -1;
2127         list = hb_get_titles( h_scan );
2128         title = (hb_title_t*)hb_list_item( list, titleindex );
2129         if (title != NULL)
2130         {
2131                 count = hb_list_count( title->list_subtitle );
2132                 used = g_hash_table_lookup(track_indices, lang);
2133                 if (used == NULL)
2134                 {
2135                         used = g_malloc0(count * sizeof(gboolean));
2136                         g_hash_table_insert(track_indices, g_strdup(lang), used);
2137                 }
2138                 // Try to find an item that matches the preferred language
2139                 for (ii = 0; ii < count; ii++)
2140                 {
2141                         if (used[ii])
2142                                 continue;
2143
2144                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2145                         if ((strcmp(lang, subtitle->iso639_2) == 0) ||
2146                                 (strcmp(lang, "und") == 0))
2147                         {
2148                                 used[ii] = TRUE;
2149                                 return ii;
2150                         }
2151                 }
2152         }
2153         return -2;
2154 }
2155
2156 static void
2157 generic_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
2158 {
2159         GtkTreeIter iter;
2160         GtkListStore *store;
2161         gint ii;
2162         
2163         g_debug("generic_opts_set ()\n");
2164         if (name == NULL || opts == NULL) return;
2165         store = get_combo_box_store(builder, name);
2166         gtk_list_store_clear(store);
2167         for (ii = 0; ii < opts->count; ii++)
2168         {
2169                 gtk_list_store_append(store, &iter);
2170                 gtk_list_store_set(store, &iter, 
2171                                                    0, opts->map[ii].option, 
2172                                                    1, TRUE, 
2173                                                    2, opts->map[ii].shortOpt, 
2174                                                    3, opts->map[ii].ivalue, 
2175                                                    4, opts->map[ii].svalue, 
2176                                                    -1);
2177         }
2178 }
2179
2180 combo_opts_t*
2181 find_combo_table(const gchar *name)
2182 {
2183         gint ii;
2184
2185         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2186         {
2187                 if (strcmp(name, combo_name_map[ii].name) == 0)
2188                 {
2189                         return combo_name_map[ii].opts;
2190                 }
2191         }
2192         return NULL;
2193 }
2194
2195 gint
2196 ghb_lookup_combo_int(const gchar *name, const GValue *gval)
2197 {
2198         if (gval == NULL)
2199                 return 0;
2200         if (strcmp(name, "AudioBitrate") == 0)
2201                 return lookup_audio_bitrate_int(gval);
2202         else if (strcmp(name, "AudioSamplerate") == 0)
2203                 return lookup_audio_rate_int(gval);
2204         else if (strcmp(name, "VideoFramerate") == 0)
2205                 return lookup_video_rate_int(gval);
2206         else if (strcmp(name, "AudioMixdown") == 0)
2207                 return lookup_mix_int(gval);
2208         else if (strcmp(name, "SrtLanguage") == 0)
2209                 return lookup_audio_lang_int(gval);
2210         else if (strcmp(name, "PreferredLanguage") == 0)
2211                 return lookup_audio_lang_int(gval);
2212         else
2213         {
2214                 return lookup_generic_int(find_combo_table(name), gval);
2215         }
2216         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2217         return 0;
2218 }
2219
2220 gdouble
2221 ghb_lookup_combo_double(const gchar *name, const GValue *gval)
2222 {
2223         if (gval == NULL)
2224                 return 0;
2225         if (strcmp(name, "AudioBitrate") == 0)
2226                 return lookup_audio_bitrate_int(gval);
2227         else if (strcmp(name, "AudioSamplerate") == 0)
2228                 return lookup_audio_rate_int(gval);
2229         else if (strcmp(name, "VideoFramerate") == 0)
2230                 return lookup_video_rate_int(gval);
2231         else if (strcmp(name, "AudioMixdown") == 0)
2232                 return lookup_mix_int(gval);
2233         else if (strcmp(name, "SrtLanguage") == 0)
2234                 return lookup_audio_lang_int(gval);
2235         else if (strcmp(name, "PreferredLanguage") == 0)
2236                 return lookup_audio_lang_int(gval);
2237         else
2238         {
2239                 return lookup_generic_double(find_combo_table(name), gval);
2240         }
2241         g_warning("ghb_lookup_combo_double() couldn't find %s", name);
2242         return 0;
2243 }
2244
2245 const gchar*
2246 ghb_lookup_combo_option(const gchar *name, const GValue *gval)
2247 {
2248         if (gval == NULL)
2249                 return NULL;
2250         if (strcmp(name, "AudioBitrate") == 0)
2251                 return lookup_audio_bitrate_option(gval);
2252         else if (strcmp(name, "AudioSamplerate") == 0)
2253                 return lookup_audio_rate_option(gval);
2254         else if (strcmp(name, "VideoFramerate") == 0)
2255                 return lookup_video_rate_option(gval);
2256         else if (strcmp(name, "AudioMixdown") == 0)
2257                 return lookup_mix_option(gval);
2258         else if (strcmp(name, "SrtLanguage") == 0)
2259                 return lookup_audio_lang_option(gval);
2260         else if (strcmp(name, "PreferredLanguage") == 0)
2261                 return lookup_audio_lang_option(gval);
2262         else
2263         {
2264                 return lookup_generic_option(find_combo_table(name), gval);
2265         }
2266         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2267         return NULL;
2268 }
2269
2270 const gchar*
2271 ghb_lookup_combo_string(const gchar *name, const GValue *gval)
2272 {
2273         if (gval == NULL)
2274                 return NULL;
2275         if (strcmp(name, "AudioBitrate") == 0)
2276                 return lookup_audio_bitrate_option(gval);
2277         else if (strcmp(name, "AudioSamplerate") == 0)
2278                 return lookup_audio_rate_option(gval);
2279         else if (strcmp(name, "VideoFramerate") == 0)
2280                 return lookup_video_rate_option(gval);
2281         else if (strcmp(name, "AudioMixdown") == 0)
2282                 return lookup_mix_option(gval);
2283         else if (strcmp(name, "SrtLanguage") == 0)
2284                 return lookup_audio_lang_option(gval);
2285         else if (strcmp(name, "PreferredLanguage") == 0)
2286                 return lookup_audio_lang_option(gval);
2287         else
2288         {
2289                 return lookup_generic_string(find_combo_table(name), gval);
2290         }
2291         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2292         return NULL;
2293 }
2294
2295 void
2296 ghb_update_ui_combo_box(
2297         signal_user_data_t *ud, 
2298         const gchar *name, 
2299         gint user_data, 
2300         gboolean all)
2301 {
2302         GtkComboBox *combo = NULL;
2303         gint signal_id;
2304         gint handler_id = 0;
2305
2306         if (name != NULL)
2307         {               
2308                 g_debug("ghb_update_ui_combo_box() %s\n", name);
2309                 // Clearing a combo box causes a rash of "changed" events, even when
2310                 // the active item is -1 (inactive).  To control things, I'm disabling
2311                 // the event till things are settled down.
2312                 combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, name));
2313                 signal_id = g_signal_lookup("changed", GTK_TYPE_COMBO_BOX);
2314                 if (signal_id > 0)
2315                 {
2316                         // Valid signal id found.  This should always succeed.
2317                         handler_id = g_signal_handler_find ((gpointer)combo, G_SIGNAL_MATCH_ID, 
2318                                                                                                 signal_id, 0, 0, 0, 0);
2319                         if (handler_id > 0)
2320                         {
2321                                 // This should also always succeed
2322                                 g_signal_handler_block ((gpointer)combo, handler_id);
2323                         }
2324                 }
2325         }       
2326         if (all)
2327         {
2328                 audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2329                 audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2330                 video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2331                 mix_opts_set(ud->builder, "AudioMixdown");
2332                 language_opts_set(ud->builder, "SrtLanguage");
2333                 language_opts_set(ud->builder, "PreferredLanguage");
2334                 srt_codeset_opts_set(ud->builder, "SrtCodeset");
2335                 title_opts_set(ud->builder, "title");
2336                 audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2337                 subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2338                 generic_opts_set(ud->builder, "VideoQualityGranularity", &vqual_granularity_opts);
2339                 generic_opts_set(ud->builder, "WhenComplete", &when_complete_opts);
2340                 generic_opts_set(ud->builder, "PicturePAR", &par_opts);
2341                 generic_opts_set(ud->builder, "PictureModulus", &alignment_opts);
2342                 generic_opts_set(ud->builder, "LoggingLevel", &logging_opts);
2343                 generic_opts_set(ud->builder, "LogLongevity", &log_longevity_opts);
2344                 generic_opts_set(ud->builder, "check_updates", &appcast_update_opts);
2345                 generic_opts_set(ud->builder, "FileFormat", &container_opts);
2346                 generic_opts_set(ud->builder, "PictureDeinterlace", &deint_opts);
2347                 generic_opts_set(ud->builder, "PictureDetelecine", &detel_opts);
2348                 generic_opts_set(ud->builder, "PictureDecomb", &decomb_opts);
2349                 generic_opts_set(ud->builder, "PictureDenoise", &denoise_opts);
2350                 generic_opts_set(ud->builder, "VideoEncoder", &vcodec_opts);
2351                 generic_opts_set(ud->builder, "AudioEncoder", &acodec_opts);
2352                 generic_opts_set(ud->builder, "x264_direct", &direct_opts);
2353                 generic_opts_set(ud->builder, "x264_b_adapt", &badapt_opts);
2354                 generic_opts_set(ud->builder, "x264_me", &me_opts);
2355                 generic_opts_set(ud->builder, "x264_subme", &subme_opts);
2356                 generic_opts_set(ud->builder, "x264_analyse", &analyse_opts);
2357                 generic_opts_set(ud->builder, "x264_trellis", &trellis_opts);
2358         }
2359         else
2360         {
2361                 if (strcmp(name, "AudioBitrate") == 0)
2362                         audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2363                 else if (strcmp(name, "AudioSamplerate") == 0)
2364                         audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2365                 else if (strcmp(name, "VideoFramerate") == 0)
2366                         video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2367                 else if (strcmp(name, "AudioMixdown") == 0)
2368                         mix_opts_set(ud->builder, "AudioMixdown");
2369                 else if (strcmp(name, "SrtLanguage") == 0)
2370                         language_opts_set(ud->builder, "SrtLanguage");
2371                 else if (strcmp(name, "PreferredLanguage") == 0)
2372                         language_opts_set(ud->builder, "PreferredLanguage");
2373                 else if (strcmp(name, "SrtCodeset") == 0)
2374                         srt_codeset_opts_set(ud->builder, "SrtCodeset");
2375                 else if (strcmp(name, "title") == 0)
2376                         title_opts_set(ud->builder, "title");
2377                 else if (strcmp(name, "SubtitleTrack") == 0)
2378                         subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2379                 else if (strcmp(name, "AudioTrack") == 0)
2380                         audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2381                 else
2382                         generic_opts_set(ud->builder, name, find_combo_table(name));
2383         }
2384         if (handler_id > 0)
2385         {
2386                 g_signal_handler_unblock ((gpointer)combo, handler_id);
2387         }
2388 }
2389         
2390 static void
2391 init_ui_combo_boxes(GtkBuilder *builder)
2392 {
2393         gint ii;
2394
2395         init_combo_box(builder, "AudioBitrate");
2396         init_combo_box(builder, "AudioSamplerate");
2397         init_combo_box(builder, "VideoFramerate");
2398         init_combo_box(builder, "AudioMixdown");
2399         init_combo_box(builder, "SrtLanguage");
2400         init_combo_box(builder, "PreferredLanguage");
2401         init_combo_box(builder, "SrtCodeset");
2402         init_combo_box(builder, "title");
2403         init_combo_box(builder, "AudioTrack");
2404         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2405         {
2406                 init_combo_box(builder, combo_name_map[ii].name);
2407         }
2408 }
2409         
2410 static const char * turbo_opts = 
2411         "ref=1:subme=1:me=dia:analyse=none:trellis=0:"
2412         "no-fast-pskip=0:8x8dct=0";
2413
2414 // Construct the x264 options string
2415 // The result is allocated, so someone must free it at some point.
2416 gchar*
2417 ghb_build_x264opts_string(GValue *settings)
2418 {
2419         gchar *result;
2420         gchar *opts = ghb_settings_get_string(settings, "x264Option");
2421         if (opts != NULL)
2422         {
2423                 result = opts;
2424         }
2425         else
2426         {
2427                 result = g_strdup("");
2428         }
2429         return result;
2430 }
2431
2432 void
2433 ghb_get_chapter_duration(gint ti, gint ii, gint *hh, gint *mm, gint *ss)
2434 {
2435         hb_list_t  * list;
2436         hb_title_t * title;
2437     hb_chapter_t * chapter;
2438         gint count;
2439         
2440         g_debug("ghb_get_chapter_duration (title = %d)\n", ti);
2441         *hh = *mm = *ss = 0;
2442         if (h_scan == NULL) return;
2443         list = hb_get_titles( h_scan );
2444     title = (hb_title_t*)hb_list_item( list, ti );
2445         if (title == NULL) return;
2446         count = hb_list_count( title->list_chapter );
2447         if (ii >= count) return;
2448         chapter = hb_list_item(title->list_chapter, ii);
2449         if (chapter == NULL) return;
2450         *hh = chapter->hours;
2451         *mm = chapter->minutes;
2452         *ss = chapter->seconds;
2453 }
2454
2455 GValue*
2456 ghb_get_chapters(gint titleindex)
2457 {
2458         hb_list_t  * list;
2459         hb_title_t * title;
2460     hb_chapter_t * chapter;
2461         gint count, ii;
2462         GValue *chapters = NULL;
2463         
2464         g_debug("ghb_get_chapters (title = %d)\n", titleindex);
2465         if (h_scan == NULL) return NULL;
2466         list = hb_get_titles( h_scan );
2467     title = (hb_title_t*)hb_list_item( list, titleindex );
2468         if (title == NULL) return NULL;
2469         count = hb_list_count( title->list_chapter );
2470         chapters = ghb_array_value_new(count);
2471         for (ii = 0; ii < count; ii++)
2472         {
2473                 chapter = hb_list_item(title->list_chapter, ii);
2474                 if (chapter == NULL) break;
2475                 if (chapter->title == NULL || chapter->title[0] == 0)
2476                 {
2477                         gchar *str;
2478                         str = g_strdup_printf ("Chapter %2d", ii+1);
2479                         ghb_array_append(chapters, ghb_string_value_new(str));
2480                         g_free(str);
2481                 }
2482                 else 
2483                 {
2484                         ghb_array_append(chapters, ghb_string_value_new(chapter->title));
2485                 }
2486         }
2487         return chapters;
2488 }
2489
2490 gboolean
2491 ghb_ac3_in_audio_list(const GValue *audio_list)
2492 {
2493         gint count, ii;
2494
2495         count = ghb_array_len(audio_list);
2496         for (ii = 0; ii < count; ii++)
2497         {
2498                 GValue *asettings;
2499                 gint acodec;
2500
2501                 asettings = ghb_array_get_nth(audio_list, ii);
2502                 acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
2503                 if (acodec & HB_ACODEC_AC3)
2504                         return TRUE;
2505         }
2506         return FALSE;
2507 }
2508
2509 static void
2510 audio_bitrate_opts_add(GtkBuilder *builder, const gchar *name, gint rate)
2511 {
2512         GtkTreeIter iter;
2513         GtkListStore *store;
2514         gchar *str;
2515         
2516         g_debug("audio_rate_opts_add ()\n");
2517         store = get_combo_box_store(builder, name);
2518         if (!find_combo_item_by_int(GTK_TREE_MODEL(store), rate, &iter))
2519         {
2520                 str = g_strdup_printf ("%d", rate);
2521                 gtk_list_store_append(store, &iter);
2522                 gtk_list_store_set(store, &iter, 
2523                                                    0, str, 
2524                                                    1, TRUE, 
2525                                                    2, str, 
2526                                                    3, (gdouble)rate, 
2527                                                    4, str, 
2528                                                    -1);
2529                 g_free(str);
2530         }
2531 }
2532
2533 static void
2534 audio_bitrate_opts_clean(GtkBuilder *builder, const gchar *name, gint last_rate)
2535 {
2536         GtkTreeIter iter;
2537         GtkListStore *store;
2538         gdouble ivalue;
2539         gboolean done = FALSE;
2540         gint ii = 0;
2541         guint last = (guint)last_rate;
2542         
2543         g_debug("audio_bitrate_opts_clean ()\n");
2544         store = get_combo_box_store(builder, name);
2545         if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL(store), &iter))
2546         {
2547                 do
2548                 {
2549                         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 3, &ivalue, -1);
2550                         if (search_rates(
2551                                 hb_audio_bitrates, ivalue, hb_audio_bitrates_count) < 0)
2552                         {
2553                                 done = !gtk_list_store_remove(store, &iter);
2554                         }
2555                         else if (ivalue > last)
2556                         {
2557                                 ii++;
2558                                 gtk_list_store_set(store, &iter, 1, FALSE, -1);
2559                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2560                         }
2561                         else
2562                         {
2563                                 ii++;
2564                                 gtk_list_store_set(store, &iter, 1, TRUE, -1);
2565                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2566                         }
2567                 } while (!done);
2568         }
2569 }
2570
2571 static void
2572 audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name)
2573 {
2574         GtkTreeIter iter;
2575         GtkListStore *store;
2576         gint ii;
2577         
2578         g_debug("audio_bitrate_opts_set ()\n");
2579         store = get_combo_box_store(builder, name);
2580         gtk_list_store_clear(store);
2581         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
2582         {
2583                 gtk_list_store_append(store, &iter);
2584                 gtk_list_store_set(store, &iter, 
2585                                                    0, hb_audio_bitrates[ii].string, 
2586                                                    1, TRUE, 
2587                                                    2, hb_audio_bitrates[ii].string, 
2588                                                    3, (gdouble)hb_audio_bitrates[ii].rate, 
2589                                                    4, hb_audio_bitrates[ii].string, 
2590                                                    -1);
2591         }
2592 }
2593
2594 void
2595 ghb_set_passthru_bitrate_opts(GtkBuilder *builder, gint bitrate)
2596 {
2597         audio_bitrate_opts_add(builder, "AudioBitrate", bitrate);
2598 }
2599
2600 void
2601 ghb_set_default_bitrate_opts(GtkBuilder *builder, gint last_rate)
2602 {
2603         audio_bitrate_opts_clean(builder, "AudioBitrate", last_rate);
2604 }
2605
2606 static ghb_status_t hb_status;
2607
2608 void
2609 ghb_combo_init(signal_user_data_t *ud)
2610 {
2611         // Set up the list model for the combos
2612         init_ui_combo_boxes(ud->builder);
2613         // Populate all the combos
2614         ghb_update_ui_combo_box(ud, NULL, 0, TRUE);
2615 }
2616
2617 void
2618 ghb_backend_init(gint debug)
2619 {
2620     /* Init libhb */
2621     h_scan = hb_init( debug, 0 );
2622     h_queue = hb_init( debug, 0 );
2623 }
2624
2625 void
2626 ghb_backend_close()
2627 {
2628         hb_close(&h_queue);
2629         hb_close(&h_scan);
2630 }
2631
2632 void
2633 ghb_backend_scan(const gchar *path, gint titleindex, gint preview_count)
2634 {
2635     hb_scan( h_scan, path, titleindex, preview_count, 1 );
2636         hb_status.scan.state |= GHB_STATE_SCANNING;
2637         // initialize count and cur to something that won't cause FPE
2638         // when computing progress
2639         hb_status.scan.title_count = 1;
2640         hb_status.scan.title_cur = 0;
2641 }
2642
2643 void
2644 ghb_backend_queue_scan(const gchar *path, gint titlenum)
2645 {
2646         g_debug("ghb_backend_queue_scan()");
2647         hb_scan( h_queue, path, titlenum, 10, 0 );
2648         hb_status.queue.state |= GHB_STATE_SCANNING;
2649 }
2650
2651 gint
2652 ghb_get_scan_state()
2653 {
2654         return hb_status.scan.state;
2655 }
2656
2657 gint
2658 ghb_get_queue_state()
2659 {
2660         return hb_status.queue.state;
2661 }
2662
2663 void
2664 ghb_clear_scan_state(gint state)
2665 {
2666         hb_status.scan.state &= ~state;
2667 }
2668
2669 void
2670 ghb_clear_queue_state(gint state)
2671 {
2672         hb_status.queue.state &= ~state;
2673 }
2674
2675 void
2676 ghb_set_scan_state(gint state)
2677 {
2678         hb_status.scan.state |= state;
2679 }
2680
2681 void
2682 ghb_set_queue_state(gint state)
2683 {
2684         hb_status.queue.state |= state;
2685 }
2686
2687 void
2688 ghb_get_status(ghb_status_t *status)
2689 {
2690         memcpy(status, &hb_status, sizeof(ghb_status_t));
2691 }
2692
2693 void 
2694 ghb_track_status()
2695 {
2696     hb_state_t s_scan;
2697     hb_state_t s_queue;
2698
2699         if (h_scan == NULL) return;
2700     hb_get_state( h_scan, &s_scan );
2701         switch( s_scan.state )
2702     {
2703 #define p s_scan.param.scanning
2704         case HB_STATE_SCANNING:
2705                 {
2706                         hb_status.scan.state |= GHB_STATE_SCANNING;
2707                         hb_status.scan.title_count = p.title_count;
2708                         hb_status.scan.title_cur = p.title_cur;
2709                 } break;
2710 #undef p
2711
2712         case HB_STATE_SCANDONE:
2713         {
2714                         hb_status.scan.state &= ~GHB_STATE_SCANNING;
2715                         hb_status.scan.state |= GHB_STATE_SCANDONE;
2716         } break;
2717
2718 #define p s_scan.param.working
2719         case HB_STATE_WORKING:
2720                         hb_status.scan.state |= GHB_STATE_WORKING;
2721                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
2722                         hb_status.scan.job_cur = p.job_cur;
2723                         hb_status.scan.job_count = p.job_count;
2724                         hb_status.scan.progress = p.progress;
2725                         hb_status.scan.rate_cur = p.rate_cur;
2726                         hb_status.scan.rate_avg = p.rate_avg;
2727                         hb_status.scan.hours = p.hours;
2728                         hb_status.scan.minutes = p.minutes;
2729                         hb_status.scan.seconds = p.seconds;
2730                         hb_status.scan.unique_id = p.sequence_id & 0xFFFFFF;
2731             break;
2732 #undef p
2733
2734         case HB_STATE_PAUSED:
2735                         hb_status.scan.state |= GHB_STATE_PAUSED;
2736             break;
2737                                 
2738         case HB_STATE_MUXING:
2739         {
2740                         hb_status.scan.state |= GHB_STATE_MUXING;
2741         } break;
2742
2743 #define p s_scan.param.workdone
2744         case HB_STATE_WORKDONE:
2745                 {
2746             hb_job_t *job;
2747
2748                         hb_status.scan.state |= GHB_STATE_WORKDONE;
2749                         hb_status.scan.state &= ~GHB_STATE_MUXING;
2750                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
2751                         hb_status.scan.state &= ~GHB_STATE_WORKING;
2752                         switch (p.error)
2753                         {
2754                         case HB_ERROR_NONE:
2755                                 hb_status.scan.error = GHB_ERROR_NONE;
2756                                 break;
2757                         case HB_ERROR_CANCELED:
2758                                 hb_status.scan.error = GHB_ERROR_CANCELED;
2759                                 break;
2760                         default:
2761                                 hb_status.scan.error = GHB_ERROR_FAIL;
2762                                 break;
2763                         }
2764                         // Delete all remaining jobs of this encode.
2765                         // An encode can be composed of multiple associated jobs.
2766                         // When a job is stopped, libhb removes it from the job list,
2767                         // but does not remove other jobs that may be associated with it.
2768                         // Associated jobs are taged in the sequence id.
2769             while ((job = hb_job(h_scan, 0)) != NULL) 
2770                 hb_rem( h_scan, job );
2771                 } break;
2772 #undef p
2773     }
2774     hb_get_state( h_queue, &s_queue );
2775         switch( s_queue.state )
2776     {
2777 #define p s_queue.param.scanning
2778         case HB_STATE_SCANNING:
2779                 {
2780                         hb_status.queue.state |= GHB_STATE_SCANNING;
2781                         hb_status.queue.title_count = p.title_count;
2782                         hb_status.queue.title_cur = p.title_cur;
2783                 } break;
2784 #undef p
2785
2786         case HB_STATE_SCANDONE:
2787         {
2788                         hb_status.queue.state &= ~GHB_STATE_SCANNING;
2789                         hb_status.queue.state |= GHB_STATE_SCANDONE;
2790         } break;
2791
2792 #define p s_queue.param.working
2793         case HB_STATE_WORKING:
2794                         hb_status.queue.state |= GHB_STATE_WORKING;
2795                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
2796                         hb_status.queue.job_cur = p.job_cur;
2797                         hb_status.queue.job_count = p.job_count;
2798                         hb_status.queue.progress = p.progress;
2799                         hb_status.queue.rate_cur = p.rate_cur;
2800                         hb_status.queue.rate_avg = p.rate_avg;
2801                         hb_status.queue.hours = p.hours;
2802                         hb_status.queue.minutes = p.minutes;
2803                         hb_status.queue.seconds = p.seconds;
2804                         hb_status.queue.unique_id = p.sequence_id & 0xFFFFFF;
2805             break;
2806 #undef p
2807
2808         case HB_STATE_PAUSED:
2809                         hb_status.queue.state |= GHB_STATE_PAUSED;
2810             break;
2811                                 
2812         case HB_STATE_MUXING:
2813         {
2814                         hb_status.queue.state |= GHB_STATE_MUXING;
2815         } break;
2816
2817 #define p s_queue.param.workdone
2818         case HB_STATE_WORKDONE:
2819                 {
2820             hb_job_t *job;
2821
2822                         hb_status.queue.state |= GHB_STATE_WORKDONE;
2823                         hb_status.queue.state &= ~GHB_STATE_MUXING;
2824                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
2825                         hb_status.queue.state &= ~GHB_STATE_WORKING;
2826                         switch (p.error)
2827                         {
2828                         case HB_ERROR_NONE:
2829                                 hb_status.queue.error = GHB_ERROR_NONE;
2830                                 break;
2831                         case HB_ERROR_CANCELED:
2832                                 hb_status.queue.error = GHB_ERROR_CANCELED;
2833                                 break;
2834                         default:
2835                                 hb_status.queue.error = GHB_ERROR_FAIL;
2836                                 break;
2837                         }
2838                         // Delete all remaining jobs of this encode.
2839                         // An encode can be composed of multiple associated jobs.
2840                         // When a job is stopped, libhb removes it from the job list,
2841                         // but does not remove other jobs that may be associated with it.
2842                         // Associated jobs are taged in the sequence id.
2843             while ((job = hb_job(h_queue, 0)) != NULL) 
2844                 hb_rem( h_queue, job );
2845                 } break;
2846 #undef p
2847     }
2848 }
2849
2850 gboolean
2851 ghb_get_title_info(ghb_title_info_t *tinfo, gint titleindex)
2852 {
2853         hb_list_t  * list;
2854         hb_title_t * title;
2855         
2856     if (h_scan == NULL) return FALSE;
2857         list = hb_get_titles( h_scan );
2858         if( !hb_list_count( list ) )
2859         {
2860                 /* No valid title, stop right there */
2861                 return FALSE;
2862         }
2863
2864     title = hb_list_item( list, titleindex );
2865         if (title == NULL) return FALSE;        // Bad titleindex
2866         tinfo->width = title->width;
2867         tinfo->height = title->height;
2868         memcpy(tinfo->crop, title->crop, 4 * sizeof(int));
2869         // Don't allow crop to 0
2870         if (title->crop[0] + title->crop[1] >= title->height)
2871                 title->crop[0] = title->crop[1] = 0;
2872         if (title->crop[2] + title->crop[3] >= title->width)
2873                 title->crop[2] = title->crop[3] = 0;
2874         tinfo->num_chapters = hb_list_count(title->list_chapter);
2875         tinfo->rate_base = title->rate_base;
2876         tinfo->rate = title->rate;
2877         hb_reduce(&(tinfo->aspect_n), &(tinfo->aspect_d), 
2878                                 title->width * title->pixel_aspect_width, 
2879                                 title->height * title->pixel_aspect_height);
2880         tinfo->hours = title->hours;
2881         tinfo->minutes = title->minutes;
2882         tinfo->seconds = title->seconds;
2883         tinfo->duration = title->duration;
2884
2885         tinfo->angle_count = title->angle_count;
2886         return TRUE;
2887 }
2888
2889 gboolean
2890 ghb_get_audio_info(ghb_audio_info_t *ainfo, gint titleindex, gint audioindex)
2891 {
2892     hb_audio_config_t *audio;
2893         
2894         audio = get_hb_audio(titleindex, audioindex);
2895         if (audio == NULL) return FALSE; // Bad audioindex
2896         ainfo->codec = audio->in.codec;
2897         ainfo->bitrate = audio->in.bitrate;
2898         ainfo->samplerate = audio->in.samplerate;
2899         return TRUE;
2900 }
2901
2902 gboolean
2903 ghb_audio_is_passthru(gint acodec)
2904 {
2905         g_debug("ghb_audio_is_passthru () \n");
2906         return (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA));
2907 }
2908
2909 gint
2910 ghb_get_default_acodec()
2911 {
2912         return HB_ACODEC_FAAC;
2913 }
2914
2915 static void
2916 picture_settings_deps(signal_user_data_t *ud)
2917 {
2918         gboolean autoscale, keep_aspect, enable_keep_aspect;
2919         gboolean enable_scale_width, enable_scale_height;
2920         gboolean enable_disp_width, enable_disp_height, enable_par;
2921         gint pic_par;
2922         GtkWidget *widget;
2923
2924         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
2925         if (pic_par == 1)
2926         {
2927                 ghb_ui_update(ud, "autoscale", ghb_boolean_value(TRUE));
2928                 ghb_ui_update(ud, "PictureModulus", ghb_int_value(2));
2929                 ghb_ui_update(ud, "PictureLooseCrop", ghb_boolean_value(TRUE));
2930         }
2931         enable_keep_aspect = (pic_par != 1 && pic_par != 2);
2932         if (!enable_keep_aspect)
2933         {
2934                 ghb_ui_update(ud, "PictureKeepRatio", ghb_boolean_value(TRUE));
2935         }
2936         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
2937         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
2938
2939         enable_scale_width = !autoscale && (pic_par != 1);
2940         enable_scale_height = !autoscale && (pic_par != 1);
2941         enable_disp_width = (pic_par == 3) && !keep_aspect;
2942         enable_par = (pic_par == 3) && !keep_aspect;
2943         enable_disp_height = FALSE;
2944
2945         widget = GHB_WIDGET(ud->builder, "PictureModulus");
2946         gtk_widget_set_sensitive(widget, pic_par != 1);
2947         widget = GHB_WIDGET(ud->builder, "PictureLooseCrop");
2948         gtk_widget_set_sensitive(widget, pic_par != 1);
2949         widget = GHB_WIDGET(ud->builder, "scale_width");
2950         gtk_widget_set_sensitive(widget, enable_scale_width);
2951         widget = GHB_WIDGET(ud->builder, "scale_height");
2952         gtk_widget_set_sensitive(widget, enable_scale_height);
2953         widget = GHB_WIDGET(ud->builder, "PictureDisplayWidth");
2954         gtk_widget_set_sensitive(widget, enable_disp_width);
2955         widget = GHB_WIDGET(ud->builder, "PictureDisplayHeight");
2956         gtk_widget_set_sensitive(widget, enable_disp_height);
2957         widget = GHB_WIDGET(ud->builder, "PicturePARWidth");
2958         gtk_widget_set_sensitive(widget, enable_par);
2959         widget = GHB_WIDGET(ud->builder, "PicturePARHeight");
2960         gtk_widget_set_sensitive(widget, enable_par);
2961         widget = GHB_WIDGET(ud->builder, "PictureKeepRatio");
2962         gtk_widget_set_sensitive(widget, enable_keep_aspect);
2963         widget = GHB_WIDGET(ud->builder, "autoscale");
2964         gtk_widget_set_sensitive(widget, pic_par != 1);
2965 }
2966
2967 void
2968 ghb_set_scale(signal_user_data_t *ud, gint mode)
2969 {
2970         hb_list_t  * list;
2971         hb_title_t * title;
2972         hb_job_t   * job;
2973         gboolean keep_aspect;
2974         gint pic_par;
2975         gboolean autocrop, autoscale, noscale;
2976         gint crop[4], width, height, par_width, par_height;
2977         gint crop_width, crop_height;
2978         gint aspect_n, aspect_d;
2979         gboolean keep_width = (mode & GHB_PIC_KEEP_WIDTH);
2980         gboolean keep_height = (mode & GHB_PIC_KEEP_HEIGHT);
2981         gint step;
2982         GtkWidget *widget;
2983         gint mod;
2984         gint max_width = 0;
2985         gint max_height = 0;
2986         static gboolean busy = FALSE;
2987         
2988         g_debug("ghb_set_scale ()\n");
2989         if (h_scan == NULL) return;
2990         list = hb_get_titles( h_scan );
2991         if( !hb_list_count( list ) )
2992         {
2993                 /* No valid title, stop right there */
2994                 return;
2995         }
2996         gint titleindex;
2997
2998         titleindex = ghb_settings_combo_int(ud->settings, "title");
2999     title = hb_list_item( list, titleindex );
3000         if (title == NULL) return;
3001         job   = title->job;
3002         if (job == NULL) return;
3003
3004         picture_settings_deps(ud);
3005         if (busy) return;
3006         busy = TRUE;
3007
3008         
3009         // First configure widgets
3010         mod = ghb_settings_combo_int(ud->settings, "PictureModulus");
3011         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
3012         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
3013         autocrop = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop");
3014         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
3015         // "Noscale" is a flag that says we prefer to crop extra to satisfy
3016         // alignment constraints rather than scaling to satisfy them.
3017         noscale = ghb_settings_get_boolean(ud->settings, "PictureLooseCrop");
3018         // Align dimensions to either 16 or 2 pixels
3019         // The scaler crashes if the dimensions are not divisible by 2
3020         // x264 also will not accept dims that are not multiple of 2
3021         if (autoscale)
3022         {
3023                 keep_width = FALSE;
3024                 keep_height = FALSE;
3025         }
3026         // Step needs to be at least 2 because odd widths cause scaler crash
3027         step = mod;
3028         widget = GHB_WIDGET (ud->builder, "scale_width");
3029         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3030         widget = GHB_WIDGET (ud->builder, "scale_height");
3031         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3032         if (noscale)
3033         {
3034                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3035                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3036                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3037                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3038                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3039                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3040                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3041                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3042         }
3043         else
3044         {
3045                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3046                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3047                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3048                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3049                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3050                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3051                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3052                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3053         }
3054         ghb_title_info_t tinfo;
3055         ghb_get_title_info (&tinfo, titleindex);
3056         if (autocrop)
3057         {
3058                 crop[0] = tinfo.crop[0];
3059                 crop[1] = tinfo.crop[1];
3060                 crop[2] = tinfo.crop[2];
3061                 crop[3] = tinfo.crop[3];
3062                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3063                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3064                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3065                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3066         }
3067         else
3068         {
3069                 crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
3070                 crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
3071                 crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
3072                 crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
3073         }
3074         if (noscale)
3075         {
3076                 gint need1, need2;
3077
3078                 // Adjust the cropping to accomplish the desired width and height
3079                 crop_width = tinfo.width - crop[2] - crop[3];
3080                 crop_height = tinfo.height - crop[0] - crop[1];
3081                 width = MOD_DOWN(crop_width, mod);
3082                 height = MOD_DOWN(crop_height, mod);
3083
3084                 need1 = (crop_height - height) / 2;
3085                 need2 = crop_height - height - need1;
3086                 crop[0] += need1;
3087                 crop[1] += need2;
3088                 need1 = (crop_width - width) / 2;
3089                 need2 = crop_width - width - need1;
3090                 crop[2] += need1;
3091                 crop[3] += need2;
3092                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3093                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3094                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3095                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3096         }
3097         hb_reduce(&aspect_n, &aspect_d, 
3098                                 title->width * title->pixel_aspect_width, 
3099                                 title->height * title->pixel_aspect_height);
3100         crop_width = title->width - crop[2] - crop[3];
3101         crop_height = title->height - crop[0] - crop[1];
3102         if (autoscale)
3103         {
3104                 width = crop_width;
3105                 height = crop_height;
3106         }
3107         else
3108         {
3109                 width = ghb_settings_get_int(ud->settings, "scale_width");
3110                 height = ghb_settings_get_int(ud->settings, "scale_height");
3111                 max_width = MOD_DOWN(
3112                         ghb_settings_get_int(ud->settings, "PictureWidth"), mod);
3113                 max_height = MOD_DOWN(
3114                         ghb_settings_get_int(ud->settings, "PictureHeight"), mod);
3115         }
3116         g_debug("max_width %d, max_height %d\n", max_width, max_height);
3117
3118         if (width < 16)
3119                 width = title->width - crop[2] - crop[3];
3120         if (height < 16)
3121                 height = title->height - crop[0] - crop[1];
3122
3123         width = MOD_ROUND(width, mod);
3124         height = MOD_ROUND(height, mod);
3125
3126         // Adjust dims according to max values
3127         if (max_height)
3128                 height = MIN(height, max_height);
3129         if (max_width)
3130                 width = MIN(width, max_width);
3131
3132         if (pic_par)
3133         {
3134                 job->anamorphic.mode = pic_par;
3135                 // The scaler crashes if the dimensions are not divisible by 2
3136                 // Align mod 2.  And so does something in x264_encoder_headers()
3137                 job->anamorphic.modulus = mod;
3138                 job->anamorphic.par_width = title->pixel_aspect_width;
3139                 job->anamorphic.par_height = title->pixel_aspect_height;
3140                 job->anamorphic.dar_width = 0;
3141                 job->anamorphic.dar_height = 0;
3142
3143                 if (keep_height && pic_par == 2)
3144                         width = ((double)height * crop_width / crop_height) + 0.5;
3145                 job->width = width;
3146                 job->height = height;
3147                 if (max_width) 
3148                         job->maxWidth = max_width;
3149                 if (max_height) 
3150                         job->maxHeight = max_height;
3151                 job->crop[0] = crop[0]; job->crop[1] = crop[1];
3152                 job->crop[2] = crop[2]; job->crop[3] = crop[3];
3153                 if (job->anamorphic.mode == 3 && !keep_aspect)
3154                 {
3155                         job->anamorphic.keep_display_aspect = 0;
3156                         if (mode & GHB_PIC_KEEP_PAR)
3157                         {
3158                                 job->anamorphic.par_width = 
3159                                         ghb_settings_get_int(ud->settings, "PicturePARWidth");
3160                                 job->anamorphic.par_height = 
3161                                         ghb_settings_get_int(ud->settings, "PicturePARHeight");
3162                         }
3163                         else
3164                         {
3165                                 job->anamorphic.dar_width = 
3166                                         ghb_settings_get_int(ud->settings, 
3167                                                                                 "PictureDisplayWidth");
3168                                 job->anamorphic.dar_height =
3169                                         ghb_settings_get_int(ud->settings, 
3170                                                                                 "PictureDisplayHeight");
3171                         }
3172                 }
3173                 else
3174                 {
3175                         job->anamorphic.keep_display_aspect = 1;
3176                 }
3177                 hb_set_anamorphic_size( job, &width, &height, 
3178                                                                 &par_width, &par_height );
3179                 if (job->anamorphic.mode == 3 && !keep_aspect && 
3180                         mode & GHB_PIC_KEEP_PAR)
3181                 {
3182                         // hb_set_anamorphic_size reduces the par, which we
3183                         // don't want in this case because the user is
3184                         // explicitely specifying it.
3185                         par_width = ghb_settings_get_int(ud->settings, 
3186                                                                                         "PicturePARWidth");
3187                         par_height = ghb_settings_get_int(ud->settings, 
3188                                                                                                 "PicturePARHeight");
3189                 }
3190         }
3191         else 
3192         {
3193                 job->anamorphic.mode = pic_par;
3194                 if (keep_aspect)
3195                 {
3196                         gdouble par;
3197                         gint new_width, new_height;
3198                         
3199                         // Compute pixel aspect ration.  
3200                         par = (gdouble)(title->height * aspect_n) / (title->width * aspect_d);
3201                         // Must scale so that par becomes 1:1
3202                         // Try to keep largest dimension
3203                         new_height = (crop_height * ((gdouble)width/crop_width) / par);
3204                         new_width = (crop_width * ((gdouble)height/crop_height) * par);
3205
3206                         if (max_width && new_width > max_width)
3207                         {
3208                                 height = new_height;
3209                         }
3210                         else if (max_height && new_height > max_height)
3211                         {
3212                                 width = new_width;
3213                         }
3214                         else if (keep_width)
3215                         {
3216                                 height = new_height;
3217                         }
3218                         else if (keep_height)
3219                         {
3220                                 width = new_width;
3221                         }
3222                         else if (width > new_width)
3223                         {
3224                                 height = new_height;
3225                         }
3226                         else
3227                         {
3228                                 width = new_width;
3229                         }
3230                         g_debug("new w %d h %d\n", width, height);
3231                 }
3232                 width = MOD_ROUND(width, mod);
3233                 height = MOD_ROUND(height, mod);
3234                 if (max_height)
3235                         height = MIN(height, max_height);
3236                 if (max_width)
3237                         width = MIN(width, max_width);
3238                 par_width = par_height = 1;
3239         }
3240         ghb_ui_update(ud, "scale_width", ghb_int64_value(width));
3241         ghb_ui_update(ud, "scale_height", ghb_int64_value(height));
3242
3243         gint disp_width, dar_width, dar_height;
3244         gchar *str;
3245
3246         disp_width = (gdouble)(width * par_width / par_height) + 0.5;
3247         hb_reduce(&dar_width, &dar_height, disp_width, height);
3248                 
3249         gint iaspect = dar_width * 9 / dar_height;
3250         if (dar_width > 2 * dar_height)
3251         {
3252                 str = g_strdup_printf("%.2f : 1", (gdouble)dar_width / dar_height);
3253         }
3254         else if (iaspect <= 16 && iaspect >= 15)
3255         {
3256                 str = g_strdup_printf("%.2f : 9", (gdouble)dar_width * 9 / dar_height);
3257         }
3258         else if (iaspect <= 12 && iaspect >= 11)
3259         {
3260                 str = g_strdup_printf("%.2f : 3", (gdouble)dar_width * 3 / dar_height);
3261         }
3262         else
3263         {
3264                 str = g_strdup_printf("%d : %d", dar_width, dar_height);
3265         }
3266         ghb_ui_update(ud, "display_aspect", ghb_string_value(str));
3267         g_free(str);
3268         ghb_ui_update(ud, "PicturePARWidth", ghb_int64_value(par_width));
3269         ghb_ui_update(ud, "PicturePARHeight", ghb_int64_value(par_height));
3270         ghb_ui_update(ud, "PictureDisplayWidth", ghb_int64_value(disp_width));
3271         ghb_ui_update(ud, "PictureDisplayHeight", ghb_int64_value(height));
3272         busy = FALSE;
3273 }
3274
3275 static void
3276 set_preview_job_settings(hb_job_t *job, GValue *settings)
3277 {
3278         job->crop[0] = ghb_settings_get_int(settings, "PictureTopCrop");
3279         job->crop[1] = ghb_settings_get_int(settings, "PictureBottomCrop");
3280         job->crop[2] = ghb_settings_get_int(settings, "PictureLeftCrop");
3281         job->crop[3] = ghb_settings_get_int(settings, "PictureRightCrop");
3282
3283         job->anamorphic.mode = ghb_settings_combo_int(settings, "PicturePAR");
3284         job->anamorphic.modulus = 
3285                 ghb_settings_combo_int(settings, "PictureModulus");
3286         job->width = ghb_settings_get_int(settings, "scale_width");
3287         job->height = ghb_settings_get_int(settings, "scale_height");
3288         if (ghb_settings_get_boolean(settings, "show_crop"))
3289         {
3290                 gdouble xscale = (gdouble)job->width / 
3291                         (gdouble)(job->title->width - job->crop[2] - job->crop[3]);
3292                 gdouble yscale = (gdouble)job->height / 
3293                         (gdouble)(job->title->height - job->crop[0] - job->crop[1]);
3294         
3295                 job->width += xscale * (job->crop[2] + job->crop[3]);
3296                 job->height += yscale * (job->crop[0] + job->crop[1]);
3297                 job->crop[0] = 0;
3298                 job->crop[1] = 0;
3299                 job->crop[2] = 0;
3300                 job->crop[3] = 0;
3301                 job->anamorphic.modulus = 2;
3302         }
3303
3304         gint deint = ghb_settings_combo_int(settings, "PictureDeinterlace");
3305         gint decomb = ghb_settings_combo_int(settings, "PictureDecomb");
3306         job->deinterlace = (!decomb && deint == 0) ? 0 : 1;
3307
3308         gboolean keep_aspect;
3309         keep_aspect = ghb_settings_get_boolean(settings, "PictureKeepRatio");
3310         if (job->anamorphic.mode)
3311         {
3312                 job->anamorphic.par_width = job->title->pixel_aspect_width;
3313                 job->anamorphic.par_height = job->title->pixel_aspect_height;
3314                 job->anamorphic.dar_width = 0;
3315                 job->anamorphic.dar_height = 0;
3316
3317                 if (job->anamorphic.mode == 3 && !keep_aspect)
3318                 {
3319                         job->anamorphic.keep_display_aspect = 0;
3320                         job->anamorphic.par_width = 
3321                                 ghb_settings_get_int(settings, "PicturePARWidth");
3322                         job->anamorphic.par_height = 
3323                                 ghb_settings_get_int(settings, "PicturePARHeight");
3324                 }
3325                 else
3326                 {
3327                         job->anamorphic.keep_display_aspect = 1;
3328                 }
3329         }
3330 }
3331
3332 gint
3333 ghb_calculate_target_bitrate(GValue *settings, gint titleindex)
3334 {
3335         hb_list_t  * list;
3336         hb_title_t * title;
3337         hb_job_t   * job;
3338         gint size;
3339
3340         if (h_scan == NULL) return 1500;
3341         list = hb_get_titles( h_scan );
3342     title = hb_list_item( list, titleindex );
3343         if (title == NULL) return 1500;
3344         job   = title->job;
3345         if (job == NULL) return 1500;
3346         size = ghb_settings_get_int(settings, "VideoTargetSize");
3347         return hb_calc_bitrate( job, size );
3348 }
3349
3350 gboolean
3351 ghb_validate_filter_string(const gchar *str, gint max_fields)
3352 {
3353         gint fields = 0;
3354         gchar *end;
3355         gdouble val;
3356
3357         if (str == NULL || *str == 0) return TRUE;
3358         while (*str)
3359         {
3360                 val = g_strtod(str, &end);
3361                 if (str != end)
3362                 { // Found a numeric value
3363                         fields++;
3364                         // negative max_fields means infinate
3365                         if (max_fields >= 0 && fields > max_fields) return FALSE;
3366                         if (*end == 0)
3367                                 return TRUE;
3368                         if (*end != ':')
3369                                 return FALSE;
3370                         str = end + 1;
3371                 }
3372                 else
3373                         return FALSE;
3374         }
3375         return FALSE;
3376 }
3377
3378 gboolean
3379 ghb_validate_filters(signal_user_data_t *ud)
3380 {
3381         gchar *str;
3382         gint index;
3383         gchar *message;
3384
3385         // deinte 4
3386         index = ghb_settings_combo_int(ud->settings, "PictureDeinterlace");
3387         if (index == 1)
3388         {
3389                 str = ghb_settings_get_string(ud->settings, "PictureDeinterlaceCustom");
3390                 if (!ghb_validate_filter_string(str, 4))
3391                 {
3392                         message = g_strdup_printf(
3393                                                 "Invalid Deinterlace Settings:\n\n%s\n",
3394                                                 str);
3395                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3396                         g_free(message);
3397                         g_free(str);
3398                         return FALSE;
3399                 }
3400                 g_free(str);
3401         }
3402         // detel
3403         index = ghb_settings_combo_int(ud->settings, "PictureDetelecine");
3404         if (index == 1)
3405         {
3406                 str = ghb_settings_get_string(ud->settings, "PictureDetelecineCustom");
3407                 if (!ghb_validate_filter_string(str, 6))
3408                 {
3409                         message = g_strdup_printf(
3410                                                 "Invalid Detelecine Settings:\n\n%s\n",
3411                                                 str);
3412                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3413                         g_free(message);
3414                         g_free(str);
3415                         return FALSE;
3416                 }
3417                 g_free(str);
3418         }
3419         // decomb 4
3420         index = ghb_settings_combo_int(ud->settings, "PictureDecomb");
3421         if (index == 1)
3422         {
3423                 str = ghb_settings_get_string(ud->settings, "PictureDecombCustom");
3424                 if (!ghb_validate_filter_string(str, 7))
3425                 {
3426                         message = g_strdup_printf(
3427                                                 "Invalid Decomb Settings:\n\n%s\n",
3428                                                 str);
3429                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3430                         g_free(message);
3431                         g_free(str);
3432                         return FALSE;
3433                 }
3434                 g_free(str);
3435         }
3436         // denois 4
3437         index = ghb_settings_combo_int(ud->settings, "PictureDenoise");
3438         if (index == 1)
3439         {
3440                 str = ghb_settings_get_string(ud->settings, "PictureDenoiseCustom");
3441                 if (!ghb_validate_filter_string(str, 4))
3442                 {
3443                         message = g_strdup_printf(
3444                                                 "Invalid Denoise Settings:\n\n%s\n",
3445                                                 str);
3446                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3447                         g_free(str);
3448                         g_free(message);
3449                         return FALSE;
3450                 }
3451                 g_free(str);
3452         }
3453         return TRUE;
3454 }
3455
3456 gboolean
3457 ghb_validate_video(signal_user_data_t *ud)
3458 {
3459         gint vcodec, mux;
3460         gchar *message;
3461
3462         mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3463         vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
3464         if ((mux == HB_MUX_MP4 || mux == HB_MUX_AVI) && 
3465                 (vcodec == HB_VCODEC_THEORA))
3466         {
3467                 // mp4|avi/theora combination is not supported.
3468                 message = g_strdup_printf(
3469                                         "Theora is not supported in the MP4 and AVI containers.\n\n"
3470                                         "You should choose a different video codec or container.\n"
3471                                         "If you continue, FFMPEG will be chosen for you.");
3472                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3473                 {
3474                         g_free(message);
3475                         return FALSE;
3476                 }
3477                 g_free(message);
3478                 vcodec = HB_VCODEC_FFMPEG;
3479                 ghb_ui_update(ud, "VideoEncoder", ghb_int64_value(vcodec));
3480         }
3481         return TRUE;
3482 }
3483
3484 gboolean
3485 ghb_validate_subtitles(signal_user_data_t *ud)
3486 {
3487         hb_list_t  * list;
3488         hb_title_t * title;
3489         gchar *message;
3490
3491         if (h_scan == NULL) return FALSE;
3492         list = hb_get_titles( h_scan );
3493         if( !hb_list_count( list ) )
3494         {
3495                 /* No valid title, stop right there */
3496                 g_message("No title found.\n");
3497                 return FALSE;
3498         }
3499
3500         gint titleindex;
3501
3502         titleindex = ghb_settings_combo_int(ud->settings, "title");
3503     title = hb_list_item( list, titleindex );
3504         if (title == NULL) return FALSE;
3505         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3506
3507         const GValue *slist, *settings;
3508         gint count, ii, source;
3509         gboolean burned, one_burned = FALSE;
3510
3511         slist = ghb_settings_get_value(ud->settings, "subtitle_list");
3512         count = ghb_array_len(slist);
3513         for (ii = 0; ii < count; ii++)
3514         {
3515                 settings = ghb_array_get_nth(slist, ii);
3516                 source = ghb_settings_get_int(settings, "SubtitleSource");
3517                 burned = ghb_settings_get_boolean(settings, "SubtitleBurned");
3518                 if (burned && one_burned)
3519                 {
3520                         // MP4 can only handle burned vobsubs.  make sure there isn't
3521                         // already something burned in the list
3522                         message = g_strdup_printf(
3523                         "Only one subtitle may be burned into the video.\n\n"
3524                                 "You should change your subtitle selections.\n"
3525                                 "If you continue, some subtitles will be lost.");
3526                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3527                         {
3528                                 g_free(message);
3529                                 return FALSE;
3530                         }
3531                         g_free(message);
3532                         break;
3533                 }
3534                 else if (burned)
3535                 {
3536                         one_burned = TRUE;
3537                 }
3538                 if (!burned && mux == HB_MUX_MP4 && source == VOBSUB)
3539                 {
3540                         // MP4 can only handle burned vobsubs.  make sure there isn't
3541                         // already something burned in the list
3542                         message = g_strdup_printf(
3543                         "Your chosen container does not support soft bitmap subtitles.\n\n"
3544                                 "You should change your subtitle selections.\n"
3545                                 "If you continue, some subtitles will be lost.");
3546                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, 
3547                                 "Cancel", "Continue"))
3548                         {
3549                                 g_free(message);
3550                                 return FALSE;
3551                         }
3552                         g_free(message);
3553                         break;
3554                 }
3555                 if (source == SRTSUB)
3556                 {
3557                         gchar *filename;
3558
3559                         filename = ghb_settings_get_string(settings, "SrtFile");
3560                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
3561                         {
3562                                 message = g_strdup_printf(
3563                                 "Srt file does not exist or not a regular file.\n\n"
3564                                         "You should choose a valid file.\n"
3565                                         "If you continue, this subtitle will be ignored.");
3566                                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, 
3567                                         "Cancel", "Continue"))
3568                                 {
3569                                         g_free(message);
3570                                         return FALSE;
3571                                 }
3572                                 g_free(message);
3573                                 break;
3574                         }
3575                 }
3576         }
3577         return TRUE;
3578 }
3579
3580 gboolean
3581 ghb_validate_audio(signal_user_data_t *ud)
3582 {
3583         hb_list_t  * list;
3584         hb_title_t * title;
3585         gchar *message;
3586         GValue *value;
3587
3588         if (h_scan == NULL) return FALSE;
3589         list = hb_get_titles( h_scan );
3590         if( !hb_list_count( list ) )
3591         {
3592                 /* No valid title, stop right there */
3593                 g_message("No title found.\n");
3594                 return FALSE;
3595         }
3596
3597         gint titleindex;
3598
3599         titleindex = ghb_settings_combo_int(ud->settings, "title");
3600     title = hb_list_item( list, titleindex );
3601         if (title == NULL) return FALSE;
3602         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3603
3604         const GValue *audio_list;
3605         gint count, ii;
3606
3607         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
3608         count = ghb_array_len(audio_list);
3609         for (ii = 0; ii < count; ii++)
3610         {
3611                 GValue *asettings;
3612             hb_audio_config_t *taudio;
3613
3614                 asettings = ghb_array_get_nth(audio_list, ii);
3615                 gint track = ghb_settings_combo_int(asettings, "AudioTrack");
3616                 gint codec = ghb_settings_combo_int(asettings, "AudioEncoder");
3617         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
3618                                                                                         title->list_audio, track );
3619                 if (!(taudio->in.codec & codec) && 
3620                         (codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)))
3621                 {
3622                         // Not supported.  AC3 is passthrough only, so input must be AC3
3623                         message = g_strdup_printf(
3624                                                 "The source does not support Pass-Thru.\n\n"
3625                                                 "You should choose a different audio codec.\n"
3626                                                 "If you continue, one will be chosen for you.");
3627                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3628                         {
3629                                 g_free(message);
3630                                 return FALSE;
3631                         }
3632                         g_free(message);
3633                         if (mux == HB_MUX_AVI)
3634                         {
3635                                 codec = HB_ACODEC_LAME;
3636                         }
3637                         else
3638                         {
3639                                 codec = HB_ACODEC_FAAC;
3640                         }
3641                         value = get_acodec_value(codec);
3642                         ghb_settings_take_value(asettings, "AudioEncoder", value);
3643                 }
3644                 gchar *a_unsup = NULL;
3645                 gchar *mux_s = NULL;
3646                 if (mux == HB_MUX_MP4)
3647                 { 
3648                         mux_s = "MP4";
3649                         // mp4/mp3|vorbis combination is not supported.
3650                         if (codec == HB_ACODEC_LAME)
3651                         {
3652                                 a_unsup = "MP3";
3653                                 codec = HB_ACODEC_FAAC;
3654                         }
3655                         if (codec == HB_ACODEC_VORBIS)
3656                         {
3657                                 a_unsup = "Vorbis";
3658                                 codec = HB_ACODEC_FAAC;
3659                         }
3660                         if (codec == HB_ACODEC_DCA)
3661                         {
3662                                 a_unsup = "DTS";
3663                                 codec = HB_ACODEC_FAAC;
3664                         }
3665                 }
3666                 else if (mux == HB_MUX_AVI)
3667                 {
3668                         mux_s = "AVI";
3669                         // avi/faac|vorbis combination is not supported.
3670                         if (codec == HB_ACODEC_FAAC)
3671                         {
3672                                 a_unsup = "FAAC";
3673                                 codec = HB_ACODEC_LAME;
3674                         }
3675                         if (codec == HB_ACODEC_VORBIS)
3676                         {
3677                                 a_unsup = "Vorbis";
3678                                 codec = HB_ACODEC_LAME;
3679                         }
3680                 }
3681                 else if (mux == HB_MUX_OGM)
3682                 {
3683                         mux_s = "OGM";
3684                         // avi/faac|vorbis combination is not supported.
3685                         if (codec == HB_ACODEC_FAAC)
3686                         {
3687                                 a_unsup = "FAAC";
3688                                 codec = HB_ACODEC_VORBIS;
3689                         }
3690                         if (codec == HB_ACODEC_AC3)
3691                         {
3692                                 a_unsup = "AC-3";
3693                                 codec = HB_ACODEC_VORBIS;
3694                         }
3695                         if (codec == HB_ACODEC_DCA)
3696                         {
3697                                 a_unsup = "DTS";
3698                                 codec = HB_ACODEC_VORBIS;
3699                         }
3700                 }
3701                 if (a_unsup)
3702                 {
3703                         message = g_strdup_printf(
3704                                                 "%s is not supported in the %s container.\n\n"
3705                                                 "You should choose a different audio codec.\n"
3706                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
3707                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3708                         {
3709                                 g_free(message);
3710                                 return FALSE;
3711                         }
3712                         g_free(message);
3713                         value = get_acodec_value(codec);
3714                         ghb_settings_take_value(asettings, "AudioEncoder", value);
3715                 }
3716                 gint mix = ghb_settings_combo_int (asettings, "AudioMixdown");
3717                 gboolean allow_mono = TRUE;
3718                 gboolean allow_stereo = TRUE;
3719                 gboolean allow_dolby = TRUE;
3720                 gboolean allow_dpl2 = TRUE;
3721                 gboolean allow_6ch = TRUE;
3722                 allow_mono =
3723                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3724                         (codec != HB_ACODEC_LAME);
3725                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
3726                 allow_stereo =
3727                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
3728                 allow_dolby =
3729                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
3730                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
3731                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
3732                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
3733                 allow_6ch =
3734                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3735                         (codec != HB_ACODEC_LAME) &&
3736                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
3737                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
3738
3739                 gchar *mix_unsup = NULL;
3740                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
3741                 {
3742                         mix_unsup = "mono";
3743                 }
3744                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
3745                 {
3746                         mix_unsup = "stereo";
3747                 }
3748                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
3749                 {
3750                         mix_unsup = "Dolby";
3751                 }
3752                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
3753                 {
3754                         mix_unsup = "Dolby Pro Logic II";
3755                 }
3756                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
3757                 {
3758                         mix_unsup = "6 Channel";
3759                 }
3760                 if (mix_unsup)
3761                 {
3762                         message = g_strdup_printf(
3763                                                 "The source audio does not support %s mixdown.\n\n"
3764                                                 "You should choose a different mixdown.\n"
3765                                                 "If you continue, one will be chosen for you.", mix_unsup);
3766                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3767                         {
3768                                 g_free(message);
3769                                 return FALSE;
3770                         }
3771                         g_free(message);
3772                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
3773                         value = get_amix_value(mix);
3774                         ghb_settings_take_value(asettings, "AudioMixdown", value);
3775                 }
3776         }
3777         return TRUE;
3778 }
3779
3780 gboolean
3781 ghb_validate_vquality(GValue *settings)
3782 {
3783         gint vcodec;
3784         gchar *message;
3785         gint min, max;
3786
3787         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
3788         vcodec = ghb_settings_combo_int(settings, "VideoEncoder");
3789         gdouble vquality;
3790         vquality = ghb_settings_get_double(settings, "VideoQualitySlider");
3791         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
3792         {
3793                 switch (vcodec)
3794                 {
3795                         case HB_VCODEC_X264:
3796                         {
3797                                 min = 16;
3798                                 max = 30;
3799                         } break;
3800
3801                         case HB_VCODEC_FFMPEG:
3802                         {
3803                                 min = 1;
3804                                 max = 8;
3805                         } break;
3806
3807                         case HB_VCODEC_THEORA:
3808                         {
3809                                 min = 0;
3810                                 max = 63;
3811                         } break;
3812
3813                         default:
3814                         {
3815                                 min = 48;
3816                                 max = 62;
3817                         } break;
3818                 }
3819                 if (vquality < min || vquality > max)
3820                 {
3821                         message = g_strdup_printf(
3822                                                 "Interesting video quality choise: %d\n\n"
3823                                                 "Typical values range from %d to %d.\n"
3824                                                 "Are you sure you wish to use this setting?",
3825                                                 (gint)vquality, min, max);
3826                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
3827                                                                         "Cancel", "Continue"))
3828                         {
3829                                 g_free(message);
3830                                 return FALSE;
3831                         }
3832                         g_free(message);
3833                 }
3834         }
3835         return TRUE;
3836 }
3837
3838 static void
3839 add_job(hb_handle_t *h, GValue *js, gint unique_id, gint titleindex)
3840 {
3841         hb_list_t  * list;
3842         hb_title_t * title;
3843         hb_job_t   * job;
3844         static gchar *x264opts;
3845         gint sub_id = 0;
3846         gboolean tweaks = FALSE;
3847         gchar *detel_str = NULL;
3848         gchar *decomb_str = NULL;
3849         gchar *deint_str = NULL;
3850         gchar *deblock_str = NULL;
3851         gchar *denoise_str = NULL;
3852         gchar *dest_str = NULL;
3853
3854         g_debug("add_job()\n");
3855         if (h == NULL) return;
3856         list = hb_get_titles( h );
3857         if( !hb_list_count( list ) )
3858         {
3859                 /* No valid title, stop right there */
3860                 return;
3861         }
3862
3863     title = hb_list_item( list, titleindex );
3864         if (title == NULL) return;
3865
3866         /* Set job settings */
3867         job   = title->job;
3868         if (job == NULL) return;
3869
3870         job->start_at_preview = ghb_settings_get_int(js, "start_frame") + 1;
3871         if (job->start_at_preview)
3872         {
3873                 job->seek_points = ghb_settings_get_int(js, "preview_count");
3874                 job->pts_to_stop = ghb_settings_get_int(js, "live_duration") * 90000LL;
3875         }
3876
3877         tweaks = ghb_settings_get_boolean(js, "allow_tweaks");
3878         job->mux = ghb_settings_combo_int(js, "FileFormat");
3879         if (job->mux == HB_MUX_MP4)
3880         {
3881                 job->largeFileSize = ghb_settings_get_boolean(js, "Mp4LargeFile");
3882                 job->mp4_optimize = ghb_settings_get_boolean(js, "Mp4HttpOptimize");
3883         }
3884         else
3885         {
3886                 job->largeFileSize = FALSE;
3887                 job->mp4_optimize = FALSE;
3888         }
3889         if (!job->start_at_preview)
3890         {
3891                 gint chapter_start, chapter_end;
3892                 chapter_start = ghb_settings_get_int(js, "start_chapter");
3893                 chapter_end = ghb_settings_get_int(js, "end_chapter");
3894                 gint num_chapters = hb_list_count(title->list_chapter);
3895                 job->chapter_start = MIN( num_chapters, chapter_start );
3896                 job->chapter_end   = MAX( job->chapter_start, chapter_end );
3897
3898                 job->chapter_markers = ghb_settings_get_boolean(js, "ChapterMarkers");
3899                 if (job->chapter_start == job->chapter_end)
3900                         job->chapter_markers = 0;
3901                 if ( job->chapter_markers )
3902                 {
3903                         GValue *chapters;
3904                         GValue *chapter;
3905                         gint chap;
3906                         gint count;
3907                 
3908                         chapters = ghb_settings_get_value(js, "chapter_list");
3909                         count = ghb_array_len(chapters);
3910                         for(chap = chapter_start; chap <= chapter_end; chap++)
3911                         {
3912                                 hb_chapter_t * chapter_s;
3913                                 gchar *name;
3914                                 
3915                                 name = NULL;
3916                                 if (chap-1 < count)
3917                                 {
3918                                         chapter = ghb_array_get_nth(chapters, chap-1);
3919                                         name = ghb_value_string(chapter); 
3920                                 }
3921                                 if (name == NULL)
3922                                 {
3923                                         name = g_strdup_printf ("Chapter %2d", chap);
3924                                 }
3925                                 chapter_s = hb_list_item( job->title->list_chapter, chap - 1);
3926                                 strncpy(chapter_s->title, name, 1023);
3927                                 chapter_s->title[1023] = '\0';
3928                                 g_free(name);
3929                         }
3930                 }
3931         }
3932         job->crop[0] = ghb_settings_get_int(js, "PictureTopCrop");
3933         job->crop[1] = ghb_settings_get_int(js, "PictureBottomCrop");
3934         job->crop[2] = ghb_settings_get_int(js, "PictureLeftCrop");
3935         job->crop[3] = ghb_settings_get_int(js, "PictureRightCrop");
3936
3937         
3938         gint decomb = ghb_settings_combo_int(js, "PictureDecomb");
3939         gint deint = ghb_settings_combo_int(js, "PictureDeinterlace");
3940         if (!decomb)
3941                 job->deinterlace = (deint != 0) ? 1 : 0;
3942         else
3943                 job->deinterlace = 0;
3944     job->grayscale   = ghb_settings_get_boolean(js, "VideoGrayScale");
3945
3946         gboolean keep_aspect;
3947         keep_aspect = ghb_settings_get_boolean(js, "PictureKeepRatio");
3948         job->anamorphic.mode = ghb_settings_combo_int(js, "PicturePAR");
3949         job->anamorphic.modulus = ghb_settings_combo_int(js, "PictureModulus");
3950         if (job->anamorphic.mode)
3951         {
3952                 job->anamorphic.par_width = title->pixel_aspect_width;
3953                 job->anamorphic.par_height = title->pixel_aspect_height;
3954                 job->anamorphic.dar_width = 0;
3955                 job->anamorphic.dar_height = 0;
3956
3957                 if (job->anamorphic.mode == 3 && !keep_aspect)
3958                 {
3959                         job->anamorphic.keep_display_aspect = 0;
3960                         job->anamorphic.par_width = 
3961                                 ghb_settings_get_int(js, "PicturePARWidth");
3962                         job->anamorphic.par_height = 
3963                                 ghb_settings_get_int(js, "PicturePARHeight");
3964                 }
3965                 else
3966                 {
3967                         job->anamorphic.keep_display_aspect = 1;
3968                 }
3969         }
3970
3971         /* Add selected filters */
3972         job->filters = hb_list_init();
3973         gint detel = ghb_settings_combo_int(js, "PictureDetelecine");
3974         if ( detel )
3975         {
3976                 if (detel != 1)
3977                 {
3978                         if (detel_opts.map[detel].svalue != NULL)
3979                                 detel_str = g_strdup(detel_opts.map[detel].svalue);
3980                 }
3981                 else
3982                         detel_str = ghb_settings_get_string(js, "PictureDetelecineCustom");
3983                 hb_filter_detelecine.settings = detel_str;
3984                 hb_list_add( job->filters, &hb_filter_detelecine );
3985         }
3986         if ( decomb )
3987         {
3988                 if (decomb != 1)
3989                 {
3990                         if (decomb_opts.map[decomb].svalue != NULL)
3991                                 decomb_str = g_strdup(decomb_opts.map[decomb].svalue);
3992                 }
3993                 else
3994                         decomb_str = ghb_settings_get_string(js, "PictureDecombCustom");
3995                 hb_filter_decomb.settings = decomb_str;
3996                 hb_list_add( job->filters, &hb_filter_decomb );
3997         }
3998         if( job->deinterlace )
3999         {
4000                 if (deint != 1)
4001                 {
4002                         if (deint_opts.map[deint].svalue != NULL)
4003                                 deint_str = g_strdup(deint_opts.map[deint].svalue);
4004                 }
4005                 else
4006                         deint_str = ghb_settings_get_string(js, "PictureDeinterlaceCustom");
4007                 hb_filter_deinterlace.settings = deint_str;
4008                 hb_list_add( job->filters, &hb_filter_deinterlace );
4009         }
4010         gint deblock = ghb_settings_get_int(js, "PictureDeblock");
4011         if( deblock >= 5 )
4012         {
4013                 deblock_str = g_strdup_printf("%d", deblock);
4014                 hb_filter_deblock.settings = deblock_str;
4015                 hb_list_add( job->filters, &hb_filter_deblock );
4016         }
4017         gint denoise = ghb_settings_combo_int(js, "PictureDenoise");
4018         if( denoise )
4019         {
4020                 if (denoise != 1)
4021                 {
4022                         if (denoise_opts.map[denoise].svalue != NULL)
4023                                 denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
4024                 }
4025                 else
4026                         denoise_str = ghb_settings_get_string(js, "PictureDenoiseCustom");
4027                 hb_filter_denoise.settings = denoise_str;
4028                 hb_list_add( job->filters, &hb_filter_denoise );
4029         }
4030         job->width = ghb_settings_get_int(js, "scale_width");
4031         job->height = ghb_settings_get_int(js, "scale_height");
4032
4033         job->vcodec = ghb_settings_combo_int(js, "VideoEncoder");
4034         if ((job->mux == HB_MUX_MP4 || job->mux == HB_MUX_AVI) && 
4035                 (job->vcodec == HB_VCODEC_THEORA))
4036         {
4037                 // mp4|avi/theora combination is not supported.
4038                 job->vcodec = HB_VCODEC_FFMPEG;
4039         }
4040         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
4041         {
4042                 job->ipod_atom = ghb_settings_get_boolean(js, "Mp4iPodCompatible");
4043         }
4044         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
4045         {
4046                 gdouble vquality;
4047                 vquality = ghb_settings_get_double(js, "VideoQualitySlider");
4048                 job->vquality =  vquality;
4049                 job->vbitrate = 0;
4050         }
4051         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
4052         {
4053                 job->vquality = -1.0;
4054                 job->vbitrate = ghb_settings_get_int(js, "VideoAvgBitrate");
4055         }
4056
4057         gint vrate = ghb_settings_combo_int(js, "VideoFramerate");
4058         if( vrate == 0 )
4059         {
4060                 job->vrate = title->rate;
4061                 job->vrate_base = title->rate_base;
4062                 job->cfr = 0;
4063         }
4064         else
4065         {
4066                 job->vrate = 27000000;
4067                 job->vrate_base = vrate;
4068                 job->cfr = 1;
4069         }
4070
4071         // AVI container does not support variable frame rate.
4072         // OGM supports variable frame rate, but bases all timing on
4073         // DTS, which breaks when b-frames are used since it is
4074         // impossible to reconstruct PTS from DTS when the framerate
4075         // is variable.  
4076         if (job->mux == HB_MUX_AVI || job->mux == HB_MUX_OGM)
4077         {
4078                 job->cfr = 1;
4079         }
4080
4081         const GValue *audio_list;
4082         gint count, ii;
4083         gint tcount = 0;
4084         
4085         audio_list = ghb_settings_get_value(js, "audio_list");
4086         count = ghb_array_len(audio_list);
4087         for (ii = 0; ii < count; ii++)
4088         {
4089                 GValue *asettings;
4090             hb_audio_config_t audio;
4091             hb_audio_config_t *taudio;
4092
4093                 hb_audio_config_init(&audio);
4094                 asettings = ghb_array_get_nth(audio_list, ii);
4095                 audio.in.track = ghb_settings_get_int(asettings, "AudioTrack");
4096                 audio.out.track = tcount;
4097                 audio.out.codec = ghb_settings_combo_int(asettings, "AudioEncoder");
4098         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
4099                                                                         title->list_audio, audio.in.track );
4100                 if (audio.out.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
4101                 {
4102                         if (!(taudio->in.codec & audio.out.codec))
4103                         {
4104                                 // Not supported.  AC3 is passthrough only, so input must be AC3
4105                                 if (job->mux == HB_MUX_AVI)
4106                                 {
4107                                         audio.out.codec = HB_ACODEC_LAME;
4108                                 }
4109                                 else
4110                                 {
4111                                         audio.out.codec = HB_ACODEC_FAAC;
4112                                 }
4113                         }
4114                         else
4115                         {
4116                                 audio.out.codec &= taudio->in.codec;
4117                         }
4118                 }
4119                 if ((job->mux == HB_MUX_MP4) && 
4120                         ((audio.out.codec == HB_ACODEC_LAME) ||
4121                         (audio.out.codec == HB_ACODEC_VORBIS)))
4122                 {
4123                         // mp4/mp3|vorbis combination is not supported.
4124                         audio.out.codec = HB_ACODEC_FAAC;
4125                 }
4126                 if ((job->mux == HB_MUX_AVI) && 
4127                         ((audio.out.codec == HB_ACODEC_FAAC) ||
4128                         (audio.out.codec == HB_ACODEC_VORBIS)))
4129                 {
4130                         // avi/faac|vorbis combination is not supported.
4131                         audio.out.codec = HB_ACODEC_LAME;
4132                 }
4133                 if ((job->mux == HB_MUX_OGM) && 
4134                         ((audio.out.codec == HB_ACODEC_FAAC) ||
4135                         (audio.out.codec == HB_ACODEC_AC3) ||
4136                         (audio.out.codec == HB_ACODEC_DCA)))
4137                 {
4138                         // ogm/faac|ac3 combination is not supported.
4139                         audio.out.codec = HB_ACODEC_VORBIS;
4140                 }
4141         audio.out.dynamic_range_compression = 
4142                         ghb_settings_get_double(asettings, "AudioTrackDRCSlider");
4143         if (audio.out.dynamic_range_compression < 1.0)
4144                 audio.out.dynamic_range_compression = 0.0;
4145
4146                 // It would be better if this were done in libhb for us, but its not yet.
4147                 if (audio.out.codec == HB_ACODEC_AC3 || audio.out.codec == HB_ACODEC_DCA)
4148                 {
4149                         audio.out.mixdown = 0;
4150                 }
4151                 else
4152                 {
4153                         audio.out.mixdown = ghb_settings_combo_int(asettings, "AudioMixdown");
4154                         // Make sure the mixdown is valid and pick a new one if not.
4155                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
4156                                 audio.in.track, audio.out.codec, audio.out.mixdown);
4157                         audio.out.bitrate = 
4158                                 ghb_settings_combo_int(asettings, "AudioBitrate");
4159                         gint srate = ghb_settings_combo_int(asettings, "AudioSamplerate");
4160                         if (srate == 0) // 0 is same as source
4161                                 audio.out.samplerate = taudio->in.samplerate;
4162                         else
4163                                 audio.out.samplerate = srate;
4164                 }
4165
4166                 // Add it to the jobs audio list
4167         hb_audio_add( job, &audio );
4168                 tcount++;
4169         }
4170         // I was tempted to move this up with the reset of the video quality
4171         // settings, but I suspect the settings above need to be made
4172         // first in order for hb_calc_bitrate to be accurate.
4173         if (ghb_settings_get_boolean(js, "vquality_type_target"))
4174         {
4175                 gint size;
4176                 
4177                 size = ghb_settings_get_int(js, "VideoTargetSize");
4178         job->vbitrate = hb_calc_bitrate( job, size );
4179                 job->vquality = -1.0;
4180         }
4181
4182         dest_str = ghb_settings_get_string(js, "destination");
4183         job->file = dest_str;
4184         job->crf = ghb_settings_get_boolean(js, "constant_rate_factor");
4185
4186         const GValue *subtitle_list;
4187         gint subtitle;
4188         gboolean force, burned, def, one_burned = FALSE;
4189         
4190         ghb_settings_set_boolean(js, "subtitle_scan", FALSE);
4191         subtitle_list = ghb_settings_get_value(js, "subtitle_list");
4192         count = ghb_array_len(subtitle_list);
4193         for (ii = 0; ii < count; ii++)
4194         {
4195                 GValue *ssettings;
4196                 gint source;
4197
4198                 ssettings = ghb_array_get_nth(subtitle_list, ii);
4199
4200                 force = ghb_settings_get_boolean(ssettings, "SubtitleForced");
4201                 burned = ghb_settings_get_boolean(ssettings, "SubtitleBurned");
4202                 def = ghb_settings_get_boolean(ssettings, "SubtitleDefaultTrack");
4203                 source = ghb_settings_get_int(ssettings, "SubtitleSource");
4204
4205                 if (source == SRTSUB)
4206                 {
4207                 hb_subtitle_config_t sub_config;
4208                         gchar *filename, *lang, *code;
4209
4210                         filename = ghb_settings_get_string(ssettings, "SrtFile");
4211                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
4212                         {
4213                                 continue;
4214                         }
4215                         sub_config.offset = ghb_settings_get_int(ssettings, "SrtOffset");
4216                         lang = ghb_settings_get_string(ssettings, "SrtLanguage");
4217                         code = ghb_settings_get_string(ssettings, "SrtCodeset");
4218                         strncpy(sub_config.src_filename, filename, 128);
4219                         strncpy(sub_config.src_codeset, code, 40);
4220                         sub_config.force = 0;
4221                         sub_config.dest = PASSTHRUSUB;
4222                         sub_config.default_track = def;
4223
4224                         hb_srt_add( job, &sub_config, lang);
4225
4226                         g_free(filename);
4227                         g_free(lang);
4228                         g_free(code);
4229                         continue;
4230                 }
4231
4232                 subtitle = ghb_settings_get_int(ssettings, "SubtitleTrack");
4233                 if (subtitle == -1)
4234                 {
4235                         if (!burned && job->mux == HB_MUX_MKV)
4236                         {
4237                                 job->select_subtitle_config.dest = PASSTHRUSUB;
4238                         }
4239                         else if (!burned && job->mux == HB_MUX_MP4)
4240                         {
4241                                 // Skip any non-burned vobsubs when output is mp4
4242                                 continue;
4243                         }
4244                         else if (burned)
4245                         {
4246                                 // Only allow one subtitle to be burned into the video
4247                                 if (one_burned)
4248                                         continue;
4249                                 job->select_subtitle_config.dest = RENDERSUB;
4250                                 one_burned = TRUE;
4251                         }
4252                         job->select_subtitle_config.force = force;
4253                         job->select_subtitle_config.default_track = def;
4254                         job->indepth_scan = 1;
4255                         ghb_settings_set_boolean(js, "subtitle_scan", TRUE);
4256                 }
4257                 else if (subtitle >= 0)
4258                 {
4259                 hb_subtitle_t * subt;
4260                 hb_subtitle_config_t sub_config;
4261
4262                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
4263                         sub_config = subt->config;
4264                         if (subt != NULL)
4265                         {
4266                                 if (!burned && job->mux == HB_MUX_MKV && 
4267                                         subt->format == PICTURESUB)
4268                                 {
4269                                         sub_config.dest = PASSTHRUSUB;
4270                                 }
4271                                 else if (!burned && job->mux == HB_MUX_MP4 && 
4272                                         subt->format == PICTURESUB)
4273                                 {
4274                                         // Skip any non-burned vobsubs when output is mp4
4275                                         continue;
4276                                 }
4277                                 else if ( burned && subt->format == PICTURESUB )
4278                                 {
4279                                         // Only allow one subtitle to be burned into the video
4280                                         if (one_burned)
4281                                                 continue;
4282                                         one_burned = TRUE;
4283                                 }
4284                                 sub_config.force = force;
4285                                 sub_config.default_track = def;
4286                         hb_subtitle_add( job, &sub_config, subtitle );
4287                         }
4288                 }
4289         }
4290
4291         // TODO: libhb holds onto a reference to the x264opts and is not
4292         // finished with it until encoding the job is done.  But I can't
4293         // find a way to get at the job before it is removed in order to
4294         // free up the memory I am allocating here.
4295         // The short story is THIS LEAKS.
4296         x264opts = ghb_build_x264opts_string(js);
4297         
4298         if( *x264opts == '\0' )
4299         {
4300                 g_free(x264opts);
4301                 x264opts = NULL;
4302         }
4303
4304         if (job->indepth_scan == 1)
4305         {
4306                 // Subtitle scan. Look for subtitle matching audio language
4307
4308                 /*
4309                  * When subtitle scan is enabled do a fast pre-scan job
4310                  * which will determine which subtitles to enable, if any.
4311                  */
4312                 job->pass = -1;
4313                 job->indepth_scan = 1;
4314                 job->x264opts = NULL;
4315
4316                 /*
4317                  * Add the pre-scan job
4318                  */
4319                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4320                 hb_add( h, job );
4321         }
4322
4323         if( ghb_settings_get_boolean(js, "VideoTwoPass") &&
4324                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
4325         {
4326                 /*
4327                  * If subtitle_scan is enabled then only turn it on
4328                  * for the second pass and then off again for the
4329                  * second.
4330                  */
4331                 job->pass = 1;
4332                 job->indepth_scan = 0;
4333
4334                 /*
4335                  * If turbo options have been selected then append them
4336                  * to the x264opts now (size includes one ':' and the '\0')
4337                  */
4338                 if( ghb_settings_get_boolean(js, "VideoTurboTwoPass") )
4339                 {
4340                         gchar *tmp_x264opts;
4341                         gchar *extra_opts;
4342                         gint badapt;
4343
4344                         badapt = ghb_lookup_badapt(x264opts);
4345                         if (badapt == 2)
4346                         {
4347                                 extra_opts = g_strdup_printf("%s", turbo_opts);
4348                         }
4349                         else
4350                         {
4351                                 extra_opts = g_strdup_printf("%s:weightb=0", turbo_opts);
4352                         }
4353         
4354                         if ( x264opts )
4355                         {
4356                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, extra_opts);
4357                         } 
4358                         else 
4359                         {
4360                                 /*
4361                                  * No x264opts to modify, but apply the turbo options
4362                                  * anyway as they may be modifying defaults
4363                                  */
4364                                 tmp_x264opts = g_strdup_printf("%s", extra_opts);
4365                         }
4366                         g_free(extra_opts);
4367
4368                         job->x264opts = tmp_x264opts;
4369                 }
4370                 else
4371                 {
4372                         job->x264opts = x264opts;
4373                 }
4374                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4375                 hb_add( h, job );
4376                 //if (job->x264opts != NULL)
4377                 //      g_free(job->x264opts);
4378
4379                 job->pass = 2;
4380                 /*
4381                  * On the second pass we turn off subtitle scan so that we
4382                  * can actually encode using any subtitles that were auto
4383                  * selected in the first pass (using the whacky select-subtitle
4384                  * attribute of the job).
4385                  */
4386                 job->indepth_scan = 0;
4387                 job->x264opts = x264opts;
4388                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4389                 hb_add( h, job );
4390                 //if (job->x264opts != NULL)
4391                 //      g_free(job->x264opts);
4392         }
4393         else
4394         {
4395                 job->x264opts = x264opts;
4396                 job->indepth_scan = 0;
4397                 job->pass = 0;
4398                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4399                 hb_add( h, job );
4400                 //if (job->x264opts != NULL)
4401                 //      g_free(job->x264opts);
4402         }
4403
4404         // clean up audio list
4405         gint num_audio_tracks = hb_list_count(job->list_audio);
4406         for(ii = 0; ii < num_audio_tracks; ii++)
4407         {
4408                 hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
4409                 hb_list_rem(job->list_audio, audio);
4410                 free(audio);
4411         }
4412
4413         // clean up subtitle list
4414         gint num_subtitle_tracks = hb_list_count(job->list_subtitle);
4415         for(ii = 0; ii < num_subtitle_tracks; ii++)
4416         {
4417                 hb_subtitle_t *subtitle = hb_list_item(job->list_subtitle, 0);
4418                 hb_list_rem(job->list_subtitle, subtitle);
4419                 free(subtitle);
4420         }
4421
4422         if (detel_str) g_free(detel_str);
4423         if (decomb_str) g_free(decomb_str);
4424         if (deint_str) g_free(deint_str);
4425         if (deblock_str) g_free(deblock_str);
4426         if (denoise_str) g_free(denoise_str);
4427         if (dest_str) g_free(dest_str);
4428 }
4429
4430 void
4431 ghb_add_job(GValue *js, gint unique_id)
4432 {
4433         // Since I'm doing a scan of the single title I want just prior 
4434         // to adding the job, there is only the one title to choose from.
4435         add_job(h_queue, js, unique_id, 0);
4436 }
4437
4438 void
4439 ghb_add_live_job(GValue *js, gint unique_id)
4440 {
4441         // Since I'm doing a scan of the single title I want just prior 
4442         // to adding the job, there is only the one title to choose from.
4443         gint titleindex = ghb_settings_combo_int(js, "title");
4444         add_job(h_scan, js, unique_id, titleindex);
4445 }
4446
4447 void
4448 ghb_remove_job(gint unique_id)
4449 {
4450     hb_job_t * job;
4451     gint ii;
4452         
4453         // Multiples passes all get the same id
4454         // remove them all.
4455         // Go backwards through list, so reordering doesn't screw me.
4456         ii = hb_count(h_queue) - 1;
4457     while ((job = hb_job(h_queue, ii--)) != NULL)
4458     {
4459         if ((job->sequence_id & 0xFFFFFF) == unique_id)
4460                         hb_rem(h_queue, job);
4461     }
4462 }
4463
4464 void
4465 ghb_start_queue()
4466 {
4467         hb_start( h_queue );
4468 }
4469
4470 void
4471 ghb_stop_queue()
4472 {
4473         hb_stop( h_queue );
4474 }
4475
4476 void
4477 ghb_start_live_encode()
4478 {
4479         hb_start( h_scan );
4480 }
4481
4482 void
4483 ghb_stop_live_encode()
4484 {
4485         hb_stop( h_scan );
4486 }
4487
4488 void
4489 ghb_pause_queue()
4490 {
4491     hb_state_t s;
4492     hb_get_state2( h_queue, &s );
4493
4494     if( s.state == HB_STATE_PAUSED )
4495     {
4496         hb_resume( h_queue );
4497     }
4498     else
4499     {
4500         hb_pause( h_queue );
4501     }
4502 }
4503
4504 static void
4505 vert_line(
4506         GdkPixbuf * pb, 
4507         guint8 r, 
4508         guint8 g, 
4509         guint8 b, 
4510         gint x, 
4511         gint y, 
4512         gint len, 
4513         gint width)
4514 {
4515         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4516         guint8 *dst;
4517         gint ii, jj;
4518         gint channels = gdk_pixbuf_get_n_channels (pb);
4519         gint stride = gdk_pixbuf_get_rowstride (pb);
4520
4521         for (jj = 0; jj < width; jj++)
4522         {
4523                 dst = pixels + y * stride + (x+jj) * channels;
4524                 for (ii = 0; ii < len; ii++)
4525                 {
4526                         dst[0] = r;
4527                         dst[1] = g;
4528                         dst[2] = b;
4529                         dst += stride;
4530                 }
4531         }
4532 }
4533
4534 static void
4535 horz_line(
4536         GdkPixbuf * pb, 
4537         guint8 r, 
4538         guint8 g, 
4539         guint8 b, 
4540         gint x, 
4541         gint y, 
4542         gint len,
4543         gint width)
4544 {
4545         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4546         guint8 *dst;
4547         gint ii, jj;
4548         gint channels = gdk_pixbuf_get_n_channels (pb);
4549         gint stride = gdk_pixbuf_get_rowstride (pb);
4550
4551         for (jj = 0; jj < width; jj++)
4552         {
4553                 dst = pixels + (y+jj) * stride + x * channels;
4554                 for (ii = 0; ii < len; ii++)
4555                 {
4556                         dst[0] = r;
4557                         dst[1] = g;
4558                         dst[2] = b;
4559                         dst += channels;
4560                 }
4561         }
4562 }
4563
4564 static void
4565 hash_pixbuf(
4566         GdkPixbuf * pb,
4567         gint        x,
4568         gint        y,
4569         gint        w,
4570         gint        h,
4571         gint        step,
4572         gint            orientation)
4573 {
4574         gint ii, jj;
4575         gint line_width = 8;
4576         struct
4577         {
4578                 guint8 r;
4579                 guint8 g;
4580                 guint8 b;
4581         } c[4] = 
4582         {{0x80, 0x80, 0x80},{0xC0, 0x80, 0x70},{0x80, 0xA0, 0x80},{0x70, 0x80, 0xA0}};
4583
4584         if (!orientation)
4585         {
4586                 // vertical lines
4587                 for (ii = x, jj = 0; ii+line_width < x+w; ii += step, jj++)
4588                 {
4589                         vert_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, ii, y, h, line_width);
4590                 }
4591         }
4592         else
4593         {
4594                 // horizontal lines
4595                 for (ii = y, jj = 0; ii+line_width < y+h; ii += step, jj++)
4596                 {
4597                         horz_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, x, ii, w, line_width);
4598                 }
4599         }
4600 }
4601
4602 GdkPixbuf*
4603 ghb_get_preview_image(
4604         gint titleindex, 
4605         gint index, 
4606         signal_user_data_t *ud,
4607         gint *out_width,
4608         gint *out_height)
4609 {
4610         GValue *settings;
4611         hb_title_t *title;
4612         hb_list_t  *list;
4613         
4614         settings = ud->settings;
4615         list = hb_get_titles( h_scan );
4616         if( !hb_list_count( list ) )
4617         {
4618                 /* No valid title, stop right there */
4619                 return NULL;
4620         }
4621     title = hb_list_item( list, titleindex );
4622         if (title == NULL) return NULL;
4623         if (title->job == NULL) return NULL;
4624         set_preview_job_settings(title->job, settings);
4625
4626         // hb_get_preview doesn't compensate for anamorphic, so lets
4627         // calculate scale factors
4628         gint width, height, par_width = 1, par_height = 1;
4629         gint pic_par = ghb_settings_combo_int(settings, "PicturePAR");
4630         if (pic_par)
4631         {
4632                 hb_set_anamorphic_size( title->job, &width, &height, 
4633                                                                 &par_width, &par_height );
4634         }
4635
4636         // Make sure we have a big enough buffer to receive the image from libhb
4637         gint dstWidth = title->job->width;
4638         gint dstHeight= title->job->height;
4639
4640         static guint8 *buffer = NULL;
4641         static gint bufferSize = 0;
4642         gint newSize;
4643
4644         newSize = dstWidth * dstHeight * 4;
4645         if( bufferSize < newSize )
4646         {
4647                 bufferSize = newSize;
4648                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
4649         }
4650         hb_get_preview( h_scan, title, index, buffer );
4651
4652         // Create an GdkPixbuf and copy the libhb image into it, converting it from
4653         // libhb's format something suitable.
4654         
4655         // The image data returned by hb_get_preview is 4 bytes per pixel, 
4656         // BGRA format. Alpha is ignored.
4657
4658         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
4659         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
4660         
4661         guint32 *src = (guint32*)buffer;
4662         guint8 *dst = pixels;
4663
4664         gint ii, jj;
4665         gint channels = gdk_pixbuf_get_n_channels (preview);
4666         gint stride = gdk_pixbuf_get_rowstride (preview);
4667         guint8 *tmp;
4668
4669         for (ii = 0; ii < dstHeight; ii++)
4670         {
4671                 tmp = dst;
4672                 for (jj = 0; jj < dstWidth; jj++)
4673                 {
4674                         tmp[0] = src[0] >> 16;
4675                         tmp[1] = src[0] >> 8;
4676                         tmp[2] = src[0] >> 0;
4677                         tmp += channels;
4678                         src++;
4679                 }
4680                 dst += stride;
4681         }
4682         gint w = ghb_settings_get_int(settings, "scale_width");
4683         gint h = ghb_settings_get_int(settings, "scale_height");
4684         ghb_par_scale(ud, &w, &h, par_width, par_height);
4685
4686         gint c0, c1, c2, c3;
4687         c0 = ghb_settings_get_int(settings, "PictureTopCrop");
4688         c1 = ghb_settings_get_int(settings, "PictureBottomCrop");
4689         c2 = ghb_settings_get_int(settings, "PictureLeftCrop");
4690         c3 = ghb_settings_get_int(settings, "PictureRightCrop");
4691
4692         gdouble xscale = (gdouble)w / (gdouble)(title->width - c2 - c3);
4693         gdouble yscale = (gdouble)h / (gdouble)(title->height - c0 - c1);
4694         
4695         ghb_par_scale(ud, &dstWidth, &dstHeight, par_width, par_height);
4696         *out_width = w;
4697         *out_height = h;
4698         if (ghb_settings_get_boolean(settings, "reduce_hd_preview"))
4699         {
4700                 GdkScreen *ss;
4701                 gint s_w, s_h;
4702                 gint orig_w, orig_h;
4703                 gint factor = 80;
4704
4705                 if (ghb_settings_get_boolean(settings, "preview_fullscreen"))
4706                 {
4707                         factor = 100;
4708                 }
4709                 ss = gdk_screen_get_default();
4710                 s_w = gdk_screen_get_width(ss);
4711                 s_h = gdk_screen_get_height(ss);
4712                 orig_w = dstWidth;
4713                 orig_h = dstHeight;
4714
4715                 if (dstWidth > s_w * factor / 100)
4716                 {
4717                         dstWidth = s_w * factor / 100;
4718                         dstHeight = dstHeight * dstWidth / orig_w;
4719                 }
4720                 if (dstHeight > s_h * factor / 100)
4721                 {
4722                         dstHeight = s_h * factor / 100;
4723                         dstWidth = dstWidth * dstHeight / orig_h;
4724                 }
4725                 xscale *= (gdouble)dstWidth / orig_w;
4726                 yscale *= (gdouble)dstHeight / orig_h;
4727                 w *= (gdouble)dstWidth / orig_w;
4728                 h *= (gdouble)dstHeight / orig_h;
4729         }
4730         GdkPixbuf *scaled_preview;
4731         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
4732         if (ghb_settings_get_boolean(settings, "show_crop"))
4733         {
4734                 c0 *= yscale;
4735                 c1 *= yscale;
4736                 c2 *= xscale;
4737                 c3 *= xscale;
4738                 // Top
4739                 hash_pixbuf(scaled_preview, c2, 0, w, c0, 32, 0);
4740                 // Bottom
4741                 hash_pixbuf(scaled_preview, c2, dstHeight-c1, w, c1, 32, 0);
4742                 // Left
4743                 hash_pixbuf(scaled_preview, 0, c0, c2, h, 32, 1);
4744                 // Right
4745                 hash_pixbuf(scaled_preview, dstWidth-c3, c0, c3, h, 32, 1);
4746         }
4747         g_object_unref (preview);
4748         return scaled_preview;
4749 }
4750
4751 static void
4752 sanitize_volname(gchar *name)
4753 {
4754         gchar *a, *b;
4755
4756         a = b = name;
4757         while (*b)
4758         {
4759                 switch(*b)
4760                 {
4761                 case '<':
4762                         b++;
4763                         break;
4764                 case '>':
4765                         b++;
4766                         break;
4767                 default:
4768                         *a = *b;
4769                         a++; b++;
4770                         break;
4771                 }
4772         }
4773         *a = 0;
4774 }
4775
4776 gchar*
4777 ghb_dvd_volname(const gchar *device)
4778 {
4779         gchar *name;
4780         name = hb_dvd_name((gchar*)device);
4781         if (name != NULL && name[0] != 0)
4782         {
4783                 name = g_strdup(name);
4784                 sanitize_volname(name);
4785                 return name;
4786         }
4787         return NULL;
4788 }