OSDN Git Service

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