OSDN Git Service

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