OSDN Git Service

LinGui: yikes, this thing leaks worse than my roof, fixed
[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 gint
487 ghb_lookup_denoise(const GValue *denoise)
488 {
489         gint ii;
490         gchar *str;
491         gint result = -1;
492
493         str = ghb_value_string(denoise);
494         for (ii = 0; ii < denoise_opts.count; ii++)
495         {
496                 if (strcmp(denoise_opts.map[ii].shortOpt, str) == 0)
497                 {
498                         result = denoise_opts.map[ii].ivalue;
499                 }
500         }
501         g_free(str);
502         // Custom
503         return result;
504 }
505
506 gint
507 ghb_lookup_deint(const GValue *deint)
508 {
509         gint ii;
510         gchar *str;
511         gint result = -1;
512
513         str = ghb_value_string(deint);
514         for (ii = 0; ii < deint_opts.count; ii++)
515         {
516                 if (strcmp(deint_opts.map[ii].shortOpt, str) == 0)
517                 {
518                         result = deint_opts.map[ii].ivalue;
519                 }
520         }
521         g_free(str);
522         // Custom
523         return result;
524 }
525
526 gint
527 ghb_lookup_mux(const GValue *mux)
528 {
529         gint ii;
530         gchar *str;
531         gint result = HB_MUX_MKV;
532
533         str = ghb_value_string(mux);
534         for (ii = 0; ii < container_opts.count; ii++)
535         {
536                 if (strcmp(container_opts.map[ii].shortOpt, str) == 0)
537                 {
538                         result = container_opts.map[ii].ivalue;
539                 }
540         }
541         g_free(str);
542         return result;
543 }
544
545 gint
546 ghb_lookup_acodec(const GValue *acodec)
547 {
548         gint ii;
549         gchar *str;
550         gint result = HB_ACODEC_FAAC;
551
552         str = ghb_value_string(acodec);
553         for (ii = 0; ii < acodec_opts.count; ii++)
554         {
555                 if (strcmp(acodec_opts.map[ii].shortOpt, str) == 0)
556                 {
557                         result = acodec_opts.map[ii].ivalue;
558                 }
559         }
560         g_free(str);
561         return result;
562 }
563
564 gint
565 ghb_lookup_mix(const GValue *mix)
566 {
567         gint ii;
568         gchar *str;
569         gint result = HB_AMIXDOWN_DOLBYPLII;
570
571
572         str = ghb_value_string(mix);
573         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
574         {
575                 if (strcmp(hb_audio_mixdowns[ii].short_name, str) == 0)
576                 {
577                         result = hb_audio_mixdowns[ii].amixdown;
578                 }
579         }
580         g_free(str);
581         return result;
582 }
583
584 #if 0
585 gint
586 ghb_lookup_bitrate(const gchar *bitrate)
587 {
588         gint ii;
589
590         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
591         {
592                 if (strcmp(hb_audio_bitrates[ii].string, bitrate) == 0)
593                 {
594                         return hb_audio_bitrates[ii].rate * 1000;
595                 }
596         }
597         return 160 * 1000;
598 }
599
600 gint
601 ghb_lookup_rate(const gchar *rate)
602 {
603         gint ii;
604
605         for (ii = 0; ii < hb_audio_rates_count; ii++)
606         {
607                 if (strcmp(hb_audio_rates[ii].string, rate) == 0)
608                 {
609                         return hb_audio_rates[ii].rate;
610                 }
611         }
612         // Coincidentally, the string "source" will return 0
613         // which is our flag to use "same as source"
614         return 0;
615 }
616
617 gdouble
618 ghb_lookup_drc(const gchar *drc)
619 {
620         gdouble dval;
621         dval = g_strtod(drc, NULL);
622         if (dval < 1.0) dval = 1.0;
623         if (dval > 4.0) dval = 4.0;
624         return dval;
625 }
626 #endif
627
628 static GValue*
629 get_acodec_value(gint val)
630 {
631         GValue *value = NULL;
632         gint ii;
633
634         for (ii = 0; ii < acodec_opts.count; ii++)
635         {
636                 if (acodec_opts.map[ii].ivalue == val)
637                 {
638                         value = ghb_combo_value_new(
639                                 ii,
640                                 acodec_opts.map[ii].option,
641                                 acodec_opts.map[ii].shortOpt,
642                                 acodec_opts.map[ii].svalue,
643                                 acodec_opts.map[ii].ivalue);
644                         break;
645                 }
646         }
647         return value;
648 }
649
650 static GValue*
651 get_amix_value(gint val)
652 {
653         GValue *value = NULL;
654         gint ii;
655
656         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
657         {
658                 if (hb_audio_mixdowns[ii].amixdown == val)
659                 {
660                         value = ghb_combo_value_new(
661                                 ii,
662                                 hb_audio_mixdowns[ii].human_readable_name,
663                                 hb_audio_mixdowns[ii].short_name,
664                                 hb_audio_mixdowns[ii].internal_name,
665                                 hb_audio_mixdowns[ii].amixdown);
666                         break;
667                 }
668         }
669         return value;
670 }
671
672 // Handle for libhb.  Gets set by ghb_backend_init()
673 static hb_handle_t * h_scan = NULL;
674 static hb_handle_t * h_queue = NULL;
675
676 extern void hb_get_tempory_directory(hb_handle_t *h, char path[512]);
677
678 void
679 ghb_hb_cleanup(gboolean partial)
680 {
681         char dir[512];
682
683         hb_get_tempory_directory(h_scan, dir);
684         del_tree(dir, !partial);
685 }
686
687 gint
688 ghb_get_title_number(gint titleindex)
689 {
690         hb_list_t  * list;
691         hb_title_t * title;
692         
693         if (h_scan == NULL) return 1;
694         list = hb_get_titles( h_scan );
695         if( !hb_list_count( list ) )
696         {
697                 /* No valid title, stop right there */
698                 return 1;
699         }
700         title = hb_list_item( list, titleindex );
701         if (title == NULL) return 1;    // Bad titleindex
702         return title->index;
703 }
704
705 static hb_audio_config_t*
706 get_hb_audio(gint titleindex, gint track)
707 {
708         hb_list_t  * list;
709         hb_title_t * title;
710     hb_audio_config_t *audio = NULL;
711         
712     if (h_scan == NULL) return NULL;
713         list = hb_get_titles( h_scan );
714         if( !hb_list_count( list ) )
715         {
716                 /* No valid title, stop right there */
717                 return NULL;
718         }
719     title = hb_list_item( list, titleindex );
720         if (title == NULL) return NULL; // Bad titleindex
721         if (!hb_list_count(title->list_audio))
722         {
723                 return NULL;
724         }
725     audio = (hb_audio_config_t *)hb_list_audio_config_item(title->list_audio, track);
726         return audio;
727 }
728
729 static gint
730 search_rates(hb_rate_t *rates, gint rate, gint count)
731 {
732         gint ii;
733         for (ii = 0; ii < count; ii++)
734         {
735                 if (rates[ii].rate == rate)
736                         return ii;
737         }
738         return -1;
739 }
740
741 static gboolean find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter);
742
743 static GtkListStore*
744 get_combo_box_store(GtkBuilder *builder, const gchar *name)
745 {
746         GtkComboBox *combo;
747         GtkListStore *store;
748
749         g_debug("get_combo_box_store() %s\n", name);
750         // First modify the combobox model to allow greying out of options
751         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
752         store = GTK_LIST_STORE(gtk_combo_box_get_model (combo));
753         return store;
754 }
755
756 static void
757 grey_combo_box_item(GtkBuilder *builder, const gchar *name, gint value, gboolean grey)
758 {
759         GtkListStore *store;
760         GtkTreeIter iter;
761         
762         store = get_combo_box_store(builder, name);
763         if (find_combo_item_by_int(GTK_TREE_MODEL(store), value, &iter))
764         {
765                 gtk_list_store_set(store, &iter, 
766                                                    1, !grey, 
767                                                    -1);
768         }
769 }
770
771 void
772 ghb_grey_combo_options(GtkBuilder *builder)
773 {
774         GtkWidget *widget;
775         gint container, track, titleindex, acodec;
776         gboolean httpopt;
777     hb_audio_config_t *audio = NULL;
778         
779         widget = GHB_WIDGET (builder, "title");
780         titleindex = ghb_widget_int(widget);
781         widget = GHB_WIDGET (builder, "audio_track");
782         track = ghb_widget_int(widget);
783         audio = get_hb_audio(titleindex, track);
784         widget = GHB_WIDGET (builder, "container");
785         container = ghb_widget_int(widget);
786         widget = GHB_WIDGET (builder, "http_optimize_mp4");
787         httpopt = ghb_widget_int(widget);
788
789         grey_combo_box_item(builder, "audio_codec", HB_ACODEC_FAAC, FALSE);
790         grey_combo_box_item(builder, "audio_codec", HB_ACODEC_LAME, FALSE);
791         grey_combo_box_item(builder, "audio_codec", HB_ACODEC_VORBIS, FALSE);
792
793         gboolean allow_ac3 = TRUE;
794         allow_ac3 = 
795                 !(container == HB_MUX_MP4 && httpopt) &&
796                 (container != HB_MUX_OGM);
797
798         if (allow_ac3)
799         {
800                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_AC3, FALSE);
801         }
802         else
803         {
804                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_AC3, TRUE);
805         }
806         if (audio && audio->in.codec != HB_ACODEC_AC3)
807         {
808                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_AC3, TRUE);
809         }
810         grey_combo_box_item(builder, "video_codec", HB_VCODEC_THEORA, FALSE);
811
812         widget = GHB_WIDGET (builder, "audio_codec");
813         acodec = ghb_widget_int(widget);
814         if (acodec != HB_ACODEC_AC3)
815         {
816                 grey_combo_box_item(builder, "audio_mix", 0, TRUE);
817         }
818         if (container == HB_MUX_MP4)
819         {
820                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_LAME, TRUE);
821                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_VORBIS, TRUE);
822                 grey_combo_box_item(builder, "video_codec", HB_VCODEC_THEORA, TRUE);
823         }
824         else if (container == HB_MUX_AVI)
825         {
826                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_FAAC, TRUE);
827                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_VORBIS, TRUE);
828                 grey_combo_box_item(builder, "video_codec", HB_VCODEC_THEORA, TRUE);
829         }
830         else if (container == HB_MUX_OGM)
831         {
832                 grey_combo_box_item(builder, "audio_codec", HB_ACODEC_FAAC, TRUE);
833         }
834
835         gboolean allow_mono = TRUE;
836         gboolean allow_stereo = TRUE;
837         gboolean allow_dolby = TRUE;
838         gboolean allow_dpl2 = TRUE;
839         gboolean allow_6ch = TRUE;
840         if (audio)
841         {
842                 allow_mono =
843                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
844                         (acodec != HB_ACODEC_LAME);
845                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
846                 allow_stereo =
847                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
848                 allow_dolby =
849                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
850                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
851                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
852                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
853                 allow_6ch =
854                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
855                         (acodec != HB_ACODEC_LAME) &&
856                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
857                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
858         }
859         grey_combo_box_item(builder, "audio_mix", HB_AMIXDOWN_MONO, !allow_mono);
860         grey_combo_box_item(builder, "audio_mix", HB_AMIXDOWN_STEREO, !allow_stereo);
861         grey_combo_box_item(builder, "audio_mix", HB_AMIXDOWN_DOLBY, !allow_dolby);
862         grey_combo_box_item(builder, "audio_mix", HB_AMIXDOWN_DOLBYPLII, !allow_dpl2);
863         grey_combo_box_item(builder, "audio_mix", HB_AMIXDOWN_6CH, !allow_6ch);
864 }
865
866 gint
867 ghb_get_best_mix(gint titleindex, gint track, gint acodec, gint mix)
868 {
869     hb_audio_config_t *audio = NULL;
870         gboolean allow_mono = TRUE;
871         gboolean allow_stereo = TRUE;
872         gboolean allow_dolby = TRUE;
873         gboolean allow_dpl2 = TRUE;
874         gboolean allow_6ch = TRUE;
875         
876         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
877         {
878                 // Audio codec pass-thru.  No mixdown
879                 return 0;
880         }
881         audio = get_hb_audio(titleindex, track);
882         if (audio)
883         {
884                 allow_mono =
885                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
886                         (acodec != HB_ACODEC_LAME);
887                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
888                 allow_stereo =
889                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
890                 allow_dolby =
891                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
892                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
893                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
894                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
895                 allow_6ch =
896                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
897                         (acodec != HB_ACODEC_LAME) &&
898                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
899                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
900         }
901         gboolean greater = FALSE;
902         if (mix == 0) 
903         {
904                 // If no mix is specified, select the best available.
905                 mix = HB_AMIXDOWN_6CH;
906         }
907         if (mix == HB_AMIXDOWN_6CH)
908         {
909                 greater = TRUE;
910                 if (allow_6ch) return HB_AMIXDOWN_6CH;
911         }
912         if (mix == HB_AMIXDOWN_DOLBYPLII || greater)
913         {
914                 greater = TRUE;
915                 if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
916         }
917         if (mix == HB_AMIXDOWN_DOLBY || greater)
918         {
919                 greater = TRUE;
920                 if (allow_dolby) return HB_AMIXDOWN_DOLBY;
921         }
922         if (mix == HB_AMIXDOWN_STEREO || greater)
923         {
924                 greater = TRUE;
925                 if (allow_stereo) return HB_AMIXDOWN_STEREO;
926         }
927         if (mix == HB_AMIXDOWN_MONO || greater)
928         {
929                 greater = TRUE;
930                 if (allow_mono) return HB_AMIXDOWN_MONO;
931         }
932         if (allow_stereo) return HB_AMIXDOWN_STEREO;
933         if (allow_dolby) return HB_AMIXDOWN_DOLBY;
934         if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
935         if (allow_6ch) return HB_AMIXDOWN_6CH;
936         return 0;
937 }
938
939 // Set up the model for the combo box
940 static void
941 init_combo_box(GtkBuilder *builder, const gchar *name)
942 {
943         GtkComboBox *combo;
944         GtkListStore *store;
945         GtkCellRenderer *cell;
946
947         g_debug("init_combo_box() %s\n", name);
948         // First modify the combobox model to allow greying out of options
949         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
950         // Store contains:
951         // 1 - String to display
952         // 2 - bool indicating whether the entry is selectable (grey or not)
953         // 3 - String that is used for presets
954         // 4 - Int value determined by backend
955         // 5 - String value determined by backend
956         store = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_BOOLEAN, 
957                                                            G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING);
958         gtk_combo_box_set_model(combo, GTK_TREE_MODEL(store));
959
960         gtk_cell_layout_clear(GTK_CELL_LAYOUT(combo));
961     cell = GTK_CELL_RENDERER(gtk_cell_renderer_text_new());
962     gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE);
963     gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell,
964       "text", 0, "sensitive", 1, NULL);
965 }       
966
967 // Set up the model for the combo box
968 static void
969 init_combo_box_entry(GtkBuilder *builder, const gchar *name)
970 {
971         GtkComboBox *combo;
972         GtkListStore *store;
973
974         g_debug("init_combo_box_entry() %s\n", name);
975         // First modify the combobox model to allow greying out of options
976         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
977         // Store contains:
978         // 1 - String to display
979         // 2 - bool indicating whether the entry is selectable (grey or not)
980         // 3 - String that is used for presets
981         // 4 - Int value determined by backend
982         // 5 - String value determined by backend
983         store = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_BOOLEAN, 
984                                                            G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING);
985         gtk_combo_box_set_model(combo, GTK_TREE_MODEL(store));
986         gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(combo), 0);
987 }       
988
989 static void
990 audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
991 {
992         GtkTreeIter iter;
993         GtkListStore *store;
994         gint ii;
995         
996         g_debug("audio_bitrate_opts_set ()\n");
997         store = get_combo_box_store(builder, name);
998         gtk_list_store_clear(store);
999         for (ii = 0; ii < count; ii++)
1000         {
1001                 gtk_list_store_append(store, &iter);
1002                 gtk_list_store_set(store, &iter, 
1003                                                    0, rates[ii].string, 
1004                                                    1, TRUE, 
1005                                                    2, rates[ii].string, 
1006                                                    3, rates[ii].rate * 1000, 
1007                                                    4, rates[ii].string, 
1008                                                    -1);
1009         }
1010 }
1011
1012 static gboolean
1013 audio_bitrate_opts_clean(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1014 {
1015         GtkTreeIter iter;
1016         GtkListStore *store;
1017         gint ivalue;
1018         gboolean done = FALSE;
1019         gboolean changed = FALSE;
1020         
1021         g_debug("audio_bitrate_opts_clean ()\n");
1022         store = get_combo_box_store(builder, name);
1023         if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL(store), &iter))
1024         {
1025                 do
1026                 {
1027                         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 3, &ivalue, -1);
1028                         if (search_rates(rates, ivalue/1000, count) < 0)
1029                         {
1030                                 done = !gtk_list_store_remove(store, &iter);
1031                                 changed = TRUE;
1032                         }
1033                         else
1034                         {
1035                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
1036                         }
1037                 } while (!done);
1038         }
1039         return changed;
1040 }
1041
1042 static void
1043 audio_samplerate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1044 {
1045         GtkTreeIter iter;
1046         GtkListStore *store;
1047         gint ii;
1048         
1049         g_debug("audio_samplerate_opts_set ()\n");
1050         store = get_combo_box_store(builder, name);
1051         gtk_list_store_clear(store);
1052         // Add an item for "Same As Source"
1053         gtk_list_store_append(store, &iter);
1054         gtk_list_store_set(store, &iter, 
1055                                            0, "Same as source", 
1056                                            1, TRUE, 
1057                                            2, "source", 
1058                                            3, 0, 
1059                                            4, "source", 
1060                                            -1);
1061         for (ii = 0; ii < count; ii++)
1062         {
1063                 gtk_list_store_append(store, &iter);
1064                 gtk_list_store_set(store, &iter, 
1065                                                    0, rates[ii].string, 
1066                                                    1, TRUE, 
1067                                                    2, rates[ii].string, 
1068                                                    3, rates[ii].rate, 
1069                                                    4, rates[ii].string, 
1070                                                    -1);
1071         }
1072 }
1073
1074 static void
1075 video_rate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1076 {
1077         GtkTreeIter iter;
1078         GtkListStore *store;
1079         gint ii;
1080         
1081         g_debug("video_rate_opts_set ()\n");
1082         store = get_combo_box_store(builder, name);
1083         gtk_list_store_clear(store);
1084         // Add an item for "Same As Source"
1085         gtk_list_store_append(store, &iter);
1086         gtk_list_store_set(store, &iter, 
1087                                            0, "Same as source", 
1088                                            1, TRUE, 
1089                                            2, "source", 
1090                                            3, 0, 
1091                                            4, "source", 
1092                                            -1);
1093         for (ii = 0; ii < count; ii++)
1094         {
1095                 gchar *desc = "";
1096                 gchar *option;
1097                 if (strcmp(rates[ii].string, "23.976") == 0)
1098                 {
1099                         desc = "(NTSC Film)";
1100                 }
1101                 else if (strcmp(rates[ii].string, "25") == 0)
1102                 {
1103                         desc = "(PAL Film/Video)";
1104                 }
1105                 else if (strcmp(rates[ii].string, "29.97") == 0)
1106                 {
1107                         desc = "(NTSC Video)";
1108                 }
1109                 option = g_strdup_printf ("%s %s", rates[ii].string, desc);
1110                 gtk_list_store_append(store, &iter);
1111                 gtk_list_store_set(store, &iter, 
1112                                                    0, option, 
1113                                                    1, TRUE, 
1114                                                    2, rates[ii].string, 
1115                                                    3, rates[ii].rate, 
1116                                                    4, rates[ii].string, 
1117                                                    -1);
1118                 g_free(option);
1119         }
1120 }
1121
1122 static void
1123 mix_opts_set(GtkBuilder *builder, const gchar *name)
1124 {
1125         GtkTreeIter iter;
1126         GtkListStore *store;
1127         gint ii;
1128         
1129         g_debug("mix_opts_set ()\n");
1130         store = get_combo_box_store(builder, name);
1131         gtk_list_store_clear(store);
1132         gtk_list_store_append(store, &iter);
1133         gtk_list_store_set(store, &iter, 
1134                                            0, "None", 
1135                                            1, TRUE, 
1136                                            2, "none", 
1137                                            3, 0, 
1138                                            4, "none", 
1139                                            -1);
1140         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1141         {
1142                 gtk_list_store_append(store, &iter);
1143                 gtk_list_store_set(store, &iter, 
1144                                                    0, hb_audio_mixdowns[ii].human_readable_name, 
1145                                                    1, TRUE, 
1146                                                    2, hb_audio_mixdowns[ii].short_name, 
1147                                                    3, hb_audio_mixdowns[ii].amixdown, 
1148                                                    4, hb_audio_mixdowns[ii].internal_name, 
1149                                                    -1);
1150         }
1151 }
1152
1153 static void
1154 language_opts_set(GtkBuilder *builder, const gchar *name)
1155 {
1156         GtkTreeIter iter;
1157         GtkListStore *store;
1158         gint ii;
1159         
1160         g_debug("language_opts_set ()\n");
1161         store = get_combo_box_store(builder, name);
1162         gtk_list_store_clear(store);
1163         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1164         {
1165                 gtk_list_store_append(store, &iter);
1166                 gtk_list_store_set(store, &iter, 
1167                                                    0, language_table[ii].eng_name, 
1168                                                    1, TRUE, 
1169                                                    2, language_table[ii].iso639_2, 
1170                                                    3, ii, 
1171                                                    4, language_table[ii].iso639_1, 
1172                                                    -1);
1173         }
1174 }
1175
1176 void
1177 title_opts_set(GtkBuilder *builder, const gchar *name)
1178 {
1179         GtkTreeIter iter;
1180         GtkListStore *store;
1181         hb_list_t  * list;
1182         hb_title_t * title;
1183         gint ii;
1184         gint count = 0;
1185         
1186         g_debug("title_opts_set ()\n");
1187         store = get_combo_box_store(builder, name);
1188         gtk_list_store_clear(store);
1189         if (h_scan != NULL)
1190         {
1191                 list = hb_get_titles( h_scan );
1192                 count = hb_list_count( list );
1193                 if (count > 100) count = 100;
1194         }
1195         if( count <= 0 )
1196         {
1197                 // No titles.  Fill in a default.
1198                 gtk_list_store_append(store, &iter);
1199                 gtk_list_store_set(store, &iter, 
1200                                                    0, "No Titles", 
1201                                                    1, TRUE, 
1202                                                    2, "none", 
1203                                                    3, -1, 
1204                                                    4, "none", 
1205                                                    -1);
1206                 return;
1207         }
1208         for (ii = 0; ii < count; ii++)
1209         {
1210                 gchar *option;
1211                 
1212                 title = (hb_title_t*)hb_list_item(list, ii);
1213                 if (title->duration != 0)
1214                 {
1215                         option  = g_strdup_printf ("%d - %02dh%02dm%02ds",
1216                                 title->index, title->hours, title->minutes, title->seconds);
1217                 }
1218                 else
1219                 {
1220                         option  = g_strdup_printf ("%d - Unknown Length", title->index);
1221                 }
1222                 gtk_list_store_append(store, &iter);
1223                 gtk_list_store_set(store, &iter, 
1224                                                    0, option, 
1225                                                    1, TRUE, 
1226                                                    2, option, 
1227                                                    3, ii, 
1228                                                    4, option, 
1229                                                    -1);
1230                 g_free(option);
1231         }
1232 }
1233
1234 static gboolean
1235 find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter)
1236 {
1237         gint ivalue;
1238         gboolean foundit = FALSE;
1239         
1240         if (gtk_tree_model_get_iter_first (store, iter))
1241         {
1242                 do
1243                 {
1244                         gtk_tree_model_get(store, iter, 3, &ivalue, -1);
1245                         if (value == ivalue)
1246                         {
1247                                 foundit = TRUE;
1248                                 break;
1249                         }
1250                 } while (gtk_tree_model_iter_next (store, iter));
1251         }
1252         return foundit;
1253 }
1254
1255 static gboolean
1256 audio_rate_opts_add(GtkBuilder *builder, const gchar *name, gint rate)
1257 {
1258         GtkTreeIter iter;
1259         GtkListStore *store;
1260         gchar *str;
1261         
1262         g_debug("audio_rate_opts_add ()\n");
1263         store = get_combo_box_store(builder, name);
1264         if (!find_combo_item_by_int(GTK_TREE_MODEL(store), rate, &iter))
1265         {
1266                 str = g_strdup_printf ("%.8g", (gdouble)rate/1000.0);
1267                 gtk_list_store_append(store, &iter);
1268                 gtk_list_store_set(store, &iter, 
1269                                                    0, str, 
1270                                                    1, TRUE, 
1271                                                    2, str, 
1272                                                    3, rate, 
1273                                                    4, str, 
1274                                                    -1);
1275                 g_free(str);
1276                 return TRUE;
1277         }
1278         return FALSE;
1279 }
1280
1281 void
1282 audio_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1283 {
1284         GtkTreeIter iter;
1285         GtkListStore *store;
1286         hb_list_t  * list;
1287         hb_title_t * title;
1288     hb_audio_config_t * audio;
1289         gint ii;
1290         gint count = 0;
1291         
1292         g_debug("audio_track_opts_set ()\n");
1293         store = get_combo_box_store(builder, name);
1294         gtk_list_store_clear(store);
1295         if (h_scan != NULL)
1296         {
1297                 list = hb_get_titles( h_scan );
1298             title = (hb_title_t*)hb_list_item( list, titleindex );
1299                 if (title != NULL)
1300                 {
1301                         count = hb_list_count( title->list_audio );
1302                 }
1303         }
1304         if (count > 10) count = 10;
1305         if( count <= 0 )
1306         {
1307                 // No audio. set some default
1308                 gtk_list_store_append(store, &iter);
1309                 gtk_list_store_set(store, &iter, 
1310                                                    0, "No Audio", 
1311                                                    1, TRUE, 
1312                                                    2, "none", 
1313                                                    3, -1, 
1314                                                    4, "none", 
1315                                                    -1);
1316                 return;
1317         }
1318         for (ii = 0; ii < count; ii++)
1319         {
1320         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, ii );
1321                 gtk_list_store_append(store, &iter);
1322                 gtk_list_store_set(store, &iter, 
1323                                                    0, audio->lang.description, 
1324                                                    1, TRUE, 
1325                                                    2, audio->lang.description, 
1326                                                    3, ii, 
1327                                                    4, audio->lang.description, 
1328                                                    -1);
1329         }
1330 }
1331
1332 void
1333 subtitle_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1334 {
1335         GtkTreeIter iter;
1336         GtkListStore *store;
1337         hb_list_t  * list;
1338         hb_title_t * title;
1339     hb_subtitle_t * subtitle;
1340         gint ii;
1341         gint count = 0;
1342         
1343         g_debug("subtitle_opts_set ()\n");
1344         store = get_combo_box_store(builder, name);
1345         gtk_list_store_clear(store);
1346         if (h_scan != NULL)
1347         {
1348                 list = hb_get_titles( h_scan );
1349             title = (hb_title_t*)hb_list_item( list, titleindex );
1350                 if (title != NULL)
1351                 {
1352                         count = hb_list_count( title->list_subtitle );
1353                 }
1354         }
1355         if (count > 10) count = 10;
1356         // Add options for "none" and "autoselect"
1357         gtk_list_store_append(store, &iter);
1358         gtk_list_store_set(store, &iter, 
1359                                            0, "None", 
1360                                            1, TRUE, 
1361                                            2, "none", 
1362                                            3, -2, 
1363                                            4, "none", 
1364                                            -1);
1365         gtk_list_store_append(store, &iter);
1366         gtk_list_store_set(store, &iter, 
1367                                            0, "Same As Audio", 
1368                                            1, TRUE, 
1369                                            2, "auto", 
1370                                            3, -1, 
1371                                            4, "auto", 
1372                                            -1);
1373         for (ii = 0; ii < count; ii++)
1374         {
1375         subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, ii );
1376                 gtk_list_store_append(store, &iter);
1377                 gtk_list_store_set(store, &iter, 
1378                                                    0, subtitle->lang, 
1379                                                    1, TRUE, 
1380                                                    2, subtitle->iso639_2, 
1381                                                    3, ii, 
1382                                                    4, subtitle->iso639_2, 
1383                                                    -1);
1384         }
1385         if (titleindex == -1)
1386         {
1387                 for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1388                 {
1389                         gtk_list_store_append(store, &iter);
1390                         gtk_list_store_set(store, &iter, 
1391                                 0, language_table[ii].eng_name, 
1392                                 1, TRUE, 
1393                                 2, language_table[ii].iso639_2, 
1394                                 3, ii, 
1395                                 4, language_table[ii].iso639_2, 
1396                                 -1);
1397                 }
1398         }
1399 }
1400
1401 gint
1402 ghb_longest_title()
1403 {
1404         hb_list_t  * list;
1405         hb_title_t * title;
1406         gint ii;
1407         gint count = 0;
1408         guint64 longest = 0;
1409         gint titleindex = 0;
1410         
1411         g_debug("ghb_longest_title ()\n");
1412         if (h_scan == NULL) return 0;
1413         list = hb_get_titles( h_scan );
1414         count = hb_list_count( list );
1415         if (count > 100) count = 100;
1416         for (ii = 0; ii < count; ii++)
1417         {
1418                 title = (hb_title_t*)hb_list_item(list, ii);
1419                 if (title->duration > longest)
1420                 {
1421                         titleindex = ii;
1422                         longest = title->duration;
1423                 }
1424         }
1425         return titleindex;
1426 }
1427
1428 gint
1429 ghb_find_audio_track(gint titleindex, const gchar *lang, gint index)
1430 {
1431         hb_list_t  * list;
1432         hb_title_t * title;
1433     hb_audio_config_t * audio;
1434         gint ii;
1435         gint count = 0;
1436         gint track = -1;
1437         gint match = 0;
1438         
1439         g_debug("find_audio_track ()\n");
1440         if (h_scan != NULL)
1441         {
1442                 list = hb_get_titles( h_scan );
1443             title = (hb_title_t*)hb_list_item( list, titleindex );
1444                 if (title != NULL)
1445                 {
1446                         count = hb_list_count( title->list_audio );
1447                 }
1448         }
1449         if (count > 10) count = 10;
1450         for (ii = 0; ii < count; ii++)
1451         {
1452         audio = (hb_audio_config_t*)hb_list_audio_config_item( title->list_audio, ii );
1453                 if ((strcmp(lang, audio->lang.iso639_2) == 0) ||
1454                         (strcmp(lang, "und") == 0))
1455                 {
1456                         if (index == match)
1457                         {
1458                                 track = ii;
1459                                 break;
1460                         }
1461                         match++;
1462                 }
1463         }
1464         return track;
1465 }
1466
1467 static void
1468 generic_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
1469 {
1470         GtkTreeIter iter;
1471         GtkListStore *store;
1472         gint ii;
1473         
1474         g_debug("generic_opts_set ()\n");
1475         store = get_combo_box_store(builder, name);
1476         gtk_list_store_clear(store);
1477         for (ii = 0; ii < opts->count; ii++)
1478         {
1479                 gtk_list_store_append(store, &iter);
1480                 gtk_list_store_set(store, &iter, 
1481                                                    0, opts->map[ii].option, 
1482                                                    1, TRUE, 
1483                                                    2, opts->map[ii].shortOpt, 
1484                                                    3, opts->map[ii].ivalue, 
1485                                                    4, opts->map[ii].svalue, 
1486                                                    -1);
1487         }
1488 }
1489
1490 void
1491 ghb_update_ui_combo_box(GtkBuilder *builder, const gchar *name, gint user_data, gboolean all)
1492 {
1493         GtkComboBox *combo = NULL;
1494         gint signal_id;
1495         gint handler_id = 0;
1496
1497         g_debug("ghb_update_ui_combo_box() %s\n", name);
1498         if (name != NULL)
1499         {               
1500                 // Clearing a combo box causes a rash of "changed" events, even when
1501                 // the active item is -1 (inactive).  To control things, I'm disabling
1502                 // the event till things are settled down.
1503                 combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1504                 signal_id = g_signal_lookup("changed", GTK_TYPE_COMBO_BOX);
1505                 if (signal_id > 0)
1506                 {
1507                         // Valid signal id found.  This should always succeed.
1508                         handler_id = g_signal_handler_find ((gpointer)combo, G_SIGNAL_MATCH_ID, 
1509                                                                                                 signal_id, 0, 0, 0, 0);
1510                         if (handler_id > 0)
1511                         {
1512                                 // This should also always succeed
1513                                 g_signal_handler_block ((gpointer)combo, handler_id);
1514                         }
1515                 }
1516         }       
1517         if (all || strcmp(name, "audio_bitrate") == 0)
1518                 audio_bitrate_opts_set(builder, "audio_bitrate", hb_audio_bitrates, hb_audio_bitrates_count);
1519         if (all || strcmp(name, "audio_rate") == 0)
1520                 audio_samplerate_opts_set(builder, "audio_rate", hb_audio_rates, hb_audio_rates_count);
1521         if (all || strcmp(name, "framerate") == 0)
1522                 video_rate_opts_set(builder, "framerate", hb_video_rates, hb_video_rates_count);
1523         if (all || strcmp(name, "audio_mix") == 0)
1524                 mix_opts_set(builder, "audio_mix");
1525         if (all || strcmp(name, "source_audio_lang") == 0)
1526                 language_opts_set(builder, "source_audio_lang");
1527         if (all || strcmp(name, "subtitle_lang") == 0)
1528                 subtitle_opts_set(builder, "subtitle_lang", user_data);
1529         if (all || strcmp(name, "title") == 0)
1530                 title_opts_set(builder, "title");
1531         if (all || strcmp(name, "audio_track") == 0)
1532                 audio_track_opts_set(builder, "audio_track", user_data);
1533         if (all || strcmp(name, "container") == 0)
1534                 generic_opts_set(builder, "container", &container_opts);
1535         if (all || strcmp(name, "deinterlace") == 0)
1536                 generic_opts_set(builder, "deinterlace", &deint_opts);
1537         if (all || strcmp(name, "tweak_deinterlace") == 0)
1538                 generic_opts_set(builder, "tweak_deinterlace", &deint_opts);
1539         if (all || strcmp(name, "denoise") == 0)
1540                 generic_opts_set(builder, "denoise", &denoise_opts);
1541         if (all || strcmp(name, "tweak_denoise") == 0)
1542                 generic_opts_set(builder, "tweak_denoise", &denoise_opts);
1543         if (all || strcmp(name, "video_codec") == 0)
1544                 generic_opts_set(builder, "video_codec", &vcodec_opts);
1545         if (all || strcmp(name, "audio_codec") == 0)
1546                 generic_opts_set(builder, "audio_codec", &acodec_opts);
1547         if (all || strcmp(name, "x264_direct") == 0)
1548                 generic_opts_set(builder, "x264_direct", &direct_opts);
1549         if (all || strcmp(name, "x264_me") == 0)
1550                 generic_opts_set(builder, "x264_me", &me_opts);
1551         if (all || strcmp(name, "x264_subme") == 0)
1552                 generic_opts_set(builder, "x264_subme", &subme_opts);
1553         if (all || strcmp(name, "x264_analyse") == 0)
1554                 generic_opts_set(builder, "x264_analyse", &analyse_opts);
1555         if (all || strcmp(name, "x264_trellis") == 0)
1556                 generic_opts_set(builder, "x264_trellis", &trellis_opts);
1557         if (handler_id > 0)
1558         {
1559                 g_signal_handler_unblock ((gpointer)combo, handler_id);
1560         }
1561 }
1562         
1563 static void
1564 init_ui_combo_boxes(GtkBuilder *builder)
1565 {
1566         init_combo_box(builder, "audio_bitrate");
1567         init_combo_box(builder, "audio_rate");
1568         init_combo_box(builder, "framerate");
1569         init_combo_box(builder, "audio_mix");
1570         init_combo_box(builder, "source_audio_lang");
1571         init_combo_box(builder, "subtitle_lang");
1572         init_combo_box(builder, "title");
1573         init_combo_box(builder, "audio_track");
1574         init_combo_box(builder, "container");
1575         init_combo_box(builder, "deinterlace");
1576         init_combo_box_entry(builder, "tweak_deinterlace");
1577         init_combo_box(builder, "denoise");
1578         init_combo_box_entry(builder, "tweak_denoise");
1579         init_combo_box(builder, "video_codec");
1580         init_combo_box(builder, "audio_codec");
1581         init_combo_box(builder, "x264_direct");
1582         init_combo_box(builder, "x264_me");
1583         init_combo_box(builder, "x264_subme");
1584         init_combo_box(builder, "x264_analyse");
1585         init_combo_box(builder, "x264_trellis");
1586 }
1587         
1588 static const char * turbo_opts = 
1589         "ref=1:subme=1:me=dia:analyse=none:trellis=0:"
1590         "no-fast-pskip=0:8x8dct=0:weightb=0";
1591
1592 // Construct the x264 options string
1593 // The result is allocated, so someone must free it at some point.
1594 gchar*
1595 ghb_build_x264opts_string(GValue *settings)
1596 {
1597         gchar *result;
1598         gchar *opts = ghb_settings_get_string(settings, "x264_options");
1599         if (opts != NULL)
1600         {
1601                 result = opts;
1602         }
1603         else
1604         {
1605                 result = g_strdup("");
1606         }
1607         return result;
1608 }
1609
1610 GValue*
1611 ghb_get_chapters(gint titleindex)
1612 {
1613         hb_list_t  * list;
1614         hb_title_t * title;
1615     hb_chapter_t * chapter;
1616         gint count, ii;
1617         GValue *chapters = NULL;
1618         
1619         g_debug("ghb_get_chapters (title = %d)\n", titleindex);
1620         if (h_scan == NULL) return NULL;
1621         list = hb_get_titles( h_scan );
1622     title = (hb_title_t*)hb_list_item( list, titleindex );
1623         if (title == NULL) return NULL;
1624         count = hb_list_count( title->list_chapter );
1625         chapters = ghb_array_value_new(count);
1626         for (ii = 0; ii < count; ii++)
1627         {
1628                 chapter = hb_list_item(title->list_chapter, ii);
1629                 if (chapter == NULL) break;
1630                 if (chapter->title == NULL || chapter->title[0] == 0)
1631                 {
1632                         gchar *str;
1633                         str = g_strdup_printf ("Chapter %2d", ii+1);
1634                         ghb_array_append(chapters, ghb_string_value_new(str));
1635                         g_free(str);
1636                 }
1637                 else 
1638                 {
1639                         ghb_array_append(chapters, ghb_string_value_new(chapter->title));
1640                 }
1641         }
1642         return chapters;
1643 }
1644
1645 gboolean
1646 ghb_ac3_in_audio_list(const GValue *audio_list)
1647 {
1648         gint count, ii;
1649
1650         count = ghb_array_len(audio_list);
1651         for (ii = 0; ii < count; ii++)
1652         {
1653                 GValue *asettings;
1654                 gint acodec;
1655
1656                 asettings = ghb_array_get_nth(audio_list, ii);
1657                 acodec = ghb_settings_get_int(asettings, "audio_codec");
1658                 if (acodec == HB_ACODEC_AC3)
1659                         return TRUE;
1660         }
1661         return FALSE;
1662 }
1663
1664 gboolean
1665 ghb_set_passthru_rate_opts(GtkBuilder *builder, gint bitrate)
1666 {
1667         gboolean changed = FALSE;
1668         changed = audio_rate_opts_add(builder, "audio_bitrate", bitrate);
1669         return changed;
1670 }
1671
1672 gboolean
1673 ghb_set_default_rate_opts(GtkBuilder *builder)
1674 {
1675         gboolean changed = FALSE;
1676         changed = audio_bitrate_opts_clean(builder, "audio_bitrate", hb_audio_bitrates, hb_audio_bitrates_count);
1677         return changed;
1678 }
1679
1680 static ghb_status_t hb_status;
1681
1682 void
1683 ghb_backend_init(GtkBuilder *builder, gint debug, gint update)
1684 {
1685     /* Init libhb */
1686     h_scan = hb_init( debug, update );
1687     h_queue = hb_init( debug, 0 );
1688         // Set up the list model for the combos
1689         init_ui_combo_boxes(builder);
1690         // Populate all the combos
1691         ghb_update_ui_combo_box(builder, NULL, 0, TRUE);
1692 }
1693
1694 void
1695 ghb_backend_close()
1696 {
1697         hb_close(&h_queue);
1698         hb_close(&h_scan);
1699 }
1700
1701 void
1702 ghb_backend_scan(const gchar *path, gint titleindex)
1703 {
1704     hb_scan( h_scan, path, titleindex );
1705         hb_status.state |= GHB_STATE_SCANNING;
1706         // initialize count and cur to something that won't cause FPE
1707         // when computing progress
1708         hb_status.title_count = 1;
1709         hb_status.title_cur = 0;
1710 }
1711
1712 void
1713 ghb_backend_queue_scan(const gchar *path, gint titlenum)
1714 {
1715         g_debug("ghb_backend_queue_scan()");
1716         hb_scan( h_queue, path, titlenum );
1717         hb_status.queue_state |= GHB_STATE_SCANNING;
1718 }
1719
1720 gint
1721 ghb_get_state()
1722 {
1723         return hb_status.state;
1724 }
1725
1726 gint
1727 ghb_get_queue_state()
1728 {
1729         return hb_status.queue_state;
1730 }
1731
1732 void
1733 ghb_clear_state(gint state)
1734 {
1735         hb_status.state &= ~state;
1736 }
1737
1738 void
1739 ghb_clear_queue_state(gint state)
1740 {
1741         hb_status.queue_state &= ~state;
1742 }
1743
1744 void
1745 ghb_set_state(gint state)
1746 {
1747         hb_status.state |= state;
1748 }
1749
1750 void
1751 ghb_set_queue_state(gint state)
1752 {
1753         hb_status.queue_state |= state;
1754 }
1755
1756 void
1757 ghb_get_status(ghb_status_t *status)
1758 {
1759         memcpy(status, &hb_status, sizeof(ghb_status_t));
1760 }
1761
1762 void 
1763 ghb_track_status()
1764 {
1765     hb_state_t s;
1766     hb_state_t s_queue;
1767
1768         if (h_scan == NULL) return;
1769     hb_get_state( h_scan, &s );
1770         switch( s.state )
1771     {
1772 #define p s.param.scanning
1773         case HB_STATE_SCANNING:
1774                 {
1775                         hb_status.state |= GHB_STATE_SCANNING;
1776                         hb_status.title_count = p.title_count;
1777                         hb_status.title_cur = p.title_cur;
1778                 } break;
1779 #undef p
1780
1781         case HB_STATE_SCANDONE:
1782         {
1783                         hb_status.state &= ~GHB_STATE_SCANNING;
1784                         hb_status.state |= GHB_STATE_SCANDONE;
1785         } break;
1786
1787     }
1788     hb_get_state( h_queue, &s_queue );
1789         switch( s_queue.state )
1790     {
1791         case HB_STATE_SCANNING:
1792                 {
1793                         hb_status.queue_state |= GHB_STATE_SCANNING;
1794                 } break;
1795
1796         case HB_STATE_SCANDONE:
1797         {
1798                         hb_status.queue_state &= ~GHB_STATE_SCANNING;
1799                         hb_status.queue_state |= GHB_STATE_SCANDONE;
1800         } break;
1801
1802 #define p s_queue.param.working
1803         case HB_STATE_WORKING:
1804                         hb_status.queue_state |= GHB_STATE_WORKING;
1805                         hb_status.queue_state &= ~GHB_STATE_PAUSED;
1806                         hb_status.job_cur = p.job_cur;
1807                         hb_status.job_count = p.job_count;
1808                         hb_status.progress = p.progress;
1809                         hb_status.rate_cur = p.rate_cur;
1810                         hb_status.rate_avg = p.rate_avg;
1811                         hb_status.hours = p.hours;
1812                         hb_status.minutes = p.minutes;
1813                         hb_status.seconds = p.seconds;
1814                         hb_status.unique_id = p.sequence_id & 0xFFFFFF;
1815             break;
1816 #undef p
1817
1818         case HB_STATE_PAUSED:
1819                         hb_status.queue_state |= GHB_STATE_PAUSED;
1820             break;
1821                                 
1822         case HB_STATE_MUXING:
1823         {
1824                         hb_status.queue_state |= GHB_STATE_MUXING;
1825         } break;
1826
1827 #define p s_queue.param.workdone
1828         case HB_STATE_WORKDONE:
1829                 {
1830             hb_job_t *job;
1831
1832                         hb_status.queue_state |= GHB_STATE_WORKDONE;
1833                         hb_status.queue_state &= ~GHB_STATE_MUXING;
1834                         hb_status.queue_state &= ~GHB_STATE_PAUSED;
1835                         hb_status.queue_state &= ~GHB_STATE_WORKING;
1836                         switch (p.error)
1837                         {
1838                         case HB_ERROR_NONE:
1839                                 hb_status.error = GHB_ERROR_NONE;
1840                         case HB_ERROR_CANCELED:
1841                                 hb_status.error = GHB_ERROR_CANCELED;
1842                         default:
1843                                 hb_status.error = GHB_ERROR_FAIL;
1844                         }
1845                         hb_status.error = p.error;
1846                         // Delete all remaining jobs of this encode.
1847                         // An encode can be composed of multiple associated jobs.
1848                         // When a job is stopped, libhb removes it from the job list,
1849                         // but does not remove other jobs that may be associated with it.
1850                         // Associated jobs are taged in the sequence id.
1851             while ((job = hb_job(h_queue, 0)) != NULL) 
1852                 hb_rem( h_queue, job );
1853                 } break;
1854 #undef p
1855     }
1856 }
1857
1858 gboolean
1859 ghb_get_title_info(ghb_title_info_t *tinfo, gint titleindex)
1860 {
1861         hb_list_t  * list;
1862         hb_title_t * title;
1863         
1864     if (h_scan == NULL) return FALSE;
1865         list = hb_get_titles( h_scan );
1866         if( !hb_list_count( list ) )
1867         {
1868                 /* No valid title, stop right there */
1869                 return FALSE;
1870         }
1871
1872     title = hb_list_item( list, titleindex );
1873         if (title == NULL) return FALSE;        // Bad titleindex
1874         tinfo->width = title->width;
1875         tinfo->height = title->height;
1876         memcpy(tinfo->crop, title->crop, 4 * sizeof(int));
1877         // Don't allow crop to 0
1878         if (title->crop[0] + title->crop[1] >= title->height)
1879                 title->crop[0] = title->crop[1] = 0;
1880         if (title->crop[2] + title->crop[3] >= title->width)
1881                 title->crop[2] = title->crop[3] = 0;
1882         tinfo->num_chapters = hb_list_count(title->list_chapter);
1883         tinfo->rate_base = title->rate_base;
1884         tinfo->rate = title->rate;
1885         hb_reduce(&(tinfo->aspect_n), &(tinfo->aspect_d), 
1886                                 title->width * title->pixel_aspect_width, 
1887                                 title->height * title->pixel_aspect_height);
1888         tinfo->hours = title->hours;
1889         tinfo->minutes = title->minutes;
1890         tinfo->seconds = title->seconds;
1891         tinfo->duration = title->duration;
1892         return TRUE;
1893 }
1894
1895 gboolean
1896 ghb_get_audio_info(ghb_audio_info_t *ainfo, gint titleindex, gint audioindex)
1897 {
1898     hb_audio_config_t *audio;
1899         
1900         audio = get_hb_audio(titleindex, audioindex);
1901         if (audio == NULL) return FALSE; // Bad audioindex
1902         ainfo->codec = audio->in.codec;
1903         ainfo->bitrate = audio->in.bitrate;
1904         ainfo->samplerate = audio->in.samplerate;
1905         return TRUE;
1906 }
1907
1908 gboolean
1909 ghb_audio_is_passthru(gint acodec)
1910 {
1911         g_debug("ghb_audio_is_passthru () \n");
1912         g_debug("acodec %d\n", acodec);
1913         return (acodec == HB_ACODEC_AC3);
1914 }
1915
1916 gint
1917 ghb_get_default_acodec()
1918 {
1919         return HB_ACODEC_FAAC;
1920 }
1921
1922 void
1923 ghb_set_scale(signal_user_data_t *ud, gint mode)
1924 {
1925         hb_list_t  * list;
1926         hb_title_t * title;
1927         hb_job_t   * job;
1928         gboolean keep_aspect, round_dims, anamorphic;
1929         gboolean autocrop, autoscale, noscale;
1930         gint crop[4], width, height, par_width, par_height;
1931         gint crop_width, crop_height;
1932         gint aspect_n, aspect_d;
1933         gboolean keep_width = (mode == GHB_SCALE_KEEP_WIDTH);
1934         gboolean keep_height = (mode == GHB_SCALE_KEEP_HEIGHT);
1935         gint step;
1936         GtkWidget *widget;
1937         gint modshift;
1938         gint modround;
1939         gint max_width = 0;
1940         gint max_height = 0;
1941         
1942         g_debug("ghb_set_scale ()\n");
1943
1944         if (h_scan == NULL) return;
1945         list = hb_get_titles( h_scan );
1946         if( !hb_list_count( list ) )
1947         {
1948                 /* No valid title, stop right there */
1949                 return;
1950         }
1951         gint titleindex = ghb_settings_get_int(ud->settings, "title");
1952     title = hb_list_item( list, titleindex );
1953         if (title == NULL) return;
1954         job   = title->job;
1955         if (job == NULL) return;
1956         
1957         // First configure widgets
1958         round_dims = ghb_settings_get_boolean(ud->settings, "round_dimensions");
1959         anamorphic = ghb_settings_get_boolean(ud->settings, "anamorphic");
1960         keep_aspect = ghb_settings_get_boolean(ud->settings, "keep_aspect");
1961         autocrop = ghb_settings_get_boolean(ud->settings, "autocrop");
1962         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
1963         // "Noscale" is a flag that says we prefer to crop extra to satisfy
1964         // alignment constraints rather than scaling to satisfy them.
1965         noscale = ghb_settings_get_boolean(ud->settings, "noscale");
1966         // Align dimensions to either 16 or 2 pixels
1967         // The scaler crashes if the dimensions are not divisible by 2
1968         // x264 also will not accept dims that are not multiple of 2
1969         modshift = round_dims ? 4 : 1;
1970         modround = round_dims ? 8 : 1;
1971         if (autoscale)
1972         {
1973                 keep_width = FALSE;
1974                 keep_height = FALSE;
1975         }
1976         if (anamorphic || keep_aspect)
1977         {
1978                 keep_height = FALSE;
1979         }
1980         // Step needs to be at least 2 because odd widths cause scaler crash
1981         step = round_dims ? 16 : 2;
1982         widget = GHB_WIDGET (ud->builder, "scale_width");
1983         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
1984         widget = GHB_WIDGET (ud->builder, "scale_height");
1985         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
1986         if (autocrop)
1987         {
1988                 ghb_title_info_t tinfo;
1989
1990                 if (ghb_get_title_info (&tinfo, titleindex))
1991                 {
1992                         crop[0] = tinfo.crop[0];
1993                         crop[1] = tinfo.crop[1];
1994                         crop[2] = tinfo.crop[2];
1995                         crop[3] = tinfo.crop[3];
1996                         if (noscale)
1997                         {
1998                                 gint need1, need2;
1999
2000                                 // Adjust the cropping to accomplish the desired width and height
2001                                 crop_width = tinfo.width - crop[2] - crop[3];
2002                                 crop_height = tinfo.height - crop[0] - crop[1];
2003                                 width = (crop_width >> modshift) << modshift;
2004                                 height = (crop_height >> modshift) << modshift;
2005                                 need1 = (crop_height - height) / 2;
2006                                 need2 = crop_height - height - need1;
2007                                 crop[0] += need1;
2008                                 crop[1] += need2;
2009                                 need1 = (crop_width - width) / 2;
2010                                 need2 = crop_width - width - need1;
2011                                 crop[2] += need1;
2012                                 crop[3] += need2;
2013                         }
2014                         ghb_ui_update(ud, "crop_top", ghb_int64_value(crop[0]));
2015                         ghb_ui_update(ud, "crop_bottom", ghb_int64_value(crop[1]));
2016                         ghb_ui_update(ud, "crop_left", ghb_int64_value(crop[2]));
2017                         ghb_ui_update(ud, "crop_right", ghb_int64_value(crop[3]));
2018                 }
2019         }
2020         crop[0] = ghb_settings_get_int(ud->settings, "crop_top");
2021         crop[1] = ghb_settings_get_int(ud->settings, "crop_bottom");
2022         crop[2] = ghb_settings_get_int(ud->settings, "crop_left");
2023         crop[3] = ghb_settings_get_int(ud->settings, "crop_right");
2024         hb_reduce(&aspect_n, &aspect_d, 
2025                                 title->width * title->pixel_aspect_width, 
2026                                 title->height * title->pixel_aspect_height);
2027         crop_width = title->width - crop[2] - crop[3];
2028         crop_height = title->height - crop[0] - crop[1];
2029         if (autoscale)
2030         {
2031                 width = crop_width;
2032                 height = crop_height;
2033                 max_width = crop_width;
2034                 max_height = crop_height;
2035         }
2036         else
2037         {
2038                 width = ghb_settings_get_int(ud->settings, "scale_width");
2039                 height = ghb_settings_get_int(ud->settings, "scale_height");
2040                 max_width = ghb_settings_get_int(ud->settings, "max_width");
2041                 max_height = ghb_settings_get_int(ud->settings, "max_width");
2042                 // Align max dims 
2043                 max_width = (max_width >> modshift) << modshift;
2044                 max_height = (max_height >> modshift) << modshift;
2045                 // Adjust dims according to max values
2046                 if (!max_height)
2047                 {
2048                         max_height = crop_height;
2049                 }
2050                 if (!max_width)
2051                 {
2052                         max_width = crop_width;
2053                 }
2054                 height = MIN(height, max_height);
2055                 width = MIN(width, max_width);
2056                 g_debug("max_width %d, max_height %d\n", max_width, max_height);
2057         }
2058         if (width < 16)
2059                 width = title->width - crop[2] - crop[3];
2060         if (height < 16)
2061                 height = title->height - crop[0] - crop[1];
2062
2063         if (anamorphic)
2064         {
2065                 if (round_dims)
2066                 {
2067                         job->modulus = 0;
2068                 }
2069                 else
2070                 {
2071                         // The scaler crashes if the dimensions are not divisible by 2
2072                         // Align mod 2.  And so does something in x264_encoder_headers()
2073                         job->modulus = 2;
2074                 }
2075                 job->width = width;
2076                 if (max_height) 
2077                         job->maxHeight = max_height;
2078                 job->crop[0] = crop[0]; job->crop[1] = crop[1];
2079                 job->crop[2] = crop[2]; job->crop[3] = crop[3];
2080                 hb_set_anamorphic_size( job, &width, &height, &par_width, &par_height );
2081         }
2082         else 
2083         {
2084                 if (keep_aspect)
2085                 {
2086                         gdouble par;
2087                         gint new_width, new_height;
2088                         
2089                         g_debug("kw %s kh %s\n", keep_width ? "y":"n", keep_height ? "y":"n");
2090                         g_debug("w %d h %d\n", width, height);
2091                         // Compute pixel aspect ration.  
2092                         par = (gdouble)(title->height * aspect_n) / (title->width * aspect_d);
2093                         // Must scale so that par becomes 1:1
2094                         // Try to keep largest dimension
2095                         new_height = (crop_height * ((gdouble)width/crop_width) / par);
2096                         new_width = (crop_width * ((gdouble)height/crop_height) * par);
2097                         // Height and width are always multiples of 2, so do the rounding
2098                         new_height = ((new_height + 1) >> 1) << 1;
2099                         new_width = ((new_width + 1) >> 1) << 1;
2100                         g_debug("max w %d, new w %d\n", max_width, new_width);
2101                         if (max_width && (new_width > max_width))
2102                         {
2103                                 height = new_height;
2104                         }
2105                         else if (max_height && (new_height > max_height))
2106                         {
2107                                 width = new_width;
2108                         }
2109                         else if (keep_width)
2110                         {
2111                                 height = new_height;
2112                         }
2113                         else if (keep_height)
2114                         {
2115                                 width = new_width;
2116                         }
2117                         else if (width > new_width)
2118                         {
2119                                 height = new_height;
2120                         }
2121                         else
2122                         {
2123                                 width = new_width;
2124                         }
2125                         g_debug("new w %d h %d\n", width, height);
2126                 }
2127                 width = ((width + modround) >> modshift) << modshift;
2128                 height = ((height + modround) >> modshift) << modshift;
2129         }
2130         ghb_ui_update(ud, "scale_width", ghb_int64_value(width));
2131         ghb_ui_update(ud, "scale_height", ghb_int64_value(height));
2132 }
2133
2134 static void
2135 set_preview_job_settings(hb_job_t *job, GValue *settings)
2136 {
2137         job->crop[0] = ghb_settings_get_int(settings, "crop_top");
2138         job->crop[1] = ghb_settings_get_int(settings, "crop_bottom");
2139         job->crop[2] = ghb_settings_get_int(settings, "crop_left");
2140         job->crop[3] = ghb_settings_get_int(settings, "crop_right");
2141
2142         gboolean anamorphic, round_dimensions;
2143         anamorphic = ghb_settings_get_boolean(settings, "anamorphic");
2144         round_dimensions = ghb_settings_get_boolean(settings, "round_dimensions");
2145         if (round_dimensions && anamorphic)
2146         {
2147                 job->modulus = 16;
2148                 job->pixel_ratio = 2;
2149         }
2150         else if (anamorphic)
2151         {
2152                 job->modulus = 2;
2153                 job->pixel_ratio = 2;
2154         }
2155         else
2156         {
2157                 job->modulus = 2;
2158                 job->pixel_ratio = 0;
2159         }
2160         job->width = ghb_settings_get_int(settings, "scale_width");
2161         job->height = ghb_settings_get_int(settings, "scale_height");
2162         gint deint = ghb_settings_get_int(settings, "deinterlace");
2163         gboolean decomb = ghb_settings_get_boolean(settings, "decomb");
2164         job->deinterlace = (!decomb && deint == 0) ? 0 : 1;
2165 }
2166
2167 gint
2168 ghb_calculate_target_bitrate(GValue *settings, gint titleindex)
2169 {
2170         hb_list_t  * list;
2171         hb_title_t * title;
2172         hb_job_t   * job;
2173         gint size;
2174
2175         if (h_scan == NULL) return 2000;
2176         list = hb_get_titles( h_scan );
2177     title = hb_list_item( list, titleindex );
2178         if (title == NULL) return 2000;
2179         job   = title->job;
2180         if (job == NULL) return 2000;
2181         size = ghb_settings_get_int(settings, "video_target_size");
2182         return hb_calc_bitrate( job, size );
2183 }
2184
2185 gint
2186 ghb_guess_bitrate(GValue *settings)
2187 {
2188         gint bitrate;
2189         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
2190         {
2191                 // This is really rough.  I'm trying to err on the high
2192                 // side since this is used to estimate if there is 
2193                 // sufficient disk space left
2194                 gint vcodec;
2195                 gdouble vquality;
2196
2197                 vcodec = ghb_settings_get_int(settings, "video_codec");
2198                 vquality = ghb_settings_get_double(settings, "video_quality")/100;
2199                 if (vcodec == HB_VCODEC_X264 && 
2200                                 !ghb_settings_get_boolean(settings, "linear_vquality"))
2201                 {
2202                         vquality = 51.0 - vquality * 51.0;
2203                         // Convert log curve to linear
2204                         vquality = exp2((vquality-12)/6);
2205                         // Don't let it go to 0
2206                         if (vquality >= 31) vquality = 30;
2207                         vquality = (31 - vquality) / 31;
2208                 }
2209                 // bitrate seems to be a log relasionship to quality
2210                 // with typical source material
2211                 // This is a real wag
2212                 bitrate = 20*1024*1024*exp10(vquality*14)/exp10(14);
2213                 // Add some bits for audio
2214                 bitrate += 500*1024;
2215         }
2216         else
2217         {
2218                 // Add some fudge to the bitrate to leave breathing room
2219                 bitrate = ghb_settings_get_int(settings, "video_bitrate")*1024;
2220                 // Add some bits for audio
2221                 bitrate += 500*1024;
2222         }
2223         return bitrate;
2224 }
2225
2226 gboolean
2227 ghb_validate_filter_string(const gchar *str, gint max_fields)
2228 {
2229         gint fields = 0;
2230         gchar *end;
2231         gdouble val;
2232
2233         if (str == NULL || *str == 0) return TRUE;
2234         while (*str)
2235         {
2236                 val = g_strtod(str, &end);
2237                 if (str != end)
2238                 { // Found a numeric value
2239                         fields++;
2240                         // negative max_fields means infinate
2241                         if (max_fields >= 0 && fields > max_fields) return FALSE;
2242                         if (*end == 0)
2243                                 return TRUE;
2244                         if (*end != ':')
2245                                 return FALSE;
2246                         str = end + 1;
2247                 }
2248                 else
2249                         return FALSE;
2250         }
2251         return FALSE;
2252 }
2253
2254 gboolean
2255 ghb_validate_filters(signal_user_data_t *ud)
2256 {
2257         gboolean tweaks;
2258         gchar *str;
2259         gint index;
2260         gchar *message;
2261         gboolean enabled;
2262
2263         tweaks = ghb_settings_get_boolean(ud->settings, "allow_tweaks");
2264         if (tweaks)
2265         {
2266                 // detele 6
2267                 str = ghb_settings_get_string(ud->settings, "tweak_detelecine");
2268                 enabled = ghb_settings_get_boolean(ud->settings, "detelecine");
2269                 if (enabled && !ghb_validate_filter_string(str, 6))
2270                 {
2271                         message = g_strdup_printf(
2272                                                 "Invalid Detelecine Settings:\n\n%s\n",
2273                                                 str);
2274                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2275                         g_free(str);
2276                         g_free(message);
2277                         return FALSE;
2278                 }
2279                 g_free(str);
2280                 // decomb 7
2281                 str = ghb_settings_get_string(ud->settings, "tweak_decomb");
2282                 enabled = ghb_settings_get_boolean(ud->settings, "decomb");
2283                 if (enabled && !ghb_validate_filter_string(str, 7))
2284                 {
2285                         message = g_strdup_printf(
2286                                                 "Invalid Decomb Settings:\n\n%s\n",
2287                                                 str);
2288                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2289                         g_free(str);
2290                         g_free(message);
2291                         return FALSE;
2292                 }
2293                 g_free(str);
2294                 // deinte 4
2295                 index = ghb_settings_get_combo_index(ud->settings, "tweak_deinterlace");
2296                 if (index < 0)
2297                 {
2298                         str = ghb_settings_get_string(ud->settings, "tweak_deinterlace");
2299                         if (!ghb_validate_filter_string(str, 4))
2300                         {
2301                                 message = g_strdup_printf(
2302                                                         "Invalid Deinterlace Settings:\n\n%s\n",
2303                                                         str);
2304                                 ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2305                                 g_free(message);
2306                                 g_free(str);
2307                                 return FALSE;
2308                         }
2309                         g_free(str);
2310                 }
2311                 // debloc 2
2312                 str = ghb_settings_get_string(ud->settings, "tweak_deblock");
2313                 enabled = ghb_settings_get_boolean(ud->settings, "deblock");
2314                 if (enabled && !ghb_validate_filter_string(str, 2))
2315                 {
2316                         message = g_strdup_printf(
2317                                                 "Invalid Deblock Settings:\n\n%s\n",
2318                                                 str);
2319                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2320                         g_free(str);
2321                         g_free(message);
2322                         return FALSE;
2323                 }
2324                 g_free(str);
2325                 // denois 4
2326                 index = ghb_settings_get_combo_index(ud->settings, "tweak_denoise");
2327                 if (index < 0)
2328                 {
2329                         str = ghb_settings_get_string(ud->settings, "tweak_denoise");
2330                         if (!ghb_validate_filter_string(str, 4))
2331                         {
2332                                 message = g_strdup_printf(
2333                                                         "Invalid Denoise Settings:\n\n%s\n",
2334                                                         str);
2335                                 ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2336                                 g_free(str);
2337                                 g_free(message);
2338                                 return FALSE;
2339                         }
2340                         g_free(str);
2341                 }
2342         }
2343         return TRUE;
2344 }
2345
2346 gboolean
2347 ghb_validate_video(signal_user_data_t *ud)
2348 {
2349         gint vcodec, mux;
2350         gchar *message;
2351
2352         mux = ghb_settings_get_int(ud->settings, "container");
2353         vcodec = ghb_settings_get_int(ud->settings, "video_codec");
2354         if ((mux == HB_MUX_MP4 || mux == HB_MUX_AVI) && 
2355                 (vcodec == HB_VCODEC_THEORA))
2356         {
2357                 // mp4|avi/theora combination is not supported.
2358                 message = g_strdup_printf(
2359                                         "Theora is not supported in the MP4 and AVI containers.\n\n"
2360                                         "You should choose a different video codec or container.\n"
2361                                         "If you continue, XviD will be chosen for you.");
2362                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2363                 {
2364                         g_free(message);
2365                         return FALSE;
2366                 }
2367                 g_free(message);
2368                 vcodec = HB_VCODEC_XVID;
2369                 ghb_ui_update(ud, "video_codec", ghb_int64_value(vcodec));
2370         }
2371         gboolean decomb;
2372         gboolean vfr;
2373         decomb = ghb_settings_get_boolean(ud->settings, "decomb");
2374         vfr = ghb_settings_get_boolean(ud->settings, "variable_frame_rate");
2375         if (decomb && !vfr)
2376         {
2377                 message = g_strdup_printf(
2378                                         "Decomb is intended to be used in conjunction\n"
2379                                         "with variable frame rate.\n\n"
2380                                         "Would you like me to enable VFR for you?");
2381                 if (ghb_message_dialog(GTK_MESSAGE_WARNING, message, "No", "Yes"))
2382                 {
2383                         ghb_ui_update(ud, "variable_frame_rate", ghb_boolean_value(TRUE));
2384                 }
2385                 g_free(message);
2386         }
2387         return TRUE;
2388 }
2389
2390 gboolean
2391 ghb_validate_container(signal_user_data_t *ud)
2392 {
2393         gint container;
2394         gchar *message;
2395
2396         container = ghb_settings_get_int(ud->settings, "container");
2397         if (container == HB_MUX_MP4)
2398         {
2399                 const GValue *audio_list;
2400                 gboolean httpopt;
2401
2402                 audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2403                 httpopt = ghb_settings_get_boolean(ud->settings, "http_optimize_mp4");
2404                 if (httpopt && ghb_ac3_in_audio_list(audio_list))
2405                 {
2406                         message = g_strdup_printf(
2407                                         "AC3 audio in HTTP optimized MP4 is not supported.\n\n"
2408                                         "You should choose a different audio codec.\n"
2409                                         "If you continue, FAAC will be chosen for you.");
2410                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2411                         {
2412                                 g_free(message);
2413                                 return FALSE;
2414                         }
2415                         g_free(message);
2416
2417                         gint count, ii;
2418
2419                         count = ghb_array_len(audio_list);
2420                         for (ii = 0; ii < count; ii++)
2421                         {
2422                                 GValue *asettings;
2423
2424                                 asettings = ghb_array_get_nth(audio_list, ii);
2425                                 gint acodec = ghb_settings_get_int(asettings, "audio_codec");
2426                                 if (acodec == HB_ACODEC_AC3)
2427                                 {
2428                                         GValue *value;
2429                                         value = get_acodec_value(HB_ACODEC_FAAC);
2430                                         ghb_settings_take_value(asettings, "audio_codec", value);
2431                                 }
2432                         }
2433                 }
2434         }
2435         return TRUE;
2436 }
2437
2438 gboolean
2439 ghb_validate_audio(signal_user_data_t *ud)
2440 {
2441         hb_list_t  * list;
2442         hb_title_t * title;
2443         gchar *message;
2444         GValue *value;
2445
2446         if (h_scan == NULL) return FALSE;
2447         list = hb_get_titles( h_scan );
2448         if( !hb_list_count( list ) )
2449         {
2450                 /* No valid title, stop right there */
2451                 g_message("No title found.\n");
2452                 return FALSE;
2453         }
2454
2455         gint titleindex = ghb_settings_get_int(ud->settings, "title");
2456     title = hb_list_item( list, titleindex );
2457         if (title == NULL) return FALSE;
2458         gint mux = ghb_settings_get_int(ud->settings, "container");
2459
2460         const GValue *audio_list;
2461         gint count, ii;
2462
2463         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2464         count = ghb_array_len(audio_list);
2465         for (ii = 0; ii < count; ii++)
2466         {
2467                 GValue *asettings;
2468             hb_audio_config_t *taudio;
2469
2470                 asettings = ghb_array_get_nth(audio_list, ii);
2471                 gint track = ghb_settings_get_int(asettings, "audio_track");
2472                 gint codec = ghb_settings_get_int(asettings, "audio_codec");
2473         taudio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, track );
2474                 if ((taudio->in.codec != HB_ACODEC_AC3) && (codec == HB_ACODEC_AC3))
2475                 {
2476                         // Not supported.  AC3 is passthrough only, so input must be AC3
2477                         message = g_strdup_printf(
2478                                                 "The source does not support AC3 Pass-Thru.\n\n"
2479                                                 "You should choose a different audio codec.\n"
2480                                                 "If you continue, one will be chosen for you.");
2481                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2482                         {
2483                                 g_free(message);
2484                                 return FALSE;
2485                         }
2486                         g_free(message);
2487                         if (mux == HB_MUX_AVI)
2488                         {
2489                                 codec = HB_ACODEC_LAME;
2490                         }
2491                         else
2492                         {
2493                                 codec = HB_ACODEC_FAAC;
2494                         }
2495                         value = get_acodec_value(codec);
2496                         ghb_settings_take_value(asettings, "audio_codec", value);
2497                 }
2498                 gchar *a_unsup = NULL;
2499                 gchar *mux_s = NULL;
2500                 if (mux == HB_MUX_MP4)
2501                 { 
2502                         mux_s = "MP4";
2503                         // mp4/mp3|vorbis combination is not supported.
2504                         if (codec == HB_ACODEC_LAME)
2505                         {
2506                                 a_unsup = "MP3";
2507                                 codec = HB_ACODEC_FAAC;
2508                         }
2509                         if (codec == HB_ACODEC_VORBIS)
2510                         {
2511                                 a_unsup = "Vorbis";
2512                                 codec = HB_ACODEC_FAAC;
2513                         }
2514                 }
2515                 else if (mux == HB_MUX_AVI)
2516                 {
2517                         mux_s = "AVI";
2518                         // avi/faac|vorbis combination is not supported.
2519                         if (codec == HB_ACODEC_FAAC)
2520                         {
2521                                 a_unsup = "FAAC";
2522                                 codec = HB_ACODEC_LAME;
2523                         }
2524                         if (codec == HB_ACODEC_VORBIS)
2525                         {
2526                                 a_unsup = "Vorbis";
2527                                 codec = HB_ACODEC_LAME;
2528                         }
2529                 }
2530                 else if (mux == HB_MUX_OGM)
2531                 {
2532                         mux_s = "OGM";
2533                         // avi/faac|vorbis combination is not supported.
2534                         if (codec == HB_ACODEC_FAAC)
2535                         {
2536                                 a_unsup = "FAAC";
2537                                 codec = HB_ACODEC_VORBIS;
2538                         }
2539                         if (codec == HB_ACODEC_AC3)
2540                         {
2541                                 a_unsup = "AC-3";
2542                                 codec = HB_ACODEC_VORBIS;
2543                         }
2544                 }
2545                 if (a_unsup)
2546                 {
2547                         message = g_strdup_printf(
2548                                                 "%s is not supported in the %s container.\n\n"
2549                                                 "You should choose a different audio codec.\n"
2550                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
2551                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2552                         {
2553                                 g_free(message);
2554                                 return FALSE;
2555                         }
2556                         g_free(message);
2557                         value = get_acodec_value(codec);
2558                         ghb_settings_take_value(asettings, "audio_codec", value);
2559                 }
2560                 gint mix = ghb_settings_get_int (asettings, "audio_mix");
2561                 gboolean allow_mono = TRUE;
2562                 gboolean allow_stereo = TRUE;
2563                 gboolean allow_dolby = TRUE;
2564                 gboolean allow_dpl2 = TRUE;
2565                 gboolean allow_6ch = TRUE;
2566                 allow_mono =
2567                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2568                         (codec != HB_ACODEC_LAME);
2569                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
2570                 allow_stereo =
2571                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
2572                 allow_dolby =
2573                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
2574                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
2575                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
2576                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
2577                 allow_6ch =
2578                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2579                         (codec != HB_ACODEC_LAME) &&
2580                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
2581                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
2582
2583                 gchar *mix_unsup = NULL;
2584                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
2585                 {
2586                         mix_unsup = "mono";
2587                 }
2588                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
2589                 {
2590                         mix_unsup = "stereo";
2591                 }
2592                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
2593                 {
2594                         mix_unsup = "Dolby";
2595                 }
2596                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
2597                 {
2598                         mix_unsup = "Dolby Pro Logic II";
2599                 }
2600                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
2601                 {
2602                         mix_unsup = "6 Channel";
2603                 }
2604                 if (mix_unsup)
2605                 {
2606                         message = g_strdup_printf(
2607                                                 "The source audio does not support %s mixdown.\n\n"
2608                                                 "You should choose a different mixdown.\n"
2609                                                 "If you continue, one will be chosen for you.", mix_unsup);
2610                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2611                         {
2612                                 g_free(message);
2613                                 return FALSE;
2614                         }
2615                         g_free(message);
2616                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
2617                         value = get_amix_value(mix);
2618                         ghb_settings_take_value(asettings, "audio_mix", value);
2619                 }
2620         }
2621         return TRUE;
2622 }
2623
2624 gboolean
2625 ghb_validate_vquality(GValue *settings)
2626 {
2627         gint vcodec;
2628         gchar *message;
2629         gint min, max;
2630
2631         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
2632         vcodec = ghb_settings_get_int(settings, "video_codec");
2633         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
2634         {
2635                 if (!ghb_settings_get_boolean(settings, "directqp"))
2636                 {
2637                         if (vcodec != HB_VCODEC_X264 || 
2638                                 ghb_settings_get_boolean(settings, "linear_vquality"))
2639                         {
2640                                 min = 68;
2641                                 max = 97;
2642                         }
2643                         else if (vcodec == HB_VCODEC_X264)
2644                         {
2645                                 min = 40;
2646                                 max = 70;
2647                         }
2648                 }
2649                 else
2650                 {
2651                         if (vcodec == HB_VCODEC_X264)
2652                         {
2653                                 min = 16;
2654                                 max = 30;
2655                         }
2656                         else if (vcodec == HB_VCODEC_FFMPEG)
2657                         {
2658                                 min = 1;
2659                                 max = 8;
2660                         }
2661                         else
2662                         {
2663                                 min = 68;
2664                                 max = 97;
2665                         }
2666                 }
2667                 gint vquality = ghb_settings_get_double(settings, "video_quality");
2668                 if (vquality < min || vquality > max)
2669                 {
2670                         message = g_strdup_printf(
2671                                                 "Interesting video quality choise: %d\n\n"
2672                                                 "Typical values range from %d to %d.\n"
2673                                                 "Are you sure you wish to use this setting?",
2674                                                 vquality, min, max);
2675                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
2676                                                                         "Cancel", "Continue"))
2677                         {
2678                                 g_free(message);
2679                                 return FALSE;
2680                         }
2681                         g_free(message);
2682                 }
2683         }
2684         return TRUE;
2685 }
2686
2687 void
2688 ghb_add_job(GValue *js, gint unique_id)
2689 {
2690         hb_list_t  * list;
2691         hb_title_t * title;
2692         hb_job_t   * job;
2693         static gchar *x264opts;
2694         gint sub_id = 0;
2695         gboolean tweaks = FALSE;
2696         gchar *detel_str = NULL;
2697         gchar *decomb_str = NULL;
2698         gchar *deint_str = NULL;
2699         gchar *deblock_str = NULL;
2700         gchar *denoise_str = NULL;
2701         gchar *dest_str = NULL;
2702
2703         g_debug("ghb_add_job()\n");
2704         if (h_queue == NULL) return;
2705         list = hb_get_titles( h_queue );
2706         if( !hb_list_count( list ) )
2707         {
2708                 /* No valid title, stop right there */
2709                 g_message("No title found.\n");
2710                 return;
2711         }
2712
2713         // Since I'm doing a scan of the single title I want just prior 
2714         // to adding the job, there is only the one title to choose from.
2715         //gint titleindex = ghb_settings_get_int(js, "title");
2716     gint titleindex = 0;
2717     title = hb_list_item( list, titleindex );
2718         if (title == NULL) return;
2719
2720         /* Set job settings */
2721         job   = title->job;
2722         if (job == NULL) return;
2723
2724         tweaks = ghb_settings_get_int(js, "allow_tweaks");
2725         job->mux = ghb_lookup_mux(ghb_settings_get_value(js, "container"));
2726         if (job->mux == HB_MUX_MP4)
2727         {
2728                 job->largeFileSize = ghb_settings_get_boolean(js, "large_mp4");
2729                 job->mp4_optimize = ghb_settings_get_boolean(js, "http_optimize_mp4");
2730         }
2731         else
2732         {
2733                 job->largeFileSize = FALSE;
2734                 job->mp4_optimize = FALSE;
2735         }
2736         gint chapter_start, chapter_end;
2737         chapter_start = ghb_settings_get_int(js, "start_chapter");
2738         chapter_end = ghb_settings_get_int(js, "end_chapter");
2739         gint num_chapters = hb_list_count(title->list_chapter);
2740         job->chapter_start = MIN( num_chapters, chapter_start );
2741         job->chapter_end   = MAX( job->chapter_start, chapter_end );
2742
2743         job->chapter_markers = ghb_settings_get_boolean(js, "chapter_markers");
2744         if ( job->chapter_markers )
2745         {
2746                 GValue *chapters;
2747                 GValue *chapter;
2748                 gint chap;
2749                 gint count;
2750                 
2751                 chapters = ghb_settings_get_value(js, "chapter_list");
2752                 count = ghb_array_len(chapters);
2753                 for(chap = chapter_start; chap <= chapter_end; chap++)
2754                 {
2755                         hb_chapter_t * chapter_s;
2756                         gchar *name;
2757                         
2758                         name = NULL;
2759                         if (chap-1 < count)
2760                         {
2761                                 chapter = ghb_array_get_nth(chapters, chap-1);
2762                                 name = ghb_value_string(chapter); 
2763                         }
2764                         if (name == NULL)
2765                         {
2766                                 name = g_strdup_printf ("Chapter %2d", chap);
2767                         }
2768                         chapter_s = hb_list_item( job->title->list_chapter, chap - 1);
2769                         strncpy(chapter_s->title, name, 1023);
2770                         chapter_s->title[1023] = '\0';
2771                         g_free(name);
2772                 }
2773         }
2774         job->crop[0] = ghb_settings_get_int(js, "crop_top");
2775         job->crop[1] = ghb_settings_get_int(js, "crop_bottom");
2776         job->crop[2] = ghb_settings_get_int(js, "crop_left");
2777         job->crop[3] = ghb_settings_get_int(js, "crop_right");
2778
2779         
2780         gboolean decomb = ghb_settings_get_boolean(js, "decomb");
2781         gint deint = ghb_lookup_deint(
2782                 ghb_settings_get_value(js, tweaks ? "tweak_deinterlace":"deinterlace"));
2783         if (!decomb)
2784                 job->deinterlace = (deint != 0) ? 1 : 0;
2785         else
2786                 job->deinterlace = 0;
2787     job->grayscale   = ghb_settings_get_boolean(js, "grayscale");
2788
2789         gboolean anamorphic = ghb_settings_get_boolean(js, "anamorphic");
2790         gboolean round_dimensions = ghb_settings_get_boolean(js, "round_dimensions");
2791         if (round_dimensions && anamorphic)
2792         {
2793                 job->pixel_ratio = 2;
2794                 job->modulus = 16;
2795         }
2796         else if (anamorphic)
2797         {
2798                 // Huh! I thought I wanted to use pixel_ratio 1 for this case, but
2799                 // when its 1, libhb discards the width and height and uses original
2800                 // title dims - crop.  Thats not what I want.
2801                 // Also, x264 requires things to divisible by 2.
2802                 job->pixel_ratio = 2;
2803                 job->modulus = 2;
2804         }
2805         else
2806         {
2807                 job->pixel_ratio = 0;
2808                 job->modulus = 2;
2809         }
2810         job->vfr = ghb_settings_get_boolean(js, "variable_frame_rate");
2811         /* Add selected filters */
2812         job->filters = hb_list_init();
2813         if( ghb_settings_get_boolean(js, "detelecine" ) || job->vfr )
2814         {
2815                 hb_filter_detelecine.settings = NULL;
2816                 if (tweaks)
2817                 {
2818                         detel_str = ghb_settings_get_string(js, "tweak_detelecine");
2819                         if (detel_str && detel_str[0])
2820                         {
2821                                 hb_filter_detelecine.settings = detel_str;
2822                         }
2823                 }
2824                 hb_list_add( job->filters, &hb_filter_detelecine );
2825         }
2826         if( decomb )
2827         {
2828                 // Use default settings
2829                 hb_filter_decomb.settings = NULL;
2830                 if (tweaks)
2831                 {
2832                         decomb_str = ghb_settings_get_string(js, "tweak_decomb");
2833                         if (decomb_str && decomb_str[0])
2834                         {
2835                                 hb_filter_decomb.settings = (gchar*)decomb_str;
2836                         }
2837                 }
2838                 hb_list_add( job->filters, &hb_filter_decomb );
2839         }
2840         if( job->deinterlace )
2841         {
2842                 if (deint > 0)
2843                         deint_str = g_strdup(deint_opts.map[deint].svalue);
2844                 else
2845                         deint_str = ghb_settings_get_string(js, 
2846                                         tweaks ? "tweak_deinterlace" : "deinterlace");
2847                 hb_filter_deinterlace.settings = deint_str;
2848                 hb_list_add( job->filters, &hb_filter_deinterlace );
2849         }
2850         if( ghb_settings_get_boolean(js, "deblock") )
2851         {
2852                 hb_filter_deblock.settings = NULL;
2853                 if (tweaks)
2854                 {
2855                         deblock_str = ghb_settings_get_string(js, "tweak_deblock");
2856                         if (deblock_str && deblock_str[0])
2857                         {
2858                                 hb_filter_deblock.settings = deblock_str;
2859                         }
2860                 }
2861                 hb_list_add( job->filters, &hb_filter_deblock );
2862         }
2863         gint denoise = ghb_lookup_denoise(
2864                 ghb_settings_get_value(js, tweaks ? "tweak_denoise" : "denoise"));
2865         if( denoise != 0 )
2866         {
2867                 if (denoise > 0)
2868                         denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
2869                 else
2870                         denoise_str = (gchar*)ghb_settings_get_string(
2871                                 js, tweaks ? "tweak_denoise" : "denoise");
2872                 hb_filter_denoise.settings = denoise_str;
2873                 hb_list_add( job->filters, &hb_filter_denoise );
2874         }
2875         job->width = ghb_settings_get_int(js, "scale_width");
2876         job->height = ghb_settings_get_int(js, "scale_height");
2877
2878         job->vcodec = ghb_lookup_vcodec(ghb_settings_get_value(js, "video_codec"));
2879         if ((job->mux == HB_MUX_MP4 || job->mux == HB_MUX_AVI) && 
2880                 (job->vcodec == HB_VCODEC_THEORA))
2881         {
2882                 // mp4|avi/theora combination is not supported.
2883                 job->vcodec = HB_VCODEC_XVID;
2884         }
2885         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
2886         {
2887                 job->ipod_atom = ghb_settings_get_boolean(js, "ipod_file");
2888         }
2889         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
2890         {
2891                 gdouble vquality;
2892                 vquality = ghb_settings_get_double(js, "video_quality");
2893                 if (!ghb_settings_get_boolean(js, "directqp"))
2894                 {
2895                         vquality /= 100.0;
2896                         if (ghb_settings_get_boolean(js, "linear_vquality"))
2897                         {
2898                                 if (job->vcodec == HB_VCODEC_X264)
2899                                 {
2900                                         // Adjust to same range as xvid and ffmpeg
2901                                         vquality = 31.0 - vquality * 31.0;
2902                                         if (vquality > 0)
2903                                         {
2904                                                 // Convert linear to log curve
2905                                                 vquality = 12 + 6 * log2(vquality);
2906                                                 if (vquality > 51) vquality = 51;
2907                                                 if (vquality < 1) vquality = 1;
2908                                         }
2909                                         else
2910                                                 vquality = 0;
2911                                 }
2912                         }
2913                         else
2914                         {
2915                                 if (vquality == 0.0) vquality = 0.01;
2916                                 if (vquality == 1.0) vquality = 0.0;
2917                         }
2918                 }
2919                 job->vquality =  vquality;
2920                 job->vbitrate = 0;
2921         }
2922         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
2923         {
2924                 job->vquality = -1.0;
2925                 job->vbitrate = ghb_settings_get_int(js, "video_bitrate");
2926         }
2927         // AVI container does not support variable frame rate.
2928         if (job->mux == HB_MUX_AVI)
2929         {
2930                 job->vfr = FALSE;
2931         }
2932
2933         gint vrate = ghb_lookup_vrate(ghb_settings_get_value(js, "framerate"));
2934         if( vrate == 0 || job->vfr )
2935         {
2936                 job->vrate = title->rate;
2937                 job->vrate_base = title->rate_base;
2938                 job->cfr = 0;
2939         }
2940         else
2941         {
2942                 job->vrate = 27000000;
2943                 job->vrate_base = vrate;
2944                 job->cfr = 1;
2945         }
2946         // First remove any audios that are already in the list
2947         // This happens if you are encoding the same title a second time.
2948         gint num_audio_tracks = hb_list_count(job->list_audio);
2949         gint ii;
2950     for(ii = 0; ii < num_audio_tracks; ii++)
2951     {
2952         hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
2953         hb_list_rem(job->list_audio, audio);
2954     }
2955
2956         const GValue *audio_list;
2957         gint count;
2958         gint tcount = 0;
2959         
2960         audio_list = ghb_settings_get_value(js, "audio_list");
2961         count = ghb_array_len(audio_list);
2962         for (ii = 0; ii < count; ii++)
2963         {
2964                 GValue *asettings;
2965             hb_audio_config_t audio;
2966             hb_audio_config_t *taudio;
2967
2968                 hb_audio_config_init(&audio);
2969                 asettings = ghb_array_get_nth(audio_list, ii);
2970                 audio.in.track = ghb_settings_get_int(asettings, "audio_track");
2971                 audio.out.track = tcount;
2972                 audio.out.codec = ghb_lookup_acodec(
2973                         ghb_settings_get_value(asettings, "audio_codec"));
2974         taudio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, audio.in.track );
2975                 if ((taudio->in.codec != HB_ACODEC_AC3) && (audio.out.codec == HB_ACODEC_AC3))
2976                 {
2977                         // Not supported.  AC3 is passthrough only, so input must be AC3
2978                         if (job->mux == HB_MUX_AVI)
2979                         {
2980                                 audio.out.codec = HB_ACODEC_LAME;
2981                         }
2982                         else
2983                         {
2984                                 audio.out.codec = HB_ACODEC_FAAC;
2985                         }
2986                 }
2987                 if ((job->mux == HB_MUX_MP4) && 
2988                         ((audio.out.codec == HB_ACODEC_LAME) ||
2989                         (audio.out.codec == HB_ACODEC_VORBIS)))
2990                 {
2991                         // mp4/mp3|vorbis combination is not supported.
2992                         audio.out.codec = HB_ACODEC_FAAC;
2993                 }
2994                 if ((job->mux == HB_MUX_AVI) && 
2995                         ((audio.out.codec == HB_ACODEC_FAAC) ||
2996                         (audio.out.codec == HB_ACODEC_VORBIS)))
2997                 {
2998                         // avi/faac|vorbis combination is not supported.
2999                         audio.out.codec = HB_ACODEC_LAME;
3000                 }
3001                 if ((job->mux == HB_MUX_OGM) && 
3002                         ((audio.out.codec == HB_ACODEC_FAAC) ||
3003                         (audio.out.codec == HB_ACODEC_AC3)))
3004                 {
3005                         // ogm/faac|ac3 combination is not supported.
3006                         audio.out.codec = HB_ACODEC_VORBIS;
3007                 }
3008         audio.out.dynamic_range_compression = 
3009                         ghb_settings_get_double(asettings, "audio_drc");
3010                 // It would be better if this were done in libhb for us, but its not yet.
3011                 if (audio.out.codec == HB_ACODEC_AC3 || audio.out.codec == HB_ACODEC_DCA)
3012                 {
3013                         audio.out.mixdown = 0;
3014                 }
3015                 else
3016                 {
3017                         audio.out.mixdown = ghb_lookup_mix(
3018                                 ghb_settings_get_value (asettings, "audio_mix"));
3019                         // Make sure the mixdown is valid and pick a new one if not.
3020                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
3021                                 audio.in.track, audio.out.codec, audio.out.mixdown);
3022                         audio.out.bitrate = 
3023                                 ghb_settings_get_int(asettings, "audio_bitrate") / 1000;
3024                         gint srate = ghb_settings_get_int(asettings, "audio_rate");
3025                         if (srate == 0) // 0 is same as source
3026                                 audio.out.samplerate = taudio->in.samplerate;
3027                         else
3028                                 audio.out.samplerate = srate;
3029                 }
3030
3031                 // Add it to the jobs audio list
3032         hb_audio_add( job, &audio );
3033                 tcount++;
3034         }
3035         // I was tempted to move this up with the reset of the video quality
3036         // settings, but I suspect the settings above need to be made
3037         // first in order for hb_calc_bitrate to be accurate.
3038         if (ghb_settings_get_boolean(js, "vquality_type_target"))
3039         {
3040                 gint size;
3041                 
3042                 size = ghb_settings_get_int(js, "video_target_size");
3043         job->vbitrate = hb_calc_bitrate( job, size );
3044                 job->vquality = -1.0;
3045         }
3046
3047         dest_str = ghb_settings_get_string(js, "destination");
3048         job->file = dest_str;
3049         job->crf = ghb_settings_get_boolean(js, "constant_rate_factor");
3050         // TODO: libhb holds onto a reference to the x264opts and is not
3051         // finished with it until encoding the job is done.  But I can't
3052         // find a way to get at the job before it is removed in order to
3053         // free up the memory I am allocating here.
3054         // The short story is THIS LEAKS.
3055         x264opts = ghb_build_x264opts_string(js);
3056         
3057         if( x264opts != NULL && *x264opts != '\0' )
3058         {
3059                 job->x264opts = x264opts;
3060         }
3061         else /*avoids a bus error crash when options aren't specified*/
3062         {
3063                 job->x264opts =  NULL;
3064         }
3065         gint subtitle = ghb_settings_get_int(js, "subtitle_lang");
3066         gchar *slang = ghb_settings_get_string(js, "subtitle_lang");
3067         subtitle = -2; // default to none
3068         if (strcmp(slang, "auto") == 0)
3069         {
3070                 subtitle = -1;
3071         }
3072         else
3073         {
3074                 gint scount;
3075         hb_subtitle_t * subt;
3076
3077                 scount = hb_list_count(title->list_subtitle);
3078                 for (ii = 0; ii < scount; ii++)
3079                 {
3080                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
3081                         if (strcmp(slang, subt->iso639_2) == 0)
3082                         {
3083                                 subtitle = ii;
3084                                 break;
3085                         }
3086                 }
3087         }
3088         gboolean forced_subtitles = ghb_settings_get_boolean(js, "forced_subtitles");
3089         job->subtitle_force = forced_subtitles;
3090         if (subtitle >= 0)
3091                 job->subtitle = subtitle;
3092         else
3093                 job->subtitle = -1;
3094         if (subtitle == -1)
3095         {
3096                 // Subtitle scan. Look for subtitle matching audio language
3097                 char *x264opts_tmp;
3098
3099                 /*
3100                  * When subtitle scan is enabled do a fast pre-scan job
3101                  * which will determine which subtitles to enable, if any.
3102                  */
3103                 job->pass = -1;
3104                 job->indepth_scan = 1;
3105
3106                 x264opts_tmp = job->x264opts;
3107                 job->x264opts = NULL;
3108
3109                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
3110                 *(job->select_subtitle) = NULL;
3111
3112                 /*
3113                  * Add the pre-scan job
3114                  */
3115                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3116                 hb_add( h_queue, job );
3117                 //if (job->x264opts != NULL)
3118                 //      g_free(job->x264opts);
3119
3120                 job->x264opts = x264opts_tmp;
3121         }
3122         else
3123         {
3124                 job->select_subtitle = NULL;
3125         }
3126         if( ghb_settings_get_boolean(js, "two_pass") &&
3127                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
3128         {
3129                 /*
3130                  * If subtitle_scan is enabled then only turn it on
3131                  * for the second pass and then off again for the
3132                  * second.
3133                  */
3134                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
3135                 job->select_subtitle = NULL;
3136                 job->pass = 1;
3137                 job->indepth_scan = 0;
3138                 gchar *x264opts2 = NULL;
3139                 if (x264opts)
3140                 {
3141                         x264opts2 = g_strdup(x264opts);
3142                 }
3143                 /*
3144                  * If turbo options have been selected then append them
3145                  * to the x264opts now (size includes one ':' and the '\0')
3146                  */
3147                 if( ghb_settings_get_boolean(js, "turbo") )
3148                 {
3149                         char *tmp_x264opts;
3150
3151                         if ( x264opts )
3152                         {
3153                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, turbo_opts);
3154                                 g_free(x264opts);
3155                         } 
3156                         else 
3157                         {
3158                                 /*
3159                                  * No x264opts to modify, but apply the turbo options
3160                                  * anyway as they may be modifying defaults
3161                                  */
3162                                 tmp_x264opts = g_strdup_printf("%s", turbo_opts);
3163                         }
3164                         x264opts = tmp_x264opts;
3165
3166                         job->x264opts = x264opts;
3167                 }
3168                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3169                 hb_add( h_queue, job );
3170                 //if (job->x264opts != NULL)
3171                 //      g_free(job->x264opts);
3172
3173                 job->select_subtitle = subtitle_tmp;
3174                 job->pass = 2;
3175                 /*
3176                  * On the second pass we turn off subtitle scan so that we
3177                  * can actually encode using any subtitles that were auto
3178                  * selected in the first pass (using the whacky select-subtitle
3179                  * attribute of the job).
3180                  */
3181                 job->indepth_scan = 0;
3182                 job->x264opts = x264opts2;
3183                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3184                 hb_add( h_queue, job );
3185                 //if (job->x264opts != NULL)
3186                 //      g_free(job->x264opts);
3187         }
3188         else
3189         {
3190                 job->indepth_scan = 0;
3191                 job->pass = 0;
3192                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3193                 hb_add( h_queue, job );
3194                 //if (job->x264opts != NULL)
3195                 //      g_free(job->x264opts);
3196         }
3197         if (detel_str) g_free(detel_str);
3198         if (decomb_str) g_free(decomb_str);
3199         if (deint_str) g_free(deint_str);
3200         if (deblock_str) g_free(deblock_str);
3201         if (denoise_str) g_free(denoise_str);
3202         if (dest_str) g_free(dest_str);
3203 }
3204
3205 void
3206 ghb_remove_job(gint unique_id)
3207 {
3208     hb_job_t * job;
3209     gint ii;
3210         
3211         // Multiples passes all get the same id
3212         // remove them all.
3213         // Go backwards through list, so reordering doesn't screw me.
3214         ii = hb_count(h_queue) - 1;
3215     while ((job = hb_job(h_queue, ii--)) != NULL)
3216     {
3217         if ((job->sequence_id & 0xFFFFFF) == unique_id)
3218                         hb_rem(h_queue, job);
3219     }
3220 }
3221
3222 void
3223 ghb_start_queue()
3224 {
3225         hb_start( h_queue );
3226 }
3227
3228 void
3229 ghb_stop_queue()
3230 {
3231         hb_stop( h_queue );
3232 }
3233
3234 void
3235 ghb_pause_queue()
3236 {
3237     hb_state_t s;
3238     hb_get_state2( h_queue, &s );
3239
3240     if( s.state == HB_STATE_PAUSED )
3241     {
3242         hb_resume( h_queue );
3243     }
3244     else
3245     {
3246         hb_pause( h_queue );
3247     }
3248 }
3249
3250 GdkPixbuf*
3251 ghb_get_preview_image(
3252         gint titleindex, 
3253         gint index, 
3254         GValue *settings, 
3255         gboolean borders)
3256 {
3257         hb_title_t *title;
3258         hb_list_t  *list;
3259         
3260         list = hb_get_titles( h_scan );
3261         if( !hb_list_count( list ) )
3262         {
3263                 /* No valid title, stop right there */
3264                 return NULL;
3265         }
3266     title = hb_list_item( list, titleindex );
3267         if (title == NULL) return NULL;
3268         if (title->job == NULL) return NULL;
3269         set_preview_job_settings(title->job, settings);
3270
3271         // hb_get_preview can't handle sizes that are larger than the original title
3272         // dimensions
3273         if (title->job->width > title->width)
3274                 title->job->width = title->width;
3275         
3276         if (title->job->height > title->height)
3277                 title->job->height = title->height;
3278         // And also creates artifacts if the width is not a multiple of 8
3279         //title->job->width = ((title->job->width + 4) >> 3) << 3;
3280         // And the height must be a multiple of 2
3281         //title->job->height = ((title->job->height + 1) >> 1) << 1;
3282         
3283         // Make sure we have a big enough buffer to receive the image from libhb. libhb
3284         // creates images with a one-pixel border around the original content. Hence we
3285         // add 2 pixels horizontally and vertically to the buffer size.
3286         gint srcWidth = title->width + 2;
3287         gint srcHeight= title->height + 2;
3288         gint dstWidth = title->width;
3289         gint dstHeight= title->height;
3290         gint borderTop = 1;
3291         gint borderLeft = 1;
3292     if (borders)
3293     {
3294         //     |<---------- title->width ----------->|
3295         //     |   |<---- title->job->width ---->|   |
3296         //     |   |                             |   |
3297         //     .......................................
3298         //     ....+-----------------------------+....
3299         //     ....|                             |....<-- gray border
3300         //     ....|                             |....
3301         //     ....|                             |....
3302         //     ....|                             |<------- image
3303         //     ....|                             |....
3304         //     ....|                             |....
3305         //     ....|                             |....
3306         //     ....|                             |....
3307         //     ....|                             |....
3308         //     ....+-----------------------------+....
3309         //     .......................................
3310                 dstWidth = title->job->width;
3311         dstHeight = title->job->height;
3312                 borderTop = (srcHeight - dstHeight) / 2;
3313                 borderLeft = (srcWidth - dstWidth) / 2;
3314                 g_debug("boarders removed\n");
3315         }
3316
3317         g_debug("src %d x %d\n", srcWidth, srcHeight);
3318         g_debug("dst %d x %d\n", dstWidth, dstHeight);
3319         g_debug("job dim %d x %d\n", title->job->width, title->job->height);
3320         g_debug("title crop %d:%d:%d:%d\n", 
3321                         title->crop[0],
3322                         title->crop[1],
3323                         title->crop[2],
3324                         title->crop[3]);
3325         g_debug("job crop %d:%d:%d:%d\n", 
3326                         title->job->crop[0],
3327                         title->job->crop[1],
3328                         title->job->crop[2],
3329                         title->job->crop[3]);
3330         static guint8 *buffer = NULL;
3331         static gint bufferSize = 0;
3332
3333         gint newSize;
3334         newSize = srcWidth * srcHeight * 4;
3335         if( bufferSize < newSize )
3336         {
3337                 bufferSize = newSize;
3338                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
3339         }
3340         hb_get_preview( h_scan, title, index, buffer );
3341
3342         // Create an GdkPixbuf and copy the libhb image into it, converting it from
3343         // libhb's format something suitable. Along the way, we'll strip off the
3344         // border around libhb's image.
3345         
3346         // The image data returned by hb_get_preview is 4 bytes per pixel, BGRA format.
3347         // Alpha is ignored.
3348
3349         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
3350         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
3351         
3352         guint32 *src = (guint32*)buffer;
3353         guint8 *dst = pixels;
3354         src += borderTop * srcWidth;    // skip top rows in src to get to first row of dst
3355         src += borderLeft;              // skip left pixels in src to get to first pixel of dst
3356         gint ii, jj;
3357         gint channels = gdk_pixbuf_get_n_channels (preview);
3358         gint stride = gdk_pixbuf_get_rowstride (preview);
3359         guint8 *tmp;
3360         for (ii = 0; ii < dstHeight; ii++)
3361         {
3362                 tmp = dst;
3363                 for (jj = 0; jj < dstWidth; jj++)
3364                 {
3365                         tmp[0] = src[0] >> 16;
3366                         tmp[1] = src[0] >> 8;
3367                         tmp[2] = src[0] >> 0;
3368                         tmp += channels;
3369                         src++;
3370                 }
3371                 dst += stride;
3372                 src += (srcWidth - dstWidth);   // skip to next row in src
3373         }
3374         // Got it, but hb_get_preview doesn't compensate for anamorphic, so lets
3375         // scale
3376         gint width, height, par_width, par_height;
3377         gboolean anamorphic = ghb_settings_get_boolean(settings, "anamorphic");
3378         if (anamorphic)
3379         {
3380                 hb_set_anamorphic_size( title->job, &width, &height, &par_width, &par_height );
3381                 if (par_width > par_height)
3382                         dstWidth = dstWidth * par_width / par_height;
3383                 else
3384                         dstHeight = dstHeight * par_height / par_width;
3385         }
3386         
3387         g_debug("scaled %d x %d\n", dstWidth, dstHeight);
3388         GdkPixbuf *scaled_preview;
3389         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
3390         g_object_unref (preview);
3391         return scaled_preview;
3392 }
3393
3394 static void
3395 sanitize_volname(gchar *name)
3396 {
3397         gchar *a, *b;
3398
3399         a = b = name;
3400         while (*b)
3401         {
3402                 switch(*b)
3403                 {
3404                 case '<':
3405                         b++;
3406                         break;
3407                 case '>':
3408                         b++;
3409                         break;
3410                 default:
3411                         *a = *b;
3412                         a++; b++;
3413                         break;
3414                 }
3415         }
3416         *a = 0;
3417 }
3418
3419 gchar*
3420 ghb_dvd_volname(const gchar *device)
3421 {
3422         gchar *name;
3423         name = hb_dvd_name((gchar*)device);
3424         if (name != NULL)
3425         {
3426                 sanitize_volname(name);
3427                 return g_strdup(name);
3428         }
3429         return name;
3430 }