OSDN Git Service

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