OSDN Git Service

LinGui: refine the drop zone for queue drag n drop. now it only highlights
[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 #if 0
2312                 // Deblock is being reworked
2313                 // debloc 2
2314                 str = ghb_settings_get_string(ud->settings, "tweak_deblock");
2315                 enabled = ghb_settings_get_boolean(ud->settings, "deblock");
2316                 if (enabled && !ghb_validate_filter_string(str, 2))
2317                 {
2318                         message = g_strdup_printf(
2319                                                 "Invalid Deblock Settings:\n\n%s\n",
2320                                                 str);
2321                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2322                         g_free(str);
2323                         g_free(message);
2324                         return FALSE;
2325                 }
2326                 g_free(str);
2327 #endif
2328                 // denois 4
2329                 index = ghb_settings_get_combo_index(ud->settings, "tweak_denoise");
2330                 if (index < 0)
2331                 {
2332                         str = ghb_settings_get_string(ud->settings, "tweak_denoise");
2333                         if (!ghb_validate_filter_string(str, 4))
2334                         {
2335                                 message = g_strdup_printf(
2336                                                         "Invalid Denoise Settings:\n\n%s\n",
2337                                                         str);
2338                                 ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
2339                                 g_free(str);
2340                                 g_free(message);
2341                                 return FALSE;
2342                         }
2343                         g_free(str);
2344                 }
2345         }
2346         return TRUE;
2347 }
2348
2349 gboolean
2350 ghb_validate_video(signal_user_data_t *ud)
2351 {
2352         gint vcodec, mux;
2353         gchar *message;
2354
2355         mux = ghb_settings_get_int(ud->settings, "container");
2356         vcodec = ghb_settings_get_int(ud->settings, "video_codec");
2357         if ((mux == HB_MUX_MP4 || mux == HB_MUX_AVI) && 
2358                 (vcodec == HB_VCODEC_THEORA))
2359         {
2360                 // mp4|avi/theora combination is not supported.
2361                 message = g_strdup_printf(
2362                                         "Theora is not supported in the MP4 and AVI containers.\n\n"
2363                                         "You should choose a different video codec or container.\n"
2364                                         "If you continue, XviD will be chosen for you.");
2365                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2366                 {
2367                         g_free(message);
2368                         return FALSE;
2369                 }
2370                 g_free(message);
2371                 vcodec = HB_VCODEC_XVID;
2372                 ghb_ui_update(ud, "video_codec", ghb_int64_value(vcodec));
2373         }
2374         gboolean decomb;
2375         gboolean vfr;
2376         decomb = ghb_settings_get_boolean(ud->settings, "decomb");
2377         vfr = ghb_settings_get_boolean(ud->settings, "variable_frame_rate");
2378         if (decomb && !vfr)
2379         {
2380                 message = g_strdup_printf(
2381                                         "Decomb is intended to be used in conjunction\n"
2382                                         "with variable frame rate.\n\n"
2383                                         "Would you like me to enable VFR for you?");
2384                 if (ghb_message_dialog(GTK_MESSAGE_WARNING, message, "No", "Yes"))
2385                 {
2386                         ghb_ui_update(ud, "variable_frame_rate", ghb_boolean_value(TRUE));
2387                 }
2388                 g_free(message);
2389         }
2390         return TRUE;
2391 }
2392
2393 gboolean
2394 ghb_validate_container(signal_user_data_t *ud)
2395 {
2396         gint container;
2397         gchar *message;
2398
2399         container = ghb_settings_get_int(ud->settings, "container");
2400         if (container == HB_MUX_MP4)
2401         {
2402                 const GValue *audio_list;
2403                 gboolean httpopt;
2404
2405                 audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2406                 httpopt = ghb_settings_get_boolean(ud->settings, "http_optimize_mp4");
2407                 if (httpopt && ghb_ac3_in_audio_list(audio_list))
2408                 {
2409                         message = g_strdup_printf(
2410                                         "AC3 audio in HTTP optimized MP4 is not supported.\n\n"
2411                                         "You should choose a different audio codec.\n"
2412                                         "If you continue, FAAC will be chosen for you.");
2413                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2414                         {
2415                                 g_free(message);
2416                                 return FALSE;
2417                         }
2418                         g_free(message);
2419
2420                         gint count, ii;
2421
2422                         count = ghb_array_len(audio_list);
2423                         for (ii = 0; ii < count; ii++)
2424                         {
2425                                 GValue *asettings;
2426
2427                                 asettings = ghb_array_get_nth(audio_list, ii);
2428                                 gint acodec = ghb_settings_get_int(asettings, "audio_codec");
2429                                 if (acodec == HB_ACODEC_AC3)
2430                                 {
2431                                         GValue *value;
2432                                         value = get_acodec_value(HB_ACODEC_FAAC);
2433                                         ghb_settings_take_value(asettings, "audio_codec", value);
2434                                 }
2435                         }
2436                 }
2437         }
2438         return TRUE;
2439 }
2440
2441 gboolean
2442 ghb_validate_audio(signal_user_data_t *ud)
2443 {
2444         hb_list_t  * list;
2445         hb_title_t * title;
2446         gchar *message;
2447         GValue *value;
2448
2449         if (h_scan == NULL) return FALSE;
2450         list = hb_get_titles( h_scan );
2451         if( !hb_list_count( list ) )
2452         {
2453                 /* No valid title, stop right there */
2454                 g_message("No title found.\n");
2455                 return FALSE;
2456         }
2457
2458         gint titleindex = ghb_settings_get_int(ud->settings, "title");
2459     title = hb_list_item( list, titleindex );
2460         if (title == NULL) return FALSE;
2461         gint mux = ghb_settings_get_int(ud->settings, "container");
2462
2463         const GValue *audio_list;
2464         gint count, ii;
2465
2466         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
2467         count = ghb_array_len(audio_list);
2468         for (ii = 0; ii < count; ii++)
2469         {
2470                 GValue *asettings;
2471             hb_audio_config_t *taudio;
2472
2473                 asettings = ghb_array_get_nth(audio_list, ii);
2474                 gint track = ghb_settings_get_int(asettings, "audio_track");
2475                 gint codec = ghb_settings_get_int(asettings, "audio_codec");
2476         taudio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, track );
2477                 if ((taudio->in.codec != HB_ACODEC_AC3) && (codec == HB_ACODEC_AC3))
2478                 {
2479                         // Not supported.  AC3 is passthrough only, so input must be AC3
2480                         message = g_strdup_printf(
2481                                                 "The source does not support AC3 Pass-Thru.\n\n"
2482                                                 "You should choose a different audio codec.\n"
2483                                                 "If you continue, one will be chosen for you.");
2484                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2485                         {
2486                                 g_free(message);
2487                                 return FALSE;
2488                         }
2489                         g_free(message);
2490                         if (mux == HB_MUX_AVI)
2491                         {
2492                                 codec = HB_ACODEC_LAME;
2493                         }
2494                         else
2495                         {
2496                                 codec = HB_ACODEC_FAAC;
2497                         }
2498                         value = get_acodec_value(codec);
2499                         ghb_settings_take_value(asettings, "audio_codec", value);
2500                 }
2501                 gchar *a_unsup = NULL;
2502                 gchar *mux_s = NULL;
2503                 if (mux == HB_MUX_MP4)
2504                 { 
2505                         mux_s = "MP4";
2506                         // mp4/mp3|vorbis combination is not supported.
2507                         if (codec == HB_ACODEC_LAME)
2508                         {
2509                                 a_unsup = "MP3";
2510                                 codec = HB_ACODEC_FAAC;
2511                         }
2512                         if (codec == HB_ACODEC_VORBIS)
2513                         {
2514                                 a_unsup = "Vorbis";
2515                                 codec = HB_ACODEC_FAAC;
2516                         }
2517                 }
2518                 else if (mux == HB_MUX_AVI)
2519                 {
2520                         mux_s = "AVI";
2521                         // avi/faac|vorbis combination is not supported.
2522                         if (codec == HB_ACODEC_FAAC)
2523                         {
2524                                 a_unsup = "FAAC";
2525                                 codec = HB_ACODEC_LAME;
2526                         }
2527                         if (codec == HB_ACODEC_VORBIS)
2528                         {
2529                                 a_unsup = "Vorbis";
2530                                 codec = HB_ACODEC_LAME;
2531                         }
2532                 }
2533                 else if (mux == HB_MUX_OGM)
2534                 {
2535                         mux_s = "OGM";
2536                         // avi/faac|vorbis combination is not supported.
2537                         if (codec == HB_ACODEC_FAAC)
2538                         {
2539                                 a_unsup = "FAAC";
2540                                 codec = HB_ACODEC_VORBIS;
2541                         }
2542                         if (codec == HB_ACODEC_AC3)
2543                         {
2544                                 a_unsup = "AC-3";
2545                                 codec = HB_ACODEC_VORBIS;
2546                         }
2547                 }
2548                 if (a_unsup)
2549                 {
2550                         message = g_strdup_printf(
2551                                                 "%s is not supported in the %s container.\n\n"
2552                                                 "You should choose a different audio codec.\n"
2553                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
2554                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2555                         {
2556                                 g_free(message);
2557                                 return FALSE;
2558                         }
2559                         g_free(message);
2560                         value = get_acodec_value(codec);
2561                         ghb_settings_take_value(asettings, "audio_codec", value);
2562                 }
2563                 gint mix = ghb_settings_get_int (asettings, "audio_mix");
2564                 gboolean allow_mono = TRUE;
2565                 gboolean allow_stereo = TRUE;
2566                 gboolean allow_dolby = TRUE;
2567                 gboolean allow_dpl2 = TRUE;
2568                 gboolean allow_6ch = TRUE;
2569                 allow_mono =
2570                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2571                         (codec != HB_ACODEC_LAME);
2572                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
2573                 allow_stereo =
2574                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
2575                 allow_dolby =
2576                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
2577                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
2578                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
2579                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
2580                 allow_6ch =
2581                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
2582                         (codec != HB_ACODEC_LAME) &&
2583                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
2584                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
2585
2586                 gchar *mix_unsup = NULL;
2587                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
2588                 {
2589                         mix_unsup = "mono";
2590                 }
2591                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
2592                 {
2593                         mix_unsup = "stereo";
2594                 }
2595                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
2596                 {
2597                         mix_unsup = "Dolby";
2598                 }
2599                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
2600                 {
2601                         mix_unsup = "Dolby Pro Logic II";
2602                 }
2603                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
2604                 {
2605                         mix_unsup = "6 Channel";
2606                 }
2607                 if (mix_unsup)
2608                 {
2609                         message = g_strdup_printf(
2610                                                 "The source audio does not support %s mixdown.\n\n"
2611                                                 "You should choose a different mixdown.\n"
2612                                                 "If you continue, one will be chosen for you.", mix_unsup);
2613                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
2614                         {
2615                                 g_free(message);
2616                                 return FALSE;
2617                         }
2618                         g_free(message);
2619                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
2620                         value = get_amix_value(mix);
2621                         ghb_settings_take_value(asettings, "audio_mix", value);
2622                 }
2623         }
2624         return TRUE;
2625 }
2626
2627 gboolean
2628 ghb_validate_vquality(GValue *settings)
2629 {
2630         gint vcodec;
2631         gchar *message;
2632         gint min, max;
2633
2634         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
2635         vcodec = ghb_settings_get_int(settings, "video_codec");
2636         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
2637         {
2638                 if (!ghb_settings_get_boolean(settings, "directqp"))
2639                 {
2640                         if (vcodec != HB_VCODEC_X264 || 
2641                                 ghb_settings_get_boolean(settings, "linear_vquality"))
2642                         {
2643                                 min = 68;
2644                                 max = 97;
2645                         }
2646                         else if (vcodec == HB_VCODEC_X264)
2647                         {
2648                                 min = 40;
2649                                 max = 70;
2650                         }
2651                 }
2652                 else
2653                 {
2654                         if (vcodec == HB_VCODEC_X264)
2655                         {
2656                                 min = 16;
2657                                 max = 30;
2658                         }
2659                         else if (vcodec == HB_VCODEC_FFMPEG)
2660                         {
2661                                 min = 1;
2662                                 max = 8;
2663                         }
2664                         else
2665                         {
2666                                 min = 68;
2667                                 max = 97;
2668                         }
2669                 }
2670                 gint vquality = ghb_settings_get_double(settings, "video_quality");
2671                 if (vquality < min || vquality > max)
2672                 {
2673                         message = g_strdup_printf(
2674                                                 "Interesting video quality choise: %d\n\n"
2675                                                 "Typical values range from %d to %d.\n"
2676                                                 "Are you sure you wish to use this setting?",
2677                                                 vquality, min, max);
2678                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
2679                                                                         "Cancel", "Continue"))
2680                         {
2681                                 g_free(message);
2682                                 return FALSE;
2683                         }
2684                         g_free(message);
2685                 }
2686         }
2687         return TRUE;
2688 }
2689
2690 void
2691 ghb_add_job(GValue *js, gint unique_id)
2692 {
2693         hb_list_t  * list;
2694         hb_title_t * title;
2695         hb_job_t   * job;
2696         static gchar *x264opts;
2697         gint sub_id = 0;
2698         gboolean tweaks = FALSE;
2699         gchar *detel_str = NULL;
2700         gchar *decomb_str = NULL;
2701         gchar *deint_str = NULL;
2702         gchar *deblock_str = NULL;
2703         gchar *denoise_str = NULL;
2704         gchar *dest_str = NULL;
2705
2706         g_debug("ghb_add_job()\n");
2707         if (h_queue == NULL) return;
2708         list = hb_get_titles( h_queue );
2709         if( !hb_list_count( list ) )
2710         {
2711                 /* No valid title, stop right there */
2712                 g_message("No title found.\n");
2713                 return;
2714         }
2715
2716         // Since I'm doing a scan of the single title I want just prior 
2717         // to adding the job, there is only the one title to choose from.
2718         //gint titleindex = ghb_settings_get_int(js, "title");
2719     gint titleindex = 0;
2720     title = hb_list_item( list, titleindex );
2721         if (title == NULL) return;
2722
2723         /* Set job settings */
2724         job   = title->job;
2725         if (job == NULL) return;
2726
2727         tweaks = ghb_settings_get_int(js, "allow_tweaks");
2728         job->mux = ghb_lookup_mux(ghb_settings_get_value(js, "container"));
2729         if (job->mux == HB_MUX_MP4)
2730         {
2731                 job->largeFileSize = ghb_settings_get_boolean(js, "large_mp4");
2732                 job->mp4_optimize = ghb_settings_get_boolean(js, "http_optimize_mp4");
2733         }
2734         else
2735         {
2736                 job->largeFileSize = FALSE;
2737                 job->mp4_optimize = FALSE;
2738         }
2739         gint chapter_start, chapter_end;
2740         chapter_start = ghb_settings_get_int(js, "start_chapter");
2741         chapter_end = ghb_settings_get_int(js, "end_chapter");
2742         gint num_chapters = hb_list_count(title->list_chapter);
2743         job->chapter_start = MIN( num_chapters, chapter_start );
2744         job->chapter_end   = MAX( job->chapter_start, chapter_end );
2745
2746         job->chapter_markers = ghb_settings_get_boolean(js, "chapter_markers");
2747         if ( job->chapter_markers )
2748         {
2749                 GValue *chapters;
2750                 GValue *chapter;
2751                 gint chap;
2752                 gint count;
2753                 
2754                 chapters = ghb_settings_get_value(js, "chapter_list");
2755                 count = ghb_array_len(chapters);
2756                 for(chap = chapter_start; chap <= chapter_end; chap++)
2757                 {
2758                         hb_chapter_t * chapter_s;
2759                         gchar *name;
2760                         
2761                         name = NULL;
2762                         if (chap-1 < count)
2763                         {
2764                                 chapter = ghb_array_get_nth(chapters, chap-1);
2765                                 name = ghb_value_string(chapter); 
2766                         }
2767                         if (name == NULL)
2768                         {
2769                                 name = g_strdup_printf ("Chapter %2d", chap);
2770                         }
2771                         chapter_s = hb_list_item( job->title->list_chapter, chap - 1);
2772                         strncpy(chapter_s->title, name, 1023);
2773                         chapter_s->title[1023] = '\0';
2774                         g_free(name);
2775                 }
2776         }
2777         job->crop[0] = ghb_settings_get_int(js, "crop_top");
2778         job->crop[1] = ghb_settings_get_int(js, "crop_bottom");
2779         job->crop[2] = ghb_settings_get_int(js, "crop_left");
2780         job->crop[3] = ghb_settings_get_int(js, "crop_right");
2781
2782         
2783         gboolean decomb = ghb_settings_get_boolean(js, "decomb");
2784         gint deint = ghb_lookup_deint(
2785                 ghb_settings_get_value(js, tweaks ? "tweak_deinterlace":"deinterlace"));
2786         if (!decomb)
2787                 job->deinterlace = (deint != 0) ? 1 : 0;
2788         else
2789                 job->deinterlace = 0;
2790     job->grayscale   = ghb_settings_get_boolean(js, "grayscale");
2791
2792         gboolean anamorphic = ghb_settings_get_boolean(js, "anamorphic");
2793         gboolean round_dimensions = ghb_settings_get_boolean(js, "round_dimensions");
2794         if (round_dimensions && anamorphic)
2795         {
2796                 job->pixel_ratio = 2;
2797                 job->modulus = 16;
2798         }
2799         else if (anamorphic)
2800         {
2801                 // Huh! I thought I wanted to use pixel_ratio 1 for this case, but
2802                 // when its 1, libhb discards the width and height and uses original
2803                 // title dims - crop.  Thats not what I want.
2804                 // Also, x264 requires things to divisible by 2.
2805                 job->pixel_ratio = 2;
2806                 job->modulus = 2;
2807         }
2808         else
2809         {
2810                 job->pixel_ratio = 0;
2811                 job->modulus = 2;
2812         }
2813         job->vfr = ghb_settings_get_boolean(js, "variable_frame_rate");
2814         /* Add selected filters */
2815         job->filters = hb_list_init();
2816         if( ghb_settings_get_boolean(js, "detelecine" ) || job->vfr )
2817         {
2818                 hb_filter_detelecine.settings = NULL;
2819                 if (tweaks)
2820                 {
2821                         detel_str = ghb_settings_get_string(js, "tweak_detelecine");
2822                         if (detel_str && detel_str[0])
2823                         {
2824                                 hb_filter_detelecine.settings = detel_str;
2825                         }
2826                 }
2827                 hb_list_add( job->filters, &hb_filter_detelecine );
2828         }
2829         if( decomb )
2830         {
2831                 // Use default settings
2832                 hb_filter_decomb.settings = NULL;
2833                 if (tweaks)
2834                 {
2835                         decomb_str = ghb_settings_get_string(js, "tweak_decomb");
2836                         if (decomb_str && decomb_str[0])
2837                         {
2838                                 hb_filter_decomb.settings = (gchar*)decomb_str;
2839                         }
2840                 }
2841                 hb_list_add( job->filters, &hb_filter_decomb );
2842         }
2843         if( job->deinterlace )
2844         {
2845                 if (deint > 0)
2846                         deint_str = g_strdup(deint_opts.map[deint].svalue);
2847                 else
2848                         deint_str = ghb_settings_get_string(js, 
2849                                         tweaks ? "tweak_deinterlace" : "deinterlace");
2850                 hb_filter_deinterlace.settings = deint_str;
2851                 hb_list_add( job->filters, &hb_filter_deinterlace );
2852         }
2853         gint deblock = ghb_settings_get_int(js, "deblock");
2854         if( deblock > 0 )
2855         {
2856                 deblock_str = g_strdup_printf("%d", deblock);
2857                 hb_filter_deblock.settings = deblock_str;
2858                 hb_list_add( job->filters, &hb_filter_deblock );
2859         }
2860         gint denoise = ghb_lookup_denoise(
2861                 ghb_settings_get_value(js, tweaks ? "tweak_denoise" : "denoise"));
2862         if( denoise != 0 )
2863         {
2864                 if (denoise > 0)
2865                         denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
2866                 else
2867                         denoise_str = (gchar*)ghb_settings_get_string(
2868                                 js, tweaks ? "tweak_denoise" : "denoise");
2869                 hb_filter_denoise.settings = denoise_str;
2870                 hb_list_add( job->filters, &hb_filter_denoise );
2871         }
2872         job->width = ghb_settings_get_int(js, "scale_width");
2873         job->height = ghb_settings_get_int(js, "scale_height");
2874
2875         job->vcodec = ghb_lookup_vcodec(ghb_settings_get_value(js, "video_codec"));
2876         if ((job->mux == HB_MUX_MP4 || job->mux == HB_MUX_AVI) && 
2877                 (job->vcodec == HB_VCODEC_THEORA))
2878         {
2879                 // mp4|avi/theora combination is not supported.
2880                 job->vcodec = HB_VCODEC_XVID;
2881         }
2882         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
2883         {
2884                 job->ipod_atom = ghb_settings_get_boolean(js, "ipod_file");
2885         }
2886         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
2887         {
2888                 gdouble vquality;
2889                 vquality = ghb_settings_get_double(js, "video_quality");
2890                 if (!ghb_settings_get_boolean(js, "directqp"))
2891                 {
2892                         vquality /= 100.0;
2893                         if (ghb_settings_get_boolean(js, "linear_vquality"))
2894                         {
2895                                 if (job->vcodec == HB_VCODEC_X264)
2896                                 {
2897                                         // Adjust to same range as xvid and ffmpeg
2898                                         vquality = 31.0 - vquality * 31.0;
2899                                         if (vquality > 0)
2900                                         {
2901                                                 // Convert linear to log curve
2902                                                 vquality = 12 + 6 * log2(vquality);
2903                                                 if (vquality > 51) vquality = 51;
2904                                                 if (vquality < 1) vquality = 1;
2905                                         }
2906                                         else
2907                                                 vquality = 0;
2908                                 }
2909                         }
2910                         else
2911                         {
2912                                 if (vquality == 0.0) vquality = 0.01;
2913                                 if (vquality == 1.0) vquality = 0.0;
2914                         }
2915                 }
2916                 job->vquality =  vquality;
2917                 job->vbitrate = 0;
2918         }
2919         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
2920         {
2921                 job->vquality = -1.0;
2922                 job->vbitrate = ghb_settings_get_int(js, "video_bitrate");
2923         }
2924         // AVI container does not support variable frame rate.
2925         if (job->mux == HB_MUX_AVI)
2926         {
2927                 job->vfr = FALSE;
2928         }
2929
2930         gint vrate = ghb_lookup_vrate(ghb_settings_get_value(js, "framerate"));
2931         if( vrate == 0 || job->vfr )
2932         {
2933                 job->vrate = title->rate;
2934                 job->vrate_base = title->rate_base;
2935                 job->cfr = 0;
2936         }
2937         else
2938         {
2939                 job->vrate = 27000000;
2940                 job->vrate_base = vrate;
2941                 job->cfr = 1;
2942         }
2943         // First remove any audios that are already in the list
2944         // This happens if you are encoding the same title a second time.
2945         gint num_audio_tracks = hb_list_count(job->list_audio);
2946         gint ii;
2947     for(ii = 0; ii < num_audio_tracks; ii++)
2948     {
2949         hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
2950         hb_list_rem(job->list_audio, audio);
2951     }
2952
2953         const GValue *audio_list;
2954         gint count;
2955         gint tcount = 0;
2956         
2957         audio_list = ghb_settings_get_value(js, "audio_list");
2958         count = ghb_array_len(audio_list);
2959         for (ii = 0; ii < count; ii++)
2960         {
2961                 GValue *asettings;
2962             hb_audio_config_t audio;
2963             hb_audio_config_t *taudio;
2964
2965                 hb_audio_config_init(&audio);
2966                 asettings = ghb_array_get_nth(audio_list, ii);
2967                 audio.in.track = ghb_settings_get_int(asettings, "audio_track");
2968                 audio.out.track = tcount;
2969                 audio.out.codec = ghb_lookup_acodec(
2970                         ghb_settings_get_value(asettings, "audio_codec"));
2971         taudio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, audio.in.track );
2972                 if ((taudio->in.codec != HB_ACODEC_AC3) && (audio.out.codec == HB_ACODEC_AC3))
2973                 {
2974                         // Not supported.  AC3 is passthrough only, so input must be AC3
2975                         if (job->mux == HB_MUX_AVI)
2976                         {
2977                                 audio.out.codec = HB_ACODEC_LAME;
2978                         }
2979                         else
2980                         {
2981                                 audio.out.codec = HB_ACODEC_FAAC;
2982                         }
2983                 }
2984                 if ((job->mux == HB_MUX_MP4) && 
2985                         ((audio.out.codec == HB_ACODEC_LAME) ||
2986                         (audio.out.codec == HB_ACODEC_VORBIS)))
2987                 {
2988                         // mp4/mp3|vorbis combination is not supported.
2989                         audio.out.codec = HB_ACODEC_FAAC;
2990                 }
2991                 if ((job->mux == HB_MUX_AVI) && 
2992                         ((audio.out.codec == HB_ACODEC_FAAC) ||
2993                         (audio.out.codec == HB_ACODEC_VORBIS)))
2994                 {
2995                         // avi/faac|vorbis combination is not supported.
2996                         audio.out.codec = HB_ACODEC_LAME;
2997                 }
2998                 if ((job->mux == HB_MUX_OGM) && 
2999                         ((audio.out.codec == HB_ACODEC_FAAC) ||
3000                         (audio.out.codec == HB_ACODEC_AC3)))
3001                 {
3002                         // ogm/faac|ac3 combination is not supported.
3003                         audio.out.codec = HB_ACODEC_VORBIS;
3004                 }
3005         audio.out.dynamic_range_compression = 
3006                         ghb_settings_get_double(asettings, "audio_drc");
3007                 // It would be better if this were done in libhb for us, but its not yet.
3008                 if (audio.out.codec == HB_ACODEC_AC3 || audio.out.codec == HB_ACODEC_DCA)
3009                 {
3010                         audio.out.mixdown = 0;
3011                 }
3012                 else
3013                 {
3014                         audio.out.mixdown = ghb_lookup_mix(
3015                                 ghb_settings_get_value (asettings, "audio_mix"));
3016                         // Make sure the mixdown is valid and pick a new one if not.
3017                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
3018                                 audio.in.track, audio.out.codec, audio.out.mixdown);
3019                         audio.out.bitrate = 
3020                                 ghb_settings_get_int(asettings, "audio_bitrate") / 1000;
3021                         gint srate = ghb_settings_get_int(asettings, "audio_rate");
3022                         if (srate == 0) // 0 is same as source
3023                                 audio.out.samplerate = taudio->in.samplerate;
3024                         else
3025                                 audio.out.samplerate = srate;
3026                 }
3027
3028                 // Add it to the jobs audio list
3029         hb_audio_add( job, &audio );
3030                 tcount++;
3031         }
3032         // I was tempted to move this up with the reset of the video quality
3033         // settings, but I suspect the settings above need to be made
3034         // first in order for hb_calc_bitrate to be accurate.
3035         if (ghb_settings_get_boolean(js, "vquality_type_target"))
3036         {
3037                 gint size;
3038                 
3039                 size = ghb_settings_get_int(js, "video_target_size");
3040         job->vbitrate = hb_calc_bitrate( job, size );
3041                 job->vquality = -1.0;
3042         }
3043
3044         dest_str = ghb_settings_get_string(js, "destination");
3045         job->file = dest_str;
3046         job->crf = ghb_settings_get_boolean(js, "constant_rate_factor");
3047         // TODO: libhb holds onto a reference to the x264opts and is not
3048         // finished with it until encoding the job is done.  But I can't
3049         // find a way to get at the job before it is removed in order to
3050         // free up the memory I am allocating here.
3051         // The short story is THIS LEAKS.
3052         x264opts = ghb_build_x264opts_string(js);
3053         
3054         if( x264opts != NULL && *x264opts != '\0' )
3055         {
3056                 job->x264opts = x264opts;
3057         }
3058         else /*avoids a bus error crash when options aren't specified*/
3059         {
3060                 job->x264opts =  NULL;
3061         }
3062         gint subtitle = ghb_settings_get_int(js, "subtitle_lang");
3063         gchar *slang = ghb_settings_get_string(js, "subtitle_lang");
3064         subtitle = -2; // default to none
3065         if (strcmp(slang, "auto") == 0)
3066         {
3067                 subtitle = -1;
3068         }
3069         else
3070         {
3071                 gint scount;
3072         hb_subtitle_t * subt;
3073
3074                 scount = hb_list_count(title->list_subtitle);
3075                 for (ii = 0; ii < scount; ii++)
3076                 {
3077                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
3078                         if (strcmp(slang, subt->iso639_2) == 0)
3079                         {
3080                                 subtitle = ii;
3081                                 break;
3082                         }
3083                 }
3084         }
3085         gboolean forced_subtitles = ghb_settings_get_boolean(js, "forced_subtitles");
3086         job->subtitle_force = forced_subtitles;
3087         if (subtitle >= 0)
3088                 job->subtitle = subtitle;
3089         else
3090                 job->subtitle = -1;
3091         if (subtitle == -1)
3092         {
3093                 // Subtitle scan. Look for subtitle matching audio language
3094                 char *x264opts_tmp;
3095
3096                 /*
3097                  * When subtitle scan is enabled do a fast pre-scan job
3098                  * which will determine which subtitles to enable, if any.
3099                  */
3100                 job->pass = -1;
3101                 job->indepth_scan = 1;
3102
3103                 x264opts_tmp = job->x264opts;
3104                 job->x264opts = NULL;
3105
3106                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
3107                 *(job->select_subtitle) = NULL;
3108
3109                 /*
3110                  * Add the pre-scan job
3111                  */
3112                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3113                 hb_add( h_queue, job );
3114                 //if (job->x264opts != NULL)
3115                 //      g_free(job->x264opts);
3116
3117                 job->x264opts = x264opts_tmp;
3118         }
3119         else
3120         {
3121                 job->select_subtitle = NULL;
3122         }
3123         if( ghb_settings_get_boolean(js, "two_pass") &&
3124                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
3125         {
3126                 /*
3127                  * If subtitle_scan is enabled then only turn it on
3128                  * for the second pass and then off again for the
3129                  * second.
3130                  */
3131                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
3132                 job->select_subtitle = NULL;
3133                 job->pass = 1;
3134                 job->indepth_scan = 0;
3135                 gchar *x264opts2 = NULL;
3136                 if (x264opts)
3137                 {
3138                         x264opts2 = g_strdup(x264opts);
3139                 }
3140                 /*
3141                  * If turbo options have been selected then append them
3142                  * to the x264opts now (size includes one ':' and the '\0')
3143                  */
3144                 if( ghb_settings_get_boolean(js, "turbo") )
3145                 {
3146                         char *tmp_x264opts;
3147
3148                         if ( x264opts )
3149                         {
3150                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, turbo_opts);
3151                                 g_free(x264opts);
3152                         } 
3153                         else 
3154                         {
3155                                 /*
3156                                  * No x264opts to modify, but apply the turbo options
3157                                  * anyway as they may be modifying defaults
3158                                  */
3159                                 tmp_x264opts = g_strdup_printf("%s", turbo_opts);
3160                         }
3161                         x264opts = tmp_x264opts;
3162
3163                         job->x264opts = x264opts;
3164                 }
3165                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3166                 hb_add( h_queue, job );
3167                 //if (job->x264opts != NULL)
3168                 //      g_free(job->x264opts);
3169
3170                 job->select_subtitle = subtitle_tmp;
3171                 job->pass = 2;
3172                 /*
3173                  * On the second pass we turn off subtitle scan so that we
3174                  * can actually encode using any subtitles that were auto
3175                  * selected in the first pass (using the whacky select-subtitle
3176                  * attribute of the job).
3177                  */
3178                 job->indepth_scan = 0;
3179                 job->x264opts = x264opts2;
3180                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3181                 hb_add( h_queue, job );
3182                 //if (job->x264opts != NULL)
3183                 //      g_free(job->x264opts);
3184         }
3185         else
3186         {
3187                 job->indepth_scan = 0;
3188                 job->pass = 0;
3189                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
3190                 hb_add( h_queue, job );
3191                 //if (job->x264opts != NULL)
3192                 //      g_free(job->x264opts);
3193         }
3194         if (detel_str) g_free(detel_str);
3195         if (decomb_str) g_free(decomb_str);
3196         if (deint_str) g_free(deint_str);
3197         if (deblock_str) g_free(deblock_str);
3198         if (denoise_str) g_free(denoise_str);
3199         if (dest_str) g_free(dest_str);
3200 }
3201
3202 void
3203 ghb_remove_job(gint unique_id)
3204 {
3205     hb_job_t * job;
3206     gint ii;
3207         
3208         // Multiples passes all get the same id
3209         // remove them all.
3210         // Go backwards through list, so reordering doesn't screw me.
3211         ii = hb_count(h_queue) - 1;
3212     while ((job = hb_job(h_queue, ii--)) != NULL)
3213     {
3214         if ((job->sequence_id & 0xFFFFFF) == unique_id)
3215                         hb_rem(h_queue, job);
3216     }
3217 }
3218
3219 void
3220 ghb_start_queue()
3221 {
3222         hb_start( h_queue );
3223 }
3224
3225 void
3226 ghb_stop_queue()
3227 {
3228         hb_stop( h_queue );
3229 }
3230
3231 void
3232 ghb_pause_queue()
3233 {
3234     hb_state_t s;
3235     hb_get_state2( h_queue, &s );
3236
3237     if( s.state == HB_STATE_PAUSED )
3238     {
3239         hb_resume( h_queue );
3240     }
3241     else
3242     {
3243         hb_pause( h_queue );
3244     }
3245 }
3246
3247 GdkPixbuf*
3248 ghb_get_preview_image(
3249         gint titleindex, 
3250         gint index, 
3251         GValue *settings, 
3252         gboolean borders)
3253 {
3254         hb_title_t *title;
3255         hb_list_t  *list;
3256         
3257         list = hb_get_titles( h_scan );
3258         if( !hb_list_count( list ) )
3259         {
3260                 /* No valid title, stop right there */
3261                 return NULL;
3262         }
3263     title = hb_list_item( list, titleindex );
3264         if (title == NULL) return NULL;
3265         if (title->job == NULL) return NULL;
3266         set_preview_job_settings(title->job, settings);
3267
3268         // hb_get_preview can't handle sizes that are larger than the original title
3269         // dimensions
3270         if (title->job->width > title->width)
3271                 title->job->width = title->width;
3272         
3273         if (title->job->height > title->height)
3274                 title->job->height = title->height;
3275         // And also creates artifacts if the width is not a multiple of 8
3276         //title->job->width = ((title->job->width + 4) >> 3) << 3;
3277         // And the height must be a multiple of 2
3278         //title->job->height = ((title->job->height + 1) >> 1) << 1;
3279         
3280         // Make sure we have a big enough buffer to receive the image from libhb. libhb
3281         // creates images with a one-pixel border around the original content. Hence we
3282         // add 2 pixels horizontally and vertically to the buffer size.
3283         gint srcWidth = title->width + 2;
3284         gint srcHeight= title->height + 2;
3285         gint dstWidth = title->width;
3286         gint dstHeight= title->height;
3287         gint borderTop = 1;
3288         gint borderLeft = 1;
3289     if (borders)
3290     {
3291         //     |<---------- title->width ----------->|
3292         //     |   |<---- title->job->width ---->|   |
3293         //     |   |                             |   |
3294         //     .......................................
3295         //     ....+-----------------------------+....
3296         //     ....|                             |....<-- gray border
3297         //     ....|                             |....
3298         //     ....|                             |....
3299         //     ....|                             |<------- image
3300         //     ....|                             |....
3301         //     ....|                             |....
3302         //     ....|                             |....
3303         //     ....|                             |....
3304         //     ....|                             |....
3305         //     ....+-----------------------------+....
3306         //     .......................................
3307                 dstWidth = title->job->width;
3308         dstHeight = title->job->height;
3309                 borderTop = (srcHeight - dstHeight) / 2;
3310                 borderLeft = (srcWidth - dstWidth) / 2;
3311                 g_debug("boarders removed\n");
3312         }
3313
3314         g_debug("src %d x %d\n", srcWidth, srcHeight);
3315         g_debug("dst %d x %d\n", dstWidth, dstHeight);
3316         g_debug("job dim %d x %d\n", title->job->width, title->job->height);
3317         g_debug("title crop %d:%d:%d:%d\n", 
3318                         title->crop[0],
3319                         title->crop[1],
3320                         title->crop[2],
3321                         title->crop[3]);
3322         g_debug("job crop %d:%d:%d:%d\n", 
3323                         title->job->crop[0],
3324                         title->job->crop[1],
3325                         title->job->crop[2],
3326                         title->job->crop[3]);
3327         static guint8 *buffer = NULL;
3328         static gint bufferSize = 0;
3329
3330         gint newSize;
3331         newSize = srcWidth * srcHeight * 4;
3332         if( bufferSize < newSize )
3333         {
3334                 bufferSize = newSize;
3335                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
3336         }
3337         hb_get_preview( h_scan, title, index, buffer );
3338
3339         // Create an GdkPixbuf and copy the libhb image into it, converting it from
3340         // libhb's format something suitable. Along the way, we'll strip off the
3341         // border around libhb's image.
3342         
3343         // The image data returned by hb_get_preview is 4 bytes per pixel, BGRA format.
3344         // Alpha is ignored.
3345
3346         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
3347         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
3348         
3349         guint32 *src = (guint32*)buffer;
3350         guint8 *dst = pixels;
3351         src += borderTop * srcWidth;    // skip top rows in src to get to first row of dst
3352         src += borderLeft;              // skip left pixels in src to get to first pixel of dst
3353         gint ii, jj;
3354         gint channels = gdk_pixbuf_get_n_channels (preview);
3355         gint stride = gdk_pixbuf_get_rowstride (preview);
3356         guint8 *tmp;
3357         for (ii = 0; ii < dstHeight; ii++)
3358         {
3359                 tmp = dst;
3360                 for (jj = 0; jj < dstWidth; jj++)
3361                 {
3362                         tmp[0] = src[0] >> 16;
3363                         tmp[1] = src[0] >> 8;
3364                         tmp[2] = src[0] >> 0;
3365                         tmp += channels;
3366                         src++;
3367                 }
3368                 dst += stride;
3369                 src += (srcWidth - dstWidth);   // skip to next row in src
3370         }
3371         // Got it, but hb_get_preview doesn't compensate for anamorphic, so lets
3372         // scale
3373         gint width, height, par_width, par_height;
3374         gboolean anamorphic = ghb_settings_get_boolean(settings, "anamorphic");
3375         if (anamorphic)
3376         {
3377                 hb_set_anamorphic_size( title->job, &width, &height, &par_width, &par_height );
3378                 if (par_width > par_height)
3379                         dstWidth = dstWidth * par_width / par_height;
3380                 else
3381                         dstHeight = dstHeight * par_height / par_width;
3382         }
3383         
3384         g_debug("scaled %d x %d\n", dstWidth, dstHeight);
3385         GdkPixbuf *scaled_preview;
3386         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
3387         g_object_unref (preview);
3388         return scaled_preview;
3389 }
3390
3391 static void
3392 sanitize_volname(gchar *name)
3393 {
3394         gchar *a, *b;
3395
3396         a = b = name;
3397         while (*b)
3398         {
3399                 switch(*b)
3400                 {
3401                 case '<':
3402                         b++;
3403                         break;
3404                 case '>':
3405                         b++;
3406                         break;
3407                 default:
3408                         *a = *b;
3409                         a++; b++;
3410                         break;
3411                 }
3412         }
3413         *a = 0;
3414 }
3415
3416 gchar*
3417 ghb_dvd_volname(const gchar *device)
3418 {
3419         gchar *name;
3420         name = hb_dvd_name((gchar*)device);
3421         if (name != NULL)
3422         {
3423                 sanitize_volname(name);
3424                 return g_strdup(name);
3425         }
3426         return name;
3427 }