OSDN Git Service

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