OSDN Git Service

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