OSDN Git Service

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