OSDN Git Service

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