OSDN Git Service

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