OSDN Git Service

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