OSDN Git Service

LinGui: add pref option to scale down high def previews
[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 static GValue*
802 get_abitrate_value(gint val)
803 {
804         GValue *value = NULL;
805         gint ii;
806
807         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
808         {
809                 if (hb_audio_bitrates[ii].rate == val)
810                 {
811                         value = ghb_string_value_new(hb_audio_bitrates[ii].string);
812                         break;
813                 }
814         }
815         return value;
816 }
817
818 static GValue*
819 get_amix_value(gint val)
820 {
821         GValue *value = NULL;
822         gint ii;
823
824         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
825         {
826                 if (hb_audio_mixdowns[ii].amixdown == val)
827                 {
828                         value = ghb_string_value_new(hb_audio_mixdowns[ii].short_name);
829                         break;
830                 }
831         }
832         return value;
833 }
834
835 // Handle for libhb.  Gets set by ghb_backend_init()
836 static hb_handle_t * h_scan = NULL;
837 static hb_handle_t * h_queue = NULL;
838
839 extern void hb_get_tempory_directory(hb_handle_t *h, char path[512]);
840
841 void
842 ghb_hb_cleanup(gboolean partial)
843 {
844         char dir[512];
845
846         hb_get_tempory_directory(h_scan, dir);
847         del_tree(dir, !partial);
848 }
849
850 gint
851 ghb_get_title_number(gint titleindex)
852 {
853         hb_list_t  * list;
854         hb_title_t * title;
855         
856         if (h_scan == NULL) return 1;
857         list = hb_get_titles( h_scan );
858         if( !hb_list_count( list ) )
859         {
860                 /* No valid title, stop right there */
861                 return 1;
862         }
863         title = hb_list_item( list, titleindex );
864         if (title == NULL) return 1;    // Bad titleindex
865         return title->index;
866 }
867
868 static hb_audio_config_t*
869 get_hb_audio(gint titleindex, gint track)
870 {
871         hb_list_t  * list;
872         hb_title_t * title;
873     hb_audio_config_t *audio = NULL;
874         
875     if (h_scan == NULL) return NULL;
876         list = hb_get_titles( h_scan );
877         if( !hb_list_count( list ) )
878         {
879                 /* No valid title, stop right there */
880                 return NULL;
881         }
882     title = hb_list_item( list, titleindex );
883         if (title == NULL) return NULL; // Bad titleindex
884         if (!hb_list_count(title->list_audio))
885         {
886                 return NULL;
887         }
888     audio = (hb_audio_config_t *)hb_list_audio_config_item(title->list_audio, track);
889         return audio;
890 }
891
892 static gint
893 search_rates(hb_rate_t *rates, gint rate, gint count)
894 {
895         gint ii;
896         for (ii = 0; ii < count; ii++)
897         {
898                 if (rates[ii].rate == rate)
899                         return ii;
900         }
901         return -1;
902 }
903
904 static gboolean find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter);
905
906 static GtkListStore*
907 get_combo_box_store(GtkBuilder *builder, const gchar *name)
908 {
909         GtkComboBox *combo;
910         GtkListStore *store;
911
912         g_debug("get_combo_box_store() %s\n", name);
913         // First modify the combobox model to allow greying out of options
914         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
915         store = GTK_LIST_STORE(gtk_combo_box_get_model (combo));
916         return store;
917 }
918
919 static void
920 grey_combo_box_item(GtkBuilder *builder, const gchar *name, gint value, gboolean grey)
921 {
922         GtkListStore *store;
923         GtkTreeIter iter;
924         
925         store = get_combo_box_store(builder, name);
926         if (find_combo_item_by_int(GTK_TREE_MODEL(store), value, &iter))
927         {
928                 gtk_list_store_set(store, &iter, 
929                                                    1, !grey, 
930                                                    -1);
931         }
932 }
933
934 void
935 ghb_grey_combo_options(GtkBuilder *builder)
936 {
937         GtkWidget *widget;
938         gint container, track, titleindex, acodec;
939         gboolean httpopt;
940     hb_audio_config_t *audio = NULL;
941         GValue *gval;
942         
943         widget = GHB_WIDGET (builder, "title");
944         gval = ghb_widget_value(widget);
945         titleindex = ghb_lookup_combo_int("title", gval);
946         ghb_value_free(gval);
947         widget = GHB_WIDGET (builder, "AudioTrack");
948         gval = ghb_widget_value(widget);
949         track = ghb_lookup_combo_int("AudioTrack", gval);
950         ghb_value_free(gval);
951         audio = get_hb_audio(titleindex, track);
952         widget = GHB_WIDGET (builder, "FileFormat");
953         gval = ghb_widget_value(widget);
954         container = ghb_lookup_combo_int("FileFormat", gval);
955         ghb_value_free(gval);
956         widget = GHB_WIDGET (builder, "Mp4HttpOptimize");
957         httpopt = ghb_widget_boolean(widget);
958
959         grey_combo_box_item(builder, "x264_analyse", 3, TRUE);
960         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, FALSE);
961         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_LAME, FALSE);
962         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, FALSE);
963
964         gboolean allow_ac3 = TRUE;
965         allow_ac3 = 
966                 !(container == HB_MUX_MP4 && httpopt) &&
967                 (container != HB_MUX_OGM);
968
969         if (allow_ac3)
970         {
971                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, FALSE);
972         }
973         else
974         {
975                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, TRUE);
976         }
977         if (audio && audio->in.codec != HB_ACODEC_AC3)
978         {
979                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, TRUE);
980         }
981         grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, FALSE);
982
983         widget = GHB_WIDGET (builder, "AudioEncoder");
984         gval = ghb_widget_value(widget);
985         acodec = ghb_lookup_combo_int("AudioEncoder", gval);
986         ghb_value_free(gval);
987         if (acodec != HB_ACODEC_AC3)
988         {
989                 grey_combo_box_item(builder, "AudioMixdown", 0, TRUE);
990         }
991         if (container == HB_MUX_MP4)
992         {
993                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_LAME, TRUE);
994                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
995                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
996         }
997         else if (container == HB_MUX_AVI)
998         {
999                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1000                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
1001                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
1002         }
1003         else if (container == HB_MUX_OGM)
1004         {
1005                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1006         }
1007
1008         gboolean allow_mono = TRUE;
1009         gboolean allow_stereo = TRUE;
1010         gboolean allow_dolby = TRUE;
1011         gboolean allow_dpl2 = TRUE;
1012         gboolean allow_6ch = TRUE;
1013         if (audio)
1014         {
1015                 allow_mono =
1016                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1017                         (acodec != HB_ACODEC_LAME);
1018                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1019                 allow_stereo =
1020                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1021                 allow_dolby =
1022                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1023                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1024                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1025                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1026                 allow_6ch =
1027                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1028                         (acodec != HB_ACODEC_LAME) &&
1029                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1030                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1031         }
1032         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_MONO, !allow_mono);
1033         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_STEREO, !allow_stereo);
1034         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBY, !allow_dolby);
1035         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBYPLII, !allow_dpl2);
1036         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_6CH, !allow_6ch);
1037 }
1038
1039 gint
1040 ghb_get_best_mix(gint titleindex, gint track, gint acodec, gint mix)
1041 {
1042     hb_audio_config_t *audio = NULL;
1043         gboolean allow_mono = TRUE;
1044         gboolean allow_stereo = TRUE;
1045         gboolean allow_dolby = TRUE;
1046         gboolean allow_dpl2 = TRUE;
1047         gboolean allow_6ch = TRUE;
1048         
1049         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1050         {
1051                 // Audio codec pass-thru.  No mixdown
1052                 return 0;
1053         }
1054         audio = get_hb_audio(titleindex, track);
1055         if (audio)
1056         {
1057                 allow_mono =
1058                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1059                         (acodec != HB_ACODEC_LAME);
1060                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1061                 allow_stereo =
1062                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1063                 allow_dolby =
1064                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1065                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1066                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1067                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1068                 allow_6ch =
1069                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1070                         (acodec != HB_ACODEC_LAME) &&
1071                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1072                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1073         }
1074         gboolean greater = FALSE;
1075         if (mix == 0) 
1076         {
1077                 // If no mix is specified, select the best available.
1078                 mix = HB_AMIXDOWN_6CH;
1079         }
1080         if (mix == HB_AMIXDOWN_6CH)
1081         {
1082                 greater = TRUE;
1083                 if (allow_6ch) return HB_AMIXDOWN_6CH;
1084         }
1085         if (mix == HB_AMIXDOWN_DOLBYPLII || greater)
1086         {
1087                 greater = TRUE;
1088                 if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1089         }
1090         if (mix == HB_AMIXDOWN_DOLBY || greater)
1091         {
1092                 greater = TRUE;
1093                 if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1094         }
1095         if (mix == HB_AMIXDOWN_STEREO || greater)
1096         {
1097                 greater = TRUE;
1098                 if (allow_stereo) return HB_AMIXDOWN_STEREO;
1099         }
1100         if (mix == HB_AMIXDOWN_MONO || greater)
1101         {
1102                 greater = TRUE;
1103                 if (allow_mono) return HB_AMIXDOWN_MONO;
1104         }
1105         if (allow_stereo) return HB_AMIXDOWN_STEREO;
1106         if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1107         if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1108         if (allow_6ch) return HB_AMIXDOWN_6CH;
1109         return 0;
1110 }
1111
1112 // Set up the model for the combo box
1113 static void
1114 init_combo_box(GtkBuilder *builder, const gchar *name)
1115 {
1116         GtkComboBox *combo;
1117         GtkListStore *store;
1118         GtkCellRenderer *cell;
1119
1120         g_debug("init_combo_box() %s\n", name);
1121         // First modify the combobox model to allow greying out of options
1122         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1123         // Store contains:
1124         // 1 - String to display
1125         // 2 - bool indicating whether the entry is selectable (grey or not)
1126         // 3 - String that is used for presets
1127         // 4 - Int value determined by backend
1128         // 5 - String value determined by backend
1129         store = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_BOOLEAN, 
1130                                                            G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING);
1131         gtk_combo_box_set_model(combo, GTK_TREE_MODEL(store));
1132
1133         if (GTK_WIDGET_TYPE(combo) == GTK_TYPE_COMBO_BOX)
1134         {
1135                 gtk_cell_layout_clear(GTK_CELL_LAYOUT(combo));
1136         cell = GTK_CELL_RENDERER(gtk_cell_renderer_text_new());
1137         gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE);
1138         gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell,
1139                 "text", 0, "sensitive", 1, NULL);
1140         }
1141         else
1142         { // Combo box entry
1143                 gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(combo), 0);
1144         }
1145 }       
1146
1147 static void
1148 audio_samplerate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1149 {
1150         GtkTreeIter iter;
1151         GtkListStore *store;
1152         gint ii;
1153         
1154         g_debug("audio_samplerate_opts_set ()\n");
1155         store = get_combo_box_store(builder, name);
1156         gtk_list_store_clear(store);
1157         // Add an item for "Same As Source"
1158         gtk_list_store_append(store, &iter);
1159         gtk_list_store_set(store, &iter, 
1160                                            0, "Same as source", 
1161                                            1, TRUE, 
1162                                            2, "source", 
1163                                            3, 0, 
1164                                            4, "source", 
1165                                            -1);
1166         for (ii = 0; ii < count; ii++)
1167         {
1168                 gtk_list_store_append(store, &iter);
1169                 gtk_list_store_set(store, &iter, 
1170                                                    0, rates[ii].string, 
1171                                                    1, TRUE, 
1172                                                    2, rates[ii].string, 
1173                                                    3, rates[ii].rate, 
1174                                                    4, rates[ii].string, 
1175                                                    -1);
1176         }
1177 }
1178
1179 static void
1180 video_rate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1181 {
1182         GtkTreeIter iter;
1183         GtkListStore *store;
1184         gint ii;
1185         
1186         g_debug("video_rate_opts_set ()\n");
1187         store = get_combo_box_store(builder, name);
1188         gtk_list_store_clear(store);
1189         // Add an item for "Same As Source"
1190         gtk_list_store_append(store, &iter);
1191         gtk_list_store_set(store, &iter, 
1192                                            0, "Same as source", 
1193                                            1, TRUE, 
1194                                            2, "source", 
1195                                            3, 0, 
1196                                            4, "source", 
1197                                            -1);
1198         for (ii = 0; ii < count; ii++)
1199         {
1200                 gchar *desc = "";
1201                 gchar *option;
1202                 if (strcmp(rates[ii].string, "23.976") == 0)
1203                 {
1204                         desc = "(NTSC Film)";
1205                 }
1206                 else if (strcmp(rates[ii].string, "25") == 0)
1207                 {
1208                         desc = "(PAL Film/Video)";
1209                 }
1210                 else if (strcmp(rates[ii].string, "29.97") == 0)
1211                 {
1212                         desc = "(NTSC Video)";
1213                 }
1214                 option = g_strdup_printf ("%s %s", rates[ii].string, desc);
1215                 gtk_list_store_append(store, &iter);
1216                 gtk_list_store_set(store, &iter, 
1217                                                    0, option, 
1218                                                    1, TRUE, 
1219                                                    2, rates[ii].string, 
1220                                                    3, rates[ii].rate, 
1221                                                    4, rates[ii].string, 
1222                                                    -1);
1223                 g_free(option);
1224         }
1225 }
1226
1227 static void
1228 mix_opts_set(GtkBuilder *builder, const gchar *name)
1229 {
1230         GtkTreeIter iter;
1231         GtkListStore *store;
1232         gint ii;
1233         
1234         g_debug("mix_opts_set ()\n");
1235         store = get_combo_box_store(builder, name);
1236         gtk_list_store_clear(store);
1237         gtk_list_store_append(store, &iter);
1238         gtk_list_store_set(store, &iter, 
1239                                            0, "None", 
1240                                            1, TRUE, 
1241                                            2, "none", 
1242                                            3, 0, 
1243                                            4, "none", 
1244                                            -1);
1245         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1246         {
1247                 gtk_list_store_append(store, &iter);
1248                 gtk_list_store_set(store, &iter, 
1249                                                    0, hb_audio_mixdowns[ii].human_readable_name, 
1250                                                    1, TRUE, 
1251                                                    2, hb_audio_mixdowns[ii].short_name, 
1252                                                    3, hb_audio_mixdowns[ii].amixdown, 
1253                                                    4, hb_audio_mixdowns[ii].internal_name, 
1254                                                    -1);
1255         }
1256 }
1257
1258 static void
1259 language_opts_set(GtkBuilder *builder, const gchar *name)
1260 {
1261         GtkTreeIter iter;
1262         GtkListStore *store;
1263         gint ii;
1264         
1265         g_debug("language_opts_set ()\n");
1266         store = get_combo_box_store(builder, name);
1267         gtk_list_store_clear(store);
1268         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1269         {
1270                 gtk_list_store_append(store, &iter);
1271                 gtk_list_store_set(store, &iter, 
1272                                                    0, ghb_language_table[ii].eng_name, 
1273                                                    1, TRUE, 
1274                                                    2, ghb_language_table[ii].iso639_2, 
1275                                                    3, ii, 
1276                                                    4, ghb_language_table[ii].iso639_1, 
1277                                                    -1);
1278         }
1279 }
1280
1281 static gchar **titles = NULL;
1282
1283 void
1284 title_opts_set(GtkBuilder *builder, const gchar *name)
1285 {
1286         GtkTreeIter iter;
1287         GtkListStore *store;
1288         hb_list_t  * list = NULL;
1289         hb_title_t * title = NULL;
1290         gint ii;
1291         gint count = 0;
1292         
1293         g_debug("title_opts_set ()\n");
1294         store = get_combo_box_store(builder, name);
1295         gtk_list_store_clear(store);
1296         if (h_scan != NULL)
1297         {
1298                 list = hb_get_titles( h_scan );
1299                 count = hb_list_count( list );
1300                 if (count > 100) count = 100;
1301         }
1302         if (titles) g_strfreev(titles);
1303         if (title_opts.map) g_free(title_opts.map);
1304         if (count > 0)
1305         {
1306                 title_opts.count = count;
1307                 title_opts.map = g_malloc(count*sizeof(options_map_t));
1308                 titles = g_malloc((count+1) * sizeof(gchar*));
1309         }
1310         else
1311         {
1312                 title_opts.count = 1;
1313                 title_opts.map = g_malloc(sizeof(options_map_t));
1314                 titles = NULL;
1315         }
1316         if( count <= 0 )
1317         {
1318                 // No titles.  Fill in a default.
1319                 gtk_list_store_append(store, &iter);
1320                 gtk_list_store_set(store, &iter, 
1321                                                    0, "No Titles", 
1322                                                    1, TRUE, 
1323                                                    2, "none", 
1324                                                    3, -1, 
1325                                                    4, "none", 
1326                                                    -1);
1327                 title_opts.map[0].option = "No Titles";
1328                 title_opts.map[0].shortOpt = "none";
1329                 title_opts.map[0].ivalue = -1;
1330                 title_opts.map[0].svalue = "none";
1331                 return;
1332         }
1333         for (ii = 0; ii < count; ii++)
1334         {
1335                 title = (hb_title_t*)hb_list_item(list, ii);
1336                 if (title->duration != 0)
1337                 {
1338                         titles[ii]  = g_strdup_printf ("%d - %02dh%02dm%02ds",
1339                                 title->index, title->hours, title->minutes, title->seconds);
1340                 }
1341                 else
1342                 {
1343                         titles[ii]  = g_strdup_printf ("%d - Unknown Length", title->index);
1344                 }
1345                 gtk_list_store_append(store, &iter);
1346                 gtk_list_store_set(store, &iter, 
1347                                                    0, titles[ii], 
1348                                                    1, TRUE, 
1349                                                    2, titles[ii], 
1350                                                    3, ii, 
1351                                                    4, titles[ii], 
1352                                                    -1);
1353                 title_opts.map[ii].option = titles[ii];
1354                 title_opts.map[ii].shortOpt = titles[ii];
1355                 title_opts.map[ii].ivalue = ii;
1356                 title_opts.map[ii].svalue = titles[ii];
1357         }
1358         titles[ii] = NULL;
1359 }
1360
1361 static gboolean
1362 find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter)
1363 {
1364         gint ivalue;
1365         gboolean foundit = FALSE;
1366         
1367         if (gtk_tree_model_get_iter_first (store, iter))
1368         {
1369                 do
1370                 {
1371                         gtk_tree_model_get(store, iter, 3, &ivalue, -1);
1372                         if (value == ivalue)
1373                         {
1374                                 foundit = TRUE;
1375                                 break;
1376                         }
1377                 } while (gtk_tree_model_iter_next (store, iter));
1378         }
1379         return foundit;
1380 }
1381
1382 void
1383 audio_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1384 {
1385         GtkTreeIter iter;
1386         GtkListStore *store;
1387         hb_list_t  * list = NULL;
1388         hb_title_t * title = NULL;
1389     hb_audio_config_t * audio;
1390         gint ii;
1391         gint count = 0;
1392         
1393         g_debug("audio_track_opts_set ()\n");
1394         store = get_combo_box_store(builder, name);
1395         gtk_list_store_clear(store);
1396         if (h_scan != NULL)
1397         {
1398                 list = hb_get_titles( h_scan );
1399             title = (hb_title_t*)hb_list_item( list, titleindex );
1400                 if (title != NULL)
1401                 {
1402                         count = hb_list_count( title->list_audio );
1403                 }
1404         }
1405         if (count > 10) count = 10;
1406         if (audio_track_opts.map) g_free(audio_track_opts.map);
1407         if (count > 0)
1408         {
1409                 audio_track_opts.count = count;
1410                 audio_track_opts.map = g_malloc(count*sizeof(options_map_t));
1411         }
1412         else
1413         {
1414                 audio_track_opts.count = 1;
1415                 audio_track_opts.map = g_malloc(sizeof(options_map_t));
1416         }
1417         if( count <= 0 )
1418         {
1419                 // No audio. set some default
1420                 gtk_list_store_append(store, &iter);
1421                 gtk_list_store_set(store, &iter, 
1422                                                    0, "No Audio", 
1423                                                    1, TRUE, 
1424                                                    2, "none", 
1425                                                    3, -1, 
1426                                                    4, "none", 
1427                                                    -1);
1428                 audio_track_opts.map[0].option = "No Audio";
1429                 audio_track_opts.map[0].shortOpt = "none";
1430                 audio_track_opts.map[0].ivalue = -1;
1431                 audio_track_opts.map[0].svalue = "none";
1432                 return;
1433         }
1434         for (ii = 0; ii < count; ii++)
1435         {
1436         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, ii );
1437                 gtk_list_store_append(store, &iter);
1438                 gtk_list_store_set(store, &iter, 
1439                                                    0, audio->lang.description, 
1440                                                    1, TRUE, 
1441                                                    2, index_str[ii], 
1442                                                    3, ii, 
1443                                                    4, index_str[ii], 
1444                                                    -1);
1445                 audio_track_opts.map[ii].option = audio->lang.description,
1446                 audio_track_opts.map[ii].shortOpt = index_str[ii];
1447                 audio_track_opts.map[ii].ivalue = ii;
1448                 audio_track_opts.map[ii].svalue = index_str[ii];
1449         }
1450 }
1451
1452
1453 void
1454 subtitle_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1455 {
1456         GtkTreeIter iter;
1457         GtkListStore *store;
1458         hb_list_t  * list = NULL;
1459         hb_title_t * title = NULL;
1460     hb_subtitle_t * subtitle;
1461         gint ii;
1462         gint count = 0;
1463         
1464         g_debug("subtitle_opts_set () %s\n", name);
1465         store = get_combo_box_store(builder, name);
1466         gtk_list_store_clear(store);
1467         if (h_scan != NULL)
1468         {
1469                 list = hb_get_titles( h_scan );
1470             title = (hb_title_t*)hb_list_item( list, titleindex );
1471                 if (title != NULL)
1472                 {
1473                         count = hb_list_count( title->list_subtitle );
1474                 }
1475         }
1476         if (count > 10) count = 10;
1477         if (subtitle_opts.map) g_free(subtitle_opts.map);
1478         if (count > 0)
1479         {
1480                 subtitle_opts.count = count+2;
1481                 subtitle_opts.map = g_malloc((count+2)*sizeof(options_map_t));
1482         }
1483         else
1484         {
1485                 subtitle_opts.count = LANG_TABLE_SIZE+2;
1486                 subtitle_opts.map = g_malloc((LANG_TABLE_SIZE+2)*sizeof(options_map_t));
1487         }
1488         // Add options for "none" and "autoselect"
1489         gtk_list_store_append(store, &iter);
1490         gtk_list_store_set(store, &iter, 
1491                                            0, "None", 
1492                                            1, TRUE, 
1493                                            2, "none", 
1494                                            3, -2, 
1495                                            4, "none", 
1496                                            -1);
1497         subtitle_opts.map[0].option = "None";
1498         subtitle_opts.map[0].shortOpt = "none";
1499         subtitle_opts.map[0].ivalue = -2;
1500         subtitle_opts.map[0].svalue = "none";
1501         gtk_list_store_append(store, &iter);
1502         gtk_list_store_set(store, &iter, 
1503                                            0, "Autoselect", 
1504                                            1, TRUE, 
1505                                            2, "auto", 
1506                                            3, -1, 
1507                                            4, "auto", 
1508                                            -1);
1509         subtitle_opts.map[0].option = "Same as audio";
1510         subtitle_opts.map[0].shortOpt = "auto";
1511         subtitle_opts.map[0].ivalue = -1;
1512         subtitle_opts.map[0].svalue = "auto";
1513         if (count >0)
1514         {
1515                 for (ii = 0; ii < count; ii++)
1516                 {
1517                 subtitle = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
1518                         gtk_list_store_append(store, &iter);
1519                         gtk_list_store_set(store, &iter, 
1520                                                 0, subtitle->lang, 
1521                                                 1, TRUE, 
1522                                                 2, subtitle->iso639_2, 
1523                                                 3, ii, 
1524                                                 4, subtitle->iso639_2, 
1525                                                 -1);
1526                         subtitle_opts.map[ii+2].option = subtitle->lang;
1527                         subtitle_opts.map[ii+2].shortOpt = subtitle->iso639_2;
1528                         subtitle_opts.map[ii+2].ivalue = ii;
1529                         subtitle_opts.map[ii+2].svalue = subtitle->iso639_2;
1530                 }
1531         }
1532         else
1533         {
1534                 for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1535                 {
1536                         gtk_list_store_append(store, &iter);
1537                         gtk_list_store_set(store, &iter, 
1538                                 0, ghb_language_table[ii].eng_name, 
1539                                 1, TRUE, 
1540                                 2, ghb_language_table[ii].iso639_2, 
1541                                 3, ii, 
1542                                 4, ghb_language_table[ii].iso639_2, 
1543                                 -1);
1544                         subtitle_opts.map[ii+2].option = ghb_language_table[ii].eng_name;
1545                         subtitle_opts.map[ii+2].shortOpt = ghb_language_table[ii].iso639_2;
1546                         subtitle_opts.map[ii+2].ivalue = ii;
1547                         subtitle_opts.map[ii+2].svalue = ghb_language_table[ii].iso639_2;
1548                 }
1549         }
1550 }
1551
1552 gint
1553 ghb_longest_title()
1554 {
1555         hb_list_t  * list;
1556         hb_title_t * title;
1557         gint ii;
1558         gint count = 0;
1559         guint64 longest = 0;
1560         gint titleindex = 0;
1561         
1562         g_debug("ghb_longest_title ()\n");
1563         if (h_scan == NULL) return 0;
1564         list = hb_get_titles( h_scan );
1565         count = hb_list_count( list );
1566         if (count > 100) count = 100;
1567         for (ii = 0; ii < count; ii++)
1568         {
1569                 title = (hb_title_t*)hb_list_item(list, ii);
1570                 if (title->duration > longest)
1571                 {
1572                         titleindex = ii;
1573                         longest = title->duration;
1574                 }
1575         }
1576         return titleindex;
1577 }
1578
1579 gint
1580 ghb_find_audio_track(gint titleindex, const gchar *lang, gint index)
1581 {
1582         hb_list_t  * list;
1583         hb_title_t * title;
1584     hb_audio_config_t * audio;
1585         gint ii;
1586         gint count = 0;
1587         gint track = -1;
1588         gint match = 0;
1589         
1590         g_debug("find_audio_track ()\n");
1591         if (h_scan != NULL)
1592         {
1593                 list = hb_get_titles( h_scan );
1594             title = (hb_title_t*)hb_list_item( list, titleindex );
1595                 if (title != NULL)
1596                 {
1597                         count = hb_list_count( title->list_audio );
1598                 }
1599         }
1600         if (count > 10) count = 10;
1601         for (ii = 0; ii < count; ii++)
1602         {
1603         audio = (hb_audio_config_t*)hb_list_audio_config_item( title->list_audio, ii );
1604                 if ((strcmp(lang, audio->lang.iso639_2) == 0) ||
1605                         (strcmp(lang, "und") == 0))
1606                 {
1607                         if (index == match)
1608                         {
1609                                 track = ii;
1610                                 break;
1611                         }
1612                         match++;
1613                 }
1614         }
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 = crop_width;
2324                 max_height = 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_container(signal_user_data_t *ud)
2614 {
2615         gint container;
2616         gchar *message;
2617
2618         container = ghb_settings_combo_int(ud->settings, "FileFormat");
2619         if (container == HB_MUX_MP4)
2620         {
2621                 const GValue *audio_list;
2622                 gboolean httpopt;
2623
2624                 audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2625                 httpopt = ghb_settings_get_boolean(ud->settings, "Mp4HttpOptimize");
2626                 if (httpopt && ghb_ac3_in_audio_list(audio_list))
2627                 {
2628                         message = g_strdup_printf(
2629                                         "AC3 audio in HTTP optimized MP4 is not supported.\n\n"
2630                                         "You should choose a different audio codec.\n"
2631                                         "If you continue, FAAC will be chosen for you.");
2632                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2633                         {
2634                                 g_free(message);
2635                                 return FALSE;
2636                         }
2637                         g_free(message);
2638
2639                         gint count, ii;
2640
2641                         count = ghb_array_len(audio_list);
2642                         for (ii = 0; ii < count; ii++)
2643                         {
2644                                 GValue *asettings;
2645
2646                                 asettings = ghb_array_get_nth(audio_list, ii);
2647                                 gint acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
2648                                 if (acodec == HB_ACODEC_AC3)
2649                                 {
2650                                         GValue *value;
2651                                         value = get_acodec_value(HB_ACODEC_FAAC);
2652                                         ghb_settings_take_value(asettings, "AudioEncoder", value);
2653                                         value = get_abitrate_value(160);
2654                                         ghb_settings_take_value(asettings, "AudioBitrate", value);
2655                                 }
2656                         }
2657                 }
2658         }
2659         return TRUE;
2660 }
2661
2662 gboolean
2663 ghb_validate_audio(signal_user_data_t *ud)
2664 {
2665         hb_list_t  * list;
2666         hb_title_t * title;
2667         gchar *message;
2668         GValue *value;
2669
2670         if (h_scan == NULL) return FALSE;
2671         list = hb_get_titles( h_scan );
2672         if( !hb_list_count( list ) )
2673         {
2674                 /* No valid title, stop right there */
2675                 g_message("No title found.\n");
2676                 return FALSE;
2677         }
2678
2679         gint titleindex;
2680
2681         titleindex = ghb_settings_combo_int(ud->settings, "title");
2682     title = hb_list_item( list, titleindex );
2683         if (title == NULL) return FALSE;
2684         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
2685
2686         const GValue *audio_list;
2687         gint count, ii;
2688
2689         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2690         count = ghb_array_len(audio_list);
2691         for (ii = 0; ii < count; ii++)
2692         {
2693                 GValue *asettings;
2694             hb_audio_config_t *taudio;
2695
2696                 asettings = ghb_array_get_nth(audio_list, ii);
2697                 gint track = ghb_settings_combo_int(asettings, "AudioTrack");
2698                 gint codec = ghb_settings_combo_int(asettings, "AudioEncoder");
2699         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
2700                                                                                         title->list_audio, track );
2701                 if ((taudio->in.codec != HB_ACODEC_AC3) && (codec == HB_ACODEC_AC3))
2702                 {
2703                         // Not supported.  AC3 is passthrough only, so input must be AC3
2704                         message = g_strdup_printf(
2705                                                 "The source does not support AC3 Pass-Thru.\n\n"
2706                                                 "You should choose a different audio codec.\n"
2707                                                 "If you continue, one will be chosen for you.");
2708                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2709                         {
2710                                 g_free(message);
2711                                 return FALSE;
2712                         }
2713                         g_free(message);
2714                         if (mux == HB_MUX_AVI)
2715                         {
2716                                 codec = HB_ACODEC_LAME;
2717                         }
2718                         else
2719                         {
2720                                 codec = HB_ACODEC_FAAC;
2721                         }
2722                         value = get_acodec_value(codec);
2723                         ghb_settings_take_value(asettings, "AudioEncoder", value);
2724                 }
2725                 gchar *a_unsup = NULL;
2726                 gchar *mux_s = NULL;
2727                 if (mux == HB_MUX_MP4)
2728                 { 
2729                         mux_s = "MP4";
2730                         // mp4/mp3|vorbis combination is not supported.
2731                         if (codec == HB_ACODEC_LAME)
2732                         {
2733                                 a_unsup = "MP3";
2734                                 codec = HB_ACODEC_FAAC;
2735                         }
2736                         if (codec == HB_ACODEC_VORBIS)
2737                         {
2738                                 a_unsup = "Vorbis";
2739                                 codec = HB_ACODEC_FAAC;
2740                         }
2741                 }
2742                 else if (mux == HB_MUX_AVI)
2743                 {
2744                         mux_s = "AVI";
2745                         // avi/faac|vorbis combination is not supported.
2746                         if (codec == HB_ACODEC_FAAC)
2747                         {
2748                                 a_unsup = "FAAC";
2749                                 codec = HB_ACODEC_LAME;
2750                         }
2751                         if (codec == HB_ACODEC_VORBIS)
2752                         {
2753                                 a_unsup = "Vorbis";
2754                                 codec = HB_ACODEC_LAME;
2755                         }
2756                 }
2757                 else if (mux == HB_MUX_OGM)
2758                 {
2759                         mux_s = "OGM";
2760                         // avi/faac|vorbis combination is not supported.
2761                         if (codec == HB_ACODEC_FAAC)
2762                         {
2763                                 a_unsup = "FAAC";
2764                                 codec = HB_ACODEC_VORBIS;
2765                         }
2766                         if (codec == HB_ACODEC_AC3)
2767                         {
2768                                 a_unsup = "AC-3";
2769                                 codec = HB_ACODEC_VORBIS;
2770                         }
2771                 }
2772                 if (a_unsup)
2773                 {
2774                         message = g_strdup_printf(
2775                                                 "%s is not supported in the %s container.\n\n"
2776                                                 "You should choose a different audio codec.\n"
2777                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
2778                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2779                         {
2780                                 g_free(message);
2781                                 return FALSE;
2782                         }
2783                         g_free(message);
2784                         value = get_acodec_value(codec);
2785                         ghb_settings_take_value(asettings, "AudioEncoder", value);
2786                 }
2787                 gint mix = ghb_settings_combo_int (asettings, "AudioMixdown");
2788                 gboolean allow_mono = TRUE;
2789                 gboolean allow_stereo = TRUE;
2790                 gboolean allow_dolby = TRUE;
2791                 gboolean allow_dpl2 = TRUE;
2792                 gboolean allow_6ch = TRUE;
2793                 allow_mono =
2794                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2795                         (codec != HB_ACODEC_LAME);
2796                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
2797                 allow_stereo =
2798                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
2799                 allow_dolby =
2800                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
2801                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
2802                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
2803                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
2804                 allow_6ch =
2805                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2806                         (codec != HB_ACODEC_LAME) &&
2807                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
2808                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
2809
2810                 gchar *mix_unsup = NULL;
2811                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
2812                 {
2813                         mix_unsup = "mono";
2814                 }
2815                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
2816                 {
2817                         mix_unsup = "stereo";
2818                 }
2819                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
2820                 {
2821                         mix_unsup = "Dolby";
2822                 }
2823                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
2824                 {
2825                         mix_unsup = "Dolby Pro Logic II";
2826                 }
2827                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
2828                 {
2829                         mix_unsup = "6 Channel";
2830                 }
2831                 if (mix_unsup)
2832                 {
2833                         message = g_strdup_printf(
2834                                                 "The source audio does not support %s mixdown.\n\n"
2835                                                 "You should choose a different mixdown.\n"
2836                                                 "If you continue, one will be chosen for you.", mix_unsup);
2837                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2838                         {
2839                                 g_free(message);
2840                                 return FALSE;
2841                         }
2842                         g_free(message);
2843                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
2844                         value = get_amix_value(mix);
2845                         ghb_settings_take_value(asettings, "AudioMixdown", value);
2846                 }
2847         }
2848         return TRUE;
2849 }
2850
2851 gboolean
2852 ghb_validate_vquality(GValue *settings)
2853 {
2854         gint vcodec;
2855         gchar *message;
2856         gint min, max;
2857
2858         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
2859         vcodec = ghb_settings_combo_int(settings, "VideoEncoder");
2860         gdouble vquality;
2861         vquality = ghb_settings_get_double(settings, "VideoQualitySlider");
2862         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
2863         {
2864                 if (!ghb_settings_get_boolean(settings, "directqp"))
2865                 {
2866                         vquality *= 100.0;
2867                         if (vcodec != HB_VCODEC_X264)
2868                         {
2869                                 min = 68;
2870                                 max = 97;
2871                         }
2872                         else
2873                         {
2874                                 min = 40;
2875                                 max = 70;
2876                         }
2877                 }
2878                 else
2879                 {
2880                         if (vcodec == HB_VCODEC_X264)
2881                         {
2882                                 min = 16;
2883                                 max = 30;
2884                         }
2885                         else if (vcodec == HB_VCODEC_FFMPEG)
2886                         {
2887                                 min = 1;
2888                                 max = 8;
2889                         }
2890                         else
2891                         {
2892                                 min = 68;
2893                                 max = 97;
2894                                 vquality *= 100.0;
2895                         }
2896                 }
2897                 if (vquality < min || vquality > max)
2898                 {
2899                         message = g_strdup_printf(
2900                                                 "Interesting video quality choise: %d\n\n"
2901                                                 "Typical values range from %d to %d.\n"
2902                                                 "Are you sure you wish to use this setting?",
2903                                                 (gint)vquality, min, max);
2904                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
2905                                                                         "Cancel", "Continue"))
2906                         {
2907                                 g_free(message);
2908                                 return FALSE;
2909                         }
2910                         g_free(message);
2911                 }
2912         }
2913         return TRUE;
2914 }
2915
2916 void
2917 ghb_add_job(GValue *js, gint unique_id)
2918 {
2919         hb_list_t  * list;
2920         hb_title_t * title;
2921         hb_job_t   * job;
2922         static gchar *x264opts;
2923         gint sub_id = 0;
2924         gboolean tweaks = FALSE;
2925         gchar *detel_str = NULL;
2926         gchar *decomb_str = NULL;
2927         gchar *deint_str = NULL;
2928         gchar *deblock_str = NULL;
2929         gchar *denoise_str = NULL;
2930         gchar *dest_str = NULL;
2931
2932         g_debug("ghb_add_job()\n");
2933         if (h_queue == NULL) return;
2934         list = hb_get_titles( h_queue );
2935         if( !hb_list_count( list ) )
2936         {
2937                 /* No valid title, stop right there */
2938                 g_message("No title found.\n");
2939                 return;
2940         }
2941
2942         // Since I'm doing a scan of the single title I want just prior 
2943         // to adding the job, there is only the one title to choose from.
2944         //gint titleindex = ghb_settings_get_int(js, "title");
2945     gint titleindex = 0;
2946     title = hb_list_item( list, titleindex );
2947         if (title == NULL) return;
2948
2949         /* Set job settings */
2950         job   = title->job;
2951         if (job == NULL) return;
2952
2953         tweaks = ghb_settings_get_boolean(js, "allow_tweaks");
2954         job->mux = ghb_settings_combo_int(js, "FileFormat");
2955         if (job->mux == HB_MUX_MP4)
2956         {
2957                 job->largeFileSize = ghb_settings_get_boolean(js, "Mp4LargeFile");
2958                 job->mp4_optimize = ghb_settings_get_boolean(js, "Mp4HttpOptimize");
2959         }
2960         else
2961         {
2962                 job->largeFileSize = FALSE;
2963                 job->mp4_optimize = FALSE;
2964         }
2965         gint chapter_start, chapter_end;
2966         chapter_start = ghb_settings_get_int(js, "start_chapter");
2967         chapter_end = ghb_settings_get_int(js, "end_chapter");
2968         gint num_chapters = hb_list_count(title->list_chapter);
2969         job->chapter_start = MIN( num_chapters, chapter_start );
2970         job->chapter_end   = MAX( job->chapter_start, chapter_end );
2971
2972         job->chapter_markers = ghb_settings_get_boolean(js, "ChapterMarkers");
2973         if ( job->chapter_markers )
2974         {
2975                 GValue *chapters;
2976                 GValue *chapter;
2977                 gint chap;
2978                 gint count;
2979                 
2980                 chapters = ghb_settings_get_value(js, "chapter_list");
2981                 count = ghb_array_len(chapters);
2982                 for(chap = chapter_start; chap <= chapter_end; chap++)
2983                 {
2984                         hb_chapter_t * chapter_s;
2985                         gchar *name;
2986                         
2987                         name = NULL;
2988                         if (chap-1 < count)
2989                         {
2990                                 chapter = ghb_array_get_nth(chapters, chap-1);
2991                                 name = ghb_value_string(chapter); 
2992                         }
2993                         if (name == NULL)
2994                         {
2995                                 name = g_strdup_printf ("Chapter %2d", chap);
2996                         }
2997                         chapter_s = hb_list_item( job->title->list_chapter, chap - 1);
2998                         strncpy(chapter_s->title, name, 1023);
2999                         chapter_s->title[1023] = '\0';
3000                         g_free(name);
3001                 }
3002         }
3003         job->crop[0] = ghb_settings_get_int(js, "PictureTopCrop");
3004         job->crop[1] = ghb_settings_get_int(js, "PictureBottomCrop");
3005         job->crop[2] = ghb_settings_get_int(js, "PictureLeftCrop");
3006         job->crop[3] = ghb_settings_get_int(js, "PictureRightCrop");
3007
3008         
3009         gboolean decomb = ghb_settings_get_boolean(js, "PictureDecomb");
3010         gint deint = ghb_settings_combo_int(js, 
3011                                         tweaks ? "tweak_PictureDeinterlace":"PictureDeinterlace");
3012         if (!decomb)
3013                 job->deinterlace = (deint != 0) ? 1 : 0;
3014         else
3015                 job->deinterlace = 0;
3016     job->grayscale   = ghb_settings_get_boolean(js, "VideoGrayScale");
3017
3018         gboolean anamorphic = ghb_settings_get_boolean(js, "anamorphic");
3019         gboolean round_dimensions = ghb_settings_get_boolean(js, "ModDimensions");
3020         if (round_dimensions && anamorphic)
3021         {
3022                 job->pixel_ratio = 2;
3023                 job->modulus = 16;
3024         }
3025         else if (anamorphic)
3026         {
3027                 // Huh! I thought I wanted to use pixel_ratio 1 for this case, but
3028                 // when its 1, libhb discards the width and height and uses original
3029                 // title dims - crop.  Thats not what I want.
3030                 // Also, x264 requires things to divisible by 2.
3031                 job->pixel_ratio = 2;
3032                 job->modulus = 2;
3033         }
3034         else
3035         {
3036                 job->pixel_ratio = 0;
3037                 job->modulus = 2;
3038         }
3039         /* Add selected filters */
3040         job->filters = hb_list_init();
3041         gint vrate = ghb_settings_combo_int(js, "VideoFramerate");
3042         if( vrate == 0 && ghb_settings_get_boolean(js, "PictureDetelecine" ) )
3043                 job->vfr = 1;
3044         else
3045                 job->vfr = 0;
3046
3047         if( ghb_settings_get_boolean(js, "PictureDetelecine" ) )
3048         {
3049                 hb_filter_detelecine.settings = NULL;
3050                 if (tweaks)
3051                 {
3052                         detel_str = ghb_settings_get_string(js, "tweak_PictureDetelecine");
3053                         if (detel_str && detel_str[0])
3054                         {
3055                                 hb_filter_detelecine.settings = detel_str;
3056                         }
3057                 }
3058                 hb_list_add( job->filters, &hb_filter_detelecine );
3059         }
3060         if( decomb )
3061         {
3062                 // Use default settings
3063                 hb_filter_decomb.settings = NULL;
3064                 if (tweaks)
3065                 {
3066                         decomb_str = ghb_settings_get_string(js, "tweak_PictureDecomb");
3067                         if (decomb_str && decomb_str[0])
3068                         {
3069                                 hb_filter_decomb.settings = (gchar*)decomb_str;
3070                         }
3071                 }
3072                 hb_list_add( job->filters, &hb_filter_decomb );
3073         }
3074         if( job->deinterlace )
3075         {
3076                 if (deint > 0)
3077                         deint_str = g_strdup(deint_opts.map[deint].svalue);
3078                 else
3079                         deint_str = ghb_settings_get_string(js, 
3080                                         tweaks ? "tweak_PictureDeinterlace" : "PictureDeinterlace");
3081                 hb_filter_deinterlace.settings = deint_str;
3082                 hb_list_add( job->filters, &hb_filter_deinterlace );
3083         }
3084         gint deblock = ghb_settings_get_int(js, "PictureDeblock");
3085         if( deblock >= 5 )
3086         {
3087                 deblock_str = g_strdup_printf("%d", deblock);
3088                 hb_filter_deblock.settings = deblock_str;
3089                 hb_list_add( job->filters, &hb_filter_deblock );
3090         }
3091         gint denoise = ghb_settings_combo_int(js, 
3092                                         tweaks ? "tweak_PictureDenoise" : "PictureDenoise");
3093         if( denoise != 0 )
3094         {
3095                 if (denoise > 0)
3096                         denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
3097                 else
3098                         denoise_str = (gchar*)ghb_settings_get_string(
3099                                 js, tweaks ? "tweak_PictureDenoise" : "PictureDenoise");
3100                 hb_filter_denoise.settings = denoise_str;
3101                 hb_list_add( job->filters, &hb_filter_denoise );
3102         }
3103         job->width = ghb_settings_get_int(js, "scale_width");
3104         job->height = ghb_settings_get_int(js, "scale_height");
3105
3106         job->vcodec = ghb_settings_combo_int(js, "VideoEncoder");
3107         if ((job->mux == HB_MUX_MP4 || job->mux == HB_MUX_AVI) && 
3108                 (job->vcodec == HB_VCODEC_THEORA))
3109         {
3110                 // mp4|avi/theora combination is not supported.
3111                 job->vcodec = HB_VCODEC_XVID;
3112         }
3113         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
3114         {
3115                 job->ipod_atom = ghb_settings_get_boolean(js, "Mp4iPodCompatible");
3116         }
3117         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
3118         {
3119                 gdouble vquality;
3120                 vquality = ghb_settings_get_double(js, "VideoQualitySlider");
3121                 if (!ghb_settings_get_boolean(js, "directqp"))
3122                 {
3123                         if (vquality == 0.0) vquality = 0.01;
3124                         if (vquality == 1.0) vquality = 0.0;
3125                 }
3126                 job->vquality =  vquality;
3127                 job->vbitrate = 0;
3128         }
3129         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
3130         {
3131                 job->vquality = -1.0;
3132                 job->vbitrate = ghb_settings_get_int(js, "VideoAvgBitrate");
3133         }
3134         // AVI container does not support variable frame rate.
3135         if (job->mux == HB_MUX_AVI)
3136         {
3137                 job->vfr = FALSE;
3138                 job->cfr = 1;
3139         }
3140
3141         if( vrate == 0 )
3142         {
3143                 job->vrate = title->rate;
3144                 job->vrate_base = title->rate_base;
3145                 job->cfr = 0;
3146         }
3147         else
3148         {
3149                 job->vrate = 27000000;
3150                 job->vrate_base = vrate;
3151                 job->cfr = 1;
3152         }
3153         // First remove any audios that are already in the list
3154         // This happens if you are encoding the same title a second time.
3155         gint num_audio_tracks = hb_list_count(job->list_audio);
3156         gint ii;
3157     for(ii = 0; ii < num_audio_tracks; ii++)
3158     {
3159         hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
3160         hb_list_rem(job->list_audio, audio);
3161     }
3162
3163         const GValue *audio_list;
3164         gint count;
3165         gint tcount = 0;
3166         
3167         audio_list = ghb_settings_get_value(js, "audio_list");
3168         count = ghb_array_len(audio_list);
3169         for (ii = 0; ii < count; ii++)
3170         {
3171                 GValue *asettings;
3172             hb_audio_config_t audio;
3173             hb_audio_config_t *taudio;
3174
3175                 hb_audio_config_init(&audio);
3176                 asettings = ghb_array_get_nth(audio_list, ii);
3177                 audio.in.track = ghb_settings_get_int(asettings, "AudioTrack");
3178                 audio.out.track = tcount;
3179                 audio.out.codec = ghb_settings_combo_int(asettings, "AudioEncoder");
3180         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
3181                                                                         title->list_audio, audio.in.track );
3182                 if ((taudio->in.codec != HB_ACODEC_AC3) && (audio.out.codec == HB_ACODEC_AC3))
3183                 {
3184                         // Not supported.  AC3 is passthrough only, so input must be AC3
3185                         if (job->mux == HB_MUX_AVI)
3186                         {
3187                                 audio.out.codec = HB_ACODEC_LAME;
3188                         }
3189                         else
3190                         {
3191                                 audio.out.codec = HB_ACODEC_FAAC;
3192                         }
3193                 }
3194                 if ((job->mux == HB_MUX_MP4) && 
3195                         ((audio.out.codec == HB_ACODEC_LAME) ||
3196                         (audio.out.codec == HB_ACODEC_VORBIS)))
3197                 {
3198                         // mp4/mp3|vorbis combination is not supported.
3199                         audio.out.codec = HB_ACODEC_FAAC;
3200                 }
3201                 if ((job->mux == HB_MUX_AVI) && 
3202                         ((audio.out.codec == HB_ACODEC_FAAC) ||
3203                         (audio.out.codec == HB_ACODEC_VORBIS)))
3204                 {
3205                         // avi/faac|vorbis combination is not supported.
3206                         audio.out.codec = HB_ACODEC_LAME;
3207                 }
3208                 if ((job->mux == HB_MUX_OGM) && 
3209                         ((audio.out.codec == HB_ACODEC_FAAC) ||
3210                         (audio.out.codec == HB_ACODEC_AC3)))
3211                 {
3212                         // ogm/faac|ac3 combination is not supported.
3213                         audio.out.codec = HB_ACODEC_VORBIS;
3214                 }
3215         audio.out.dynamic_range_compression = 
3216                         ghb_settings_get_double(asettings, "AudioTrackDRCSlider");
3217                 // It would be better if this were done in libhb for us, but its not yet.
3218                 if (audio.out.codec == HB_ACODEC_AC3 || audio.out.codec == HB_ACODEC_DCA)
3219                 {
3220                         audio.out.mixdown = 0;
3221                 }
3222                 else
3223                 {
3224                         audio.out.mixdown = ghb_settings_combo_int(asettings, "AudioMixdown");
3225                         // Make sure the mixdown is valid and pick a new one if not.
3226                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
3227                                 audio.in.track, audio.out.codec, audio.out.mixdown);
3228                         audio.out.bitrate = 
3229                                 ghb_settings_combo_int(asettings, "AudioBitrate");
3230                         gint srate = ghb_settings_combo_int(asettings, "AudioSamplerate");
3231                         if (srate == 0) // 0 is same as source
3232                                 audio.out.samplerate = taudio->in.samplerate;
3233                         else
3234                                 audio.out.samplerate = srate;
3235                 }
3236
3237                 // Add it to the jobs audio list
3238         hb_audio_add( job, &audio );
3239                 tcount++;
3240         }
3241         // I was tempted to move this up with the reset of the video quality
3242         // settings, but I suspect the settings above need to be made
3243         // first in order for hb_calc_bitrate to be accurate.
3244         if (ghb_settings_get_boolean(js, "vquality_type_target"))
3245         {
3246                 gint size;
3247                 
3248                 size = ghb_settings_get_int(js, "VideoTargetSize");
3249         job->vbitrate = hb_calc_bitrate( job, size );
3250                 job->vquality = -1.0;
3251         }
3252
3253         dest_str = ghb_settings_get_string(js, "destination");
3254         job->file = dest_str;
3255         job->crf = ghb_settings_get_boolean(js, "constant_rate_factor");
3256         // TODO: libhb holds onto a reference to the x264opts and is not
3257         // finished with it until encoding the job is done.  But I can't
3258         // find a way to get at the job before it is removed in order to
3259         // free up the memory I am allocating here.
3260         // The short story is THIS LEAKS.
3261         x264opts = ghb_build_x264opts_string(js);
3262         
3263         if( x264opts != NULL && *x264opts != '\0' )
3264         {
3265                 job->x264opts = x264opts;
3266         }
3267         else /*avoids a bus error crash when options aren't specified*/
3268         {
3269                 job->x264opts =  NULL;
3270         }
3271         gint subtitle;
3272         gchar *slang = ghb_settings_get_string(js, "Subtitles");
3273         subtitle = -2; // default to none
3274         if (strcmp(slang, "auto") == 0)
3275         {
3276                 subtitle = -1;
3277         }
3278         else
3279         {
3280                 gint scount;
3281         hb_subtitle_t * subt;
3282
3283                 scount = hb_list_count(title->list_subtitle);
3284                 for (ii = 0; ii < scount; ii++)
3285                 {
3286                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
3287                         if (strcmp(slang, subt->iso639_2) == 0)
3288                         {
3289                                 subtitle = ii;
3290                                 break;
3291                         }
3292                 }
3293         }
3294         gboolean forced_subtitles = ghb_settings_get_boolean(js, "SubtitlesForced");
3295         job->subtitle_force = forced_subtitles;
3296         if (subtitle >= 0)
3297                 job->subtitle = subtitle;
3298         else
3299                 job->subtitle = -1;
3300         if (subtitle == -1)
3301         {
3302                 // Subtitle scan. Look for subtitle matching audio language
3303                 char *x264opts_tmp;
3304
3305                 /*
3306                  * When subtitle scan is enabled do a fast pre-scan job
3307                  * which will determine which subtitles to enable, if any.
3308                  */
3309                 job->pass = -1;
3310                 job->indepth_scan = 1;
3311
3312                 x264opts_tmp = job->x264opts;
3313                 job->x264opts = NULL;
3314
3315                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
3316                 *(job->select_subtitle) = NULL;
3317
3318                 /*
3319                  * Add the pre-scan job
3320                  */
3321                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3322                 hb_add( h_queue, job );
3323                 //if (job->x264opts != NULL)
3324                 //      g_free(job->x264opts);
3325
3326                 job->x264opts = x264opts_tmp;
3327         }
3328         else
3329         {
3330                 job->select_subtitle = NULL;
3331         }
3332         if( ghb_settings_get_boolean(js, "VideoTwoPass") &&
3333                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
3334         {
3335                 /*
3336                  * If subtitle_scan is enabled then only turn it on
3337                  * for the second pass and then off again for the
3338                  * second.
3339                  */
3340                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
3341                 job->select_subtitle = NULL;
3342                 job->pass = 1;
3343                 job->indepth_scan = 0;
3344                 gchar *x264opts2 = NULL;
3345                 if (x264opts)
3346                 {
3347                         x264opts2 = g_strdup(x264opts);
3348                 }
3349                 /*
3350                  * If turbo options have been selected then append them
3351                  * to the x264opts now (size includes one ':' and the '\0')
3352                  */
3353                 if( ghb_settings_get_boolean(js, "VideoTurboTwoPass") )
3354                 {
3355                         char *tmp_x264opts;
3356
3357                         if ( x264opts )
3358                         {
3359                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, turbo_opts);
3360                                 g_free(x264opts);
3361                         } 
3362                         else 
3363                         {
3364                                 /*
3365                                  * No x264opts to modify, but apply the turbo options
3366                                  * anyway as they may be modifying defaults
3367                                  */
3368                                 tmp_x264opts = g_strdup_printf("%s", turbo_opts);
3369                         }
3370                         x264opts = tmp_x264opts;
3371
3372                         job->x264opts = x264opts;
3373                 }
3374                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3375                 hb_add( h_queue, job );
3376                 //if (job->x264opts != NULL)
3377                 //      g_free(job->x264opts);
3378
3379                 job->select_subtitle = subtitle_tmp;
3380                 job->pass = 2;
3381                 /*
3382                  * On the second pass we turn off subtitle scan so that we
3383                  * can actually encode using any subtitles that were auto
3384                  * selected in the first pass (using the whacky select-subtitle
3385                  * attribute of the job).
3386                  */
3387                 job->indepth_scan = 0;
3388                 job->x264opts = x264opts2;
3389                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3390                 hb_add( h_queue, job );
3391                 //if (job->x264opts != NULL)
3392                 //      g_free(job->x264opts);
3393         }
3394         else
3395         {
3396                 job->indepth_scan = 0;
3397                 job->pass = 0;
3398                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3399                 hb_add( h_queue, job );
3400                 //if (job->x264opts != NULL)
3401                 //      g_free(job->x264opts);
3402         }
3403         if (detel_str) g_free(detel_str);
3404         if (decomb_str) g_free(decomb_str);
3405         if (deint_str) g_free(deint_str);
3406         if (deblock_str) g_free(deblock_str);
3407         if (denoise_str) g_free(denoise_str);
3408         if (dest_str) g_free(dest_str);
3409 }
3410
3411 void
3412 ghb_remove_job(gint unique_id)
3413 {
3414     hb_job_t * job;
3415     gint ii;
3416         
3417         // Multiples passes all get the same id
3418         // remove them all.
3419         // Go backwards through list, so reordering doesn't screw me.
3420         ii = hb_count(h_queue) - 1;
3421     while ((job = hb_job(h_queue, ii--)) != NULL)
3422     {
3423         if ((job->sequence_id & 0xFFFFFF) == unique_id)
3424                         hb_rem(h_queue, job);
3425     }
3426 }
3427
3428 void
3429 ghb_start_queue()
3430 {
3431         hb_start( h_queue );
3432 }
3433
3434 void
3435 ghb_stop_queue()
3436 {
3437         hb_stop( h_queue );
3438 }
3439
3440 void
3441 ghb_pause_queue()
3442 {
3443     hb_state_t s;
3444     hb_get_state2( h_queue, &s );
3445
3446     if( s.state == HB_STATE_PAUSED )
3447     {
3448         hb_resume( h_queue );
3449     }
3450     else
3451     {
3452         hb_pause( h_queue );
3453     }
3454 }
3455
3456 #define RED_HEIGHT      720.0
3457 #define RED_WIDTH       1280.0
3458
3459 GdkPixbuf*
3460 ghb_get_preview_image(
3461         gint titleindex, 
3462         gint index, 
3463         GValue *settings, 
3464         gboolean borders)
3465 {
3466         hb_title_t *title;
3467         hb_list_t  *list;
3468         
3469         list = hb_get_titles( h_scan );
3470         if( !hb_list_count( list ) )
3471         {
3472                 /* No valid title, stop right there */
3473                 return NULL;
3474         }
3475     title = hb_list_item( list, titleindex );
3476         if (title == NULL) return NULL;
3477         if (title->job == NULL) return NULL;
3478         set_preview_job_settings(title->job, settings);
3479
3480         // hb_get_preview can't handle sizes that are larger than the original title
3481         // dimensions
3482         if (title->job->width > title->width)
3483                 title->job->width = title->width;
3484         
3485         if (title->job->height > title->height)
3486                 title->job->height = title->height;
3487         // And also creates artifacts if the width is not a multiple of 8
3488         //title->job->width = ((title->job->width + 4) >> 3) << 3;
3489         // And the height must be a multiple of 2
3490         //title->job->height = ((title->job->height + 1) >> 1) << 1;
3491         
3492         // Make sure we have a big enough buffer to receive the image from libhb. libhb
3493         // creates images with a one-pixel border around the original content. Hence we
3494         // add 2 pixels horizontally and vertically to the buffer size.
3495         gint srcWidth = title->width + 2;
3496         gint srcHeight= title->height + 2;
3497         gint dstWidth = title->width;
3498         gint dstHeight= title->height;
3499         gint borderTop = 1;
3500         gint borderLeft = 1;
3501     if (borders)
3502     {
3503         //     |<---------- title->width ----------->|
3504         //     |   |<---- title->job->width ---->|   |
3505         //     |   |                             |   |
3506         //     .......................................
3507         //     ....+-----------------------------+....
3508         //     ....|                             |....<-- gray border
3509         //     ....|                             |....
3510         //     ....|                             |....
3511         //     ....|                             |<------- image
3512         //     ....|                             |....
3513         //     ....|                             |....
3514         //     ....|                             |....
3515         //     ....|                             |....
3516         //     ....|                             |....
3517         //     ....+-----------------------------+....
3518         //     .......................................
3519                 dstWidth = title->job->width;
3520         dstHeight = title->job->height;
3521                 borderTop = (srcHeight - dstHeight) / 2;
3522                 borderLeft = (srcWidth - dstWidth) / 2;
3523                 g_debug("boarders removed\n");
3524         }
3525
3526         g_debug("src %d x %d\n", srcWidth, srcHeight);
3527         g_debug("dst %d x %d\n", dstWidth, dstHeight);
3528         g_debug("job dim %d x %d\n", title->job->width, title->job->height);
3529         g_debug("title crop %d:%d:%d:%d\n", 
3530                         title->crop[0],
3531                         title->crop[1],
3532                         title->crop[2],
3533                         title->crop[3]);
3534         g_debug("job crop %d:%d:%d:%d\n", 
3535                         title->job->crop[0],
3536                         title->job->crop[1],
3537                         title->job->crop[2],
3538                         title->job->crop[3]);
3539         static guint8 *buffer = NULL;
3540         static gint bufferSize = 0;
3541
3542         gint newSize;
3543         newSize = srcWidth * srcHeight * 4;
3544         if( bufferSize < newSize )
3545         {
3546                 bufferSize = newSize;
3547                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
3548         }
3549         hb_get_preview( h_scan, title, index, buffer );
3550
3551         // Create an GdkPixbuf and copy the libhb image into it, converting it from
3552         // libhb's format something suitable. Along the way, we'll strip off the
3553         // border around libhb's image.
3554         
3555         // The image data returned by hb_get_preview is 4 bytes per pixel, BGRA format.
3556         // Alpha is ignored.
3557
3558         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
3559         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
3560         
3561         guint32 *src = (guint32*)buffer;
3562         guint8 *dst = pixels;
3563         src += borderTop * srcWidth;    // skip top rows in src to get to first row of dst
3564         src += borderLeft;              // skip left pixels in src to get to first pixel of dst
3565         gint ii, jj;
3566         gint channels = gdk_pixbuf_get_n_channels (preview);
3567         gint stride = gdk_pixbuf_get_rowstride (preview);
3568         guint8 *tmp;
3569         for (ii = 0; ii < dstHeight; ii++)
3570         {
3571                 tmp = dst;
3572                 for (jj = 0; jj < dstWidth; jj++)
3573                 {
3574                         tmp[0] = src[0] >> 16;
3575                         tmp[1] = src[0] >> 8;
3576                         tmp[2] = src[0] >> 0;
3577                         tmp += channels;
3578                         src++;
3579                 }
3580                 dst += stride;
3581                 src += (srcWidth - dstWidth);   // skip to next row in src
3582         }
3583         // Got it, but hb_get_preview doesn't compensate for anamorphic, so lets
3584         // scale
3585         gint width, height, par_width, par_height;
3586         gboolean anamorphic = ghb_settings_get_boolean(settings, "anamorphic");
3587         if (anamorphic)
3588         {
3589                 hb_set_anamorphic_size( title->job, &width, &height, &par_width, &par_height );
3590                 if (par_width > par_height)
3591                         dstWidth = dstWidth * par_width / par_height;
3592                 else
3593                         dstHeight = dstHeight * par_height / par_width;
3594         }
3595         if (ghb_settings_get_boolean(settings, "reduce_hd_preview"))
3596         {
3597                 gdouble factor = 1.0;
3598
3599                 if (dstHeight > RED_HEIGHT)
3600                 {
3601                         factor = RED_HEIGHT / (gdouble)dstHeight;
3602                 }
3603                 if (dstWidth * factor > RED_WIDTH)
3604                 {
3605                         factor = RED_WIDTH / (gdouble)dstWidth;
3606                 }
3607                 dstHeight = dstHeight * factor + 0.5;
3608                 dstWidth = dstWidth * factor + 0.5;
3609         }
3610         
3611         g_debug("scaled %d x %d\n", dstWidth, dstHeight);
3612         GdkPixbuf *scaled_preview;
3613         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
3614         g_object_unref (preview);
3615         return scaled_preview;
3616 }
3617
3618 static void
3619 sanitize_volname(gchar *name)
3620 {
3621         gchar *a, *b;
3622
3623         a = b = name;
3624         while (*b)
3625         {
3626                 switch(*b)
3627                 {
3628                 case '<':
3629                         b++;
3630                         break;
3631                 case '>':
3632                         b++;
3633                         break;
3634                 default:
3635                         *a = *b;
3636                         a++; b++;
3637                         break;
3638                 }
3639         }
3640         *a = 0;
3641 }
3642
3643 gchar*
3644 ghb_dvd_volname(const gchar *device)
3645 {
3646         gchar *name;
3647         name = hb_dvd_name((gchar*)device);
3648         if (name != NULL)
3649         {
3650                 sanitize_volname(name);
3651                 return g_strdup(name);
3652         }
3653         return name;
3654 }