OSDN Git Service

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