OSDN Git Service

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