OSDN Git Service

LinGui: fix initial audio selection problem
[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         if (match) return track;
1616         if (index < count)
1617                 track = index;
1618         return track;
1619 }
1620
1621 static void
1622 generic_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
1623 {
1624         GtkTreeIter iter;
1625         GtkListStore *store;
1626         gint ii;
1627         
1628         g_debug("generic_opts_set ()\n");
1629         if (name == NULL || opts == NULL) return;
1630         store = get_combo_box_store(builder, name);
1631         gtk_list_store_clear(store);
1632         for (ii = 0; ii < opts->count; ii++)
1633         {
1634                 gtk_list_store_append(store, &iter);
1635                 gtk_list_store_set(store, &iter, 
1636                                                    0, opts->map[ii].option, 
1637                                                    1, TRUE, 
1638                                                    2, opts->map[ii].shortOpt, 
1639                                                    3, opts->map[ii].ivalue, 
1640                                                    4, opts->map[ii].svalue, 
1641                                                    -1);
1642         }
1643 }
1644
1645 combo_opts_t*
1646 find_combo_table(const gchar *name)
1647 {
1648         gint ii;
1649
1650         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
1651         {
1652                 if (strcmp(name, combo_name_map[ii].name) == 0)
1653                 {
1654                         return combo_name_map[ii].opts;
1655                 }
1656         }
1657         return NULL;
1658 }
1659
1660 gint
1661 ghb_lookup_combo_int(const gchar *name, const GValue *gval)
1662 {
1663         if (strcmp(name, "AudioBitrate") == 0)
1664                 return lookup_audio_bitrate_int(gval);
1665         else if (strcmp(name, "AudioSamplerate") == 0)
1666                 return lookup_audio_rate_int(gval);
1667         else if (strcmp(name, "VideoFramerate") == 0)
1668                 return lookup_video_rate_int(gval);
1669         else if (strcmp(name, "AudioMixdown") == 0)
1670                 return lookup_mix_int(gval);
1671         else if (strcmp(name, "SourceAudioLang") == 0)
1672                 return lookup_audio_lang_int(gval);
1673         else
1674         {
1675                 return lookup_generic_int(find_combo_table(name), gval);
1676         }
1677         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
1678         return 0;
1679 }
1680
1681 const gchar*
1682 ghb_lookup_combo_option(const gchar *name, const GValue *gval)
1683 {
1684         if (strcmp(name, "AudioBitrate") == 0)
1685                 return lookup_audio_bitrate_option(gval);
1686         else if (strcmp(name, "AudioSamplerate") == 0)
1687                 return lookup_audio_rate_option(gval);
1688         else if (strcmp(name, "VideoFramerate") == 0)
1689                 return lookup_video_rate_option(gval);
1690         else if (strcmp(name, "AudioMixdown") == 0)
1691                 return lookup_mix_option(gval);
1692         else if (strcmp(name, "SourceAudioLang") == 0)
1693                 return lookup_audio_lang_option(gval);
1694         else
1695         {
1696                 return lookup_generic_option(find_combo_table(name), gval);
1697         }
1698         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
1699         return 0;
1700 }
1701
1702 void
1703 ghb_update_ui_combo_box(GtkBuilder *builder, const gchar *name, gint user_data, gboolean all)
1704 {
1705         GtkComboBox *combo = NULL;
1706         gint signal_id;
1707         gint handler_id = 0;
1708
1709         g_debug("ghb_update_ui_combo_box() %s\n", name);
1710         if (name != NULL)
1711         {               
1712                 // Clearing a combo box causes a rash of "changed" events, even when
1713                 // the active item is -1 (inactive).  To control things, I'm disabling
1714                 // the event till things are settled down.
1715                 combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1716                 signal_id = g_signal_lookup("changed", GTK_TYPE_COMBO_BOX);
1717                 if (signal_id > 0)
1718                 {
1719                         // Valid signal id found.  This should always succeed.
1720                         handler_id = g_signal_handler_find ((gpointer)combo, G_SIGNAL_MATCH_ID, 
1721                                                                                                 signal_id, 0, 0, 0, 0);
1722                         if (handler_id > 0)
1723                         {
1724                                 // This should also always succeed
1725                                 g_signal_handler_block ((gpointer)combo, handler_id);
1726                         }
1727                 }
1728         }       
1729         if (all)
1730         {
1731                 audio_bitrate_opts_set(builder, "AudioBitrate");
1732                 audio_samplerate_opts_set(builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
1733                 video_rate_opts_set(builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
1734                 mix_opts_set(builder, "AudioMixdown");
1735                 language_opts_set(builder, "SourceAudioLang");
1736                 subtitle_opts_set(builder, "Subtitles", user_data);
1737                 title_opts_set(builder, "title");
1738                 audio_track_opts_set(builder, "AudioTrack", user_data);
1739                 generic_opts_set(builder, "FileFormat", &container_opts);
1740                 generic_opts_set(builder, "PictureDeinterlace", &deint_opts);
1741                 generic_opts_set(builder, "tweak_PictureDeinterlace", &deint_opts);
1742                 generic_opts_set(builder, "PictureDenoise", &denoise_opts);
1743                 generic_opts_set(builder, "tweak_PictureDenoise", &denoise_opts);
1744                 generic_opts_set(builder, "VideoEncoder", &vcodec_opts);
1745                 generic_opts_set(builder, "AudioEncoder", &acodec_opts);
1746                 generic_opts_set(builder, "x264_direct", &direct_opts);
1747                 generic_opts_set(builder, "x264_me", &me_opts);
1748                 generic_opts_set(builder, "x264_subme", &subme_opts);
1749                 generic_opts_set(builder, "x264_analyse", &analyse_opts);
1750                 generic_opts_set(builder, "x264_trellis", &trellis_opts);
1751         }
1752         else
1753         {
1754                 if (strcmp(name, "AudioBitrate") == 0)
1755                         audio_bitrate_opts_set(builder, "AudioBitrate");
1756                 else if (strcmp(name, "AudioSamplerate") == 0)
1757                         audio_samplerate_opts_set(builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
1758                 else if (strcmp(name, "VideoFramerate") == 0)
1759                         video_rate_opts_set(builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
1760                 else if (strcmp(name, "AudioMixdown") == 0)
1761                         mix_opts_set(builder, "AudioMixdown");
1762                 else if (strcmp(name, "SourceAudioLang") == 0)
1763                         language_opts_set(builder, "SourceAudioLang");
1764                 else if (strcmp(name, "Subtitles") == 0)
1765                         subtitle_opts_set(builder, "Subtitles", user_data);
1766                 else if (strcmp(name, "title") == 0)
1767                         title_opts_set(builder, "title");
1768                 else if (strcmp(name, "AudioTrack") == 0)
1769                         audio_track_opts_set(builder, "AudioTrack", user_data);
1770                 else
1771                         generic_opts_set(builder, name, find_combo_table(name));
1772         }
1773         if (handler_id > 0)
1774         {
1775                 g_signal_handler_unblock ((gpointer)combo, handler_id);
1776         }
1777 }
1778         
1779 static void
1780 init_ui_combo_boxes(GtkBuilder *builder)
1781 {
1782         gint ii;
1783
1784         init_combo_box(builder, "AudioBitrate");
1785         init_combo_box(builder, "AudioSamplerate");
1786         init_combo_box(builder, "VideoFramerate");
1787         init_combo_box(builder, "AudioMixdown");
1788         init_combo_box(builder, "SourceAudioLang");
1789         init_combo_box(builder, "Subtitles");
1790         init_combo_box(builder, "title");
1791         init_combo_box(builder, "AudioTrack");
1792         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
1793         {
1794                 init_combo_box(builder, combo_name_map[ii].name);
1795         }
1796 }
1797         
1798 static const char * turbo_opts = 
1799         "ref=1:subme=1:me=dia:analyse=none:trellis=0:"
1800         "no-fast-pskip=0:8x8dct=0:weightb=0";
1801
1802 // Construct the x264 options string
1803 // The result is allocated, so someone must free it at some point.
1804 gchar*
1805 ghb_build_x264opts_string(GValue *settings)
1806 {
1807         gchar *result;
1808         gchar *opts = ghb_settings_get_string(settings, "x264Option");
1809         if (opts != NULL)
1810         {
1811                 result = opts;
1812         }
1813         else
1814         {
1815                 result = g_strdup("");
1816         }
1817         return result;
1818 }
1819
1820 GValue*
1821 ghb_get_chapters(gint titleindex)
1822 {
1823         hb_list_t  * list;
1824         hb_title_t * title;
1825     hb_chapter_t * chapter;
1826         gint count, ii;
1827         GValue *chapters = NULL;
1828         
1829         g_debug("ghb_get_chapters (title = %d)\n", titleindex);
1830         if (h_scan == NULL) return NULL;
1831         list = hb_get_titles( h_scan );
1832     title = (hb_title_t*)hb_list_item( list, titleindex );
1833         if (title == NULL) return NULL;
1834         count = hb_list_count( title->list_chapter );
1835         chapters = ghb_array_value_new(count);
1836         for (ii = 0; ii < count; ii++)
1837         {
1838                 chapter = hb_list_item(title->list_chapter, ii);
1839                 if (chapter == NULL) break;
1840                 if (chapter->title == NULL || chapter->title[0] == 0)
1841                 {
1842                         gchar *str;
1843                         str = g_strdup_printf ("Chapter %2d", ii+1);
1844                         ghb_array_append(chapters, ghb_string_value_new(str));
1845                         g_free(str);
1846                 }
1847                 else 
1848                 {
1849                         ghb_array_append(chapters, ghb_string_value_new(chapter->title));
1850                 }
1851         }
1852         return chapters;
1853 }
1854
1855 gboolean
1856 ghb_ac3_in_audio_list(const GValue *audio_list)
1857 {
1858         gint count, ii;
1859
1860         count = ghb_array_len(audio_list);
1861         for (ii = 0; ii < count; ii++)
1862         {
1863                 GValue *asettings;
1864                 gint acodec;
1865
1866                 asettings = ghb_array_get_nth(audio_list, ii);
1867                 acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
1868                 if (acodec == HB_ACODEC_AC3)
1869                         return TRUE;
1870         }
1871         return FALSE;
1872 }
1873
1874 static void
1875 audio_bitrate_opts_add(GtkBuilder *builder, const gchar *name, gint rate)
1876 {
1877         GtkTreeIter iter;
1878         GtkListStore *store;
1879         gchar *str;
1880         
1881         g_debug("audio_rate_opts_add ()\n");
1882         store = get_combo_box_store(builder, name);
1883         if (!find_combo_item_by_int(GTK_TREE_MODEL(store), rate, &iter))
1884         {
1885                 str = g_strdup_printf ("%d", rate);
1886                 gtk_list_store_append(store, &iter);
1887                 gtk_list_store_set(store, &iter, 
1888                                                    0, str, 
1889                                                    1, TRUE, 
1890                                                    2, str, 
1891                                                    3, rate, 
1892                                                    4, str, 
1893                                                    -1);
1894                 g_free(str);
1895         }
1896 }
1897
1898 static void
1899 audio_bitrate_opts_clean(GtkBuilder *builder, const gchar *name, gint last_rate)
1900 {
1901         GtkTreeIter iter;
1902         GtkListStore *store;
1903         gint ivalue;
1904         gboolean done = FALSE;
1905         gint ii = 0;
1906         guint last = (guint)last_rate;
1907         
1908         g_debug("audio_bitrate_opts_clean ()\n");
1909         store = get_combo_box_store(builder, name);
1910         if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL(store), &iter))
1911         {
1912                 do
1913                 {
1914                         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 3, &ivalue, -1);
1915                         if (search_rates(
1916                                 hb_audio_bitrates, ivalue, hb_audio_bitrates_count) < 0)
1917                         {
1918                                 done = !gtk_list_store_remove(store, &iter);
1919                         }
1920                         else if (ivalue > last)
1921                         {
1922                                 ii++;
1923                                 gtk_list_store_set(store, &iter, 1, FALSE, -1);
1924                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
1925                         }
1926                         else
1927                         {
1928                                 ii++;
1929                                 gtk_list_store_set(store, &iter, 1, TRUE, -1);
1930                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
1931                         }
1932                 } while (!done);
1933         }
1934 }
1935
1936 static void
1937 audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name)
1938 {
1939         GtkTreeIter iter;
1940         GtkListStore *store;
1941         gint ii;
1942         
1943         g_debug("audio_bitrate_opts_set ()\n");
1944         store = get_combo_box_store(builder, name);
1945         gtk_list_store_clear(store);
1946         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
1947         {
1948                 gtk_list_store_append(store, &iter);
1949                 gtk_list_store_set(store, &iter, 
1950                                                    0, hb_audio_bitrates[ii].string, 
1951                                                    1, TRUE, 
1952                                                    2, hb_audio_bitrates[ii].string, 
1953                                                    3, hb_audio_bitrates[ii].rate, 
1954                                                    4, hb_audio_bitrates[ii].string, 
1955                                                    -1);
1956         }
1957 }
1958
1959 void
1960 ghb_set_passthru_bitrate_opts(GtkBuilder *builder, gint bitrate)
1961 {
1962         audio_bitrate_opts_add(builder, "AudioBitrate", bitrate);
1963 }
1964
1965 void
1966 ghb_set_default_bitrate_opts(GtkBuilder *builder, gint last_rate)
1967 {
1968         audio_bitrate_opts_clean(builder, "AudioBitrate", last_rate);
1969 }
1970
1971 static ghb_status_t hb_status;
1972
1973 void
1974 ghb_backend_init(GtkBuilder *builder, gint debug, gint update)
1975 {
1976     /* Init libhb */
1977     h_scan = hb_init( debug, update );
1978     h_queue = hb_init( debug, 0 );
1979         // Set up the list model for the combos
1980         init_ui_combo_boxes(builder);
1981         // Populate all the combos
1982         ghb_update_ui_combo_box(builder, NULL, 0, TRUE);
1983 }
1984
1985 void
1986 ghb_backend_close()
1987 {
1988         hb_close(&h_queue);
1989         hb_close(&h_scan);
1990 }
1991
1992 void
1993 ghb_backend_scan(const gchar *path, gint titleindex)
1994 {
1995     hb_scan( h_scan, path, titleindex );
1996         hb_status.state |= GHB_STATE_SCANNING;
1997         // initialize count and cur to something that won't cause FPE
1998         // when computing progress
1999         hb_status.title_count = 1;
2000         hb_status.title_cur = 0;
2001 }
2002
2003 void
2004 ghb_backend_queue_scan(const gchar *path, gint titlenum)
2005 {
2006         g_debug("ghb_backend_queue_scan()");
2007         hb_scan( h_queue, path, titlenum );
2008         hb_status.queue_state |= GHB_STATE_SCANNING;
2009 }
2010
2011 gint
2012 ghb_get_state()
2013 {
2014         return hb_status.state;
2015 }
2016
2017 gint
2018 ghb_get_queue_state()
2019 {
2020         return hb_status.queue_state;
2021 }
2022
2023 void
2024 ghb_clear_state(gint state)
2025 {
2026         hb_status.state &= ~state;
2027 }
2028
2029 void
2030 ghb_clear_queue_state(gint state)
2031 {
2032         hb_status.queue_state &= ~state;
2033 }
2034
2035 void
2036 ghb_set_state(gint state)
2037 {
2038         hb_status.state |= state;
2039 }
2040
2041 void
2042 ghb_set_queue_state(gint state)
2043 {
2044         hb_status.queue_state |= state;
2045 }
2046
2047 void
2048 ghb_get_status(ghb_status_t *status)
2049 {
2050         memcpy(status, &hb_status, sizeof(ghb_status_t));
2051 }
2052
2053 void 
2054 ghb_track_status()
2055 {
2056     hb_state_t s;
2057     hb_state_t s_queue;
2058
2059         if (h_scan == NULL) return;
2060     hb_get_state( h_scan, &s );
2061         switch( s.state )
2062     {
2063 #define p s.param.scanning
2064         case HB_STATE_SCANNING:
2065                 {
2066                         hb_status.state |= GHB_STATE_SCANNING;
2067                         hb_status.title_count = p.title_count;
2068                         hb_status.title_cur = p.title_cur;
2069                 } break;
2070 #undef p
2071
2072         case HB_STATE_SCANDONE:
2073         {
2074                         hb_status.state &= ~GHB_STATE_SCANNING;
2075                         hb_status.state |= GHB_STATE_SCANDONE;
2076         } break;
2077
2078     }
2079     hb_get_state( h_queue, &s_queue );
2080         switch( s_queue.state )
2081     {
2082         case HB_STATE_SCANNING:
2083                 {
2084                         hb_status.queue_state |= GHB_STATE_SCANNING;
2085                 } break;
2086
2087         case HB_STATE_SCANDONE:
2088         {
2089                         hb_status.queue_state &= ~GHB_STATE_SCANNING;
2090                         hb_status.queue_state |= GHB_STATE_SCANDONE;
2091         } break;
2092
2093 #define p s_queue.param.working
2094         case HB_STATE_WORKING:
2095                         hb_status.queue_state |= GHB_STATE_WORKING;
2096                         hb_status.queue_state &= ~GHB_STATE_PAUSED;
2097                         hb_status.job_cur = p.job_cur;
2098                         hb_status.job_count = p.job_count;
2099                         hb_status.progress = p.progress;
2100                         hb_status.rate_cur = p.rate_cur;
2101                         hb_status.rate_avg = p.rate_avg;
2102                         hb_status.hours = p.hours;
2103                         hb_status.minutes = p.minutes;
2104                         hb_status.seconds = p.seconds;
2105                         hb_status.unique_id = p.sequence_id & 0xFFFFFF;
2106             break;
2107 #undef p
2108
2109         case HB_STATE_PAUSED:
2110                         hb_status.queue_state |= GHB_STATE_PAUSED;
2111             break;
2112                                 
2113         case HB_STATE_MUXING:
2114         {
2115                         hb_status.queue_state |= GHB_STATE_MUXING;
2116         } break;
2117
2118 #define p s_queue.param.workdone
2119         case HB_STATE_WORKDONE:
2120                 {
2121             hb_job_t *job;
2122
2123                         hb_status.queue_state |= GHB_STATE_WORKDONE;
2124                         hb_status.queue_state &= ~GHB_STATE_MUXING;
2125                         hb_status.queue_state &= ~GHB_STATE_PAUSED;
2126                         hb_status.queue_state &= ~GHB_STATE_WORKING;
2127                         switch (p.error)
2128                         {
2129                         case HB_ERROR_NONE:
2130                                 hb_status.error = GHB_ERROR_NONE;
2131                         case HB_ERROR_CANCELED:
2132                                 hb_status.error = GHB_ERROR_CANCELED;
2133                         default:
2134                                 hb_status.error = GHB_ERROR_FAIL;
2135                         }
2136                         hb_status.error = p.error;
2137                         // Delete all remaining jobs of this encode.
2138                         // An encode can be composed of multiple associated jobs.
2139                         // When a job is stopped, libhb removes it from the job list,
2140                         // but does not remove other jobs that may be associated with it.
2141                         // Associated jobs are taged in the sequence id.
2142             while ((job = hb_job(h_queue, 0)) != NULL) 
2143                 hb_rem( h_queue, job );
2144                 } break;
2145 #undef p
2146     }
2147 }
2148
2149 gboolean
2150 ghb_get_title_info(ghb_title_info_t *tinfo, gint titleindex)
2151 {
2152         hb_list_t  * list;
2153         hb_title_t * title;
2154         
2155     if (h_scan == NULL) return FALSE;
2156         list = hb_get_titles( h_scan );
2157         if( !hb_list_count( list ) )
2158         {
2159                 /* No valid title, stop right there */
2160                 return FALSE;
2161         }
2162
2163     title = hb_list_item( list, titleindex );
2164         if (title == NULL) return FALSE;        // Bad titleindex
2165         tinfo->width = title->width;
2166         tinfo->height = title->height;
2167         memcpy(tinfo->crop, title->crop, 4 * sizeof(int));
2168         // Don't allow crop to 0
2169         if (title->crop[0] + title->crop[1] >= title->height)
2170                 title->crop[0] = title->crop[1] = 0;
2171         if (title->crop[2] + title->crop[3] >= title->width)
2172                 title->crop[2] = title->crop[3] = 0;
2173         tinfo->num_chapters = hb_list_count(title->list_chapter);
2174         tinfo->rate_base = title->rate_base;
2175         tinfo->rate = title->rate;
2176         hb_reduce(&(tinfo->aspect_n), &(tinfo->aspect_d), 
2177                                 title->width * title->pixel_aspect_width, 
2178                                 title->height * title->pixel_aspect_height);
2179         tinfo->hours = title->hours;
2180         tinfo->minutes = title->minutes;
2181         tinfo->seconds = title->seconds;
2182         tinfo->duration = title->duration;
2183         return TRUE;
2184 }
2185
2186 gboolean
2187 ghb_get_audio_info(ghb_audio_info_t *ainfo, gint titleindex, gint audioindex)
2188 {
2189     hb_audio_config_t *audio;
2190         
2191         audio = get_hb_audio(titleindex, audioindex);
2192         if (audio == NULL) return FALSE; // Bad audioindex
2193         ainfo->codec = audio->in.codec;
2194         ainfo->bitrate = audio->in.bitrate;
2195         ainfo->samplerate = audio->in.samplerate;
2196         return TRUE;
2197 }
2198
2199 gboolean
2200 ghb_audio_is_passthru(gint acodec)
2201 {
2202         g_debug("ghb_audio_is_passthru () \n");
2203         g_debug("acodec %d\n", acodec);
2204         return (acodec == HB_ACODEC_AC3);
2205 }
2206
2207 gint
2208 ghb_get_default_acodec()
2209 {
2210         return HB_ACODEC_FAAC;
2211 }
2212
2213 void
2214 ghb_set_scale(signal_user_data_t *ud, gint mode)
2215 {
2216         hb_list_t  * list;
2217         hb_title_t * title;
2218         hb_job_t   * job;
2219         gboolean keep_aspect, round_dims, anamorphic;
2220         gboolean autocrop, autoscale, noscale;
2221         gint crop[4], width, height, par_width, par_height;
2222         gint crop_width, crop_height;
2223         gint aspect_n, aspect_d;
2224         gboolean keep_width = (mode == GHB_SCALE_KEEP_WIDTH);
2225         gboolean keep_height = (mode == GHB_SCALE_KEEP_HEIGHT);
2226         gint step;
2227         GtkWidget *widget;
2228         gint modshift;
2229         gint modround;
2230         gint max_width = 0;
2231         gint max_height = 0;
2232         
2233         g_debug("ghb_set_scale ()\n");
2234
2235         if (h_scan == NULL) return;
2236         list = hb_get_titles( h_scan );
2237         if( !hb_list_count( list ) )
2238         {
2239                 /* No valid title, stop right there */
2240                 return;
2241         }
2242         gint titleindex;
2243
2244         titleindex = ghb_settings_combo_int(ud->settings, "title");
2245     title = hb_list_item( list, titleindex );
2246         if (title == NULL) return;
2247         job   = title->job;
2248         if (job == NULL) return;
2249         
2250         // First configure widgets
2251         round_dims = ghb_settings_get_boolean(ud->settings, "ModDimensions");
2252         anamorphic = ghb_settings_get_boolean(ud->settings, "anamorphic");
2253         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
2254         autocrop = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop");
2255         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
2256         // "Noscale" is a flag that says we prefer to crop extra to satisfy
2257         // alignment constraints rather than scaling to satisfy them.
2258         noscale = ghb_settings_get_boolean(ud->settings, "noscale");
2259         // Align dimensions to either 16 or 2 pixels
2260         // The scaler crashes if the dimensions are not divisible by 2
2261         // x264 also will not accept dims that are not multiple of 2
2262         modshift = round_dims ? 4 : 1;
2263         modround = round_dims ? 8 : 1;
2264         if (autoscale)
2265         {
2266                 keep_width = FALSE;
2267                 keep_height = FALSE;
2268         }
2269         if (anamorphic || keep_aspect)
2270         {
2271                 keep_height = FALSE;
2272         }
2273         // Step needs to be at least 2 because odd widths cause scaler crash
2274         step = round_dims ? 16 : 2;
2275         widget = GHB_WIDGET (ud->builder, "scale_width");
2276         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2277         widget = GHB_WIDGET (ud->builder, "scale_height");
2278         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2279         if (autocrop)
2280         {
2281                 ghb_title_info_t tinfo;
2282
2283                 if (ghb_get_title_info (&tinfo, titleindex))
2284                 {
2285                         crop[0] = tinfo.crop[0];
2286                         crop[1] = tinfo.crop[1];
2287                         crop[2] = tinfo.crop[2];
2288                         crop[3] = tinfo.crop[3];
2289                         if (noscale)
2290                         {
2291                                 gint need1, need2;
2292
2293                                 // Adjust the cropping to accomplish the desired width and height
2294                                 crop_width = tinfo.width - crop[2] - crop[3];
2295                                 crop_height = tinfo.height - crop[0] - crop[1];
2296                                 width = (crop_width >> modshift) << modshift;
2297                                 height = (crop_height >> modshift) << modshift;
2298                                 need1 = (crop_height - height) / 2;
2299                                 need2 = crop_height - height - need1;
2300                                 crop[0] += need1;
2301                                 crop[1] += need2;
2302                                 need1 = (crop_width - width) / 2;
2303                                 need2 = crop_width - width - need1;
2304                                 crop[2] += need1;
2305                                 crop[3] += need2;
2306                         }
2307                         ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
2308                         ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
2309                         ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
2310                         ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
2311                 }
2312         }
2313         crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
2314         crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
2315         crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
2316         crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
2317         hb_reduce(&aspect_n, &aspect_d, 
2318                                 title->width * title->pixel_aspect_width, 
2319                                 title->height * title->pixel_aspect_height);
2320         crop_width = title->width - crop[2] - crop[3];
2321         crop_height = title->height - crop[0] - crop[1];
2322         if (autoscale)
2323         {
2324                 width = crop_width;
2325                 height = crop_height;
2326                 max_width = crop_width;
2327                 max_height = crop_height;
2328         }
2329         else
2330         {
2331                 width = ghb_settings_get_int(ud->settings, "scale_width");
2332                 height = ghb_settings_get_int(ud->settings, "scale_height");
2333                 max_width = ghb_settings_get_int(ud->settings, "PictureWidth");
2334                 max_height = ghb_settings_get_int(ud->settings, "PictureHeight");
2335                 // Align max dims 
2336                 max_width = (max_width >> modshift) << modshift;
2337                 max_height = (max_height >> modshift) << modshift;
2338                 // Adjust dims according to max values
2339                 if (!max_height)
2340                 {
2341                         max_height = crop_height;
2342                 }
2343                 if (!max_width)
2344                 {
2345                         max_width = crop_width;
2346                 }
2347                 height = MIN(height, max_height);
2348                 width = MIN(width, max_width);
2349                 g_debug("max_width %d, max_height %d\n", max_width, max_height);
2350         }
2351         if (width < 16)
2352                 width = title->width - crop[2] - crop[3];
2353         if (height < 16)
2354                 height = title->height - crop[0] - crop[1];
2355
2356         if (anamorphic)
2357         {
2358                 if (round_dims)
2359                 {
2360                         job->modulus = 0;
2361                 }
2362                 else
2363                 {
2364                         // The scaler crashes if the dimensions are not divisible by 2
2365                         // Align mod 2.  And so does something in x264_encoder_headers()
2366                         job->modulus = 2;
2367                 }
2368                 job->width = width;
2369                 if (max_height) 
2370                         job->maxHeight = max_height;
2371                 job->crop[0] = crop[0]; job->crop[1] = crop[1];
2372                 job->crop[2] = crop[2]; job->crop[3] = crop[3];
2373                 hb_set_anamorphic_size( job, &width, &height, 
2374                                                                 &par_width, &par_height );
2375         }
2376         else 
2377         {
2378                 if (keep_aspect)
2379                 {
2380                         gdouble par;
2381                         gint new_width, new_height;
2382                         
2383                         g_debug("kw %s kh %s\n", keep_width ? "y":"n", keep_height ? "y":"n");
2384                         g_debug("w %d h %d\n", width, height);
2385                         // Compute pixel aspect ration.  
2386                         par = (gdouble)(title->height * aspect_n) / (title->width * aspect_d);
2387                         // Must scale so that par becomes 1:1
2388                         // Try to keep largest dimension
2389                         new_height = (crop_height * ((gdouble)width/crop_width) / par);
2390                         new_width = (crop_width * ((gdouble)height/crop_height) * par);
2391                         // Height and width are always multiples of 2, so do the rounding
2392                         new_height = ((new_height + 1) >> 1) << 1;
2393                         new_width = ((new_width + 1) >> 1) << 1;
2394                         g_debug("max w %d, new w %d\n", max_width, new_width);
2395                         if (max_width && (new_width > max_width))
2396                         {
2397                                 height = new_height;
2398                         }
2399                         else if (max_height && (new_height > max_height))
2400                         {
2401                                 width = new_width;
2402                         }
2403                         else if (keep_width)
2404                         {
2405                                 height = new_height;
2406                         }
2407                         else if (keep_height)
2408                         {
2409                                 width = new_width;
2410                         }
2411                         else if (width > new_width)
2412                         {
2413                                 height = new_height;
2414                         }
2415                         else
2416                         {
2417                                 width = new_width;
2418                         }
2419                         g_debug("new w %d h %d\n", width, height);
2420                 }
2421                 width = ((width + modround) >> modshift) << modshift;
2422                 height = ((height + modround) >> modshift) << modshift;
2423         }
2424         ghb_ui_update(ud, "scale_width", ghb_int64_value(width));
2425         ghb_ui_update(ud, "scale_height", ghb_int64_value(height));
2426 }
2427
2428 static void
2429 set_preview_job_settings(hb_job_t *job, GValue *settings)
2430 {
2431         job->crop[0] = ghb_settings_get_int(settings, "PictureTopCrop");
2432         job->crop[1] = ghb_settings_get_int(settings, "PictureBottomCrop");
2433         job->crop[2] = ghb_settings_get_int(settings, "PictureLeftCrop");
2434         job->crop[3] = ghb_settings_get_int(settings, "PictureRightCrop");
2435
2436         gboolean anamorphic, round_dimensions;
2437         anamorphic = ghb_settings_get_boolean(settings, "anamorphic");
2438         round_dimensions = ghb_settings_get_boolean(settings, "ModDimensions");
2439         if (round_dimensions && anamorphic)
2440         {
2441                 job->modulus = 16;
2442                 job->pixel_ratio = 2;
2443         }
2444         else if (anamorphic)
2445         {
2446                 job->modulus = 2;
2447                 job->pixel_ratio = 2;
2448         }
2449         else
2450         {
2451                 job->modulus = 2;
2452                 job->pixel_ratio = 0;
2453         }
2454         job->width = ghb_settings_get_int(settings, "scale_width");
2455         job->height = ghb_settings_get_int(settings, "scale_height");
2456         gint deint = ghb_settings_combo_int(settings, "PictureDeinterlace");
2457         gboolean decomb = ghb_settings_get_boolean(settings, "PictureDecomb");
2458         job->deinterlace = (!decomb && deint == 0) ? 0 : 1;
2459 }
2460
2461 gint
2462 ghb_calculate_target_bitrate(GValue *settings, gint titleindex)
2463 {
2464         hb_list_t  * list;
2465         hb_title_t * title;
2466         hb_job_t   * job;
2467         gint size;
2468
2469         if (h_scan == NULL) return 1500;
2470         list = hb_get_titles( h_scan );
2471     title = hb_list_item( list, titleindex );
2472         if (title == NULL) return 1500;
2473         job   = title->job;
2474         if (job == NULL) return 1500;
2475         size = ghb_settings_get_int(settings, "VideoTargetSize");
2476         return hb_calc_bitrate( job, size );
2477 }
2478
2479 gboolean
2480 ghb_validate_filter_string(const gchar *str, gint max_fields)
2481 {
2482         gint fields = 0;
2483         gchar *end;
2484         gdouble val;
2485
2486         if (str == NULL || *str == 0) return TRUE;
2487         while (*str)
2488         {
2489                 val = g_strtod(str, &end);
2490                 if (str != end)
2491                 { // Found a numeric value
2492                         fields++;
2493                         // negative max_fields means infinate
2494                         if (max_fields >= 0 && fields > max_fields) return FALSE;
2495                         if (*end == 0)
2496                                 return TRUE;
2497                         if (*end != ':')
2498                                 return FALSE;
2499                         str = end + 1;
2500                 }
2501                 else
2502                         return FALSE;
2503         }
2504         return FALSE;
2505 }
2506
2507 gboolean
2508 ghb_validate_filters(signal_user_data_t *ud)
2509 {
2510         gboolean tweaks;
2511         gchar *str;
2512         gint index;
2513         gchar *message;
2514         gboolean enabled;
2515
2516         tweaks = ghb_settings_get_boolean(ud->settings, "allow_tweaks");
2517         if (tweaks)
2518         {
2519                 // detele 6
2520                 str = ghb_settings_get_string(ud->settings, "tweak_PictureDetelecine");
2521                 enabled = ghb_settings_get_boolean(ud->settings, "PictureDetelecine");
2522                 if (enabled && !ghb_validate_filter_string(str, 6))
2523                 {
2524                         message = g_strdup_printf(
2525                                                 "Invalid Detelecine Settings:\n\n%s\n",
2526                                                 str);
2527                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2528                         g_free(str);
2529                         g_free(message);
2530                         return FALSE;
2531                 }
2532                 g_free(str);
2533                 // decomb 7
2534                 str = ghb_settings_get_string(ud->settings, "tweak_PictureDecomb");
2535                 enabled = ghb_settings_get_boolean(ud->settings, "PictureDecomb");
2536                 if (enabled && !ghb_validate_filter_string(str, 7))
2537                 {
2538                         message = g_strdup_printf(
2539                                                 "Invalid Decomb Settings:\n\n%s\n",
2540                                                 str);
2541                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2542                         g_free(str);
2543                         g_free(message);
2544                         return FALSE;
2545                 }
2546                 g_free(str);
2547                 // deinte 4
2548                 index = ghb_lookup_combo_int("tweak_PictureDeinterlace", 
2549                         ghb_settings_get_value(ud->settings, "tweak_PictureDeinterlace"));
2550                 if (index < 0)
2551                 {
2552                         str = ghb_settings_get_string(ud->settings, "tweak_PictureDeinterlace");
2553                         if (!ghb_validate_filter_string(str, 4))
2554                         {
2555                                 message = g_strdup_printf(
2556                                                         "Invalid Deinterlace Settings:\n\n%s\n",
2557                                                         str);
2558                                 ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2559                                 g_free(message);
2560                                 g_free(str);
2561                                 return FALSE;
2562                         }
2563                         g_free(str);
2564                 }
2565                 // denois 4
2566                 index = ghb_lookup_combo_int("tweak_PictureDenoise", 
2567                                 ghb_settings_get_value(ud->settings, "tweak_PictureDenoise"));
2568                 if (index < 0)
2569                 {
2570                         str = ghb_settings_get_string(ud->settings, "tweak_PictureDenoise");
2571                         if (!ghb_validate_filter_string(str, 4))
2572                         {
2573                                 message = g_strdup_printf(
2574                                                         "Invalid Denoise Settings:\n\n%s\n",
2575                                                         str);
2576                                 ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2577                                 g_free(str);
2578                                 g_free(message);
2579                                 return FALSE;
2580                         }
2581                         g_free(str);
2582                 }
2583         }
2584         return TRUE;
2585 }
2586
2587 gboolean
2588 ghb_validate_video(signal_user_data_t *ud)
2589 {
2590         gint vcodec, mux;
2591         gchar *message;
2592
2593         mux = ghb_settings_combo_int(ud->settings, "FileFormat");
2594         vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
2595         if ((mux == HB_MUX_MP4 || mux == HB_MUX_AVI) && 
2596                 (vcodec == HB_VCODEC_THEORA))
2597         {
2598                 // mp4|avi/theora combination is not supported.
2599                 message = g_strdup_printf(
2600                                         "Theora is not supported in the MP4 and AVI containers.\n\n"
2601                                         "You should choose a different video codec or container.\n"
2602                                         "If you continue, XviD will be chosen for you.");
2603                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2604                 {
2605                         g_free(message);
2606                         return FALSE;
2607                 }
2608                 g_free(message);
2609                 vcodec = HB_VCODEC_XVID;
2610                 ghb_ui_update(ud, "VideoEncoder", ghb_int64_value(vcodec));
2611         }
2612         return TRUE;
2613 }
2614
2615 gboolean
2616 ghb_validate_container(signal_user_data_t *ud)
2617 {
2618         gint container;
2619         gchar *message;
2620
2621         container = ghb_settings_combo_int(ud->settings, "FileFormat");
2622         if (container == HB_MUX_MP4)
2623         {
2624                 const GValue *audio_list;
2625                 gboolean httpopt;
2626
2627                 audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2628                 httpopt = ghb_settings_get_boolean(ud->settings, "Mp4HttpOptimize");
2629                 if (httpopt && ghb_ac3_in_audio_list(audio_list))
2630                 {
2631                         message = g_strdup_printf(
2632                                         "AC3 audio in HTTP optimized MP4 is not supported.\n\n"
2633                                         "You should choose a different audio codec.\n"
2634                                         "If you continue, FAAC will be chosen for you.");
2635                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2636                         {
2637                                 g_free(message);
2638                                 return FALSE;
2639                         }
2640                         g_free(message);
2641
2642                         gint count, ii;
2643
2644                         count = ghb_array_len(audio_list);
2645                         for (ii = 0; ii < count; ii++)
2646                         {
2647                                 GValue *asettings;
2648
2649                                 asettings = ghb_array_get_nth(audio_list, ii);
2650                                 gint acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
2651                                 if (acodec == HB_ACODEC_AC3)
2652                                 {
2653                                         GValue *value;
2654                                         value = get_acodec_value(HB_ACODEC_FAAC);
2655                                         ghb_settings_take_value(asettings, "AudioEncoder", value);
2656                                         value = get_abitrate_value(160);
2657                                         ghb_settings_take_value(asettings, "AudioBitrate", value);
2658                                 }
2659                         }
2660                 }
2661         }
2662         return TRUE;
2663 }
2664
2665 gboolean
2666 ghb_validate_audio(signal_user_data_t *ud)
2667 {
2668         hb_list_t  * list;
2669         hb_title_t * title;
2670         gchar *message;
2671         GValue *value;
2672
2673         if (h_scan == NULL) return FALSE;
2674         list = hb_get_titles( h_scan );
2675         if( !hb_list_count( list ) )
2676         {
2677                 /* No valid title, stop right there */
2678                 g_message("No title found.\n");
2679                 return FALSE;
2680         }
2681
2682         gint titleindex;
2683
2684         titleindex = ghb_settings_combo_int(ud->settings, "title");
2685     title = hb_list_item( list, titleindex );
2686         if (title == NULL) return FALSE;
2687         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
2688
2689         const GValue *audio_list;
2690         gint count, ii;
2691
2692         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2693         count = ghb_array_len(audio_list);
2694         for (ii = 0; ii < count; ii++)
2695         {
2696                 GValue *asettings;
2697             hb_audio_config_t *taudio;
2698
2699                 asettings = ghb_array_get_nth(audio_list, ii);
2700                 gint track = ghb_settings_combo_int(asettings, "AudioTrack");
2701                 gint codec = ghb_settings_combo_int(asettings, "AudioEncoder");
2702         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
2703                                                                                         title->list_audio, track );
2704                 if ((taudio->in.codec != HB_ACODEC_AC3) && (codec == HB_ACODEC_AC3))
2705                 {
2706                         // Not supported.  AC3 is passthrough only, so input must be AC3
2707                         message = g_strdup_printf(
2708                                                 "The source does not support AC3 Pass-Thru.\n\n"
2709                                                 "You should choose a different audio codec.\n"
2710                                                 "If you continue, one will be chosen for you.");
2711                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2712                         {
2713                                 g_free(message);
2714                                 return FALSE;
2715                         }
2716                         g_free(message);
2717                         if (mux == HB_MUX_AVI)
2718                         {
2719                                 codec = HB_ACODEC_LAME;
2720                         }
2721                         else
2722                         {
2723                                 codec = HB_ACODEC_FAAC;
2724                         }
2725                         value = get_acodec_value(codec);
2726                         ghb_settings_take_value(asettings, "AudioEncoder", value);
2727                 }
2728                 gchar *a_unsup = NULL;
2729                 gchar *mux_s = NULL;
2730                 if (mux == HB_MUX_MP4)
2731                 { 
2732                         mux_s = "MP4";
2733                         // mp4/mp3|vorbis combination is not supported.
2734                         if (codec == HB_ACODEC_LAME)
2735                         {
2736                                 a_unsup = "MP3";
2737                                 codec = HB_ACODEC_FAAC;
2738                         }
2739                         if (codec == HB_ACODEC_VORBIS)
2740                         {
2741                                 a_unsup = "Vorbis";
2742                                 codec = HB_ACODEC_FAAC;
2743                         }
2744                 }
2745                 else if (mux == HB_MUX_AVI)
2746                 {
2747                         mux_s = "AVI";
2748                         // avi/faac|vorbis combination is not supported.
2749                         if (codec == HB_ACODEC_FAAC)
2750                         {
2751                                 a_unsup = "FAAC";
2752                                 codec = HB_ACODEC_LAME;
2753                         }
2754                         if (codec == HB_ACODEC_VORBIS)
2755                         {
2756                                 a_unsup = "Vorbis";
2757                                 codec = HB_ACODEC_LAME;
2758                         }
2759                 }
2760                 else if (mux == HB_MUX_OGM)
2761                 {
2762                         mux_s = "OGM";
2763                         // avi/faac|vorbis combination is not supported.
2764                         if (codec == HB_ACODEC_FAAC)
2765                         {
2766                                 a_unsup = "FAAC";
2767                                 codec = HB_ACODEC_VORBIS;
2768                         }
2769                         if (codec == HB_ACODEC_AC3)
2770                         {
2771                                 a_unsup = "AC-3";
2772                                 codec = HB_ACODEC_VORBIS;
2773                         }
2774                 }
2775                 if (a_unsup)
2776                 {
2777                         message = g_strdup_printf(
2778                                                 "%s is not supported in the %s container.\n\n"
2779                                                 "You should choose a different audio codec.\n"
2780                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
2781                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2782                         {
2783                                 g_free(message);
2784                                 return FALSE;
2785                         }
2786                         g_free(message);
2787                         value = get_acodec_value(codec);
2788                         ghb_settings_take_value(asettings, "AudioEncoder", value);
2789                 }
2790                 gint mix = ghb_settings_combo_int (asettings, "AudioMixdown");
2791                 gboolean allow_mono = TRUE;
2792                 gboolean allow_stereo = TRUE;
2793                 gboolean allow_dolby = TRUE;
2794                 gboolean allow_dpl2 = TRUE;
2795                 gboolean allow_6ch = TRUE;
2796                 allow_mono =
2797                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2798                         (codec != HB_ACODEC_LAME);
2799                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
2800                 allow_stereo =
2801                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
2802                 allow_dolby =
2803                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
2804                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
2805                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
2806                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
2807                 allow_6ch =
2808                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2809                         (codec != HB_ACODEC_LAME) &&
2810                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
2811                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
2812
2813                 gchar *mix_unsup = NULL;
2814                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
2815                 {
2816                         mix_unsup = "mono";
2817                 }
2818                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
2819                 {
2820                         mix_unsup = "stereo";
2821                 }
2822                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
2823                 {
2824                         mix_unsup = "Dolby";
2825                 }
2826                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
2827                 {
2828                         mix_unsup = "Dolby Pro Logic II";
2829                 }
2830                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
2831                 {
2832                         mix_unsup = "6 Channel";
2833                 }
2834                 if (mix_unsup)
2835                 {
2836                         message = g_strdup_printf(
2837                                                 "The source audio does not support %s mixdown.\n\n"
2838                                                 "You should choose a different mixdown.\n"
2839                                                 "If you continue, one will be chosen for you.", mix_unsup);
2840                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2841                         {
2842                                 g_free(message);
2843                                 return FALSE;
2844                         }
2845                         g_free(message);
2846                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
2847                         value = get_amix_value(mix);
2848                         ghb_settings_take_value(asettings, "AudioMixdown", value);
2849                 }
2850         }
2851         return TRUE;
2852 }
2853
2854 gboolean
2855 ghb_validate_vquality(GValue *settings)
2856 {
2857         gint vcodec;
2858         gchar *message;
2859         gint min, max;
2860
2861         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
2862         vcodec = ghb_settings_combo_int(settings, "VideoEncoder");
2863         gdouble vquality;
2864         vquality = ghb_settings_get_double(settings, "VideoQualitySlider");
2865         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
2866         {
2867                 if (!ghb_settings_get_boolean(settings, "directqp"))
2868                 {
2869                         vquality *= 100.0;
2870                         if (vcodec != HB_VCODEC_X264)
2871                         {
2872                                 min = 68;
2873                                 max = 97;
2874                         }
2875                         else
2876                         {
2877                                 min = 40;
2878                                 max = 70;
2879                         }
2880                 }
2881                 else
2882                 {
2883                         if (vcodec == HB_VCODEC_X264)
2884                         {
2885                                 min = 16;
2886                                 max = 30;
2887                         }
2888                         else if (vcodec == HB_VCODEC_FFMPEG)
2889                         {
2890                                 min = 1;
2891                                 max = 8;
2892                         }
2893                         else
2894                         {
2895                                 min = 68;
2896                                 max = 97;
2897                                 vquality *= 100.0;
2898                         }
2899                 }
2900                 if (vquality < min || vquality > max)
2901                 {
2902                         message = g_strdup_printf(
2903                                                 "Interesting video quality choise: %d\n\n"
2904                                                 "Typical values range from %d to %d.\n"
2905                                                 "Are you sure you wish to use this setting?",
2906                                                 (gint)vquality, min, max);
2907                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
2908                                                                         "Cancel", "Continue"))
2909                         {
2910                                 g_free(message);
2911                                 return FALSE;
2912                         }
2913                         g_free(message);
2914                 }
2915         }
2916         return TRUE;
2917 }
2918
2919 void
2920 ghb_add_job(GValue *js, gint unique_id)
2921 {
2922         hb_list_t  * list;
2923         hb_title_t * title;
2924         hb_job_t   * job;
2925         static gchar *x264opts;
2926         gint sub_id = 0;
2927         gboolean tweaks = FALSE;
2928         gchar *detel_str = NULL;
2929         gchar *decomb_str = NULL;
2930         gchar *deint_str = NULL;
2931         gchar *deblock_str = NULL;
2932         gchar *denoise_str = NULL;
2933         gchar *dest_str = NULL;
2934
2935         g_debug("ghb_add_job()\n");
2936         if (h_queue == NULL) return;
2937         list = hb_get_titles( h_queue );
2938         if( !hb_list_count( list ) )
2939         {
2940                 /* No valid title, stop right there */
2941                 g_message("No title found.\n");
2942                 return;
2943         }
2944
2945         // Since I'm doing a scan of the single title I want just prior 
2946         // to adding the job, there is only the one title to choose from.
2947         //gint titleindex = ghb_settings_get_int(js, "title");
2948     gint titleindex = 0;
2949     title = hb_list_item( list, titleindex );
2950         if (title == NULL) return;
2951
2952         /* Set job settings */
2953         job   = title->job;
2954         if (job == NULL) return;
2955
2956         tweaks = ghb_settings_get_boolean(js, "allow_tweaks");
2957         job->mux = ghb_settings_combo_int(js, "FileFormat");
2958         if (job->mux == HB_MUX_MP4)
2959         {
2960                 job->largeFileSize = ghb_settings_get_boolean(js, "Mp4LargeFile");
2961                 job->mp4_optimize = ghb_settings_get_boolean(js, "Mp4HttpOptimize");
2962         }
2963         else
2964         {
2965                 job->largeFileSize = FALSE;
2966                 job->mp4_optimize = FALSE;
2967         }
2968         gint chapter_start, chapter_end;
2969         chapter_start = ghb_settings_get_int(js, "start_chapter");
2970         chapter_end = ghb_settings_get_int(js, "end_chapter");
2971         gint num_chapters = hb_list_count(title->list_chapter);
2972         job->chapter_start = MIN( num_chapters, chapter_start );
2973         job->chapter_end   = MAX( job->chapter_start, chapter_end );
2974
2975         job->chapter_markers = ghb_settings_get_boolean(js, "ChapterMarkers");
2976         if ( job->chapter_markers )
2977         {
2978                 GValue *chapters;
2979                 GValue *chapter;
2980                 gint chap;
2981                 gint count;
2982                 
2983                 chapters = ghb_settings_get_value(js, "chapter_list");
2984                 count = ghb_array_len(chapters);
2985                 for(chap = chapter_start; chap <= chapter_end; chap++)
2986                 {
2987                         hb_chapter_t * chapter_s;
2988                         gchar *name;
2989                         
2990                         name = NULL;
2991                         if (chap-1 < count)
2992                         {
2993                                 chapter = ghb_array_get_nth(chapters, chap-1);
2994                                 name = ghb_value_string(chapter); 
2995                         }
2996                         if (name == NULL)
2997                         {
2998                                 name = g_strdup_printf ("Chapter %2d", chap);
2999                         }
3000                         chapter_s = hb_list_item( job->title->list_chapter, chap - 1);
3001                         strncpy(chapter_s->title, name, 1023);
3002                         chapter_s->title[1023] = '\0';
3003                         g_free(name);
3004                 }
3005         }
3006         job->crop[0] = ghb_settings_get_int(js, "PictureTopCrop");
3007         job->crop[1] = ghb_settings_get_int(js, "PictureBottomCrop");
3008         job->crop[2] = ghb_settings_get_int(js, "PictureLeftCrop");
3009         job->crop[3] = ghb_settings_get_int(js, "PictureRightCrop");
3010
3011         
3012         gboolean decomb = ghb_settings_get_boolean(js, "PictureDecomb");
3013         gint deint = ghb_settings_combo_int(js, 
3014                                         tweaks ? "tweak_PictureDeinterlace":"PictureDeinterlace");
3015         if (!decomb)
3016                 job->deinterlace = (deint != 0) ? 1 : 0;
3017         else
3018                 job->deinterlace = 0;
3019     job->grayscale   = ghb_settings_get_boolean(js, "VideoGrayScale");
3020
3021         gboolean anamorphic = ghb_settings_get_boolean(js, "anamorphic");
3022         gboolean round_dimensions = ghb_settings_get_boolean(js, "ModDimensions");
3023         if (round_dimensions && anamorphic)
3024         {
3025                 job->pixel_ratio = 2;
3026                 job->modulus = 16;
3027         }
3028         else if (anamorphic)
3029         {
3030                 // Huh! I thought I wanted to use pixel_ratio 1 for this case, but
3031                 // when its 1, libhb discards the width and height and uses original
3032                 // title dims - crop.  Thats not what I want.
3033                 // Also, x264 requires things to divisible by 2.
3034                 job->pixel_ratio = 2;
3035                 job->modulus = 2;
3036         }
3037         else
3038         {
3039                 job->pixel_ratio = 0;
3040                 job->modulus = 2;
3041         }
3042         /* Add selected filters */
3043         job->filters = hb_list_init();
3044         gint vrate = ghb_settings_combo_int(js, "VideoFramerate");
3045         if( vrate == 0 && ghb_settings_get_boolean(js, "PictureDetelecine" ) )
3046                 job->vfr = 1;
3047         else
3048                 job->vfr = 0;
3049
3050         if( ghb_settings_get_boolean(js, "PictureDetelecine" ) )
3051         {
3052                 hb_filter_detelecine.settings = NULL;
3053                 if (tweaks)
3054                 {
3055                         detel_str = ghb_settings_get_string(js, "tweak_PictureDetelecine");
3056                         if (detel_str && detel_str[0])
3057                         {
3058                                 hb_filter_detelecine.settings = detel_str;
3059                         }
3060                 }
3061                 hb_list_add( job->filters, &hb_filter_detelecine );
3062         }
3063         if( decomb )
3064         {
3065                 // Use default settings
3066                 hb_filter_decomb.settings = NULL;
3067                 if (tweaks)
3068                 {
3069                         decomb_str = ghb_settings_get_string(js, "tweak_PictureDecomb");
3070                         if (decomb_str && decomb_str[0])
3071                         {
3072                                 hb_filter_decomb.settings = (gchar*)decomb_str;
3073                         }
3074                 }
3075                 hb_list_add( job->filters, &hb_filter_decomb );
3076         }
3077         if( job->deinterlace )
3078         {
3079                 if (deint > 0)
3080                         deint_str = g_strdup(deint_opts.map[deint].svalue);
3081                 else
3082                         deint_str = ghb_settings_get_string(js, 
3083                                         tweaks ? "tweak_PictureDeinterlace" : "PictureDeinterlace");
3084                 hb_filter_deinterlace.settings = deint_str;
3085                 hb_list_add( job->filters, &hb_filter_deinterlace );
3086         }
3087         gint deblock = ghb_settings_get_int(js, "PictureDeblock");
3088         if( deblock >= 5 )
3089         {
3090                 deblock_str = g_strdup_printf("%d", deblock);
3091                 hb_filter_deblock.settings = deblock_str;
3092                 hb_list_add( job->filters, &hb_filter_deblock );
3093         }
3094         gint denoise = ghb_settings_combo_int(js, 
3095                                         tweaks ? "tweak_PictureDenoise" : "PictureDenoise");
3096         if( denoise != 0 )
3097         {
3098                 if (denoise > 0)
3099                         denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
3100                 else
3101                         denoise_str = (gchar*)ghb_settings_get_string(
3102                                 js, tweaks ? "tweak_PictureDenoise" : "PictureDenoise");
3103                 hb_filter_denoise.settings = denoise_str;
3104                 hb_list_add( job->filters, &hb_filter_denoise );
3105         }
3106         job->width = ghb_settings_get_int(js, "scale_width");
3107         job->height = ghb_settings_get_int(js, "scale_height");
3108
3109         job->vcodec = ghb_settings_combo_int(js, "VideoEncoder");
3110         if ((job->mux == HB_MUX_MP4 || job->mux == HB_MUX_AVI) && 
3111                 (job->vcodec == HB_VCODEC_THEORA))
3112         {
3113                 // mp4|avi/theora combination is not supported.
3114                 job->vcodec = HB_VCODEC_XVID;
3115         }
3116         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
3117         {
3118                 job->ipod_atom = ghb_settings_get_boolean(js, "Mp4iPodCompatible");
3119         }
3120         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
3121         {
3122                 gdouble vquality;
3123                 vquality = ghb_settings_get_double(js, "VideoQualitySlider");
3124                 if (!ghb_settings_get_boolean(js, "directqp"))
3125                 {
3126                         if (vquality == 0.0) vquality = 0.01;
3127                         if (vquality == 1.0) vquality = 0.0;
3128                 }
3129                 job->vquality =  vquality;
3130                 job->vbitrate = 0;
3131         }
3132         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
3133         {
3134                 job->vquality = -1.0;
3135                 job->vbitrate = ghb_settings_get_int(js, "VideoAvgBitrate");
3136         }
3137         // AVI container does not support variable frame rate.
3138         if (job->mux == HB_MUX_AVI)
3139         {
3140                 job->vfr = FALSE;
3141                 job->cfr = 1;
3142         }
3143
3144         if( vrate == 0 )
3145         {
3146                 job->vrate = title->rate;
3147                 job->vrate_base = title->rate_base;
3148                 job->cfr = 0;
3149         }
3150         else
3151         {
3152                 job->vrate = 27000000;
3153                 job->vrate_base = vrate;
3154                 job->cfr = 1;
3155         }
3156         // First remove any audios that are already in the list
3157         // This happens if you are encoding the same title a second time.
3158         gint num_audio_tracks = hb_list_count(job->list_audio);
3159         gint ii;
3160     for(ii = 0; ii < num_audio_tracks; ii++)
3161     {
3162         hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
3163         hb_list_rem(job->list_audio, audio);
3164     }
3165
3166         const GValue *audio_list;
3167         gint count;
3168         gint tcount = 0;
3169         
3170         audio_list = ghb_settings_get_value(js, "audio_list");
3171         count = ghb_array_len(audio_list);
3172         for (ii = 0; ii < count; ii++)
3173         {
3174                 GValue *asettings;
3175             hb_audio_config_t audio;
3176             hb_audio_config_t *taudio;
3177
3178                 hb_audio_config_init(&audio);
3179                 asettings = ghb_array_get_nth(audio_list, ii);
3180                 audio.in.track = ghb_settings_get_int(asettings, "AudioTrack");
3181                 audio.out.track = tcount;
3182                 audio.out.codec = ghb_settings_combo_int(asettings, "AudioEncoder");
3183         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
3184                                                                         title->list_audio, audio.in.track );
3185                 if ((taudio->in.codec != HB_ACODEC_AC3) && (audio.out.codec == HB_ACODEC_AC3))
3186                 {
3187                         // Not supported.  AC3 is passthrough only, so input must be AC3
3188                         if (job->mux == HB_MUX_AVI)
3189                         {
3190                                 audio.out.codec = HB_ACODEC_LAME;
3191                         }
3192                         else
3193                         {
3194                                 audio.out.codec = HB_ACODEC_FAAC;
3195                         }
3196                 }
3197                 if ((job->mux == HB_MUX_MP4) && 
3198                         ((audio.out.codec == HB_ACODEC_LAME) ||
3199                         (audio.out.codec == HB_ACODEC_VORBIS)))
3200                 {
3201                         // mp4/mp3|vorbis combination is not supported.
3202                         audio.out.codec = HB_ACODEC_FAAC;
3203                 }
3204                 if ((job->mux == HB_MUX_AVI) && 
3205                         ((audio.out.codec == HB_ACODEC_FAAC) ||
3206                         (audio.out.codec == HB_ACODEC_VORBIS)))
3207                 {
3208                         // avi/faac|vorbis combination is not supported.
3209                         audio.out.codec = HB_ACODEC_LAME;
3210                 }
3211                 if ((job->mux == HB_MUX_OGM) && 
3212                         ((audio.out.codec == HB_ACODEC_FAAC) ||
3213                         (audio.out.codec == HB_ACODEC_AC3)))
3214                 {
3215                         // ogm/faac|ac3 combination is not supported.
3216                         audio.out.codec = HB_ACODEC_VORBIS;
3217                 }
3218         audio.out.dynamic_range_compression = 
3219                         ghb_settings_get_double(asettings, "AudioTrackDRCSlider");
3220                 // It would be better if this were done in libhb for us, but its not yet.
3221                 if (audio.out.codec == HB_ACODEC_AC3 || audio.out.codec == HB_ACODEC_DCA)
3222                 {
3223                         audio.out.mixdown = 0;
3224                 }
3225                 else
3226                 {
3227                         audio.out.mixdown = ghb_settings_combo_int(asettings, "AudioMixdown");
3228                         // Make sure the mixdown is valid and pick a new one if not.
3229                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
3230                                 audio.in.track, audio.out.codec, audio.out.mixdown);
3231                         audio.out.bitrate = 
3232                                 ghb_settings_combo_int(asettings, "AudioBitrate");
3233                         gint srate = ghb_settings_combo_int(asettings, "AudioSamplerate");
3234                         if (srate == 0) // 0 is same as source
3235                                 audio.out.samplerate = taudio->in.samplerate;
3236                         else
3237                                 audio.out.samplerate = srate;
3238                 }
3239
3240                 // Add it to the jobs audio list
3241         hb_audio_add( job, &audio );
3242                 tcount++;
3243         }
3244         // I was tempted to move this up with the reset of the video quality
3245         // settings, but I suspect the settings above need to be made
3246         // first in order for hb_calc_bitrate to be accurate.
3247         if (ghb_settings_get_boolean(js, "vquality_type_target"))
3248         {
3249                 gint size;
3250                 
3251                 size = ghb_settings_get_int(js, "VideoTargetSize");
3252         job->vbitrate = hb_calc_bitrate( job, size );
3253                 job->vquality = -1.0;
3254         }
3255
3256         dest_str = ghb_settings_get_string(js, "destination");
3257         job->file = dest_str;
3258         job->crf = ghb_settings_get_boolean(js, "constant_rate_factor");
3259         // TODO: libhb holds onto a reference to the x264opts and is not
3260         // finished with it until encoding the job is done.  But I can't
3261         // find a way to get at the job before it is removed in order to
3262         // free up the memory I am allocating here.
3263         // The short story is THIS LEAKS.
3264         x264opts = ghb_build_x264opts_string(js);
3265         
3266         if( x264opts != NULL && *x264opts != '\0' )
3267         {
3268                 job->x264opts = x264opts;
3269         }
3270         else /*avoids a bus error crash when options aren't specified*/
3271         {
3272                 job->x264opts =  NULL;
3273         }
3274         gint subtitle;
3275         gchar *slang = ghb_settings_get_string(js, "Subtitles");
3276         subtitle = -2; // default to none
3277         if (strcmp(slang, "auto") == 0)
3278         {
3279                 subtitle = -1;
3280         }
3281         else
3282         {
3283                 gint scount;
3284         hb_subtitle_t * subt;
3285
3286                 scount = hb_list_count(title->list_subtitle);
3287                 for (ii = 0; ii < scount; ii++)
3288                 {
3289                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
3290                         if (strcmp(slang, subt->iso639_2) == 0)
3291                         {
3292                                 subtitle = ii;
3293                                 break;
3294                         }
3295                 }
3296         }
3297         gboolean forced_subtitles = ghb_settings_get_boolean(js, "SubtitlesForced");
3298         job->subtitle_force = forced_subtitles;
3299         if (subtitle >= 0)
3300                 job->subtitle = subtitle;
3301         else
3302                 job->subtitle = -1;
3303         if (subtitle == -1)
3304         {
3305                 // Subtitle scan. Look for subtitle matching audio language
3306                 char *x264opts_tmp;
3307
3308                 /*
3309                  * When subtitle scan is enabled do a fast pre-scan job
3310                  * which will determine which subtitles to enable, if any.
3311                  */
3312                 job->pass = -1;
3313                 job->indepth_scan = 1;
3314
3315                 x264opts_tmp = job->x264opts;
3316                 job->x264opts = NULL;
3317
3318                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
3319                 *(job->select_subtitle) = NULL;
3320
3321                 /*
3322                  * Add the pre-scan job
3323                  */
3324                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3325                 hb_add( h_queue, job );
3326                 //if (job->x264opts != NULL)
3327                 //      g_free(job->x264opts);
3328
3329                 job->x264opts = x264opts_tmp;
3330         }
3331         else
3332         {
3333                 job->select_subtitle = NULL;
3334         }
3335         if( ghb_settings_get_boolean(js, "VideoTwoPass") &&
3336                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
3337         {
3338                 /*
3339                  * If subtitle_scan is enabled then only turn it on
3340                  * for the second pass and then off again for the
3341                  * second.
3342                  */
3343                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
3344                 job->select_subtitle = NULL;
3345                 job->pass = 1;
3346                 job->indepth_scan = 0;
3347                 gchar *x264opts2 = NULL;
3348                 if (x264opts)
3349                 {
3350                         x264opts2 = g_strdup(x264opts);
3351                 }
3352                 /*
3353                  * If turbo options have been selected then append them
3354                  * to the x264opts now (size includes one ':' and the '\0')
3355                  */
3356                 if( ghb_settings_get_boolean(js, "VideoTurboTwoPass") )
3357                 {
3358                         char *tmp_x264opts;
3359
3360                         if ( x264opts )
3361                         {
3362                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, turbo_opts);
3363                                 g_free(x264opts);
3364                         } 
3365                         else 
3366                         {
3367                                 /*
3368                                  * No x264opts to modify, but apply the turbo options
3369                                  * anyway as they may be modifying defaults
3370                                  */
3371                                 tmp_x264opts = g_strdup_printf("%s", turbo_opts);
3372                         }
3373                         x264opts = tmp_x264opts;
3374
3375                         job->x264opts = x264opts;
3376                 }
3377                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3378                 hb_add( h_queue, job );
3379                 //if (job->x264opts != NULL)
3380                 //      g_free(job->x264opts);
3381
3382                 job->select_subtitle = subtitle_tmp;
3383                 job->pass = 2;
3384                 /*
3385                  * On the second pass we turn off subtitle scan so that we
3386                  * can actually encode using any subtitles that were auto
3387                  * selected in the first pass (using the whacky select-subtitle
3388                  * attribute of the job).
3389                  */
3390                 job->indepth_scan = 0;
3391                 job->x264opts = x264opts2;
3392                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3393                 hb_add( h_queue, job );
3394                 //if (job->x264opts != NULL)
3395                 //      g_free(job->x264opts);
3396         }
3397         else
3398         {
3399                 job->indepth_scan = 0;
3400                 job->pass = 0;
3401                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3402                 hb_add( h_queue, job );
3403                 //if (job->x264opts != NULL)
3404                 //      g_free(job->x264opts);
3405         }
3406         if (detel_str) g_free(detel_str);
3407         if (decomb_str) g_free(decomb_str);
3408         if (deint_str) g_free(deint_str);
3409         if (deblock_str) g_free(deblock_str);
3410         if (denoise_str) g_free(denoise_str);
3411         if (dest_str) g_free(dest_str);
3412 }
3413
3414 void
3415 ghb_remove_job(gint unique_id)
3416 {
3417     hb_job_t * job;
3418     gint ii;
3419         
3420         // Multiples passes all get the same id
3421         // remove them all.
3422         // Go backwards through list, so reordering doesn't screw me.
3423         ii = hb_count(h_queue) - 1;
3424     while ((job = hb_job(h_queue, ii--)) != NULL)
3425     {
3426         if ((job->sequence_id & 0xFFFFFF) == unique_id)
3427                         hb_rem(h_queue, job);
3428     }
3429 }
3430
3431 void
3432 ghb_start_queue()
3433 {
3434         hb_start( h_queue );
3435 }
3436
3437 void
3438 ghb_stop_queue()
3439 {
3440         hb_stop( h_queue );
3441 }
3442
3443 void
3444 ghb_pause_queue()
3445 {
3446     hb_state_t s;
3447     hb_get_state2( h_queue, &s );
3448
3449     if( s.state == HB_STATE_PAUSED )
3450     {
3451         hb_resume( h_queue );
3452     }
3453     else
3454     {
3455         hb_pause( h_queue );
3456     }
3457 }
3458
3459 #define RED_HEIGHT      720.0
3460 #define RED_WIDTH       1280.0
3461
3462 GdkPixbuf*
3463 ghb_get_preview_image(
3464         gint titleindex, 
3465         gint index, 
3466         GValue *settings, 
3467         gboolean borders)
3468 {
3469         hb_title_t *title;
3470         hb_list_t  *list;
3471         
3472         list = hb_get_titles( h_scan );
3473         if( !hb_list_count( list ) )
3474         {
3475                 /* No valid title, stop right there */
3476                 return NULL;
3477         }
3478     title = hb_list_item( list, titleindex );
3479         if (title == NULL) return NULL;
3480         if (title->job == NULL) return NULL;
3481         set_preview_job_settings(title->job, settings);
3482
3483         // hb_get_preview can't handle sizes that are larger than the original title
3484         // dimensions
3485         if (title->job->width > title->width)
3486                 title->job->width = title->width;
3487         
3488         if (title->job->height > title->height)
3489                 title->job->height = title->height;
3490         // And also creates artifacts if the width is not a multiple of 8
3491         //title->job->width = ((title->job->width + 4) >> 3) << 3;
3492         // And the height must be a multiple of 2
3493         //title->job->height = ((title->job->height + 1) >> 1) << 1;
3494         
3495         // Make sure we have a big enough buffer to receive the image from libhb. libhb
3496         // creates images with a one-pixel border around the original content. Hence we
3497         // add 2 pixels horizontally and vertically to the buffer size.
3498         gint srcWidth = title->width + 2;
3499         gint srcHeight= title->height + 2;
3500         gint dstWidth = title->width;
3501         gint dstHeight= title->height;
3502         gint borderTop = 1;
3503         gint borderLeft = 1;
3504     if (borders)
3505     {
3506         //     |<---------- title->width ----------->|
3507         //     |   |<---- title->job->width ---->|   |
3508         //     |   |                             |   |
3509         //     .......................................
3510         //     ....+-----------------------------+....
3511         //     ....|                             |....<-- gray border
3512         //     ....|                             |....
3513         //     ....|                             |....
3514         //     ....|                             |<------- image
3515         //     ....|                             |....
3516         //     ....|                             |....
3517         //     ....|                             |....
3518         //     ....|                             |....
3519         //     ....|                             |....
3520         //     ....+-----------------------------+....
3521         //     .......................................
3522                 dstWidth = title->job->width;
3523         dstHeight = title->job->height;
3524                 borderTop = (srcHeight - dstHeight) / 2;
3525                 borderLeft = (srcWidth - dstWidth) / 2;
3526                 g_debug("boarders removed\n");
3527         }
3528
3529         g_debug("src %d x %d\n", srcWidth, srcHeight);
3530         g_debug("dst %d x %d\n", dstWidth, dstHeight);
3531         g_debug("job dim %d x %d\n", title->job->width, title->job->height);
3532         g_debug("title crop %d:%d:%d:%d\n", 
3533                         title->crop[0],
3534                         title->crop[1],
3535                         title->crop[2],
3536                         title->crop[3]);
3537         g_debug("job crop %d:%d:%d:%d\n", 
3538                         title->job->crop[0],
3539                         title->job->crop[1],
3540                         title->job->crop[2],
3541                         title->job->crop[3]);
3542         static guint8 *buffer = NULL;
3543         static gint bufferSize = 0;
3544
3545         gint newSize;
3546         newSize = srcWidth * srcHeight * 4;
3547         if( bufferSize < newSize )
3548         {
3549                 bufferSize = newSize;
3550                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
3551         }
3552         hb_get_preview( h_scan, title, index, buffer );
3553
3554         // Create an GdkPixbuf and copy the libhb image into it, converting it from
3555         // libhb's format something suitable. Along the way, we'll strip off the
3556         // border around libhb's image.
3557         
3558         // The image data returned by hb_get_preview is 4 bytes per pixel, BGRA format.
3559         // Alpha is ignored.
3560
3561         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
3562         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
3563         
3564         guint32 *src = (guint32*)buffer;
3565         guint8 *dst = pixels;
3566         src += borderTop * srcWidth;    // skip top rows in src to get to first row of dst
3567         src += borderLeft;              // skip left pixels in src to get to first pixel of dst
3568         gint ii, jj;
3569         gint channels = gdk_pixbuf_get_n_channels (preview);
3570         gint stride = gdk_pixbuf_get_rowstride (preview);
3571         guint8 *tmp;
3572         for (ii = 0; ii < dstHeight; ii++)
3573         {
3574                 tmp = dst;
3575                 for (jj = 0; jj < dstWidth; jj++)
3576                 {
3577                         tmp[0] = src[0] >> 16;
3578                         tmp[1] = src[0] >> 8;
3579                         tmp[2] = src[0] >> 0;
3580                         tmp += channels;
3581                         src++;
3582                 }
3583                 dst += stride;
3584                 src += (srcWidth - dstWidth);   // skip to next row in src
3585         }
3586         // Got it, but hb_get_preview doesn't compensate for anamorphic, so lets
3587         // scale
3588         gint width, height, par_width, par_height;
3589         gboolean anamorphic = ghb_settings_get_boolean(settings, "anamorphic");
3590         if (anamorphic)
3591         {
3592                 hb_set_anamorphic_size( title->job, &width, &height, &par_width, &par_height );
3593                 if (par_width > par_height)
3594                         dstWidth = dstWidth * par_width / par_height;
3595                 else
3596                         dstHeight = dstHeight * par_height / par_width;
3597         }
3598         if (ghb_settings_get_boolean(settings, "reduce_hd_preview"))
3599         {
3600                 gdouble factor = 1.0;
3601
3602                 if (dstHeight > RED_HEIGHT)
3603                 {
3604                         factor = RED_HEIGHT / (gdouble)dstHeight;
3605                 }
3606                 if (dstWidth * factor > RED_WIDTH)
3607                 {
3608                         factor = RED_WIDTH / (gdouble)dstWidth;
3609                 }
3610                 dstHeight = dstHeight * factor + 0.5;
3611                 dstWidth = dstWidth * factor + 0.5;
3612         }
3613         
3614         g_debug("scaled %d x %d\n", dstWidth, dstHeight);
3615         GdkPixbuf *scaled_preview;
3616         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
3617         g_object_unref (preview);
3618         return scaled_preview;
3619 }
3620
3621 static void
3622 sanitize_volname(gchar *name)
3623 {
3624         gchar *a, *b;
3625
3626         a = b = name;
3627         while (*b)
3628         {
3629                 switch(*b)
3630                 {
3631                 case '<':
3632                         b++;
3633                         break;
3634                 case '>':
3635                         b++;
3636                         break;
3637                 default:
3638                         *a = *b;
3639                         a++; b++;
3640                         break;
3641                 }
3642         }
3643         *a = 0;
3644 }
3645
3646 gchar*
3647 ghb_dvd_volname(const gchar *device)
3648 {
3649         gchar *name;
3650         name = hb_dvd_name((gchar*)device);
3651         if (name != NULL)
3652         {
3653                 sanitize_volname(name);
3654                 return g_strdup(name);
3655         }
3656         return name;
3657 }