OSDN Git Service

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