OSDN Git Service

LinGui: add individual activity log longevity preference option
[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 <gtk/gtk.h>
29 #include <glib/gstdio.h>
30 #include "hb-backend.h"
31 #include "settings.h"
32 #include "callbacks.h"
33 #include "subtitlehandler.h"
34 #include "x264handler.h"
35 #include "preview.h"
36 #include "values.h"
37 #include "lang.h"
38
39 typedef struct
40 {
41         const gchar *option;
42         const gchar *shortOpt;
43         gdouble ivalue;
44         const gchar *svalue;
45 } options_map_t;
46
47 typedef struct
48 {
49         gint count;
50         options_map_t *map;
51 } combo_opts_t;
52
53 static gchar **index_str = NULL;
54 static gint index_str_size = 0;
55
56 static void 
57 index_str_init(gint max_index)
58 {
59         int ii;
60
61         if (max_index+1 > index_str_size)
62         {
63                 index_str = realloc(index_str, (max_index+1) * sizeof(char*));
64                 for (ii = index_str_size; ii <= max_index; ii++)
65                 {
66                         index_str[ii] = g_strdup_printf("%d", ii);
67                 }
68                 index_str_size = max_index + 1;
69         }
70 }
71
72 static options_map_t d_when_complete_opts[] =
73 {
74         {"Do Nothing",            "nothing",  0, "0"},
75         {"Show Notification",     "notify",   1, "1"},
76         {"Put Computer To Sleep", "sleep",    2, "2"},
77         {"Shutdown Computer",     "shutdown", 3, "3"},
78 };
79 combo_opts_t when_complete_opts =
80 {
81         sizeof(d_when_complete_opts)/sizeof(options_map_t),
82         d_when_complete_opts
83 };
84
85 static options_map_t d_par_opts[] =
86 {
87         {"Off", "0", 0, "0"},
88         {"Strict", "1", 1, "1"},
89         {"Loose", "2", 2, "2"},
90         {"Custom", "3", 3, "3"},
91 };
92 combo_opts_t par_opts =
93 {
94         sizeof(d_par_opts)/sizeof(options_map_t),
95         d_par_opts
96 };
97
98 static options_map_t d_alignment_opts[] =
99 {
100         {"2", "2", 2, "2"},
101         {"4", "4", 4, "4"},
102         {"8", "8", 8, "8"},
103         {"16", "16", 16, "16"},
104 };
105 combo_opts_t alignment_opts =
106 {
107         sizeof(d_alignment_opts)/sizeof(options_map_t),
108         d_alignment_opts
109 };
110
111 static options_map_t d_logging_opts[] =
112 {
113         {"0", "0", 0, "0"},
114         {"1", "1", 1, "1"},
115         {"2", "2", 2, "2"},
116 };
117 combo_opts_t logging_opts =
118 {
119         sizeof(d_logging_opts)/sizeof(options_map_t),
120         d_logging_opts
121 };
122
123 static options_map_t d_log_longevity_opts[] =
124 {
125         {"Week",     "week",     7, "7"},
126         {"Month",    "month",    30, "30"},
127         {"Year",     "year",     365, "365"},
128         {"Immortal", "immortal", 366, "366"},
129 };
130 combo_opts_t log_longevity_opts =
131 {
132         sizeof(d_log_longevity_opts)/sizeof(options_map_t),
133         d_log_longevity_opts
134 };
135
136 static options_map_t d_appcast_update_opts[] =
137 {
138         {"Never", "never", 0, "never"},
139         {"Daily", "daily", 1, "daily"},
140         {"Weekly", "weekly", 2, "weekly"},
141         {"Monthly", "monthly", 3, "monthly"},
142 };
143 combo_opts_t appcast_update_opts =
144 {
145         sizeof(d_appcast_update_opts)/sizeof(options_map_t),
146         d_appcast_update_opts
147 };
148
149 static options_map_t d_vqual_granularity_opts[] =
150 {
151         {"0.2",  "0.2",  0.2,  "0.2"},
152         {"0.25", "0.25", 0.25, "0.25"},
153         {"0.5",  "0.5",  0.5,  "0.5"},
154         {"1",    "1",    1,    "1"},
155 };
156 combo_opts_t vqual_granularity_opts =
157 {
158         sizeof(d_vqual_granularity_opts)/sizeof(options_map_t),
159         d_vqual_granularity_opts
160 };
161
162 static options_map_t d_container_opts[] =
163 {
164         {"MKV", "mkv", HB_MUX_MKV, "mkv"},
165         {"MP4", "mp4", HB_MUX_MP4, "mp4"},
166 };
167 combo_opts_t container_opts =
168 {
169         sizeof(d_container_opts)/sizeof(options_map_t),
170         d_container_opts
171 };
172
173 static options_map_t d_detel_opts[] =
174 {
175         {"None",   "none",   0, ""},
176         {"Custom", "custom", 1, ""},
177         {"Default","default",2, NULL},
178 };
179 combo_opts_t detel_opts =
180 {
181         sizeof(d_detel_opts)/sizeof(options_map_t),
182         d_detel_opts
183 };
184
185 static options_map_t d_decomb_opts[] =
186 {
187         {"None",   "none",   0, ""},
188         {"Custom", "custom", 1, ""},
189         {"Default","default",2, NULL},
190 };
191 combo_opts_t decomb_opts =
192 {
193         sizeof(d_decomb_opts)/sizeof(options_map_t),
194         d_decomb_opts
195 };
196
197 static options_map_t d_deint_opts[] =
198 {
199         {"None",   "none",   0, ""},
200         {"Custom", "custom", 1, ""},
201         {"Fast",   "fast",   2, "-1:-1:-1:0:1"},
202         {"Slow",   "slow",   3, "2:-1:-1:0:1"},
203         {"Slower", "slower", 4, "0:-1:-1:0:1"},
204 };
205 combo_opts_t deint_opts =
206 {
207         sizeof(d_deint_opts)/sizeof(options_map_t),
208         d_deint_opts
209 };
210
211 static options_map_t d_denoise_opts[] =
212 {
213         {"None",   "none",   0, ""},
214         {"Custom", "custom", 1, ""},
215         {"Weak",   "weak",   2, "2:1:2:3"},
216         {"Medium", "medium", 3, "3:2:2:3"},
217         {"Strong", "strong", 4, "7:7:5:5"},
218 };
219 combo_opts_t denoise_opts =
220 {
221         sizeof(d_denoise_opts)/sizeof(options_map_t),
222         d_denoise_opts
223 };
224
225 static options_map_t d_vcodec_opts[] =
226 {
227         {"H.264 (x264)",    "x264",   HB_VCODEC_X264, ""},
228         {"MPEG-4 (FFMPEG)", "ffmpeg", HB_VCODEC_FFMPEG, ""},
229         {"Theora",          "theora", HB_VCODEC_THEORA, ""},
230 };
231 combo_opts_t vcodec_opts =
232 {
233         sizeof(d_vcodec_opts)/sizeof(options_map_t),
234         d_vcodec_opts
235 };
236
237 static options_map_t d_acodec_opts[] =
238 {
239         {"AAC (faac)",      "faac",   HB_ACODEC_FAAC, "faac"},
240         {"MP3 (lame)",      "lame",   HB_ACODEC_LAME, "lame"},
241         {"Vorbis",          "vorbis", HB_ACODEC_VORBIS, "vorbis"},
242         {"AC3 (pass-thru)", "ac3",    HB_ACODEC_AC3, "ac3"},
243         {"DTS (pass-thru)", "dts",    HB_ACODEC_DCA, "dts"},
244         {"Auto Pass-Thru", "auto",    HB_ACODEC_DCA|HB_ACODEC_AC3, "auto"},
245 };
246 combo_opts_t acodec_opts =
247 {
248         sizeof(d_acodec_opts)/sizeof(options_map_t),
249         d_acodec_opts
250 };
251
252 static options_map_t d_direct_opts[] =
253 {
254         {"None",      "none",     0, "none"},
255         {"Spatial",   "spatial",  1, "spatial"},
256         {"Temporal",  "temporal", 2, "temporal"},
257         {"Automatic", "auto",     3, "auto"},
258 };
259 combo_opts_t direct_opts =
260 {
261         sizeof(d_direct_opts)/sizeof(options_map_t),
262         d_direct_opts
263 };
264
265 static options_map_t d_badapt_opts[] =
266 {
267         {"Off",             "0", 0, "0"},
268         {"Fast",            "1", 1, "1"},
269         {"Optimal",         "2", 2, "2"},
270 };
271 combo_opts_t badapt_opts =
272 {
273         sizeof(d_badapt_opts)/sizeof(options_map_t),
274         d_badapt_opts
275 };
276
277 static options_map_t d_me_opts[] =
278 {
279         {"Diamond",              "dia",  0, "dia"},
280         {"Hexagon",              "hex",  1, "hex"},
281         {"Uneven Multi-Hexagon", "umh",  2, "umh"},
282         {"Exhaustive",           "esa",  3, "esa"},
283         {"Hadamard Exhaustive",  "tesa", 4, "tesa"},
284 };
285 combo_opts_t me_opts =
286 {
287         sizeof(d_me_opts)/sizeof(options_map_t),
288         d_me_opts
289 };
290
291 static options_map_t d_subme_opts[] =
292 {
293         {"1", "1", 1, "1"},
294         {"2", "2", 2, "2"},
295         {"3", "3", 3, "3"},
296         {"4", "4", 4, "4"},
297         {"5", "5", 5, "5"},
298         {"6", "6", 6, "6"},
299         {"7", "7", 7, "7"},
300         {"8", "8", 8, "8"},
301         {"9", "9", 9, "9"},
302 };
303 combo_opts_t subme_opts =
304 {
305         sizeof(d_subme_opts)/sizeof(options_map_t),
306         d_subme_opts
307 };
308
309 static options_map_t d_analyse_opts[] =
310 {
311         {"Some", "some", 0, "some"},
312         {"None", "none", 1, "none"},
313         {"All",  "all",  2, "all"},
314         {"Custom",  "custom",  3, "all"},
315 };
316 combo_opts_t analyse_opts =
317 {
318         sizeof(d_analyse_opts)/sizeof(options_map_t),
319         d_analyse_opts
320 };
321
322 static options_map_t d_trellis_opts[] =
323 {
324         {"Disabled",          "0", 0, "0"},
325         {"Final Macro Block", "1", 1, "1"},
326         {"Always",            "2", 2, "2"},
327 };
328 combo_opts_t trellis_opts =
329 {
330         sizeof(d_trellis_opts)/sizeof(options_map_t),
331         d_trellis_opts
332 };
333
334 combo_opts_t subtitle_opts =
335 {
336         0,
337         NULL
338 };
339
340 combo_opts_t title_opts =
341 {
342         0,
343         NULL
344 };
345
346 combo_opts_t audio_track_opts =
347 {
348         0,
349         NULL
350 };
351
352 typedef struct
353 {
354         const gchar *name;
355         combo_opts_t *opts;
356 } combo_name_map_t;
357
358 combo_name_map_t combo_name_map[] =
359 {
360         {"WhenComplete", &when_complete_opts},
361         {"PicturePAR", &par_opts},
362         {"PictureModulus", &alignment_opts},
363         {"LoggingLevel", &logging_opts},
364         {"LogLongevity", &log_longevity_opts},
365         {"check_updates", &appcast_update_opts},
366         {"VideoQualityGranularity", &vqual_granularity_opts},
367         {"FileFormat", &container_opts},
368         {"PictureDeinterlace", &deint_opts},
369         {"PictureDecomb", &decomb_opts},
370         {"PictureDetelecine", &detel_opts},
371         {"PictureDenoise", &denoise_opts},
372         {"VideoEncoder", &vcodec_opts},
373         {"AudioEncoder", &acodec_opts},
374         {"x264_direct", &direct_opts},
375         {"x264_b_adapt", &badapt_opts},
376         {"x264_me", &me_opts},
377         {"x264_subme", &subme_opts},
378         {"x264_analyse", &analyse_opts},
379         {"x264_trellis", &trellis_opts},
380         {"SubtitleTrack", &subtitle_opts},
381         {"title", &title_opts},
382         {"AudioTrack", &audio_track_opts},
383         {NULL, NULL}
384 };
385
386 #if 0
387 typedef struct iso639_lang_t
388 {
389     char * eng_name;        /* Description in English */
390     char * native_name;     /* Description in native language */
391     char * iso639_1;       /* ISO-639-1 (2 characters) code */
392     char * iso639_2;        /* ISO-639-2/t (3 character) code */
393     char * iso639_2b;       /* ISO-639-2/b code (if different from above) */
394 } iso639_lang_t;
395 #endif
396
397 const iso639_lang_t ghb_language_table[] =
398
399         { "Any", "", "zz", "und" },
400         { "Afar", "", "aa", "aar" },
401         { "Abkhazian", "", "ab", "abk" },
402         { "Afrikaans", "", "af", "afr" },
403         { "Akan", "", "ak", "aka" },
404         { "Albanian", "", "sq", "sqi", "alb" },
405         { "Amharic", "", "am", "amh" },
406         { "Arabic", "", "ar", "ara" },
407         { "Aragonese", "", "an", "arg" },
408         { "Armenian", "", "hy", "hye", "arm" },
409         { "Assamese", "", "as", "asm" },
410         { "Avaric", "", "av", "ava" },
411         { "Avestan", "", "ae", "ave" },
412         { "Aymara", "", "ay", "aym" },
413         { "Azerbaijani", "", "az", "aze" },
414         { "Bashkir", "", "ba", "bak" },
415         { "Bambara", "", "bm", "bam" },
416         { "Basque", "", "eu", "eus", "baq" },
417         { "Belarusian", "", "be", "bel" },
418         { "Bengali", "", "bn", "ben" },
419         { "Bihari", "", "bh", "bih" },
420         { "Bislama", "", "bi", "bis" },
421         { "Bosnian", "", "bs", "bos" },
422         { "Breton", "", "br", "bre" },
423         { "Bulgarian", "", "bg", "bul" },
424         { "Burmese", "", "my", "mya", "bur" },
425         { "Catalan", "", "ca", "cat" },
426         { "Chamorro", "", "ch", "cha" },
427         { "Chechen", "", "ce", "che" },
428         { "Chinese", "", "zh", "zho", "chi" },
429         { "Church Slavic", "", "cu", "chu" },
430         { "Chuvash", "", "cv", "chv" },
431         { "Cornish", "", "kw", "cor" },
432         { "Corsican", "", "co", "cos" },
433         { "Cree", "", "cr", "cre" },
434         { "Czech", "", "cs", "ces", "cze" },
435         { "Danish", "Dansk", "da", "dan" },
436         { "Divehi", "", "dv", "div" },
437         { "Dutch", "Nederlands", "nl", "nld", "dut" },
438         { "Dzongkha", "", "dz", "dzo" },
439         { "English", "English", "en", "eng" },
440         { "Esperanto", "", "eo", "epo" },
441         { "Estonian", "", "et", "est" },
442         { "Ewe", "", "ee", "ewe" },
443         { "Faroese", "", "fo", "fao" },
444         { "Fijian", "", "fj", "fij" },
445         { "Finnish", "Suomi", "fi", "fin" },
446         { "French", "Francais", "fr", "fra", "fre" },
447         { "Western Frisian", "", "fy", "fry" },
448         { "Fulah", "", "ff", "ful" },
449         { "Georgian", "", "ka", "kat", "geo" },
450         { "German", "Deutsch", "de", "deu", "ger" },
451         { "Gaelic (Scots)", "", "gd", "gla" },
452         { "Irish", "", "ga", "gle" },
453         { "Galician", "", "gl", "glg" },
454         { "Manx", "", "gv", "glv" },
455         { "Greek, Modern", "", "el", "ell", "gre" },
456         { "Guarani", "", "gn", "grn" },
457         { "Gujarati", "", "gu", "guj" },
458         { "Haitian", "", "ht", "hat" },
459         { "Hausa", "", "ha", "hau" },
460         { "Hebrew", "", "he", "heb" },
461         { "Herero", "", "hz", "her" },
462         { "Hindi", "", "hi", "hin" },
463         { "Hiri Motu", "", "ho", "hmo" },
464         { "Hungarian", "Magyar", "hu", "hun" },
465         { "Igbo", "", "ig", "ibo" },
466         { "Icelandic", "Islenska", "is", "isl", "ice" },
467         { "Ido", "", "io", "ido" },
468         { "Sichuan Yi", "", "ii", "iii" },
469         { "Inuktitut", "", "iu", "iku" },
470         { "Interlingue", "", "ie", "ile" },
471         { "Interlingua", "", "ia", "ina" },
472         { "Indonesian", "", "id", "ind" },
473         { "Inupiaq", "", "ik", "ipk" },
474         { "Italian", "Italiano", "it", "ita" },
475         { "Javanese", "", "jv", "jav" },
476         { "Japanese", "", "ja", "jpn" },
477         { "Kalaallisut", "", "kl", "kal" },
478         { "Kannada", "", "kn", "kan" },
479         { "Kashmiri", "", "ks", "kas" },
480         { "Kanuri", "", "kr", "kau" },
481         { "Kazakh", "", "kk", "kaz" },
482         { "Central Khmer", "", "km", "khm" },
483         { "Kikuyu", "", "ki", "kik" },
484         { "Kinyarwanda", "", "rw", "kin" },
485         { "Kirghiz", "", "ky", "kir" },
486         { "Komi", "", "kv", "kom" },
487         { "Kongo", "", "kg", "kon" },
488         { "Korean", "", "ko", "kor" },
489         { "Kuanyama", "", "kj", "kua" },
490         { "Kurdish", "", "ku", "kur" },
491         { "Lao", "", "lo", "lao" },
492         { "Latin", "", "la", "lat" },
493         { "Latvian", "", "lv", "lav" },
494         { "Limburgan", "", "li", "lim" },
495         { "Lingala", "", "ln", "lin" },
496         { "Lithuanian", "", "lt", "lit" },
497         { "Luxembourgish", "", "lb", "ltz" },
498         { "Luba-Katanga", "", "lu", "lub" },
499         { "Ganda", "", "lg", "lug" },
500         { "Macedonian", "", "mk", "mkd", "mac" },
501         { "Marshallese", "", "mh", "mah" },
502         { "Malayalam", "", "ml", "mal" },
503         { "Maori", "", "mi", "mri", "mao" },
504         { "Marathi", "", "mr", "mar" },
505         { "Malay", "", "ms", "msa", "msa" },
506         { "Malagasy", "", "mg", "mlg" },
507         { "Maltese", "", "mt", "mlt" },
508         { "Moldavian", "", "mo", "mol" },
509         { "Mongolian", "", "mn", "mon" },
510         { "Nauru", "", "na", "nau" },
511         { "Navajo", "", "nv", "nav" },
512         { "Ndebele, South", "", "nr", "nbl" },
513         { "Ndebele, North", "", "nd", "nde" },
514         { "Ndonga", "", "ng", "ndo" },
515         { "Nepali", "", "ne", "nep" },
516         { "Norwegian Nynorsk", "", "nn", "nno" },
517         { "Norwegian Bokmål", "", "nb", "nob" },
518         { "Norwegian", "Norsk", "no", "nor" },
519         { "Chichewa; Nyanja", "", "ny", "nya" },
520         { "Occitan", "", "oc", "oci" },
521         { "Ojibwa", "", "oj", "oji" },
522         { "Oriya", "", "or", "ori" },
523         { "Oromo", "", "om", "orm" },
524         { "Ossetian", "", "os", "oss" },
525         { "Panjabi", "", "pa", "pan" },
526         { "Persian", "", "fa", "fas", "per" },
527         { "Pali", "", "pi", "pli" },
528         { "Polish", "", "pl", "pol" },
529         { "Portuguese", "Portugues", "pt", "por" },
530         { "Pushto", "", "ps", "pus" },
531         { "Quechua", "", "qu", "que" },
532         { "Romansh", "", "rm", "roh" },
533         { "Romanian", "", "ro", "ron", "rum" },
534         { "Rundi", "", "rn", "run" },
535         { "Russian", "", "ru", "rus" },
536         { "Sango", "", "sg", "sag" },
537         { "Sanskrit", "", "sa", "san" },
538         { "Serbian", "", "sr", "srp", "scc" },
539         { "Croatian", "Hrvatski", "hr", "hrv", "scr" },
540         { "Sinhala", "", "si", "sin" },
541         { "Slovak", "", "sk", "slk", "slo" },
542         { "Slovenian", "", "sl", "slv" },
543         { "Northern Sami", "", "se", "sme" },
544         { "Samoan", "", "sm", "smo" },
545         { "Shona", "", "sn", "sna" },
546         { "Sindhi", "", "sd", "snd" },
547         { "Somali", "", "so", "som" },
548         { "Sotho, Southern", "", "st", "sot" },
549         { "Spanish", "Espanol", "es", "spa" },
550         { "Sardinian", "", "sc", "srd" },
551         { "Swati", "", "ss", "ssw" },
552         { "Sundanese", "", "su", "sun" },
553         { "Swahili", "", "sw", "swa" },
554         { "Swedish", "Svenska", "sv", "swe" },
555         { "Tahitian", "", "ty", "tah" },
556         { "Tamil", "", "ta", "tam" },
557         { "Tatar", "", "tt", "tat" },
558         { "Telugu", "", "te", "tel" },
559         { "Tajik", "", "tg", "tgk" },
560         { "Tagalog", "", "tl", "tgl" },
561         { "Thai", "", "th", "tha" },
562         { "Tibetan", "", "bo", "bod", "tib" },
563         { "Tigrinya", "", "ti", "tir" },
564         { "Tonga", "", "to", "ton" },
565         { "Tswana", "", "tn", "tsn" },
566         { "Tsonga", "", "ts", "tso" },
567         { "Turkmen", "", "tk", "tuk" },
568         { "Turkish", "", "tr", "tur" },
569         { "Twi", "", "tw", "twi" },
570         { "Uighur", "", "ug", "uig" },
571         { "Ukrainian", "", "uk", "ukr" },
572         { "Urdu", "", "ur", "urd" },
573         { "Uzbek", "", "uz", "uzb" },
574         { "Venda", "", "ve", "ven" },
575         { "Vietnamese", "", "vi", "vie" },
576         { "Volapük", "", "vo", "vol" },
577         { "Welsh", "", "cy", "cym", "wel" },
578         { "Walloon", "", "wa", "wln" },
579         { "Wolof", "", "wo", "wol" },
580         { "Xhosa", "", "xh", "xho" },
581         { "Yiddish", "", "yi", "yid" },
582         { "Yoruba", "", "yo", "yor" },
583         { "Zhuang", "", "za", "zha" },
584         { "Zulu", "", "zu", "zul" },
585         {NULL, NULL, NULL, NULL}
586 };
587 #define LANG_TABLE_SIZE (sizeof(ghb_language_table)/ sizeof(iso639_lang_t)-1)
588
589 static void audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name);
590
591 static void
592 del_tree(const gchar *name, gboolean del_top)
593 {
594         const gchar *file;
595
596         if (g_file_test(name, G_FILE_TEST_IS_DIR))
597         {
598                 GDir *gdir = g_dir_open(name, 0, NULL);
599                 file = g_dir_read_name(gdir);
600                 while (file)
601                 {
602                         gchar *path;
603                         path = g_strdup_printf("%s/%s", name, file);
604                         del_tree(path, TRUE);
605                         g_free(path);
606                         file = g_dir_read_name(gdir);
607                 }
608                 if (del_top)
609                         g_rmdir(name);
610                 g_dir_close(gdir);
611         }
612         else
613         {
614                 g_unlink(name);
615         }
616 }
617
618 const gchar*
619 ghb_version()
620 {
621         return hb_get_version(NULL);
622 }
623
624 void
625 ghb_vquality_range(
626         signal_user_data_t *ud, 
627         gdouble *min, 
628         gdouble *max,
629         gdouble *step,
630         gdouble *page,
631         gint *digits,
632         gboolean *inverted)
633 {
634         gint vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
635         *page = 10;
636         *digits = 0;
637         switch (vcodec)
638         {
639                 case HB_VCODEC_X264:
640                 {
641                         *min = 0;
642                         *max = 51;
643                         *step = ghb_settings_combo_double(ud->settings, 
644                                                                                         "VideoQualityGranularity");
645                         if (*step == 0.2 || *step == 0.5)
646                                 *digits = 1;
647                         else if (*step == 0.25)
648                                 *digits = 2;
649                         *inverted = TRUE;
650                 } break;
651
652                 case HB_VCODEC_FFMPEG:
653                 {
654                         *min = 1;
655                         *max = 31;
656                         *step = 1;
657                         *inverted = TRUE;
658                 } break;
659
660                 case HB_VCODEC_THEORA:
661                 {
662                         *min = 0;
663                         *max = 63;
664                         *step = 1;
665                         *inverted = FALSE;
666                 } break;
667
668                 default:
669                 {
670                         *min = 0;
671                         *max = 100;
672                         *step = 1;
673                         *inverted = FALSE;
674                 } break;
675         }
676 }
677
678 static const gchar*
679 lookup_generic_string(combo_opts_t *opts, const GValue *gval)
680 {
681         gint ii;
682         gchar *str;
683         const gchar *result = "";
684
685         str = ghb_value_string(gval);
686         for (ii = 0; ii < opts->count; ii++)
687         {
688                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
689                 {
690                         result = opts->map[ii].svalue;
691                         break;
692                 }
693         }
694         g_free(str);
695         return result;
696 }
697
698 static gint
699 lookup_generic_int(combo_opts_t *opts, const GValue *gval)
700 {
701         gint ii;
702         gchar *str;
703         gint result = -1;
704
705         str = ghb_value_string(gval);
706         for (ii = 0; ii < opts->count; ii++)
707         {
708                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
709                 {
710                         result = opts->map[ii].ivalue;
711                         break;
712                 }
713         }
714         g_free(str);
715         return result;
716 }
717
718 static gdouble
719 lookup_generic_double(combo_opts_t *opts, const GValue *gval)
720 {
721         gint ii;
722         gchar *str;
723         gdouble result = -1;
724
725         str = ghb_value_string(gval);
726         for (ii = 0; ii < opts->count; ii++)
727         {
728                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
729                 {
730                         result = opts->map[ii].ivalue;
731                         break;
732                 }
733         }
734         g_free(str);
735         return result;
736 }
737
738 static const gchar*
739 lookup_generic_option(combo_opts_t *opts, const GValue *gval)
740 {
741         gint ii;
742         gchar *str;
743         const gchar *result = "";
744
745         str = ghb_value_string(gval);
746         for (ii = 0; ii < opts->count; ii++)
747         {
748                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
749                 {
750                         result = opts->map[ii].option;
751                         break;
752                 }
753         }
754         g_free(str);
755         return result;
756 }
757
758 static gint
759 lookup_mix_int(const GValue *mix)
760 {
761         gint ii;
762         gchar *str;
763         gint result = 0;
764
765
766         str = ghb_value_string(mix);
767         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
768         {
769                 if (strcmp(hb_audio_mixdowns[ii].short_name, str) == 0)
770                 {
771                         result = hb_audio_mixdowns[ii].amixdown;
772                         break;
773                 }
774         }
775         g_free(str);
776         return result;
777 }
778
779 static const gchar*
780 lookup_mix_option(const GValue *mix)
781 {
782         gint ii;
783         gchar *str;
784         gchar *result = "None";
785
786
787         str = ghb_value_string(mix);
788         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
789         {
790                 if (strcmp(hb_audio_mixdowns[ii].short_name, str) == 0)
791                 {
792                         result = hb_audio_mixdowns[ii].human_readable_name;
793                         break;
794                 }
795         }
796         g_free(str);
797         return result;
798 }
799
800 static gint
801 lookup_video_rate_int(const GValue *vrate)
802 {
803         gint ii;
804         gchar *str;
805         gint result = 0;
806
807         str = ghb_value_string(vrate);
808         for (ii = 0; ii < hb_video_rates_count; ii++)
809         {
810                 if (strcmp(hb_video_rates[ii].string, str) == 0)
811                 {
812                         result = hb_video_rates[ii].rate;
813                         break;
814                 }
815         }
816         g_free(str);
817         // Default to "same as source"
818         return result;
819 }
820
821 static const gchar*
822 lookup_video_rate_option(const GValue *vrate)
823 {
824         gint ii;
825         gchar *str;
826         const gchar *result = "Same as source";
827
828         str = ghb_value_string(vrate);
829         for (ii = 0; ii < hb_video_rates_count; ii++)
830         {
831                 if (strcmp(hb_video_rates[ii].string, str) == 0)
832                 {
833                         result = hb_video_rates[ii].string;
834                         break;
835                 }
836         }
837         g_free(str);
838         // Default to "same as source"
839         return result;
840 }
841
842 static gint
843 lookup_audio_rate_int(const GValue *rate)
844 {
845         gint ii;
846         gchar *str;
847         gint result = 0;
848
849         // Coincidentally, the string "source" will return 0
850         // which is our flag to use "same as source"
851         str = ghb_value_string(rate);
852         for (ii = 0; ii < hb_audio_rates_count; ii++)
853         {
854                 if (strcmp(hb_audio_rates[ii].string, str) == 0)
855                 {
856                         result = hb_audio_rates[ii].rate;
857                         break;
858                 }
859         }
860         g_free(str);
861         return result;
862 }
863
864 static const gchar*
865 lookup_audio_rate_option(const GValue *rate)
866 {
867         gint ii;
868         gchar *str;
869         const gchar *result = "Same as source";
870
871         // Coincidentally, the string "source" will return 0
872         // which is our flag to use "same as source"
873         str = ghb_value_string(rate);
874         for (ii = 0; ii < hb_audio_rates_count; ii++)
875         {
876                 if (strcmp(hb_audio_rates[ii].string, str) == 0)
877                 {
878                         result = hb_audio_rates[ii].string;
879                         break;
880                 }
881         }
882         g_free(str);
883         return result;
884 }
885
886 static gint
887 lookup_audio_bitrate_int(const GValue *rate)
888 {
889         gint ii;
890         gchar *str;
891         gint result = 0;
892
893         // Coincidentally, the string "source" will return 0
894         // which is our flag to use "same as source"
895         str = ghb_value_string(rate);
896         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
897         {
898                 if (strcmp(hb_audio_bitrates[ii].string, str) == 0)
899                 {
900                         result = hb_audio_bitrates[ii].rate;
901                         break;
902                 }
903         }
904         g_free(str);
905         return result;
906 }
907
908 static const gchar*
909 lookup_audio_bitrate_option(const GValue *rate)
910 {
911         gint ii;
912         gchar *str;
913         const gchar *result = "Same as source";
914
915         // Coincidentally, the string "source" will return 0
916         // which is our flag to use "same as source"
917         str = ghb_value_string(rate);
918         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
919         {
920                 if (strcmp(hb_audio_bitrates[ii].string, str) == 0)
921                 {
922                         result = hb_audio_bitrates[ii].string;
923                         break;
924                 }
925         }
926         g_free(str);
927         return result;
928 }
929
930 static gint
931 lookup_audio_lang_int(const GValue *rate)
932 {
933         gint ii;
934         gchar *str;
935         gint result = 0;
936
937         // Coincidentally, the string "source" will return 0
938         // which is our flag to use "same as source"
939         str = ghb_value_string(rate);
940         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
941         {
942                 if (strcmp(ghb_language_table[ii].iso639_2, str) == 0)
943                 {
944                         result = ii;
945                         break;
946                 }
947         }
948         g_free(str);
949         return result;
950 }
951
952 static const gchar*
953 lookup_audio_lang_option(const GValue *rate)
954 {
955         gint ii;
956         gchar *str;
957         const gchar *result = "Same as source";
958
959         // Coincidentally, the string "source" will return 0
960         // which is our flag to use "same as source"
961         str = ghb_value_string(rate);
962         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
963         {
964                 if (strcmp(ghb_language_table[ii].iso639_2, str) == 0)
965                 {
966                         result = ghb_language_table[ii].eng_name;
967                         break;
968                 }
969         }
970         g_free(str);
971         return result;
972 }
973
974 static GValue*
975 get_acodec_value(gint val)
976 {
977         GValue *value = NULL;
978         gint ii;
979
980         for (ii = 0; ii < acodec_opts.count; ii++)
981         {
982                 if ((int)acodec_opts.map[ii].ivalue == val)
983                 {
984                         value = ghb_string_value_new(acodec_opts.map[ii].shortOpt);
985                         break;
986                 }
987         }
988         return value;
989 }
990
991 static GValue*
992 get_amix_value(gint val)
993 {
994         GValue *value = NULL;
995         gint ii;
996
997         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
998         {
999                 if (hb_audio_mixdowns[ii].amixdown == val)
1000                 {
1001                         value = ghb_string_value_new(hb_audio_mixdowns[ii].short_name);
1002                         break;
1003                 }
1004         }
1005         return value;
1006 }
1007
1008 // Handle for libhb.  Gets set by ghb_backend_init()
1009 static hb_handle_t * h_scan = NULL;
1010 static hb_handle_t * h_queue = NULL;
1011
1012 extern void hb_get_tempory_directory(hb_handle_t *h, char path[512]);
1013
1014 gchar*
1015 ghb_get_tmp_dir()
1016 {
1017         char dir[512];
1018
1019         hb_get_tempory_directory(h_scan, dir);
1020         return g_strdup(dir);
1021 }
1022
1023 void
1024 ghb_hb_cleanup(gboolean partial)
1025 {
1026         char dir[512];
1027
1028         hb_get_tempory_directory(h_scan, dir);
1029         del_tree(dir, !partial);
1030 }
1031
1032 gint
1033 ghb_subtitle_track_source(signal_user_data_t *ud, gint track)
1034 {
1035         gint titleindex;
1036
1037         if (track == -2)
1038                 return CC608SUB;
1039         if (track < 0)
1040                 return VOBSUB;
1041         titleindex = ghb_settings_combo_int(ud->settings, "title");
1042         if (titleindex < 0)
1043                 return VOBSUB;
1044
1045         hb_list_t  * list;
1046         hb_title_t * title;
1047         hb_subtitle_t * sub;
1048         
1049         if (h_scan == NULL) return VOBSUB;
1050         list = hb_get_titles( h_scan );
1051         if( !hb_list_count( list ) )
1052         {
1053                 /* No valid title, stop right there */
1054                 return VOBSUB;
1055         }
1056         title = hb_list_item( list, titleindex );
1057         if (title == NULL) return VOBSUB;       // Bad titleindex
1058         sub = hb_list_item( title->list_subtitle, track);
1059         if (sub != NULL)
1060                 return sub->source;
1061         else
1062                 return VOBSUB;
1063 }
1064
1065 const char*
1066 ghb_subtitle_track_source_name(signal_user_data_t *ud, gint track)
1067 {
1068         gint titleindex;
1069         const gchar * name = "Unknown";
1070
1071         if (track == -2)
1072         {
1073                 name = "Text";
1074                 goto done;
1075         }
1076         if (track == -1)
1077         {
1078                 name = "Bitmap";
1079                 goto done;
1080         }
1081
1082         titleindex = ghb_settings_combo_int(ud->settings, "title");
1083         if (titleindex < 0)
1084                 goto done;
1085
1086         hb_list_t  * list;
1087         hb_title_t * title;
1088         hb_subtitle_t * sub;
1089         
1090         if (h_scan == NULL) 
1091                 goto done;
1092         list = hb_get_titles( h_scan );
1093         if( !hb_list_count( list ) )
1094                 goto done;
1095
1096         title = hb_list_item( list, titleindex );
1097         if (title == NULL)
1098                 goto done;
1099
1100         sub = hb_list_item( title->list_subtitle, track);
1101         if (sub != NULL)
1102         {
1103                 switch (sub->source)
1104                 {
1105                         case VOBSUB:
1106                                 name = "Bitmap";
1107                                 break;
1108                         case CC708SUB:
1109                         case CC608SUB:
1110                         case SRTSUB:
1111                                 name = "Text";
1112                                 break;
1113                         default:
1114                                 break;
1115                 }
1116         }
1117
1118 done:
1119         return name;
1120 }
1121
1122
1123 gint
1124 ghb_get_title_number(gint titleindex)
1125 {
1126         hb_list_t  * list;
1127         hb_title_t * title;
1128         
1129         if (h_scan == NULL) return 1;
1130         list = hb_get_titles( h_scan );
1131         if( !hb_list_count( list ) )
1132         {
1133                 /* No valid title, stop right there */
1134                 return 1;
1135         }
1136         title = hb_list_item( list, titleindex );
1137         if (title == NULL) return 1;    // Bad titleindex
1138         return title->index;
1139 }
1140
1141 static hb_audio_config_t*
1142 get_hb_audio(gint titleindex, gint track)
1143 {
1144         hb_list_t  * list;
1145         hb_title_t * title;
1146     hb_audio_config_t *audio = NULL;
1147         
1148     if (h_scan == NULL) return NULL;
1149         list = hb_get_titles( h_scan );
1150         if( !hb_list_count( list ) )
1151         {
1152                 /* No valid title, stop right there */
1153                 return NULL;
1154         }
1155     title = hb_list_item( list, titleindex );
1156         if (title == NULL) return NULL; // Bad titleindex
1157         if (!hb_list_count(title->list_audio))
1158         {
1159                 return NULL;
1160         }
1161     audio = (hb_audio_config_t *)hb_list_audio_config_item(title->list_audio, track);
1162         return audio;
1163 }
1164
1165 static gint
1166 search_rates(hb_rate_t *rates, gint rate, gint count)
1167 {
1168         gint ii;
1169         for (ii = 0; ii < count; ii++)
1170         {
1171                 if (rates[ii].rate == rate)
1172                         return ii;
1173         }
1174         return -1;
1175 }
1176
1177 static gboolean find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter);
1178
1179 static GtkListStore*
1180 get_combo_box_store(GtkBuilder *builder, const gchar *name)
1181 {
1182         GtkComboBox *combo;
1183         GtkListStore *store;
1184
1185         g_debug("get_combo_box_store() %s\n", name);
1186         // First modify the combobox model to allow greying out of options
1187         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1188         store = GTK_LIST_STORE(gtk_combo_box_get_model (combo));
1189         return store;
1190 }
1191
1192 static void
1193 grey_combo_box_item(GtkBuilder *builder, const gchar *name, gint value, gboolean grey)
1194 {
1195         GtkListStore *store;
1196         GtkTreeIter iter;
1197         
1198         store = get_combo_box_store(builder, name);
1199         if (find_combo_item_by_int(GTK_TREE_MODEL(store), value, &iter))
1200         {
1201                 gtk_list_store_set(store, &iter, 
1202                                                    1, !grey, 
1203                                                    -1);
1204         }
1205 }
1206
1207 void
1208 ghb_grey_combo_options(GtkBuilder *builder)
1209 {
1210         GtkWidget *widget;
1211         gint container, track, titleindex, acodec;
1212     hb_audio_config_t *audio = NULL;
1213         GValue *gval;
1214         
1215         widget = GHB_WIDGET (builder, "title");
1216         gval = ghb_widget_value(widget);
1217         titleindex = ghb_lookup_combo_int("title", gval);
1218         ghb_value_free(gval);
1219         widget = GHB_WIDGET (builder, "AudioTrack");
1220         gval = ghb_widget_value(widget);
1221         track = ghb_lookup_combo_int("AudioTrack", gval);
1222         ghb_value_free(gval);
1223         audio = get_hb_audio(titleindex, track);
1224         widget = GHB_WIDGET (builder, "FileFormat");
1225         gval = ghb_widget_value(widget);
1226         container = ghb_lookup_combo_int("FileFormat", gval);
1227         ghb_value_free(gval);
1228
1229         grey_combo_box_item(builder, "x264_analyse", 3, TRUE);
1230         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, FALSE);
1231         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_LAME, FALSE);
1232         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, FALSE);
1233
1234         gboolean allow_dca = TRUE;
1235         allow_dca = (container != HB_MUX_MP4);
1236
1237         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, FALSE);
1238         if (allow_dca)
1239                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, FALSE);
1240         else
1241                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, TRUE);
1242
1243         if (audio && audio->in.codec != HB_ACODEC_AC3)
1244         {
1245                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, TRUE);
1246         }
1247         if (audio && audio->in.codec != HB_ACODEC_DCA)
1248         {
1249                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, TRUE);
1250         }
1251         grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, FALSE);
1252
1253         widget = GHB_WIDGET (builder, "AudioEncoder");
1254         gval = ghb_widget_value(widget);
1255         acodec = ghb_lookup_combo_int("AudioEncoder", gval);
1256         ghb_value_free(gval);
1257         if (acodec != HB_ACODEC_AC3)
1258         {
1259                 grey_combo_box_item(builder, "AudioMixdown", 0, TRUE);
1260         }
1261         if (container == HB_MUX_MP4)
1262         {
1263                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_LAME, TRUE);
1264                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
1265                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
1266         }
1267         else if (container == HB_MUX_AVI)
1268         {
1269                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1270                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
1271                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
1272         }
1273         else if (container == HB_MUX_OGM)
1274         {
1275                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1276         }
1277
1278         gboolean allow_mono = TRUE;
1279         gboolean allow_stereo = TRUE;
1280         gboolean allow_dolby = TRUE;
1281         gboolean allow_dpl2 = TRUE;
1282         gboolean allow_6ch = TRUE;
1283         if (audio)
1284         {
1285                 allow_mono =
1286                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1287                         (acodec != HB_ACODEC_LAME);
1288                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1289                 allow_stereo =
1290                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1291                 allow_dolby =
1292                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1293                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1294                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1295                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1296                 allow_6ch =
1297                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1298                         (acodec != HB_ACODEC_LAME) &&
1299                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1300                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1301         }
1302         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_MONO, !allow_mono);
1303         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_STEREO, !allow_stereo);
1304         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBY, !allow_dolby);
1305         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBYPLII, !allow_dpl2);
1306         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_6CH, !allow_6ch);
1307 }
1308
1309 gint
1310 ghb_get_best_mix(gint titleindex, gint track, gint acodec, gint mix)
1311 {
1312     hb_audio_config_t *audio = NULL;
1313         gboolean allow_mono = TRUE;
1314         gboolean allow_stereo = TRUE;
1315         gboolean allow_dolby = TRUE;
1316         gboolean allow_dpl2 = TRUE;
1317         gboolean allow_6ch = TRUE;
1318         
1319         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1320         {
1321                 // Audio codec pass-thru.  No mixdown
1322                 return 0;
1323         }
1324         audio = get_hb_audio(titleindex, track);
1325         if (audio)
1326         {
1327                 allow_mono =
1328                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1329                         (acodec != HB_ACODEC_LAME);
1330                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1331                 allow_stereo =
1332                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1333                 allow_dolby =
1334                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1335                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1336                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1337                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1338                 allow_6ch =
1339                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1340                         (acodec != HB_ACODEC_LAME) &&
1341                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1342                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1343         }
1344         gboolean greater = FALSE;
1345         if (mix == 0) 
1346         {
1347                 // If no mix is specified, select the best available.
1348                 mix = HB_AMIXDOWN_6CH;
1349         }
1350         if (mix == HB_AMIXDOWN_6CH)
1351         {
1352                 greater = TRUE;
1353                 if (allow_6ch) return HB_AMIXDOWN_6CH;
1354         }
1355         if (mix == HB_AMIXDOWN_DOLBYPLII || greater)
1356         {
1357                 greater = TRUE;
1358                 if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1359         }
1360         if (mix == HB_AMIXDOWN_DOLBY || greater)
1361         {
1362                 greater = TRUE;
1363                 if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1364         }
1365         if (mix == HB_AMIXDOWN_STEREO || greater)
1366         {
1367                 greater = TRUE;
1368                 if (allow_stereo) return HB_AMIXDOWN_STEREO;
1369         }
1370         if (mix == HB_AMIXDOWN_MONO || greater)
1371         {
1372                 greater = TRUE;
1373                 if (allow_mono) return HB_AMIXDOWN_MONO;
1374         }
1375         if (allow_stereo) return HB_AMIXDOWN_STEREO;
1376         if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1377         if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1378         if (allow_6ch) return HB_AMIXDOWN_6CH;
1379         return 0;
1380 }
1381
1382 // Set up the model for the combo box
1383 static void
1384 init_combo_box(GtkBuilder *builder, const gchar *name)
1385 {
1386         GtkComboBox *combo;
1387         GtkListStore *store;
1388         GtkCellRenderer *cell;
1389
1390         g_debug("init_combo_box() %s\n", name);
1391         // First modify the combobox model to allow greying out of options
1392         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1393         if (combo == NULL)
1394                 return;
1395         // Store contains:
1396         // 1 - String to display
1397         // 2 - bool indicating whether the entry is selectable (grey or not)
1398         // 3 - String that is used for presets
1399         // 4 - Int value determined by backend
1400         // 5 - String value determined by backend
1401         store = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_BOOLEAN, 
1402                                                            G_TYPE_STRING, G_TYPE_DOUBLE, G_TYPE_STRING);
1403         gtk_combo_box_set_model(combo, GTK_TREE_MODEL(store));
1404
1405         if (GTK_WIDGET_TYPE(combo) == GTK_TYPE_COMBO_BOX)
1406         {
1407                 gtk_cell_layout_clear(GTK_CELL_LAYOUT(combo));
1408         cell = GTK_CELL_RENDERER(gtk_cell_renderer_text_new());
1409         gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE);
1410         gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell,
1411                 "text", 0, "sensitive", 1, NULL);
1412         }
1413         else
1414         { // Combo box entry
1415                 gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(combo), 0);
1416         }
1417 }       
1418
1419 static void
1420 audio_samplerate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1421 {
1422         GtkTreeIter iter;
1423         GtkListStore *store;
1424         gint ii;
1425         
1426         g_debug("audio_samplerate_opts_set ()\n");
1427         store = get_combo_box_store(builder, name);
1428         gtk_list_store_clear(store);
1429         // Add an item for "Same As Source"
1430         gtk_list_store_append(store, &iter);
1431         gtk_list_store_set(store, &iter, 
1432                                            0, "Same as source", 
1433                                            1, TRUE, 
1434                                            2, "source", 
1435                                            3, 0.0, 
1436                                            4, "source", 
1437                                            -1);
1438         for (ii = 0; ii < count; ii++)
1439         {
1440                 gtk_list_store_append(store, &iter);
1441                 gtk_list_store_set(store, &iter, 
1442                                                    0, rates[ii].string, 
1443                                                    1, TRUE, 
1444                                                    2, rates[ii].string, 
1445                                                    3, (gdouble)rates[ii].rate, 
1446                                                    4, rates[ii].string, 
1447                                                    -1);
1448         }
1449 }
1450
1451 static void
1452 video_rate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1453 {
1454         GtkTreeIter iter;
1455         GtkListStore *store;
1456         gint ii;
1457         
1458         g_debug("video_rate_opts_set ()\n");
1459         store = get_combo_box_store(builder, name);
1460         gtk_list_store_clear(store);
1461         // Add an item for "Same As Source"
1462         gtk_list_store_append(store, &iter);
1463         gtk_list_store_set(store, &iter, 
1464                                            0, "Same as source", 
1465                                            1, TRUE, 
1466                                            2, "source", 
1467                                            3, 0.0, 
1468                                            4, "source", 
1469                                            -1);
1470         for (ii = 0; ii < count; ii++)
1471         {
1472                 gchar *desc = "";
1473                 gchar *option;
1474                 if (strcmp(rates[ii].string, "23.976") == 0)
1475                 {
1476                         desc = "(NTSC Film)";
1477                 }
1478                 else if (strcmp(rates[ii].string, "25") == 0)
1479                 {
1480                         desc = "(PAL Film/Video)";
1481                 }
1482                 else if (strcmp(rates[ii].string, "29.97") == 0)
1483                 {
1484                         desc = "(NTSC Video)";
1485                 }
1486                 option = g_strdup_printf ("%s %s", rates[ii].string, desc);
1487                 gtk_list_store_append(store, &iter);
1488                 gtk_list_store_set(store, &iter, 
1489                                                    0, option, 
1490                                                    1, TRUE, 
1491                                                    2, rates[ii].string, 
1492                                                    3, (gdouble)rates[ii].rate, 
1493                                                    4, rates[ii].string, 
1494                                                    -1);
1495                 g_free(option);
1496         }
1497 }
1498
1499 static void
1500 mix_opts_set(GtkBuilder *builder, const gchar *name)
1501 {
1502         GtkTreeIter iter;
1503         GtkListStore *store;
1504         gint ii;
1505         
1506         g_debug("mix_opts_set ()\n");
1507         store = get_combo_box_store(builder, name);
1508         gtk_list_store_clear(store);
1509         gtk_list_store_append(store, &iter);
1510         gtk_list_store_set(store, &iter, 
1511                                            0, "None", 
1512                                            1, TRUE, 
1513                                            2, "none", 
1514                                            3, 0.0, 
1515                                            4, "none", 
1516                                            -1);
1517         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1518         {
1519                 gtk_list_store_append(store, &iter);
1520                 gtk_list_store_set(store, &iter, 
1521                                                    0, hb_audio_mixdowns[ii].human_readable_name, 
1522                                                    1, TRUE, 
1523                                                    2, hb_audio_mixdowns[ii].short_name, 
1524                                                    3, (gdouble)hb_audio_mixdowns[ii].amixdown, 
1525                                                    4, hb_audio_mixdowns[ii].internal_name, 
1526                                                    -1);
1527         }
1528 }
1529
1530 static void
1531 language_opts_set(GtkBuilder *builder, const gchar *name)
1532 {
1533         GtkTreeIter iter;
1534         GtkListStore *store;
1535         gint ii;
1536         
1537         g_debug("language_opts_set ()\n");
1538         store = get_combo_box_store(builder, name);
1539         gtk_list_store_clear(store);
1540         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1541         {
1542                 gtk_list_store_append(store, &iter);
1543                 gtk_list_store_set(store, &iter, 
1544                                                    0, ghb_language_table[ii].eng_name, 
1545                                                    1, TRUE, 
1546                                                    2, ghb_language_table[ii].iso639_2, 
1547                                                    3, (gdouble)ii, 
1548                                                    4, ghb_language_table[ii].iso639_1, 
1549                                                    -1);
1550         }
1551 }
1552
1553 static gchar **titles = NULL;
1554
1555 void
1556 title_opts_set(GtkBuilder *builder, const gchar *name)
1557 {
1558         GtkTreeIter iter;
1559         GtkListStore *store;
1560         hb_list_t  * list = NULL;
1561         hb_title_t * title = NULL;
1562         gint ii;
1563         gint count = 0;
1564         
1565         g_debug("title_opts_set ()\n");
1566         store = get_combo_box_store(builder, name);
1567         gtk_list_store_clear(store);
1568         if (h_scan != NULL)
1569         {
1570                 list = hb_get_titles( h_scan );
1571                 count = hb_list_count( list );
1572                 if (count > 100) count = 100;
1573         }
1574         if (titles) g_strfreev(titles);
1575         if (title_opts.map) g_free(title_opts.map);
1576         if (count > 0)
1577         {
1578                 title_opts.count = count;
1579                 title_opts.map = g_malloc(count*sizeof(options_map_t));
1580                 titles = g_malloc((count+1) * sizeof(gchar*));
1581         }
1582         else
1583         {
1584                 title_opts.count = 1;
1585                 title_opts.map = g_malloc(sizeof(options_map_t));
1586                 titles = NULL;
1587         }
1588         if( count <= 0 )
1589         {
1590                 // No titles.  Fill in a default.
1591                 gtk_list_store_append(store, &iter);
1592                 gtk_list_store_set(store, &iter, 
1593                                                    0, "No Titles", 
1594                                                    1, TRUE, 
1595                                                    2, "none", 
1596                                                    3, -1.0, 
1597                                                    4, "none", 
1598                                                    -1);
1599                 title_opts.map[0].option = "No Titles";
1600                 title_opts.map[0].shortOpt = "none";
1601                 title_opts.map[0].ivalue = -1;
1602                 title_opts.map[0].svalue = "none";
1603                 return;
1604         }
1605         for (ii = 0; ii < count; ii++)
1606         {
1607                 title = (hb_title_t*)hb_list_item(list, ii);
1608                 if (title->duration != 0)
1609                 {
1610                         titles[ii]  = g_strdup_printf ("%d - %02dh%02dm%02ds",
1611                                 title->index, title->hours, title->minutes, title->seconds);
1612                 }
1613                 else
1614                 {
1615                         titles[ii]  = g_strdup_printf ("%d - Unknown Length", title->index);
1616                 }
1617                 gtk_list_store_append(store, &iter);
1618                 gtk_list_store_set(store, &iter, 
1619                                                    0, titles[ii], 
1620                                                    1, TRUE, 
1621                                                    2, titles[ii], 
1622                                                    3, (gdouble)ii, 
1623                                                    4, titles[ii], 
1624                                                    -1);
1625                 title_opts.map[ii].option = titles[ii];
1626                 title_opts.map[ii].shortOpt = titles[ii];
1627                 title_opts.map[ii].ivalue = ii;
1628                 title_opts.map[ii].svalue = titles[ii];
1629         }
1630         titles[ii] = NULL;
1631 }
1632
1633 static gboolean
1634 find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter)
1635 {
1636         gdouble ivalue;
1637         gboolean foundit = FALSE;
1638         
1639         if (gtk_tree_model_get_iter_first (store, iter))
1640         {
1641                 do
1642                 {
1643                         gtk_tree_model_get(store, iter, 3, &ivalue, -1);
1644                         if (value == (int)ivalue)
1645                         {
1646                                 foundit = TRUE;
1647                                 break;
1648                         }
1649                 } while (gtk_tree_model_iter_next (store, iter));
1650         }
1651         return foundit;
1652 }
1653
1654 void
1655 audio_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1656 {
1657         GtkTreeIter iter;
1658         GtkListStore *store;
1659         hb_list_t  * list = NULL;
1660         hb_title_t * title = NULL;
1661     hb_audio_config_t * audio;
1662         gint ii;
1663         gint count = 0;
1664         
1665         g_debug("audio_track_opts_set ()\n");
1666         store = get_combo_box_store(builder, name);
1667         gtk_list_store_clear(store);
1668         if (h_scan != NULL)
1669         {
1670                 list = hb_get_titles( h_scan );
1671             title = (hb_title_t*)hb_list_item( list, titleindex );
1672                 if (title != NULL)
1673                 {
1674                         count = hb_list_count( title->list_audio );
1675                 }
1676         }
1677         if (count > 100) count = 100;
1678         if (audio_track_opts.map) g_free(audio_track_opts.map);
1679         if (count > 0)
1680         {
1681                 audio_track_opts.count = count;
1682                 audio_track_opts.map = g_malloc(count*sizeof(options_map_t));
1683         }
1684         else
1685         {
1686                 audio_track_opts.count = 1;
1687                 audio_track_opts.map = g_malloc(sizeof(options_map_t));
1688         }
1689         if( count <= 0 )
1690         {
1691                 // No audio. set some default
1692                 gtk_list_store_append(store, &iter);
1693                 gtk_list_store_set(store, &iter, 
1694                                                    0, "No Audio", 
1695                                                    1, TRUE, 
1696                                                    2, "none", 
1697                                                    3, -1.0, 
1698                                                    4, "none", 
1699                                                    -1);
1700                 audio_track_opts.map[0].option = "No Audio";
1701                 audio_track_opts.map[0].shortOpt = "none";
1702                 audio_track_opts.map[0].ivalue = -1;
1703                 audio_track_opts.map[0].svalue = "none";
1704                 return;
1705         }
1706         index_str_init(count-1);
1707         for (ii = 0; ii < count; ii++)
1708         {
1709         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, ii );
1710                 gtk_list_store_append(store, &iter);
1711                 gtk_list_store_set(store, &iter, 
1712                                                    0, audio->lang.description, 
1713                                                    1, TRUE, 
1714                                                    2, index_str[ii], 
1715                                                    3, (gdouble)ii, 
1716                                                    4, index_str[ii], 
1717                                                    -1);
1718                 audio_track_opts.map[ii].option = audio->lang.description,
1719                 audio_track_opts.map[ii].shortOpt = index_str[ii];
1720                 audio_track_opts.map[ii].ivalue = ii;
1721                 audio_track_opts.map[ii].svalue = index_str[ii];
1722         }
1723 }
1724
1725 void
1726 subtitle_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1727 {
1728         GtkTreeIter iter;
1729         GtkListStore *store;
1730         hb_list_t  * list = NULL;
1731         hb_title_t * title = NULL;
1732         hb_subtitle_t * subtitle;
1733         gint ii, count = 0;
1734         static char ** options = NULL;
1735         
1736         g_debug("subtitle_track_opts_set ()\n");
1737         store = get_combo_box_store(builder, name);
1738         gtk_list_store_clear(store);
1739         if (h_scan != NULL)
1740         {
1741                 list = hb_get_titles( h_scan );
1742             title = (hb_title_t*)hb_list_item( list, titleindex );
1743                 if (title != NULL)
1744                 {
1745                         count = hb_list_count( title->list_subtitle );
1746                 }
1747         }
1748         if (count > 100) count = 100;
1749         if (subtitle_opts.map) g_free(subtitle_opts.map);
1750         if (count > 0)
1751         {
1752                 subtitle_opts.count = count+1;
1753                 subtitle_opts.map = g_malloc((count+1)*sizeof(options_map_t));
1754         }
1755         else
1756         {
1757                 subtitle_opts.count = LANG_TABLE_SIZE+1;
1758                 subtitle_opts.map = g_malloc((LANG_TABLE_SIZE+1)*sizeof(options_map_t));
1759         }
1760         gtk_list_store_append(store, &iter);
1761         gtk_list_store_set(store, &iter, 
1762                                            0, "Foreign Audio Search", 
1763                                            1, TRUE, 
1764                                            2, "-1", 
1765                                            3, -1.0, 
1766                                            4, "auto", 
1767                                            -1);
1768         subtitle_opts.map[0].option = "Foreign Audio Search";
1769         subtitle_opts.map[0].shortOpt = "-1";
1770         subtitle_opts.map[0].ivalue = -1;
1771         subtitle_opts.map[0].svalue = "auto";
1772         if (count > 0)
1773         {
1774                 if (options != NULL)
1775                         g_strfreev(options);
1776                 options = g_malloc((count+1)*sizeof(gchar*));
1777                 index_str_init(count-1);
1778                 for (ii = 0; ii < count; ii++)
1779                 {
1780                 subtitle = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
1781                         // Skip subtitles that must be burned if there is already
1782                         // a burned subtitle in the list
1783                         options[ii] = g_strdup_printf("%d - %s", ii+1, subtitle->lang);
1784                         subtitle_opts.map[ii+1].option = options[ii];
1785                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
1786                         subtitle_opts.map[ii+1].ivalue = ii;
1787                         subtitle_opts.map[ii+1].svalue = subtitle->iso639_2;
1788                         gtk_list_store_append(store, &iter);
1789                         gtk_list_store_set(store, &iter, 
1790                                                 0, options[ii], 
1791                                                 1, TRUE, 
1792                                                 2, index_str[ii], 
1793                                                 3, (gdouble)ii, 
1794                                                 4, subtitle->iso639_2, 
1795                                                 -1);
1796                 }
1797                 options[count] = NULL;
1798         }
1799         else
1800         {
1801                 index_str_init(LANG_TABLE_SIZE-1);
1802                 for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1803                 {
1804                         subtitle_opts.map[ii+1].option = ghb_language_table[ii].eng_name;
1805                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
1806                         subtitle_opts.map[ii+1].ivalue = ii;
1807                         subtitle_opts.map[ii+1].svalue = ghb_language_table[ii].iso639_2;
1808                         gtk_list_store_append(store, &iter);
1809                         gtk_list_store_set(store, &iter, 
1810                                         0, ghb_language_table[ii].eng_name, 
1811                                         1, TRUE, 
1812                                         2, index_str[ii],
1813                                         3, (gdouble)ii, 
1814                                         4, ghb_language_table[ii].iso639_2, 
1815                                         -1);
1816                 }
1817         }
1818 }
1819
1820 gint
1821 ghb_longest_title()
1822 {
1823         hb_list_t  * list;
1824         hb_title_t * title;
1825         gint ii;
1826         gint count = 0;
1827         guint64 longest = 0;
1828         gint titleindex = 0;
1829         
1830         g_debug("ghb_longest_title ()\n");
1831         if (h_scan == NULL) return 0;
1832         list = hb_get_titles( h_scan );
1833         count = hb_list_count( list );
1834         if (count > 100) count = 100;
1835         for (ii = 0; ii < count; ii++)
1836         {
1837                 title = (hb_title_t*)hb_list_item(list, ii);
1838                 if (title->duration > longest)
1839                 {
1840                         titleindex = ii;
1841                         longest = title->duration;
1842                 }
1843         }
1844         return titleindex;
1845 }
1846
1847 gchar*
1848 ghb_get_source_audio_lang(gint titleindex, gint track)
1849 {
1850         hb_list_t  * list;
1851         hb_title_t * title;
1852     hb_audio_config_t * audio;
1853         gchar *lang = NULL;
1854         
1855         g_debug("ghb_lookup_1st_audio_lang ()\n");
1856         if (h_scan == NULL) 
1857                 return NULL;
1858         list = hb_get_titles( h_scan );
1859     title = (hb_title_t*)hb_list_item( list, titleindex );
1860         if (title == NULL)
1861                 return NULL;
1862         if (hb_list_count( title->list_audio ) <= track)
1863                 return NULL;
1864
1865         audio = hb_list_audio_config_item(title->list_audio, track);
1866         if (audio == NULL)
1867                 return NULL;
1868
1869         lang = g_strdup(audio->lang.iso639_2);
1870         return lang;
1871 }
1872
1873 gint
1874 ghb_find_audio_track(
1875         gint titleindex, 
1876         const gchar *lang, 
1877         gint acodec,
1878         GHashTable *track_indices)
1879 {
1880         hb_list_t  * list;
1881         hb_title_t * title;
1882     hb_audio_config_t * audio;
1883         gint ii;
1884         gint count = 0;
1885         gint track = -1;
1886         gint max_chan = 0;
1887         gboolean *used;
1888         
1889         g_debug("find_audio_track ()\n");
1890         if (h_scan == NULL) return -1;
1891         list = hb_get_titles( h_scan );
1892     title = (hb_title_t*)hb_list_item( list, titleindex );
1893         if (title != NULL)
1894         {
1895                 count = hb_list_count( title->list_audio );
1896         }
1897         if (count > 10) count = 10;
1898         used = g_hash_table_lookup(track_indices, &acodec);
1899         if (used == NULL)
1900         {
1901                 used = g_malloc0(count * sizeof(gboolean));
1902                 g_hash_table_insert(track_indices, &acodec, used);
1903         }
1904         // Try to find an item that matches the preferred language and
1905         // the passthru codec type
1906         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1907         {
1908                 for (ii = 0; ii < count; ii++)
1909                 {
1910                         gint channels;
1911
1912                         if (used[ii])
1913                                 continue;
1914
1915                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
1916                                                                                                         title->list_audio, ii );
1917                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
1918                                                                                                         audio->in.channel_layout);
1919                         // Find a track that is not visually impaired or dirctor's
1920                         // commentary, and has the highest channel count.
1921                         if ((audio->in.codec & acodec) &&
1922                                 (audio->lang.type < 2) &&
1923                                 ((strcmp(lang, audio->lang.iso639_2) == 0) ||
1924                                 (strcmp(lang, "und") == 0)))
1925                         {
1926                                 if (channels > max_chan)
1927                                 {
1928                                         track = ii;
1929                                         max_chan = channels;
1930                                 }
1931                         }
1932                 }
1933         }
1934         if (track > -1)
1935         {
1936                 used[track] = TRUE;
1937                 return track;
1938         }
1939         // Try to find an item that matches the preferred language
1940         for (ii = 0; ii < count; ii++)
1941         {
1942                 if (used[ii])
1943                         continue;
1944         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
1945                                                                                                         title->list_audio, ii );
1946                 // Find a track that is not visually impaired or dirctor's commentary
1947                 if ((audio->lang.type < 2) &&
1948                         ((strcmp(lang, audio->lang.iso639_2) == 0) ||
1949                         (strcmp(lang, "und") == 0)))
1950                 {
1951                         track = ii;
1952                         break;
1953                 }
1954         }
1955         if (track > -1)
1956         {
1957                 used[track] = TRUE;
1958                 return track;
1959         }
1960         // Try to fine an item that does not match the preferred language and
1961         // matches the passthru codec type
1962         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1963         {
1964                 for (ii = 0; ii < count; ii++)
1965                 {
1966                         gint channels;
1967
1968                         if (used[ii])
1969                                 continue;
1970
1971                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
1972                                                                                                         title->list_audio, ii );
1973                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
1974                                                                                                         audio->in.channel_layout);
1975                         // Find a track that is not visually impaired or dirctor's
1976                         // commentary, and has the highest channel count.
1977                         if ((audio->in.codec & acodec) &&
1978                                 (audio->lang.type < 2))
1979                         {
1980                                 if (channels > max_chan)
1981                                 {
1982                                         track = ii;
1983                                         max_chan = channels;
1984                                 }
1985                         }
1986                 }
1987         }
1988         if (track > -1)
1989         {
1990                 used[track] = TRUE;
1991                 return track;
1992         }
1993         // Try to fine an item that does not match the preferred language
1994         for (ii = 0; ii < count; ii++)
1995         {
1996                 if (used[ii])
1997                         continue;
1998         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
1999                                                                                                         title->list_audio, ii );
2000                 // Find a track that is not visually impaired or dirctor's commentary
2001                 if (audio->lang.type < 2)
2002                 {
2003                         track = ii;
2004                         break;
2005                 }
2006         }
2007         if (track > -1)
2008         {
2009                 used[track] = TRUE;
2010                 return track;
2011         }
2012         // Last ditch, anything goes
2013         for (ii = 0; ii < count; ii++)
2014         {
2015         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2016                                                                                                         title->list_audio, ii );
2017                 if (!used[ii])
2018                 {
2019                         track = ii;
2020                         break;
2021                 }
2022         }
2023         if (track > -1)
2024         {
2025                 used[track] = TRUE;
2026         }
2027         return track;
2028 }
2029
2030 gint
2031 ghb_find_pref_subtitle_track(const gchar *lang)
2032 {
2033         gint ii, count;
2034         count = subtitle_opts.count;
2035         for (ii = 0; ii < count; ii++)
2036         {
2037                 if (strcmp(lang, subtitle_opts.map[ii].svalue) == 0)
2038                 {
2039                         return subtitle_opts.map[ii].ivalue;
2040                 }
2041         }
2042         return -2;
2043 }
2044
2045 gint
2046 ghb_find_subtitle_track(
2047         gint titleindex, 
2048         const gchar *lang, 
2049         GHashTable *track_indices)
2050 {
2051         hb_list_t  * list;
2052         hb_title_t * title;
2053         hb_subtitle_t * subtitle;
2054         gint count, ii;
2055         gboolean *used;
2056         
2057         g_debug("find_subtitle_track ()\n");
2058         if (strcmp(lang, "auto") == 0)
2059                 return -1;
2060         if (h_scan == NULL) return -1;
2061         list = hb_get_titles( h_scan );
2062         title = (hb_title_t*)hb_list_item( list, titleindex );
2063         if (title != NULL)
2064         {
2065                 count = hb_list_count( title->list_subtitle );
2066                 used = g_hash_table_lookup(track_indices, lang);
2067                 if (used == NULL)
2068                 {
2069                         used = g_malloc0(count * sizeof(gboolean));
2070                         g_hash_table_insert(track_indices, g_strdup(lang), used);
2071                 }
2072                 // Try to find an item that matches the preferred language
2073                 for (ii = 0; ii < count; ii++)
2074                 {
2075                         if (used[ii])
2076                                 continue;
2077
2078                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2079                         if ((strcmp(lang, subtitle->iso639_2) == 0) ||
2080                                 (strcmp(lang, "und") == 0))
2081                         {
2082                                 used[ii] = TRUE;
2083                                 return ii;
2084                         }
2085                 }
2086         }
2087         return -2;
2088 }
2089
2090 static void
2091 generic_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
2092 {
2093         GtkTreeIter iter;
2094         GtkListStore *store;
2095         gint ii;
2096         
2097         g_debug("generic_opts_set ()\n");
2098         if (name == NULL || opts == NULL) return;
2099         store = get_combo_box_store(builder, name);
2100         gtk_list_store_clear(store);
2101         for (ii = 0; ii < opts->count; ii++)
2102         {
2103                 gtk_list_store_append(store, &iter);
2104                 gtk_list_store_set(store, &iter, 
2105                                                    0, opts->map[ii].option, 
2106                                                    1, TRUE, 
2107                                                    2, opts->map[ii].shortOpt, 
2108                                                    3, opts->map[ii].ivalue, 
2109                                                    4, opts->map[ii].svalue, 
2110                                                    -1);
2111         }
2112 }
2113
2114 combo_opts_t*
2115 find_combo_table(const gchar *name)
2116 {
2117         gint ii;
2118
2119         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2120         {
2121                 if (strcmp(name, combo_name_map[ii].name) == 0)
2122                 {
2123                         return combo_name_map[ii].opts;
2124                 }
2125         }
2126         return NULL;
2127 }
2128
2129 gint
2130 ghb_lookup_combo_int(const gchar *name, const GValue *gval)
2131 {
2132         if (gval == NULL)
2133                 return 0;
2134         if (strcmp(name, "AudioBitrate") == 0)
2135                 return lookup_audio_bitrate_int(gval);
2136         else if (strcmp(name, "AudioSamplerate") == 0)
2137                 return lookup_audio_rate_int(gval);
2138         else if (strcmp(name, "VideoFramerate") == 0)
2139                 return lookup_video_rate_int(gval);
2140         else if (strcmp(name, "AudioMixdown") == 0)
2141                 return lookup_mix_int(gval);
2142         else if (strcmp(name, "PreferredLanguage") == 0)
2143                 return lookup_audio_lang_int(gval);
2144         else
2145         {
2146                 return lookup_generic_int(find_combo_table(name), gval);
2147         }
2148         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2149         return 0;
2150 }
2151
2152 gdouble
2153 ghb_lookup_combo_double(const gchar *name, const GValue *gval)
2154 {
2155         if (gval == NULL)
2156                 return 0;
2157         if (strcmp(name, "AudioBitrate") == 0)
2158                 return lookup_audio_bitrate_int(gval);
2159         else if (strcmp(name, "AudioSamplerate") == 0)
2160                 return lookup_audio_rate_int(gval);
2161         else if (strcmp(name, "VideoFramerate") == 0)
2162                 return lookup_video_rate_int(gval);
2163         else if (strcmp(name, "AudioMixdown") == 0)
2164                 return lookup_mix_int(gval);
2165         else if (strcmp(name, "PreferredLanguage") == 0)
2166                 return lookup_audio_lang_int(gval);
2167         else
2168         {
2169                 return lookup_generic_double(find_combo_table(name), gval);
2170         }
2171         g_warning("ghb_lookup_combo_double() couldn't find %s", name);
2172         return 0;
2173 }
2174
2175 const gchar*
2176 ghb_lookup_combo_option(const gchar *name, const GValue *gval)
2177 {
2178         if (gval == NULL)
2179                 return NULL;
2180         if (strcmp(name, "AudioBitrate") == 0)
2181                 return lookup_audio_bitrate_option(gval);
2182         else if (strcmp(name, "AudioSamplerate") == 0)
2183                 return lookup_audio_rate_option(gval);
2184         else if (strcmp(name, "VideoFramerate") == 0)
2185                 return lookup_video_rate_option(gval);
2186         else if (strcmp(name, "AudioMixdown") == 0)
2187                 return lookup_mix_option(gval);
2188         else if (strcmp(name, "PreferredLanguage") == 0)
2189                 return lookup_audio_lang_option(gval);
2190         else
2191         {
2192                 return lookup_generic_option(find_combo_table(name), gval);
2193         }
2194         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2195         return NULL;
2196 }
2197
2198 const gchar*
2199 ghb_lookup_combo_string(const gchar *name, const GValue *gval)
2200 {
2201         if (gval == NULL)
2202                 return NULL;
2203         if (strcmp(name, "AudioBitrate") == 0)
2204                 return lookup_audio_bitrate_option(gval);
2205         else if (strcmp(name, "AudioSamplerate") == 0)
2206                 return lookup_audio_rate_option(gval);
2207         else if (strcmp(name, "VideoFramerate") == 0)
2208                 return lookup_video_rate_option(gval);
2209         else if (strcmp(name, "AudioMixdown") == 0)
2210                 return lookup_mix_option(gval);
2211         else if (strcmp(name, "PreferredLanguage") == 0)
2212                 return lookup_audio_lang_option(gval);
2213         else
2214         {
2215                 return lookup_generic_string(find_combo_table(name), gval);
2216         }
2217         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2218         return NULL;
2219 }
2220
2221 void
2222 ghb_update_ui_combo_box(
2223         signal_user_data_t *ud, 
2224         const gchar *name, 
2225         gint user_data, 
2226         gboolean all)
2227 {
2228         GtkComboBox *combo = NULL;
2229         gint signal_id;
2230         gint handler_id = 0;
2231
2232         if (name != NULL)
2233         {               
2234                 g_debug("ghb_update_ui_combo_box() %s\n", name);
2235                 // Clearing a combo box causes a rash of "changed" events, even when
2236                 // the active item is -1 (inactive).  To control things, I'm disabling
2237                 // the event till things are settled down.
2238                 combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, name));
2239                 signal_id = g_signal_lookup("changed", GTK_TYPE_COMBO_BOX);
2240                 if (signal_id > 0)
2241                 {
2242                         // Valid signal id found.  This should always succeed.
2243                         handler_id = g_signal_handler_find ((gpointer)combo, G_SIGNAL_MATCH_ID, 
2244                                                                                                 signal_id, 0, 0, 0, 0);
2245                         if (handler_id > 0)
2246                         {
2247                                 // This should also always succeed
2248                                 g_signal_handler_block ((gpointer)combo, handler_id);
2249                         }
2250                 }
2251         }       
2252         if (all)
2253         {
2254                 audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2255                 audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2256                 video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2257                 mix_opts_set(ud->builder, "AudioMixdown");
2258                 language_opts_set(ud->builder, "PreferredLanguage");
2259                 title_opts_set(ud->builder, "title");
2260                 audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2261                 subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2262                 generic_opts_set(ud->builder, "VideoQualityGranularity", &vqual_granularity_opts);
2263                 generic_opts_set(ud->builder, "WhenComplete", &when_complete_opts);
2264                 generic_opts_set(ud->builder, "PicturePAR", &par_opts);
2265                 generic_opts_set(ud->builder, "PictureModulus", &alignment_opts);
2266                 generic_opts_set(ud->builder, "LoggingLevel", &logging_opts);
2267                 generic_opts_set(ud->builder, "LogLongevity", &log_longevity_opts);
2268                 generic_opts_set(ud->builder, "check_updates", &appcast_update_opts);
2269                 generic_opts_set(ud->builder, "FileFormat", &container_opts);
2270                 generic_opts_set(ud->builder, "PictureDeinterlace", &deint_opts);
2271                 generic_opts_set(ud->builder, "PictureDetelecine", &detel_opts);
2272                 generic_opts_set(ud->builder, "PictureDecomb", &decomb_opts);
2273                 generic_opts_set(ud->builder, "PictureDenoise", &denoise_opts);
2274                 generic_opts_set(ud->builder, "VideoEncoder", &vcodec_opts);
2275                 generic_opts_set(ud->builder, "AudioEncoder", &acodec_opts);
2276                 generic_opts_set(ud->builder, "x264_direct", &direct_opts);
2277                 generic_opts_set(ud->builder, "x264_b_adapt", &badapt_opts);
2278                 generic_opts_set(ud->builder, "x264_me", &me_opts);
2279                 generic_opts_set(ud->builder, "x264_subme", &subme_opts);
2280                 generic_opts_set(ud->builder, "x264_analyse", &analyse_opts);
2281                 generic_opts_set(ud->builder, "x264_trellis", &trellis_opts);
2282         }
2283         else
2284         {
2285                 if (strcmp(name, "AudioBitrate") == 0)
2286                         audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2287                 else if (strcmp(name, "AudioSamplerate") == 0)
2288                         audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2289                 else if (strcmp(name, "VideoFramerate") == 0)
2290                         video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2291                 else if (strcmp(name, "AudioMixdown") == 0)
2292                         mix_opts_set(ud->builder, "AudioMixdown");
2293                 else if (strcmp(name, "PreferredLanguage") == 0)
2294                         language_opts_set(ud->builder, "PreferredLanguage");
2295                 else if (strcmp(name, "title") == 0)
2296                         title_opts_set(ud->builder, "title");
2297                 else if (strcmp(name, "SubtitleTrack") == 0)
2298                         subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2299                 else if (strcmp(name, "AudioTrack") == 0)
2300                         audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2301                 else
2302                         generic_opts_set(ud->builder, name, find_combo_table(name));
2303         }
2304         if (handler_id > 0)
2305         {
2306                 g_signal_handler_unblock ((gpointer)combo, handler_id);
2307         }
2308 }
2309         
2310 static void
2311 init_ui_combo_boxes(GtkBuilder *builder)
2312 {
2313         gint ii;
2314
2315         init_combo_box(builder, "AudioBitrate");
2316         init_combo_box(builder, "AudioSamplerate");
2317         init_combo_box(builder, "VideoFramerate");
2318         init_combo_box(builder, "AudioMixdown");
2319         init_combo_box(builder, "PreferredLanguage");
2320         init_combo_box(builder, "title");
2321         init_combo_box(builder, "AudioTrack");
2322         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2323         {
2324                 init_combo_box(builder, combo_name_map[ii].name);
2325         }
2326 }
2327         
2328 static const char * turbo_opts = 
2329         "ref=1:subme=1:me=dia:analyse=none:trellis=0:"
2330         "no-fast-pskip=0:8x8dct=0";
2331
2332 // Construct the x264 options string
2333 // The result is allocated, so someone must free it at some point.
2334 gchar*
2335 ghb_build_x264opts_string(GValue *settings)
2336 {
2337         gchar *result;
2338         gchar *opts = ghb_settings_get_string(settings, "x264Option");
2339         if (opts != NULL)
2340         {
2341                 result = opts;
2342         }
2343         else
2344         {
2345                 result = g_strdup("");
2346         }
2347         return result;
2348 }
2349
2350 void
2351 ghb_get_chapter_duration(gint ti, gint ii, gint *hh, gint *mm, gint *ss)
2352 {
2353         hb_list_t  * list;
2354         hb_title_t * title;
2355     hb_chapter_t * chapter;
2356         gint count;
2357         
2358         g_debug("ghb_get_chapter_duration (title = %d)\n", ti);
2359         *hh = *mm = *ss = 0;
2360         if (h_scan == NULL) return;
2361         list = hb_get_titles( h_scan );
2362     title = (hb_title_t*)hb_list_item( list, ti );
2363         if (title == NULL) return;
2364         count = hb_list_count( title->list_chapter );
2365         if (ii >= count) return;
2366         chapter = hb_list_item(title->list_chapter, ii);
2367         if (chapter == NULL) return;
2368         *hh = chapter->hours;
2369         *mm = chapter->minutes;
2370         *ss = chapter->seconds;
2371 }
2372
2373 GValue*
2374 ghb_get_chapters(gint titleindex)
2375 {
2376         hb_list_t  * list;
2377         hb_title_t * title;
2378     hb_chapter_t * chapter;
2379         gint count, ii;
2380         GValue *chapters = NULL;
2381         
2382         g_debug("ghb_get_chapters (title = %d)\n", titleindex);
2383         if (h_scan == NULL) return NULL;
2384         list = hb_get_titles( h_scan );
2385     title = (hb_title_t*)hb_list_item( list, titleindex );
2386         if (title == NULL) return NULL;
2387         count = hb_list_count( title->list_chapter );
2388         chapters = ghb_array_value_new(count);
2389         for (ii = 0; ii < count; ii++)
2390         {
2391                 chapter = hb_list_item(title->list_chapter, ii);
2392                 if (chapter == NULL) break;
2393                 if (chapter->title == NULL || chapter->title[0] == 0)
2394                 {
2395                         gchar *str;
2396                         str = g_strdup_printf ("Chapter %2d", ii+1);
2397                         ghb_array_append(chapters, ghb_string_value_new(str));
2398                         g_free(str);
2399                 }
2400                 else 
2401                 {
2402                         ghb_array_append(chapters, ghb_string_value_new(chapter->title));
2403                 }
2404         }
2405         return chapters;
2406 }
2407
2408 gboolean
2409 ghb_ac3_in_audio_list(const GValue *audio_list)
2410 {
2411         gint count, ii;
2412
2413         count = ghb_array_len(audio_list);
2414         for (ii = 0; ii < count; ii++)
2415         {
2416                 GValue *asettings;
2417                 gint acodec;
2418
2419                 asettings = ghb_array_get_nth(audio_list, ii);
2420                 acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
2421                 if (acodec & HB_ACODEC_AC3)
2422                         return TRUE;
2423         }
2424         return FALSE;
2425 }
2426
2427 static void
2428 audio_bitrate_opts_add(GtkBuilder *builder, const gchar *name, gint rate)
2429 {
2430         GtkTreeIter iter;
2431         GtkListStore *store;
2432         gchar *str;
2433         
2434         g_debug("audio_rate_opts_add ()\n");
2435         store = get_combo_box_store(builder, name);
2436         if (!find_combo_item_by_int(GTK_TREE_MODEL(store), rate, &iter))
2437         {
2438                 str = g_strdup_printf ("%d", rate);
2439                 gtk_list_store_append(store, &iter);
2440                 gtk_list_store_set(store, &iter, 
2441                                                    0, str, 
2442                                                    1, TRUE, 
2443                                                    2, str, 
2444                                                    3, (gdouble)rate, 
2445                                                    4, str, 
2446                                                    -1);
2447                 g_free(str);
2448         }
2449 }
2450
2451 static void
2452 audio_bitrate_opts_clean(GtkBuilder *builder, const gchar *name, gint last_rate)
2453 {
2454         GtkTreeIter iter;
2455         GtkListStore *store;
2456         gdouble ivalue;
2457         gboolean done = FALSE;
2458         gint ii = 0;
2459         guint last = (guint)last_rate;
2460         
2461         g_debug("audio_bitrate_opts_clean ()\n");
2462         store = get_combo_box_store(builder, name);
2463         if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL(store), &iter))
2464         {
2465                 do
2466                 {
2467                         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 3, &ivalue, -1);
2468                         if (search_rates(
2469                                 hb_audio_bitrates, ivalue, hb_audio_bitrates_count) < 0)
2470                         {
2471                                 done = !gtk_list_store_remove(store, &iter);
2472                         }
2473                         else if (ivalue > last)
2474                         {
2475                                 ii++;
2476                                 gtk_list_store_set(store, &iter, 1, FALSE, -1);
2477                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2478                         }
2479                         else
2480                         {
2481                                 ii++;
2482                                 gtk_list_store_set(store, &iter, 1, TRUE, -1);
2483                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2484                         }
2485                 } while (!done);
2486         }
2487 }
2488
2489 static void
2490 audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name)
2491 {
2492         GtkTreeIter iter;
2493         GtkListStore *store;
2494         gint ii;
2495         
2496         g_debug("audio_bitrate_opts_set ()\n");
2497         store = get_combo_box_store(builder, name);
2498         gtk_list_store_clear(store);
2499         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
2500         {
2501                 gtk_list_store_append(store, &iter);
2502                 gtk_list_store_set(store, &iter, 
2503                                                    0, hb_audio_bitrates[ii].string, 
2504                                                    1, TRUE, 
2505                                                    2, hb_audio_bitrates[ii].string, 
2506                                                    3, (gdouble)hb_audio_bitrates[ii].rate, 
2507                                                    4, hb_audio_bitrates[ii].string, 
2508                                                    -1);
2509         }
2510 }
2511
2512 void
2513 ghb_set_passthru_bitrate_opts(GtkBuilder *builder, gint bitrate)
2514 {
2515         audio_bitrate_opts_add(builder, "AudioBitrate", bitrate);
2516 }
2517
2518 void
2519 ghb_set_default_bitrate_opts(GtkBuilder *builder, gint last_rate)
2520 {
2521         audio_bitrate_opts_clean(builder, "AudioBitrate", last_rate);
2522 }
2523
2524 static ghb_status_t hb_status;
2525
2526 void
2527 ghb_combo_init(signal_user_data_t *ud)
2528 {
2529         // Set up the list model for the combos
2530         init_ui_combo_boxes(ud->builder);
2531         // Populate all the combos
2532         ghb_update_ui_combo_box(ud, NULL, 0, TRUE);
2533 }
2534
2535 void
2536 ghb_backend_init(gint debug)
2537 {
2538     /* Init libhb */
2539     h_scan = hb_init( debug, 0 );
2540     h_queue = hb_init( debug, 0 );
2541 }
2542
2543 void
2544 ghb_backend_close()
2545 {
2546         hb_close(&h_queue);
2547         hb_close(&h_scan);
2548 }
2549
2550 void
2551 ghb_backend_scan(const gchar *path, gint titleindex, gint preview_count)
2552 {
2553     hb_scan( h_scan, path, titleindex, preview_count, 1 );
2554         hb_status.scan.state |= GHB_STATE_SCANNING;
2555         // initialize count and cur to something that won't cause FPE
2556         // when computing progress
2557         hb_status.scan.title_count = 1;
2558         hb_status.scan.title_cur = 0;
2559 }
2560
2561 void
2562 ghb_backend_queue_scan(const gchar *path, gint titlenum)
2563 {
2564         g_debug("ghb_backend_queue_scan()");
2565         hb_scan( h_queue, path, titlenum, 10, 0 );
2566         hb_status.queue.state |= GHB_STATE_SCANNING;
2567 }
2568
2569 gint
2570 ghb_get_scan_state()
2571 {
2572         return hb_status.scan.state;
2573 }
2574
2575 gint
2576 ghb_get_queue_state()
2577 {
2578         return hb_status.queue.state;
2579 }
2580
2581 void
2582 ghb_clear_scan_state(gint state)
2583 {
2584         hb_status.scan.state &= ~state;
2585 }
2586
2587 void
2588 ghb_clear_queue_state(gint state)
2589 {
2590         hb_status.queue.state &= ~state;
2591 }
2592
2593 void
2594 ghb_set_scan_state(gint state)
2595 {
2596         hb_status.scan.state |= state;
2597 }
2598
2599 void
2600 ghb_set_queue_state(gint state)
2601 {
2602         hb_status.queue.state |= state;
2603 }
2604
2605 void
2606 ghb_get_status(ghb_status_t *status)
2607 {
2608         memcpy(status, &hb_status, sizeof(ghb_status_t));
2609 }
2610
2611 void 
2612 ghb_track_status()
2613 {
2614     hb_state_t s_scan;
2615     hb_state_t s_queue;
2616
2617         if (h_scan == NULL) return;
2618     hb_get_state( h_scan, &s_scan );
2619         switch( s_scan.state )
2620     {
2621 #define p s_scan.param.scanning
2622         case HB_STATE_SCANNING:
2623                 {
2624                         hb_status.scan.state |= GHB_STATE_SCANNING;
2625                         hb_status.scan.title_count = p.title_count;
2626                         hb_status.scan.title_cur = p.title_cur;
2627                 } break;
2628 #undef p
2629
2630         case HB_STATE_SCANDONE:
2631         {
2632                         hb_status.scan.state &= ~GHB_STATE_SCANNING;
2633                         hb_status.scan.state |= GHB_STATE_SCANDONE;
2634         } break;
2635
2636 #define p s_scan.param.working
2637         case HB_STATE_WORKING:
2638                         hb_status.scan.state |= GHB_STATE_WORKING;
2639                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
2640                         hb_status.scan.job_cur = p.job_cur;
2641                         hb_status.scan.job_count = p.job_count;
2642                         hb_status.scan.progress = p.progress;
2643                         hb_status.scan.rate_cur = p.rate_cur;
2644                         hb_status.scan.rate_avg = p.rate_avg;
2645                         hb_status.scan.hours = p.hours;
2646                         hb_status.scan.minutes = p.minutes;
2647                         hb_status.scan.seconds = p.seconds;
2648                         hb_status.scan.unique_id = p.sequence_id & 0xFFFFFF;
2649             break;
2650 #undef p
2651
2652         case HB_STATE_PAUSED:
2653                         hb_status.scan.state |= GHB_STATE_PAUSED;
2654             break;
2655                                 
2656         case HB_STATE_MUXING:
2657         {
2658                         hb_status.scan.state |= GHB_STATE_MUXING;
2659         } break;
2660
2661 #define p s_scan.param.workdone
2662         case HB_STATE_WORKDONE:
2663                 {
2664             hb_job_t *job;
2665
2666                         hb_status.scan.state |= GHB_STATE_WORKDONE;
2667                         hb_status.scan.state &= ~GHB_STATE_MUXING;
2668                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
2669                         hb_status.scan.state &= ~GHB_STATE_WORKING;
2670                         switch (p.error)
2671                         {
2672                         case HB_ERROR_NONE:
2673                                 hb_status.scan.error = GHB_ERROR_NONE;
2674                                 break;
2675                         case HB_ERROR_CANCELED:
2676                                 hb_status.scan.error = GHB_ERROR_CANCELED;
2677                                 break;
2678                         default:
2679                                 hb_status.scan.error = GHB_ERROR_FAIL;
2680                                 break;
2681                         }
2682                         // Delete all remaining jobs of this encode.
2683                         // An encode can be composed of multiple associated jobs.
2684                         // When a job is stopped, libhb removes it from the job list,
2685                         // but does not remove other jobs that may be associated with it.
2686                         // Associated jobs are taged in the sequence id.
2687             while ((job = hb_job(h_scan, 0)) != NULL) 
2688                 hb_rem( h_scan, job );
2689                 } break;
2690 #undef p
2691     }
2692     hb_get_state( h_queue, &s_queue );
2693         switch( s_queue.state )
2694     {
2695 #define p s_queue.param.scanning
2696         case HB_STATE_SCANNING:
2697                 {
2698                         hb_status.queue.state |= GHB_STATE_SCANNING;
2699                         hb_status.queue.title_count = p.title_count;
2700                         hb_status.queue.title_cur = p.title_cur;
2701                 } break;
2702 #undef p
2703
2704         case HB_STATE_SCANDONE:
2705         {
2706                         hb_status.queue.state &= ~GHB_STATE_SCANNING;
2707                         hb_status.queue.state |= GHB_STATE_SCANDONE;
2708         } break;
2709
2710 #define p s_queue.param.working
2711         case HB_STATE_WORKING:
2712                         hb_status.queue.state |= GHB_STATE_WORKING;
2713                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
2714                         hb_status.queue.job_cur = p.job_cur;
2715                         hb_status.queue.job_count = p.job_count;
2716                         hb_status.queue.progress = p.progress;
2717                         hb_status.queue.rate_cur = p.rate_cur;
2718                         hb_status.queue.rate_avg = p.rate_avg;
2719                         hb_status.queue.hours = p.hours;
2720                         hb_status.queue.minutes = p.minutes;
2721                         hb_status.queue.seconds = p.seconds;
2722                         hb_status.queue.unique_id = p.sequence_id & 0xFFFFFF;
2723             break;
2724 #undef p
2725
2726         case HB_STATE_PAUSED:
2727                         hb_status.queue.state |= GHB_STATE_PAUSED;
2728             break;
2729                                 
2730         case HB_STATE_MUXING:
2731         {
2732                         hb_status.queue.state |= GHB_STATE_MUXING;
2733         } break;
2734
2735 #define p s_queue.param.workdone
2736         case HB_STATE_WORKDONE:
2737                 {
2738             hb_job_t *job;
2739
2740                         hb_status.queue.state |= GHB_STATE_WORKDONE;
2741                         hb_status.queue.state &= ~GHB_STATE_MUXING;
2742                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
2743                         hb_status.queue.state &= ~GHB_STATE_WORKING;
2744                         switch (p.error)
2745                         {
2746                         case HB_ERROR_NONE:
2747                                 hb_status.queue.error = GHB_ERROR_NONE;
2748                                 break;
2749                         case HB_ERROR_CANCELED:
2750                                 hb_status.queue.error = GHB_ERROR_CANCELED;
2751                                 break;
2752                         default:
2753                                 hb_status.queue.error = GHB_ERROR_FAIL;
2754                                 break;
2755                         }
2756                         // Delete all remaining jobs of this encode.
2757                         // An encode can be composed of multiple associated jobs.
2758                         // When a job is stopped, libhb removes it from the job list,
2759                         // but does not remove other jobs that may be associated with it.
2760                         // Associated jobs are taged in the sequence id.
2761             while ((job = hb_job(h_queue, 0)) != NULL) 
2762                 hb_rem( h_queue, job );
2763                 } break;
2764 #undef p
2765     }
2766 }
2767
2768 gboolean
2769 ghb_get_title_info(ghb_title_info_t *tinfo, gint titleindex)
2770 {
2771         hb_list_t  * list;
2772         hb_title_t * title;
2773         
2774     if (h_scan == NULL) return FALSE;
2775         list = hb_get_titles( h_scan );
2776         if( !hb_list_count( list ) )
2777         {
2778                 /* No valid title, stop right there */
2779                 return FALSE;
2780         }
2781
2782     title = hb_list_item( list, titleindex );
2783         if (title == NULL) return FALSE;        // Bad titleindex
2784         tinfo->width = title->width;
2785         tinfo->height = title->height;
2786         memcpy(tinfo->crop, title->crop, 4 * sizeof(int));
2787         // Don't allow crop to 0
2788         if (title->crop[0] + title->crop[1] >= title->height)
2789                 title->crop[0] = title->crop[1] = 0;
2790         if (title->crop[2] + title->crop[3] >= title->width)
2791                 title->crop[2] = title->crop[3] = 0;
2792         tinfo->num_chapters = hb_list_count(title->list_chapter);
2793         tinfo->rate_base = title->rate_base;
2794         tinfo->rate = title->rate;
2795         hb_reduce(&(tinfo->aspect_n), &(tinfo->aspect_d), 
2796                                 title->width * title->pixel_aspect_width, 
2797                                 title->height * title->pixel_aspect_height);
2798         tinfo->hours = title->hours;
2799         tinfo->minutes = title->minutes;
2800         tinfo->seconds = title->seconds;
2801         tinfo->duration = title->duration;
2802
2803         tinfo->angle_count = title->angle_count;
2804         return TRUE;
2805 }
2806
2807 gboolean
2808 ghb_get_audio_info(ghb_audio_info_t *ainfo, gint titleindex, gint audioindex)
2809 {
2810     hb_audio_config_t *audio;
2811         
2812         audio = get_hb_audio(titleindex, audioindex);
2813         if (audio == NULL) return FALSE; // Bad audioindex
2814         ainfo->codec = audio->in.codec;
2815         ainfo->bitrate = audio->in.bitrate;
2816         ainfo->samplerate = audio->in.samplerate;
2817         return TRUE;
2818 }
2819
2820 gboolean
2821 ghb_audio_is_passthru(gint acodec)
2822 {
2823         g_debug("ghb_audio_is_passthru () \n");
2824         return (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA));
2825 }
2826
2827 gint
2828 ghb_get_default_acodec()
2829 {
2830         return HB_ACODEC_FAAC;
2831 }
2832
2833 static void
2834 picture_settings_deps(signal_user_data_t *ud)
2835 {
2836         gboolean autoscale, keep_aspect, enable_keep_aspect;
2837         gboolean enable_scale_width, enable_scale_height;
2838         gboolean enable_disp_width, enable_disp_height, enable_par;
2839         gint pic_par;
2840         GtkWidget *widget;
2841
2842         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
2843         if (pic_par == 1)
2844         {
2845                 ghb_ui_update(ud, "autoscale", ghb_boolean_value(TRUE));
2846                 ghb_ui_update(ud, "PictureModulus", ghb_int_value(2));
2847                 ghb_ui_update(ud, "PictureLooseCrop", ghb_boolean_value(TRUE));
2848         }
2849         enable_keep_aspect = (pic_par != 1 && pic_par != 2);
2850         if (!enable_keep_aspect)
2851         {
2852                 ghb_ui_update(ud, "PictureKeepRatio", ghb_boolean_value(TRUE));
2853         }
2854         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
2855         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
2856
2857         enable_scale_width = !autoscale && (pic_par != 1);
2858         enable_scale_height = !autoscale && (pic_par != 1);
2859         enable_disp_width = (pic_par == 3) && !keep_aspect;
2860         enable_par = (pic_par == 3) && !keep_aspect;
2861         enable_disp_height = FALSE;
2862
2863         widget = GHB_WIDGET(ud->builder, "PictureModulus");
2864         gtk_widget_set_sensitive(widget, pic_par != 1);
2865         widget = GHB_WIDGET(ud->builder, "PictureLooseCrop");
2866         gtk_widget_set_sensitive(widget, pic_par != 1);
2867         widget = GHB_WIDGET(ud->builder, "scale_width");
2868         gtk_widget_set_sensitive(widget, enable_scale_width);
2869         widget = GHB_WIDGET(ud->builder, "scale_height");
2870         gtk_widget_set_sensitive(widget, enable_scale_height);
2871         widget = GHB_WIDGET(ud->builder, "PictureDisplayWidth");
2872         gtk_widget_set_sensitive(widget, enable_disp_width);
2873         widget = GHB_WIDGET(ud->builder, "PictureDisplayHeight");
2874         gtk_widget_set_sensitive(widget, enable_disp_height);
2875         widget = GHB_WIDGET(ud->builder, "PicturePARWidth");
2876         gtk_widget_set_sensitive(widget, enable_par);
2877         widget = GHB_WIDGET(ud->builder, "PicturePARHeight");
2878         gtk_widget_set_sensitive(widget, enable_par);
2879         widget = GHB_WIDGET(ud->builder, "PictureKeepRatio");
2880         gtk_widget_set_sensitive(widget, enable_keep_aspect);
2881         widget = GHB_WIDGET(ud->builder, "autoscale");
2882         gtk_widget_set_sensitive(widget, pic_par != 1);
2883 }
2884
2885 void
2886 ghb_set_scale(signal_user_data_t *ud, gint mode)
2887 {
2888         hb_list_t  * list;
2889         hb_title_t * title;
2890         hb_job_t   * job;
2891         gboolean keep_aspect;
2892         gint pic_par;
2893         gboolean autocrop, autoscale, noscale;
2894         gint crop[4], width, height, par_width, par_height;
2895         gint crop_width, crop_height;
2896         gint aspect_n, aspect_d;
2897         gboolean keep_width = (mode & GHB_PIC_KEEP_WIDTH);
2898         gboolean keep_height = (mode & GHB_PIC_KEEP_HEIGHT);
2899         gint step;
2900         GtkWidget *widget;
2901         gint mod;
2902         gint max_width = 0;
2903         gint max_height = 0;
2904         static gboolean busy = FALSE;
2905         
2906         g_debug("ghb_set_scale ()\n");
2907         if (h_scan == NULL) return;
2908         list = hb_get_titles( h_scan );
2909         if( !hb_list_count( list ) )
2910         {
2911                 /* No valid title, stop right there */
2912                 return;
2913         }
2914         gint titleindex;
2915
2916         titleindex = ghb_settings_combo_int(ud->settings, "title");
2917     title = hb_list_item( list, titleindex );
2918         if (title == NULL) return;
2919         job   = title->job;
2920         if (job == NULL) return;
2921
2922         picture_settings_deps(ud);
2923         if (busy) return;
2924         busy = TRUE;
2925
2926         
2927         // First configure widgets
2928         mod = ghb_settings_combo_int(ud->settings, "PictureModulus");
2929         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
2930         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
2931         autocrop = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop");
2932         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
2933         // "Noscale" is a flag that says we prefer to crop extra to satisfy
2934         // alignment constraints rather than scaling to satisfy them.
2935         noscale = ghb_settings_get_boolean(ud->settings, "PictureLooseCrop");
2936         // Align dimensions to either 16 or 2 pixels
2937         // The scaler crashes if the dimensions are not divisible by 2
2938         // x264 also will not accept dims that are not multiple of 2
2939         if (autoscale)
2940         {
2941                 keep_width = FALSE;
2942                 keep_height = FALSE;
2943         }
2944         // Step needs to be at least 2 because odd widths cause scaler crash
2945         step = mod;
2946         widget = GHB_WIDGET (ud->builder, "scale_width");
2947         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2948         widget = GHB_WIDGET (ud->builder, "scale_height");
2949         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2950         if (noscale)
2951         {
2952                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
2953                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2954                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
2955                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2956                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
2957                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2958                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
2959                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
2960         }
2961         else
2962         {
2963                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
2964                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
2965                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
2966                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
2967                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
2968                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
2969                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
2970                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
2971         }
2972         ghb_title_info_t tinfo;
2973         ghb_get_title_info (&tinfo, titleindex);
2974         if (autocrop)
2975         {
2976                 crop[0] = tinfo.crop[0];
2977                 crop[1] = tinfo.crop[1];
2978                 crop[2] = tinfo.crop[2];
2979                 crop[3] = tinfo.crop[3];
2980                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
2981                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
2982                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
2983                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
2984         }
2985         else
2986         {
2987                 crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
2988                 crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
2989                 crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
2990                 crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
2991         }
2992         if (noscale)
2993         {
2994                 gint need1, need2;
2995
2996                 // Adjust the cropping to accomplish the desired width and height
2997                 crop_width = tinfo.width - crop[2] - crop[3];
2998                 crop_height = tinfo.height - crop[0] - crop[1];
2999                 width = MOD_DOWN(crop_width, mod);
3000                 height = MOD_DOWN(crop_height, mod);
3001
3002                 need1 = (crop_height - height) / 2;
3003                 need2 = crop_height - height - need1;
3004                 crop[0] += need1;
3005                 crop[1] += need2;
3006                 need1 = (crop_width - width) / 2;
3007                 need2 = crop_width - width - need1;
3008                 crop[2] += need1;
3009                 crop[3] += need2;
3010                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3011                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3012                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3013                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3014         }
3015         hb_reduce(&aspect_n, &aspect_d, 
3016                                 title->width * title->pixel_aspect_width, 
3017                                 title->height * title->pixel_aspect_height);
3018         crop_width = title->width - crop[2] - crop[3];
3019         crop_height = title->height - crop[0] - crop[1];
3020         if (autoscale)
3021         {
3022                 width = crop_width;
3023                 height = crop_height;
3024         }
3025         else
3026         {
3027                 width = ghb_settings_get_int(ud->settings, "scale_width");
3028                 height = ghb_settings_get_int(ud->settings, "scale_height");
3029                 max_width = MOD_DOWN(
3030                         ghb_settings_get_int(ud->settings, "PictureWidth"), mod);
3031                 max_height = MOD_DOWN(
3032                         ghb_settings_get_int(ud->settings, "PictureHeight"), mod);
3033         }
3034         g_debug("max_width %d, max_height %d\n", max_width, max_height);
3035
3036         if (width < 16)
3037                 width = title->width - crop[2] - crop[3];
3038         if (height < 16)
3039                 height = title->height - crop[0] - crop[1];
3040
3041         width = MOD_ROUND(width, mod);
3042         height = MOD_ROUND(height, mod);
3043
3044         // Adjust dims according to max values
3045         if (max_height)
3046                 height = MIN(height, max_height);
3047         if (max_width)
3048                 width = MIN(width, max_width);
3049
3050         if (pic_par)
3051         {
3052                 job->anamorphic.mode = pic_par;
3053                 // The scaler crashes if the dimensions are not divisible by 2
3054                 // Align mod 2.  And so does something in x264_encoder_headers()
3055                 job->anamorphic.modulus = mod;
3056                 job->anamorphic.par_width = title->pixel_aspect_width;
3057                 job->anamorphic.par_height = title->pixel_aspect_height;
3058                 job->anamorphic.dar_width = 0;
3059                 job->anamorphic.dar_height = 0;
3060
3061                 if (keep_height && pic_par == 2)
3062                         width = ((double)height * crop_width / crop_height) + 0.5;
3063                 job->width = width;
3064                 job->height = height;
3065                 if (max_width) 
3066                         job->maxWidth = max_width;
3067                 if (max_height) 
3068                         job->maxHeight = max_height;
3069                 job->crop[0] = crop[0]; job->crop[1] = crop[1];
3070                 job->crop[2] = crop[2]; job->crop[3] = crop[3];
3071                 if (job->anamorphic.mode == 3 && !keep_aspect)
3072                 {
3073                         job->anamorphic.keep_display_aspect = 0;
3074                         if (mode & GHB_PIC_KEEP_PAR)
3075                         {
3076                                 job->anamorphic.par_width = 
3077                                         ghb_settings_get_int(ud->settings, "PicturePARWidth");
3078                                 job->anamorphic.par_height = 
3079                                         ghb_settings_get_int(ud->settings, "PicturePARHeight");
3080                         }
3081                         else
3082                         {
3083                                 job->anamorphic.dar_width = 
3084                                         ghb_settings_get_int(ud->settings, 
3085                                                                                 "PictureDisplayWidth");
3086                                 job->anamorphic.dar_height =
3087                                         ghb_settings_get_int(ud->settings, 
3088                                                                                 "PictureDisplayHeight");
3089                         }
3090                 }
3091                 else
3092                 {
3093                         job->anamorphic.keep_display_aspect = 1;
3094                 }
3095                 hb_set_anamorphic_size( job, &width, &height, 
3096                                                                 &par_width, &par_height );
3097                 if (job->anamorphic.mode == 3 && !keep_aspect && 
3098                         mode & GHB_PIC_KEEP_PAR)
3099                 {
3100                         // hb_set_anamorphic_size reduces the par, which we
3101                         // don't want in this case because the user is
3102                         // explicitely specifying it.
3103                         par_width = ghb_settings_get_int(ud->settings, 
3104                                                                                         "PicturePARWidth");
3105                         par_height = ghb_settings_get_int(ud->settings, 
3106                                                                                                 "PicturePARHeight");
3107                 }
3108         }
3109         else 
3110         {
3111                 job->anamorphic.mode = pic_par;
3112                 if (keep_aspect)
3113                 {
3114                         gdouble par;
3115                         gint new_width, new_height;
3116                         
3117                         // Compute pixel aspect ration.  
3118                         par = (gdouble)(title->height * aspect_n) / (title->width * aspect_d);
3119                         // Must scale so that par becomes 1:1
3120                         // Try to keep largest dimension
3121                         new_height = (crop_height * ((gdouble)width/crop_width) / par);
3122                         new_width = (crop_width * ((gdouble)height/crop_height) * par);
3123
3124                         if (max_width && new_width > max_width)
3125                         {
3126                                 height = new_height;
3127                         }
3128                         else if (max_height && new_height > max_height)
3129                         {
3130                                 width = new_width;
3131                         }
3132                         else if (keep_width)
3133                         {
3134                                 height = new_height;
3135                         }
3136                         else if (keep_height)
3137                         {
3138                                 width = new_width;
3139                         }
3140                         else if (width > new_width)
3141                         {
3142                                 height = new_height;
3143                         }
3144                         else
3145                         {
3146                                 width = new_width;
3147                         }
3148                         g_debug("new w %d h %d\n", width, height);
3149                 }
3150                 width = MOD_ROUND(width, mod);
3151                 height = MOD_ROUND(height, mod);
3152                 if (max_height)
3153                         height = MIN(height, max_height);
3154                 if (max_width)
3155                         width = MIN(width, max_width);
3156                 par_width = par_height = 1;
3157         }
3158         ghb_ui_update(ud, "scale_width", ghb_int64_value(width));
3159         ghb_ui_update(ud, "scale_height", ghb_int64_value(height));
3160
3161         gint disp_width, dar_width, dar_height;
3162         gchar *str;
3163
3164         disp_width = (gdouble)(width * par_width / par_height) + 0.5;
3165         hb_reduce(&dar_width, &dar_height, disp_width, height);
3166                 
3167         gint iaspect = dar_width * 9 / dar_height;
3168         if (dar_width > 2 * dar_height)
3169         {
3170                 str = g_strdup_printf("%.2f : 1", (gdouble)dar_width / dar_height);
3171         }
3172         else if (iaspect <= 16 && iaspect >= 15)
3173         {
3174                 str = g_strdup_printf("%.2f : 9", (gdouble)dar_width * 9 / dar_height);
3175         }
3176         else if (iaspect <= 12 && iaspect >= 11)
3177         {
3178                 str = g_strdup_printf("%.2f : 3", (gdouble)dar_width * 3 / dar_height);
3179         }
3180         else
3181         {
3182                 str = g_strdup_printf("%d : %d", dar_width, dar_height);
3183         }
3184         ghb_ui_update(ud, "display_aspect", ghb_string_value(str));
3185         g_free(str);
3186         ghb_ui_update(ud, "PicturePARWidth", ghb_int64_value(par_width));
3187         ghb_ui_update(ud, "PicturePARHeight", ghb_int64_value(par_height));
3188         ghb_ui_update(ud, "PictureDisplayWidth", ghb_int64_value(disp_width));
3189         ghb_ui_update(ud, "PictureDisplayHeight", ghb_int64_value(height));
3190         busy = FALSE;
3191 }
3192
3193 static void
3194 set_preview_job_settings(hb_job_t *job, GValue *settings)
3195 {
3196         job->crop[0] = ghb_settings_get_int(settings, "PictureTopCrop");
3197         job->crop[1] = ghb_settings_get_int(settings, "PictureBottomCrop");
3198         job->crop[2] = ghb_settings_get_int(settings, "PictureLeftCrop");
3199         job->crop[3] = ghb_settings_get_int(settings, "PictureRightCrop");
3200
3201         job->anamorphic.mode = ghb_settings_combo_int(settings, "PicturePAR");
3202         job->anamorphic.modulus = 
3203                 ghb_settings_combo_int(settings, "PictureModulus");
3204         job->width = ghb_settings_get_int(settings, "scale_width");
3205         job->height = ghb_settings_get_int(settings, "scale_height");
3206         if (ghb_settings_get_boolean(settings, "show_crop"))
3207         {
3208                 gdouble xscale = (gdouble)job->width / 
3209                         (gdouble)(job->title->width - job->crop[2] - job->crop[3]);
3210                 gdouble yscale = (gdouble)job->height / 
3211                         (gdouble)(job->title->height - job->crop[0] - job->crop[1]);
3212         
3213                 job->width += xscale * (job->crop[2] + job->crop[3]);
3214                 job->height += yscale * (job->crop[0] + job->crop[1]);
3215                 job->crop[0] = 0;
3216                 job->crop[1] = 0;
3217                 job->crop[2] = 0;
3218                 job->crop[3] = 0;
3219                 job->anamorphic.modulus = 2;
3220         }
3221
3222         gint deint = ghb_settings_combo_int(settings, "PictureDeinterlace");
3223         gint decomb = ghb_settings_combo_int(settings, "PictureDecomb");
3224         job->deinterlace = (!decomb && deint == 0) ? 0 : 1;
3225
3226         gboolean keep_aspect;
3227         keep_aspect = ghb_settings_get_boolean(settings, "PictureKeepRatio");
3228         if (job->anamorphic.mode)
3229         {
3230                 job->anamorphic.par_width = job->title->pixel_aspect_width;
3231                 job->anamorphic.par_height = job->title->pixel_aspect_height;
3232                 job->anamorphic.dar_width = 0;
3233                 job->anamorphic.dar_height = 0;
3234
3235                 if (job->anamorphic.mode == 3 && !keep_aspect)
3236                 {
3237                         job->anamorphic.keep_display_aspect = 0;
3238                         job->anamorphic.par_width = 
3239                                 ghb_settings_get_int(settings, "PicturePARWidth");
3240                         job->anamorphic.par_height = 
3241                                 ghb_settings_get_int(settings, "PicturePARHeight");
3242                 }
3243                 else
3244                 {
3245                         job->anamorphic.keep_display_aspect = 1;
3246                 }
3247         }
3248 }
3249
3250 gint
3251 ghb_calculate_target_bitrate(GValue *settings, gint titleindex)
3252 {
3253         hb_list_t  * list;
3254         hb_title_t * title;
3255         hb_job_t   * job;
3256         gint size;
3257
3258         if (h_scan == NULL) return 1500;
3259         list = hb_get_titles( h_scan );
3260     title = hb_list_item( list, titleindex );
3261         if (title == NULL) return 1500;
3262         job   = title->job;
3263         if (job == NULL) return 1500;
3264         size = ghb_settings_get_int(settings, "VideoTargetSize");
3265         return hb_calc_bitrate( job, size );
3266 }
3267
3268 gboolean
3269 ghb_validate_filter_string(const gchar *str, gint max_fields)
3270 {
3271         gint fields = 0;
3272         gchar *end;
3273         gdouble val;
3274
3275         if (str == NULL || *str == 0) return TRUE;
3276         while (*str)
3277         {
3278                 val = g_strtod(str, &end);
3279                 if (str != end)
3280                 { // Found a numeric value
3281                         fields++;
3282                         // negative max_fields means infinate
3283                         if (max_fields >= 0 && fields > max_fields) return FALSE;
3284                         if (*end == 0)
3285                                 return TRUE;
3286                         if (*end != ':')
3287                                 return FALSE;
3288                         str = end + 1;
3289                 }
3290                 else
3291                         return FALSE;
3292         }
3293         return FALSE;
3294 }
3295
3296 gboolean
3297 ghb_validate_filters(signal_user_data_t *ud)
3298 {
3299         gchar *str;
3300         gint index;
3301         gchar *message;
3302
3303         // deinte 4
3304         index = ghb_settings_combo_int(ud->settings, "PictureDeinterlace");
3305         if (index == 1)
3306         {
3307                 str = ghb_settings_get_string(ud->settings, "PictureDeinterlaceCustom");
3308                 if (!ghb_validate_filter_string(str, 4))
3309                 {
3310                         message = g_strdup_printf(
3311                                                 "Invalid Deinterlace Settings:\n\n%s\n",
3312                                                 str);
3313                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3314                         g_free(message);
3315                         g_free(str);
3316                         return FALSE;
3317                 }
3318                 g_free(str);
3319         }
3320         // detel
3321         index = ghb_settings_combo_int(ud->settings, "PictureDetelecine");
3322         if (index == 1)
3323         {
3324                 str = ghb_settings_get_string(ud->settings, "PictureDetelecineCustom");
3325                 if (!ghb_validate_filter_string(str, 6))
3326                 {
3327                         message = g_strdup_printf(
3328                                                 "Invalid Detelecine Settings:\n\n%s\n",
3329                                                 str);
3330                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3331                         g_free(message);
3332                         g_free(str);
3333                         return FALSE;
3334                 }
3335                 g_free(str);
3336         }
3337         // decomb 4
3338         index = ghb_settings_combo_int(ud->settings, "PictureDecomb");
3339         if (index == 1)
3340         {
3341                 str = ghb_settings_get_string(ud->settings, "PictureDecombCustom");
3342                 if (!ghb_validate_filter_string(str, 7))
3343                 {
3344                         message = g_strdup_printf(
3345                                                 "Invalid Decomb Settings:\n\n%s\n",
3346                                                 str);
3347                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3348                         g_free(message);
3349                         g_free(str);
3350                         return FALSE;
3351                 }
3352                 g_free(str);
3353         }
3354         // denois 4
3355         index = ghb_settings_combo_int(ud->settings, "PictureDenoise");
3356         if (index == 1)
3357         {
3358                 str = ghb_settings_get_string(ud->settings, "PictureDenoiseCustom");
3359                 if (!ghb_validate_filter_string(str, 4))
3360                 {
3361                         message = g_strdup_printf(
3362                                                 "Invalid Denoise Settings:\n\n%s\n",
3363                                                 str);
3364                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3365                         g_free(str);
3366                         g_free(message);
3367                         return FALSE;
3368                 }
3369                 g_free(str);
3370         }
3371         return TRUE;
3372 }
3373
3374 gboolean
3375 ghb_validate_video(signal_user_data_t *ud)
3376 {
3377         gint vcodec, mux;
3378         gchar *message;
3379
3380         mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3381         vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
3382         if ((mux == HB_MUX_MP4 || mux == HB_MUX_AVI) && 
3383                 (vcodec == HB_VCODEC_THEORA))
3384         {
3385                 // mp4|avi/theora combination is not supported.
3386                 message = g_strdup_printf(
3387                                         "Theora is not supported in the MP4 and AVI containers.\n\n"
3388                                         "You should choose a different video codec or container.\n"
3389                                         "If you continue, FFMPEG will be chosen for you.");
3390                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3391                 {
3392                         g_free(message);
3393                         return FALSE;
3394                 }
3395                 g_free(message);
3396                 vcodec = HB_VCODEC_FFMPEG;
3397                 ghb_ui_update(ud, "VideoEncoder", ghb_int64_value(vcodec));
3398         }
3399         return TRUE;
3400 }
3401
3402 gboolean
3403 ghb_validate_subtitles(signal_user_data_t *ud)
3404 {
3405         hb_list_t  * list;
3406         hb_title_t * title;
3407         gchar *message;
3408
3409         if (h_scan == NULL) return FALSE;
3410         list = hb_get_titles( h_scan );
3411         if( !hb_list_count( list ) )
3412         {
3413                 /* No valid title, stop right there */
3414                 g_message("No title found.\n");
3415                 return FALSE;
3416         }
3417
3418         gint titleindex;
3419
3420         titleindex = ghb_settings_combo_int(ud->settings, "title");
3421     title = hb_list_item( list, titleindex );
3422         if (title == NULL) return FALSE;
3423         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3424
3425         const GValue *slist, *settings;
3426         gint count, ii, track, source;
3427         gboolean burned, one_burned = FALSE;
3428
3429         slist = ghb_settings_get_value(ud->settings, "subtitle_list");
3430         count = ghb_array_len(slist);
3431         for (ii = 0; ii < count; ii++)
3432         {
3433                 settings = ghb_array_get_nth(slist, ii);
3434                 track = ghb_settings_combo_int(settings, "SubtitleTrack");
3435                 burned = ghb_settings_get_boolean(settings, "SubtitleBurned");
3436                 source = ghb_subtitle_track_source(ud, track);
3437                 if (burned && one_burned)
3438                 {
3439                         // MP4 can only handle burned vobsubs.  make sure there isn't
3440                         // already something burned in the list
3441                         message = g_strdup_printf(
3442                         "Only one subtitle may be burned into the video.\n\n"
3443                                 "You should change your subtitle selections.\n"
3444                                 "If you continue, some subtitles will be lost.");
3445                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3446                         {
3447                                 g_free(message);
3448                                 return FALSE;
3449                         }
3450                         g_free(message);
3451                         break;
3452                 }
3453                 else if (burned)
3454                 {
3455                         one_burned = TRUE;
3456                 }
3457                 if (!burned && mux == HB_MUX_MP4 && source == VOBSUB)
3458                 {
3459                         // MP4 can only handle burned vobsubs.  make sure there isn't
3460                         // already something burned in the list
3461                         message = g_strdup_printf(
3462                         "Your chosen container does not support soft bitmap subtitles.\n\n"
3463                                 "You should change your subtitle selections.\n"
3464                                 "If you continue, some subtitles will be lost.");
3465                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3466                         {
3467                                 g_free(message);
3468                                 return FALSE;
3469                         }
3470                         g_free(message);
3471                         break;
3472                 }
3473         }
3474         return TRUE;
3475 }
3476
3477 gboolean
3478 ghb_validate_audio(signal_user_data_t *ud)
3479 {
3480         hb_list_t  * list;
3481         hb_title_t * title;
3482         gchar *message;
3483         GValue *value;
3484
3485         if (h_scan == NULL) return FALSE;
3486         list = hb_get_titles( h_scan );
3487         if( !hb_list_count( list ) )
3488         {
3489                 /* No valid title, stop right there */
3490                 g_message("No title found.\n");
3491                 return FALSE;
3492         }
3493
3494         gint titleindex;
3495
3496         titleindex = ghb_settings_combo_int(ud->settings, "title");
3497     title = hb_list_item( list, titleindex );
3498         if (title == NULL) return FALSE;
3499         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3500
3501         const GValue *audio_list;
3502         gint count, ii;
3503
3504         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
3505         count = ghb_array_len(audio_list);
3506         for (ii = 0; ii < count; ii++)
3507         {
3508                 GValue *asettings;
3509             hb_audio_config_t *taudio;
3510
3511                 asettings = ghb_array_get_nth(audio_list, ii);
3512                 gint track = ghb_settings_combo_int(asettings, "AudioTrack");
3513                 gint codec = ghb_settings_combo_int(asettings, "AudioEncoder");
3514         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
3515                                                                                         title->list_audio, track );
3516                 if (!(taudio->in.codec & codec) && 
3517                         (codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)))
3518                 {
3519                         // Not supported.  AC3 is passthrough only, so input must be AC3
3520                         message = g_strdup_printf(
3521                                                 "The source does not support Pass-Thru.\n\n"
3522                                                 "You should choose a different audio codec.\n"
3523                                                 "If you continue, one will be chosen for you.");
3524                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3525                         {
3526                                 g_free(message);
3527                                 return FALSE;
3528                         }
3529                         g_free(message);
3530                         if (mux == HB_MUX_AVI)
3531                         {
3532                                 codec = HB_ACODEC_LAME;
3533                         }
3534                         else
3535                         {
3536                                 codec = HB_ACODEC_FAAC;
3537                         }
3538                         value = get_acodec_value(codec);
3539                         ghb_settings_take_value(asettings, "AudioEncoder", value);
3540                 }
3541                 gchar *a_unsup = NULL;
3542                 gchar *mux_s = NULL;
3543                 if (mux == HB_MUX_MP4)
3544                 { 
3545                         mux_s = "MP4";
3546                         // mp4/mp3|vorbis combination is not supported.
3547                         if (codec == HB_ACODEC_LAME)
3548                         {
3549                                 a_unsup = "MP3";
3550                                 codec = HB_ACODEC_FAAC;
3551                         }
3552                         if (codec == HB_ACODEC_VORBIS)
3553                         {
3554                                 a_unsup = "Vorbis";
3555                                 codec = HB_ACODEC_FAAC;
3556                         }
3557                         if (codec == HB_ACODEC_DCA)
3558                         {
3559                                 a_unsup = "DTS";
3560                                 codec = HB_ACODEC_FAAC;
3561                         }
3562                 }
3563                 else if (mux == HB_MUX_AVI)
3564                 {
3565                         mux_s = "AVI";
3566                         // avi/faac|vorbis combination is not supported.
3567                         if (codec == HB_ACODEC_FAAC)
3568                         {
3569                                 a_unsup = "FAAC";
3570                                 codec = HB_ACODEC_LAME;
3571                         }
3572                         if (codec == HB_ACODEC_VORBIS)
3573                         {
3574                                 a_unsup = "Vorbis";
3575                                 codec = HB_ACODEC_LAME;
3576                         }
3577                 }
3578                 else if (mux == HB_MUX_OGM)
3579                 {
3580                         mux_s = "OGM";
3581                         // avi/faac|vorbis combination is not supported.
3582                         if (codec == HB_ACODEC_FAAC)
3583                         {
3584                                 a_unsup = "FAAC";
3585                                 codec = HB_ACODEC_VORBIS;
3586                         }
3587                         if (codec == HB_ACODEC_AC3)
3588                         {
3589                                 a_unsup = "AC-3";
3590                                 codec = HB_ACODEC_VORBIS;
3591                         }
3592                         if (codec == HB_ACODEC_DCA)
3593                         {
3594                                 a_unsup = "DTS";
3595                                 codec = HB_ACODEC_VORBIS;
3596                         }
3597                 }
3598                 if (a_unsup)
3599                 {
3600                         message = g_strdup_printf(
3601                                                 "%s is not supported in the %s container.\n\n"
3602                                                 "You should choose a different audio codec.\n"
3603                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
3604                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3605                         {
3606                                 g_free(message);
3607                                 return FALSE;
3608                         }
3609                         g_free(message);
3610                         value = get_acodec_value(codec);
3611                         ghb_settings_take_value(asettings, "AudioEncoder", value);
3612                 }
3613                 gint mix = ghb_settings_combo_int (asettings, "AudioMixdown");
3614                 gboolean allow_mono = TRUE;
3615                 gboolean allow_stereo = TRUE;
3616                 gboolean allow_dolby = TRUE;
3617                 gboolean allow_dpl2 = TRUE;
3618                 gboolean allow_6ch = TRUE;
3619                 allow_mono =
3620                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3621                         (codec != HB_ACODEC_LAME);
3622                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
3623                 allow_stereo =
3624                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
3625                 allow_dolby =
3626                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
3627                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
3628                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
3629                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
3630                 allow_6ch =
3631                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3632                         (codec != HB_ACODEC_LAME) &&
3633                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
3634                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
3635
3636                 gchar *mix_unsup = NULL;
3637                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
3638                 {
3639                         mix_unsup = "mono";
3640                 }
3641                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
3642                 {
3643                         mix_unsup = "stereo";
3644                 }
3645                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
3646                 {
3647                         mix_unsup = "Dolby";
3648                 }
3649                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
3650                 {
3651                         mix_unsup = "Dolby Pro Logic II";
3652                 }
3653                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
3654                 {
3655                         mix_unsup = "6 Channel";
3656                 }
3657                 if (mix_unsup)
3658                 {
3659                         message = g_strdup_printf(
3660                                                 "The source audio does not support %s mixdown.\n\n"
3661                                                 "You should choose a different mixdown.\n"
3662                                                 "If you continue, one will be chosen for you.", mix_unsup);
3663                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3664                         {
3665                                 g_free(message);
3666                                 return FALSE;
3667                         }
3668                         g_free(message);
3669                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
3670                         value = get_amix_value(mix);
3671                         ghb_settings_take_value(asettings, "AudioMixdown", value);
3672                 }
3673         }
3674         return TRUE;
3675 }
3676
3677 gboolean
3678 ghb_validate_vquality(GValue *settings)
3679 {
3680         gint vcodec;
3681         gchar *message;
3682         gint min, max;
3683
3684         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
3685         vcodec = ghb_settings_combo_int(settings, "VideoEncoder");
3686         gdouble vquality;
3687         vquality = ghb_settings_get_double(settings, "VideoQualitySlider");
3688         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
3689         {
3690                 switch (vcodec)
3691                 {
3692                         case HB_VCODEC_X264:
3693                         {
3694                                 min = 16;
3695                                 max = 30;
3696                         } break;
3697
3698                         case HB_VCODEC_FFMPEG:
3699                         {
3700                                 min = 1;
3701                                 max = 8;
3702                         } break;
3703
3704                         case HB_VCODEC_THEORA:
3705                         {
3706                                 min = 0;
3707                                 max = 63;
3708                         } break;
3709
3710                         default:
3711                         {
3712                                 min = 48;
3713                                 max = 62;
3714                         } break;
3715                 }
3716                 if (vquality < min || vquality > max)
3717                 {
3718                         message = g_strdup_printf(
3719                                                 "Interesting video quality choise: %d\n\n"
3720                                                 "Typical values range from %d to %d.\n"
3721                                                 "Are you sure you wish to use this setting?",
3722                                                 (gint)vquality, min, max);
3723                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
3724                                                                         "Cancel", "Continue"))
3725                         {
3726                                 g_free(message);
3727                                 return FALSE;
3728                         }
3729                         g_free(message);
3730                 }
3731         }
3732         return TRUE;
3733 }
3734
3735 static void
3736 add_job(hb_handle_t *h, GValue *js, gint unique_id, gint titleindex)
3737 {
3738         hb_list_t  * list;
3739         hb_title_t * title;
3740         hb_job_t   * job;
3741         static gchar *x264opts;
3742         gint sub_id = 0;
3743         gboolean tweaks = FALSE;
3744         gchar *detel_str = NULL;
3745         gchar *decomb_str = NULL;
3746         gchar *deint_str = NULL;
3747         gchar *deblock_str = NULL;
3748         gchar *denoise_str = NULL;
3749         gchar *dest_str = NULL;
3750
3751         g_debug("add_job()\n");
3752         if (h == NULL) return;
3753         list = hb_get_titles( h );
3754         if( !hb_list_count( list ) )
3755         {
3756                 /* No valid title, stop right there */
3757                 return;
3758         }
3759
3760     title = hb_list_item( list, titleindex );
3761         if (title == NULL) return;
3762
3763         /* Set job settings */
3764         job   = title->job;
3765         if (job == NULL) return;
3766
3767         job->start_at_preview = ghb_settings_get_int(js, "start_frame") + 1;
3768         if (job->start_at_preview)
3769         {
3770                 job->seek_points = ghb_settings_get_int(js, "preview_count");
3771                 job->pts_to_stop = ghb_settings_get_int(js, "live_duration") * 90000LL;
3772         }
3773
3774         tweaks = ghb_settings_get_boolean(js, "allow_tweaks");
3775         job->mux = ghb_settings_combo_int(js, "FileFormat");
3776         if (job->mux == HB_MUX_MP4)
3777         {
3778                 job->largeFileSize = ghb_settings_get_boolean(js, "Mp4LargeFile");
3779                 job->mp4_optimize = ghb_settings_get_boolean(js, "Mp4HttpOptimize");
3780         }
3781         else
3782         {
3783                 job->largeFileSize = FALSE;
3784                 job->mp4_optimize = FALSE;
3785         }
3786         if (!job->start_at_preview)
3787         {
3788                 gint chapter_start, chapter_end;
3789                 chapter_start = ghb_settings_get_int(js, "start_chapter");
3790                 chapter_end = ghb_settings_get_int(js, "end_chapter");
3791                 gint num_chapters = hb_list_count(title->list_chapter);
3792                 job->chapter_start = MIN( num_chapters, chapter_start );
3793                 job->chapter_end   = MAX( job->chapter_start, chapter_end );
3794
3795                 job->chapter_markers = ghb_settings_get_boolean(js, "ChapterMarkers");
3796                 if (job->chapter_start == job->chapter_end)
3797                         job->chapter_markers = 0;
3798                 if ( job->chapter_markers )
3799                 {
3800                         GValue *chapters;
3801                         GValue *chapter;
3802                         gint chap;
3803                         gint count;
3804                 
3805                         chapters = ghb_settings_get_value(js, "chapter_list");
3806                         count = ghb_array_len(chapters);
3807                         for(chap = chapter_start; chap <= chapter_end; chap++)
3808                         {
3809                                 hb_chapter_t * chapter_s;
3810                                 gchar *name;
3811                                 
3812                                 name = NULL;
3813                                 if (chap-1 < count)
3814                                 {
3815                                         chapter = ghb_array_get_nth(chapters, chap-1);
3816                                         name = ghb_value_string(chapter); 
3817                                 }
3818                                 if (name == NULL)
3819                                 {
3820                                         name = g_strdup_printf ("Chapter %2d", chap);
3821                                 }
3822                                 chapter_s = hb_list_item( job->title->list_chapter, chap - 1);
3823                                 strncpy(chapter_s->title, name, 1023);
3824                                 chapter_s->title[1023] = '\0';
3825                                 g_free(name);
3826                         }
3827                 }
3828         }
3829         job->crop[0] = ghb_settings_get_int(js, "PictureTopCrop");
3830         job->crop[1] = ghb_settings_get_int(js, "PictureBottomCrop");
3831         job->crop[2] = ghb_settings_get_int(js, "PictureLeftCrop");
3832         job->crop[3] = ghb_settings_get_int(js, "PictureRightCrop");
3833
3834         
3835         gint decomb = ghb_settings_combo_int(js, "PictureDecomb");
3836         gint deint = ghb_settings_combo_int(js, "PictureDeinterlace");
3837         if (!decomb)
3838                 job->deinterlace = (deint != 0) ? 1 : 0;
3839         else
3840                 job->deinterlace = 0;
3841     job->grayscale   = ghb_settings_get_boolean(js, "VideoGrayScale");
3842
3843         gboolean keep_aspect;
3844         keep_aspect = ghb_settings_get_boolean(js, "PictureKeepRatio");
3845         job->anamorphic.mode = ghb_settings_combo_int(js, "PicturePAR");
3846         job->anamorphic.modulus = ghb_settings_combo_int(js, "PictureModulus");
3847         if (job->anamorphic.mode)
3848         {
3849                 job->anamorphic.par_width = title->pixel_aspect_width;
3850                 job->anamorphic.par_height = title->pixel_aspect_height;
3851                 job->anamorphic.dar_width = 0;
3852                 job->anamorphic.dar_height = 0;
3853
3854                 if (job->anamorphic.mode == 3 && !keep_aspect)
3855                 {
3856                         job->anamorphic.keep_display_aspect = 0;
3857                         job->anamorphic.par_width = 
3858                                 ghb_settings_get_int(js, "PicturePARWidth");
3859                         job->anamorphic.par_height = 
3860                                 ghb_settings_get_int(js, "PicturePARHeight");
3861                 }
3862                 else
3863                 {
3864                         job->anamorphic.keep_display_aspect = 1;
3865                 }
3866         }
3867
3868         /* Add selected filters */
3869         job->filters = hb_list_init();
3870         gint detel = ghb_settings_combo_int(js, "PictureDetelecine");
3871         if ( detel )
3872         {
3873                 if (detel != 1)
3874                 {
3875                         if (detel_opts.map[detel].svalue != NULL)
3876                                 detel_str = g_strdup(detel_opts.map[detel].svalue);
3877                 }
3878                 else
3879                         detel_str = ghb_settings_get_string(js, "PictureDetelecineCustom");
3880                 hb_filter_detelecine.settings = detel_str;
3881                 hb_list_add( job->filters, &hb_filter_detelecine );
3882         }
3883         if ( decomb )
3884         {
3885                 if (decomb != 1)
3886                 {
3887                         if (decomb_opts.map[decomb].svalue != NULL)
3888                                 decomb_str = g_strdup(decomb_opts.map[decomb].svalue);
3889                 }
3890                 else
3891                         decomb_str = ghb_settings_get_string(js, "PictureDecombCustom");
3892                 hb_filter_decomb.settings = decomb_str;
3893                 hb_list_add( job->filters, &hb_filter_decomb );
3894         }
3895         if( job->deinterlace )
3896         {
3897                 if (deint != 1)
3898                 {
3899                         if (deint_opts.map[deint].svalue != NULL)
3900                                 deint_str = g_strdup(deint_opts.map[deint].svalue);
3901                 }
3902                 else
3903                         deint_str = ghb_settings_get_string(js, "PictureDeinterlaceCustom");
3904                 hb_filter_deinterlace.settings = deint_str;
3905                 hb_list_add( job->filters, &hb_filter_deinterlace );
3906         }
3907         gint deblock = ghb_settings_get_int(js, "PictureDeblock");
3908         if( deblock >= 5 )
3909         {
3910                 deblock_str = g_strdup_printf("%d", deblock);
3911                 hb_filter_deblock.settings = deblock_str;
3912                 hb_list_add( job->filters, &hb_filter_deblock );
3913         }
3914         gint denoise = ghb_settings_combo_int(js, "PictureDenoise");
3915         if( denoise )
3916         {
3917                 if (denoise != 1)
3918                 {
3919                         if (denoise_opts.map[denoise].svalue != NULL)
3920                                 denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
3921                 }
3922                 else
3923                         denoise_str = ghb_settings_get_string(js, "PictureDenoiseCustom");
3924                 hb_filter_denoise.settings = denoise_str;
3925                 hb_list_add( job->filters, &hb_filter_denoise );
3926         }
3927         job->width = ghb_settings_get_int(js, "scale_width");
3928         job->height = ghb_settings_get_int(js, "scale_height");
3929
3930         job->vcodec = ghb_settings_combo_int(js, "VideoEncoder");
3931         if ((job->mux == HB_MUX_MP4 || job->mux == HB_MUX_AVI) && 
3932                 (job->vcodec == HB_VCODEC_THEORA))
3933         {
3934                 // mp4|avi/theora combination is not supported.
3935                 job->vcodec = HB_VCODEC_FFMPEG;
3936         }
3937         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
3938         {
3939                 job->ipod_atom = ghb_settings_get_boolean(js, "Mp4iPodCompatible");
3940         }
3941         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
3942         {
3943                 gdouble vquality;
3944                 vquality = ghb_settings_get_double(js, "VideoQualitySlider");
3945                 job->vquality =  vquality;
3946                 job->vbitrate = 0;
3947         }
3948         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
3949         {
3950                 job->vquality = -1.0;
3951                 job->vbitrate = ghb_settings_get_int(js, "VideoAvgBitrate");
3952         }
3953
3954         gint vrate = ghb_settings_combo_int(js, "VideoFramerate");
3955         if( vrate == 0 )
3956         {
3957                 job->vrate = title->rate;
3958                 job->vrate_base = title->rate_base;
3959                 job->cfr = 0;
3960         }
3961         else
3962         {
3963                 job->vrate = 27000000;
3964                 job->vrate_base = vrate;
3965                 job->cfr = 1;
3966         }
3967
3968         // AVI container does not support variable frame rate.
3969         // OGM supports variable frame rate, but bases all timing on
3970         // DTS, which breaks when b-frames are used since it is
3971         // impossible to reconstruct PTS from DTS when the framerate
3972         // is variable.  
3973         if (job->mux == HB_MUX_AVI || job->mux == HB_MUX_OGM)
3974         {
3975                 job->cfr = 1;
3976         }
3977
3978         const GValue *audio_list;
3979         gint count, ii;
3980         gint tcount = 0;
3981         
3982         audio_list = ghb_settings_get_value(js, "audio_list");
3983         count = ghb_array_len(audio_list);
3984         for (ii = 0; ii < count; ii++)
3985         {
3986                 GValue *asettings;
3987             hb_audio_config_t audio;
3988             hb_audio_config_t *taudio;
3989
3990                 hb_audio_config_init(&audio);
3991                 asettings = ghb_array_get_nth(audio_list, ii);
3992                 audio.in.track = ghb_settings_get_int(asettings, "AudioTrack");
3993                 audio.out.track = tcount;
3994                 audio.out.codec = ghb_settings_combo_int(asettings, "AudioEncoder");
3995         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
3996                                                                         title->list_audio, audio.in.track );
3997                 if (audio.out.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
3998                 {
3999                         if (!(taudio->in.codec & audio.out.codec))
4000                         {
4001                                 // Not supported.  AC3 is passthrough only, so input must be AC3
4002                                 if (job->mux == HB_MUX_AVI)
4003                                 {
4004                                         audio.out.codec = HB_ACODEC_LAME;
4005                                 }
4006                                 else
4007                                 {
4008                                         audio.out.codec = HB_ACODEC_FAAC;
4009                                 }
4010                         }
4011                         else
4012                         {
4013                                 audio.out.codec &= taudio->in.codec;
4014                         }
4015                 }
4016                 if ((job->mux == HB_MUX_MP4) && 
4017                         ((audio.out.codec == HB_ACODEC_LAME) ||
4018                         (audio.out.codec == HB_ACODEC_VORBIS)))
4019                 {
4020                         // mp4/mp3|vorbis combination is not supported.
4021                         audio.out.codec = HB_ACODEC_FAAC;
4022                 }
4023                 if ((job->mux == HB_MUX_AVI) && 
4024                         ((audio.out.codec == HB_ACODEC_FAAC) ||
4025                         (audio.out.codec == HB_ACODEC_VORBIS)))
4026                 {
4027                         // avi/faac|vorbis combination is not supported.
4028                         audio.out.codec = HB_ACODEC_LAME;
4029                 }
4030                 if ((job->mux == HB_MUX_OGM) && 
4031                         ((audio.out.codec == HB_ACODEC_FAAC) ||
4032                         (audio.out.codec == HB_ACODEC_AC3) ||
4033                         (audio.out.codec == HB_ACODEC_DCA)))
4034                 {
4035                         // ogm/faac|ac3 combination is not supported.
4036                         audio.out.codec = HB_ACODEC_VORBIS;
4037                 }
4038         audio.out.dynamic_range_compression = 
4039                         ghb_settings_get_double(asettings, "AudioTrackDRCSlider");
4040         if (audio.out.dynamic_range_compression < 1.0)
4041                 audio.out.dynamic_range_compression = 0.0;
4042
4043                 // It would be better if this were done in libhb for us, but its not yet.
4044                 if (audio.out.codec == HB_ACODEC_AC3 || audio.out.codec == HB_ACODEC_DCA)
4045                 {
4046                         audio.out.mixdown = 0;
4047                 }
4048                 else
4049                 {
4050                         audio.out.mixdown = ghb_settings_combo_int(asettings, "AudioMixdown");
4051                         // Make sure the mixdown is valid and pick a new one if not.
4052                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
4053                                 audio.in.track, audio.out.codec, audio.out.mixdown);
4054                         audio.out.bitrate = 
4055                                 ghb_settings_combo_int(asettings, "AudioBitrate");
4056                         gint srate = ghb_settings_combo_int(asettings, "AudioSamplerate");
4057                         if (srate == 0) // 0 is same as source
4058                                 audio.out.samplerate = taudio->in.samplerate;
4059                         else
4060                                 audio.out.samplerate = srate;
4061                 }
4062
4063                 // Add it to the jobs audio list
4064         hb_audio_add( job, &audio );
4065                 tcount++;
4066         }
4067         // I was tempted to move this up with the reset of the video quality
4068         // settings, but I suspect the settings above need to be made
4069         // first in order for hb_calc_bitrate to be accurate.
4070         if (ghb_settings_get_boolean(js, "vquality_type_target"))
4071         {
4072                 gint size;
4073                 
4074                 size = ghb_settings_get_int(js, "VideoTargetSize");
4075         job->vbitrate = hb_calc_bitrate( job, size );
4076                 job->vquality = -1.0;
4077         }
4078
4079         dest_str = ghb_settings_get_string(js, "destination");
4080         job->file = dest_str;
4081         job->crf = ghb_settings_get_boolean(js, "constant_rate_factor");
4082
4083         const GValue *subtitle_list;
4084         gint subtitle;
4085         gboolean force, burned, def, one_burned = FALSE;
4086         
4087         subtitle_list = ghb_settings_get_value(js, "subtitle_list");
4088         count = ghb_array_len(subtitle_list);
4089         for (ii = 0; ii < count; ii++)
4090         {
4091                 GValue *ssettings;
4092
4093                 ssettings = ghb_array_get_nth(subtitle_list, ii);
4094
4095                 subtitle = ghb_settings_get_int(ssettings, "SubtitleTrack");
4096                 force = ghb_settings_get_boolean(ssettings, "SubtitleForced");
4097                 burned = ghb_settings_get_boolean(ssettings, "SubtitleBurned");
4098                 def = ghb_settings_get_boolean(ssettings, "SubtitleDefaultTrack");
4099
4100                 if (subtitle == -1)
4101                 {
4102                         if (!burned && job->mux == HB_MUX_MKV)
4103                         {
4104                                 job->select_subtitle_config.dest = PASSTHRUSUB;
4105                         }
4106                         else if (!burned && job->mux == HB_MUX_MP4)
4107                         {
4108                                 // Skip any non-burned vobsubs when output is mp4
4109                                 continue;
4110                         }
4111                         else if (burned)
4112                         {
4113                                 // Only allow one subtitle to be burned into the video
4114                                 if (one_burned)
4115                                         continue;
4116                                 job->select_subtitle_config.dest = RENDERSUB;
4117                                 one_burned = TRUE;
4118                         }
4119                         job->select_subtitle_config.force = force;
4120                         job->select_subtitle_config.default_track = def;
4121                         job->indepth_scan = 1;
4122                 }
4123                 else if (subtitle >= 0)
4124                 {
4125                 hb_subtitle_t * subt;
4126                 hb_subtitle_config_t sub_config;
4127
4128                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
4129                         sub_config = subt->config;
4130                         if (subt != NULL)
4131                         {
4132                                 if (!burned && job->mux == HB_MUX_MKV && 
4133                                         subt->format == PICTURESUB)
4134                                 {
4135                                         sub_config.dest = PASSTHRUSUB;
4136                                 }
4137                                 else if (!burned && job->mux == HB_MUX_MP4 && 
4138                                         subt->format == PICTURESUB)
4139                                 {
4140                                         // Skip any non-burned vobsubs when output is mp4
4141                                         continue;
4142                                 }
4143                                 else if ( burned && subt->format == PICTURESUB )
4144                                 {
4145                                         // Only allow one subtitle to be burned into the video
4146                                         if (one_burned)
4147                                                 continue;
4148                                         one_burned = TRUE;
4149                                 }
4150                                 sub_config.force = force;
4151                                 sub_config.default_track = def;
4152                         hb_subtitle_add( job, &sub_config, subtitle );
4153                         }
4154                 }
4155         }
4156
4157         // TODO: libhb holds onto a reference to the x264opts and is not
4158         // finished with it until encoding the job is done.  But I can't
4159         // find a way to get at the job before it is removed in order to
4160         // free up the memory I am allocating here.
4161         // The short story is THIS LEAKS.
4162         x264opts = ghb_build_x264opts_string(js);
4163         
4164         if( *x264opts == '\0' )
4165         {
4166                 g_free(x264opts);
4167                 x264opts = NULL;
4168         }
4169
4170         if (job->indepth_scan == 1)
4171         {
4172                 // Subtitle scan. Look for subtitle matching audio language
4173
4174                 /*
4175                  * When subtitle scan is enabled do a fast pre-scan job
4176                  * which will determine which subtitles to enable, if any.
4177                  */
4178                 job->pass = -1;
4179                 job->indepth_scan = 1;
4180                 job->x264opts = NULL;
4181
4182                 /*
4183                  * Add the pre-scan job
4184                  */
4185                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4186                 hb_add( h, job );
4187         }
4188
4189         if( ghb_settings_get_boolean(js, "VideoTwoPass") &&
4190                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
4191         {
4192                 /*
4193                  * If subtitle_scan is enabled then only turn it on
4194                  * for the second pass and then off again for the
4195                  * second.
4196                  */
4197                 job->pass = 1;
4198                 job->indepth_scan = 0;
4199
4200                 /*
4201                  * If turbo options have been selected then append them
4202                  * to the x264opts now (size includes one ':' and the '\0')
4203                  */
4204                 if( ghb_settings_get_boolean(js, "VideoTurboTwoPass") )
4205                 {
4206                         gchar *tmp_x264opts;
4207                         gchar *extra_opts;
4208                         gint badapt;
4209
4210                         badapt = ghb_lookup_badapt(x264opts);
4211                         if (badapt == 2)
4212                         {
4213                                 extra_opts = g_strdup_printf("%s", turbo_opts);
4214                         }
4215                         else
4216                         {
4217                                 extra_opts = g_strdup_printf("%s:weightb=0", turbo_opts);
4218                         }
4219         
4220                         if ( x264opts )
4221                         {
4222                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, extra_opts);
4223                         } 
4224                         else 
4225                         {
4226                                 /*
4227                                  * No x264opts to modify, but apply the turbo options
4228                                  * anyway as they may be modifying defaults
4229                                  */
4230                                 tmp_x264opts = g_strdup_printf("%s", extra_opts);
4231                         }
4232                         g_free(extra_opts);
4233
4234                         job->x264opts = tmp_x264opts;
4235                 }
4236                 else
4237                 {
4238                         job->x264opts = x264opts;
4239                 }
4240                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4241                 hb_add( h, job );
4242                 //if (job->x264opts != NULL)
4243                 //      g_free(job->x264opts);
4244
4245                 job->pass = 2;
4246                 /*
4247                  * On the second pass we turn off subtitle scan so that we
4248                  * can actually encode using any subtitles that were auto
4249                  * selected in the first pass (using the whacky select-subtitle
4250                  * attribute of the job).
4251                  */
4252                 job->indepth_scan = 0;
4253                 job->x264opts = x264opts;
4254                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4255                 hb_add( h, job );
4256                 //if (job->x264opts != NULL)
4257                 //      g_free(job->x264opts);
4258         }
4259         else
4260         {
4261                 job->x264opts = x264opts;
4262                 job->indepth_scan = 0;
4263                 job->pass = 0;
4264                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4265                 hb_add( h, job );
4266                 //if (job->x264opts != NULL)
4267                 //      g_free(job->x264opts);
4268         }
4269
4270         // clean up audio list
4271         gint num_audio_tracks = hb_list_count(job->list_audio);
4272         for(ii = 0; ii < num_audio_tracks; ii++)
4273         {
4274                 hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
4275                 hb_list_rem(job->list_audio, audio);
4276                 free(audio);
4277         }
4278
4279         // clean up subtitle list
4280         gint num_subtitle_tracks = hb_list_count(job->list_subtitle);
4281         for(ii = 0; ii < num_subtitle_tracks; ii++)
4282         {
4283                 hb_subtitle_t *subtitle = hb_list_item(job->list_subtitle, 0);
4284                 hb_list_rem(job->list_subtitle, subtitle);
4285                 free(subtitle);
4286         }
4287
4288         if (detel_str) g_free(detel_str);
4289         if (decomb_str) g_free(decomb_str);
4290         if (deint_str) g_free(deint_str);
4291         if (deblock_str) g_free(deblock_str);
4292         if (denoise_str) g_free(denoise_str);
4293         if (dest_str) g_free(dest_str);
4294 }
4295
4296 void
4297 ghb_add_job(GValue *js, gint unique_id)
4298 {
4299         // Since I'm doing a scan of the single title I want just prior 
4300         // to adding the job, there is only the one title to choose from.
4301         add_job(h_queue, js, unique_id, 0);
4302 }
4303
4304 void
4305 ghb_add_live_job(GValue *js, gint unique_id)
4306 {
4307         // Since I'm doing a scan of the single title I want just prior 
4308         // to adding the job, there is only the one title to choose from.
4309         gint titleindex = ghb_settings_combo_int(js, "title");
4310         add_job(h_scan, js, unique_id, titleindex);
4311 }
4312
4313 void
4314 ghb_remove_job(gint unique_id)
4315 {
4316     hb_job_t * job;
4317     gint ii;
4318         
4319         // Multiples passes all get the same id
4320         // remove them all.
4321         // Go backwards through list, so reordering doesn't screw me.
4322         ii = hb_count(h_queue) - 1;
4323     while ((job = hb_job(h_queue, ii--)) != NULL)
4324     {
4325         if ((job->sequence_id & 0xFFFFFF) == unique_id)
4326                         hb_rem(h_queue, job);
4327     }
4328 }
4329
4330 void
4331 ghb_start_queue()
4332 {
4333         hb_start( h_queue );
4334 }
4335
4336 void
4337 ghb_stop_queue()
4338 {
4339         hb_stop( h_queue );
4340 }
4341
4342 void
4343 ghb_start_live_encode()
4344 {
4345         hb_start( h_scan );
4346 }
4347
4348 void
4349 ghb_stop_live_encode()
4350 {
4351         hb_stop( h_scan );
4352 }
4353
4354 void
4355 ghb_pause_queue()
4356 {
4357     hb_state_t s;
4358     hb_get_state2( h_queue, &s );
4359
4360     if( s.state == HB_STATE_PAUSED )
4361     {
4362         hb_resume( h_queue );
4363     }
4364     else
4365     {
4366         hb_pause( h_queue );
4367     }
4368 }
4369
4370 static void
4371 vert_line(
4372         GdkPixbuf * pb, 
4373         guint8 r, 
4374         guint8 g, 
4375         guint8 b, 
4376         gint x, 
4377         gint y, 
4378         gint len, 
4379         gint width)
4380 {
4381         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4382         guint8 *dst;
4383         gint ii, jj;
4384         gint channels = gdk_pixbuf_get_n_channels (pb);
4385         gint stride = gdk_pixbuf_get_rowstride (pb);
4386
4387         for (jj = 0; jj < width; jj++)
4388         {
4389                 dst = pixels + y * stride + (x+jj) * channels;
4390                 for (ii = 0; ii < len; ii++)
4391                 {
4392                         dst[0] = r;
4393                         dst[1] = g;
4394                         dst[2] = b;
4395                         dst += stride;
4396                 }
4397         }
4398 }
4399
4400 static void
4401 horz_line(
4402         GdkPixbuf * pb, 
4403         guint8 r, 
4404         guint8 g, 
4405         guint8 b, 
4406         gint x, 
4407         gint y, 
4408         gint len,
4409         gint width)
4410 {
4411         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4412         guint8 *dst;
4413         gint ii, jj;
4414         gint channels = gdk_pixbuf_get_n_channels (pb);
4415         gint stride = gdk_pixbuf_get_rowstride (pb);
4416
4417         for (jj = 0; jj < width; jj++)
4418         {
4419                 dst = pixels + (y+jj) * stride + x * channels;
4420                 for (ii = 0; ii < len; ii++)
4421                 {
4422                         dst[0] = r;
4423                         dst[1] = g;
4424                         dst[2] = b;
4425                         dst += channels;
4426                 }
4427         }
4428 }
4429
4430 static void
4431 hash_pixbuf(
4432         GdkPixbuf * pb,
4433         gint        x,
4434         gint        y,
4435         gint        w,
4436         gint        h,
4437         gint        step,
4438         gint            orientation)
4439 {
4440         gint ii, jj;
4441         gint line_width = 8;
4442         struct
4443         {
4444                 guint8 r;
4445                 guint8 g;
4446                 guint8 b;
4447         } c[4] = 
4448         {{0x80, 0x80, 0x80},{0xC0, 0x80, 0x70},{0x80, 0xA0, 0x80},{0x70, 0x80, 0xA0}};
4449
4450         if (!orientation)
4451         {
4452                 // vertical lines
4453                 for (ii = x, jj = 0; ii+line_width < x+w; ii += step, jj++)
4454                 {
4455                         vert_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, ii, y, h, line_width);
4456                 }
4457         }
4458         else
4459         {
4460                 // horizontal lines
4461                 for (ii = y, jj = 0; ii+line_width < y+h; ii += step, jj++)
4462                 {
4463                         horz_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, x, ii, w, line_width);
4464                 }
4465         }
4466 }
4467
4468 GdkPixbuf*
4469 ghb_get_preview_image(
4470         gint titleindex, 
4471         gint index, 
4472         signal_user_data_t *ud,
4473         gint *out_width,
4474         gint *out_height)
4475 {
4476         GValue *settings;
4477         hb_title_t *title;
4478         hb_list_t  *list;
4479         
4480         settings = ud->settings;
4481         list = hb_get_titles( h_scan );
4482         if( !hb_list_count( list ) )
4483         {
4484                 /* No valid title, stop right there */
4485                 return NULL;
4486         }
4487     title = hb_list_item( list, titleindex );
4488         if (title == NULL) return NULL;
4489         if (title->job == NULL) return NULL;
4490         set_preview_job_settings(title->job, settings);
4491
4492         // hb_get_preview doesn't compensate for anamorphic, so lets
4493         // calculate scale factors
4494         gint width, height, par_width = 1, par_height = 1;
4495         gint pic_par = ghb_settings_combo_int(settings, "PicturePAR");
4496         if (pic_par)
4497         {
4498                 hb_set_anamorphic_size( title->job, &width, &height, 
4499                                                                 &par_width, &par_height );
4500         }
4501
4502         // Make sure we have a big enough buffer to receive the image from libhb
4503         gint dstWidth = title->job->width;
4504         gint dstHeight= title->job->height;
4505
4506         static guint8 *buffer = NULL;
4507         static gint bufferSize = 0;
4508         gint newSize;
4509
4510         newSize = dstWidth * dstHeight * 4;
4511         if( bufferSize < newSize )
4512         {
4513                 bufferSize = newSize;
4514                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
4515         }
4516         hb_get_preview( h_scan, title, index, buffer );
4517
4518         // Create an GdkPixbuf and copy the libhb image into it, converting it from
4519         // libhb's format something suitable.
4520         
4521         // The image data returned by hb_get_preview is 4 bytes per pixel, 
4522         // BGRA format. Alpha is ignored.
4523
4524         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
4525         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
4526         
4527         guint32 *src = (guint32*)buffer;
4528         guint8 *dst = pixels;
4529
4530         gint ii, jj;
4531         gint channels = gdk_pixbuf_get_n_channels (preview);
4532         gint stride = gdk_pixbuf_get_rowstride (preview);
4533         guint8 *tmp;
4534
4535         for (ii = 0; ii < dstHeight; ii++)
4536         {
4537                 tmp = dst;
4538                 for (jj = 0; jj < dstWidth; jj++)
4539                 {
4540                         tmp[0] = src[0] >> 16;
4541                         tmp[1] = src[0] >> 8;
4542                         tmp[2] = src[0] >> 0;
4543                         tmp += channels;
4544                         src++;
4545                 }
4546                 dst += stride;
4547         }
4548         gint w = ghb_settings_get_int(settings, "scale_width");
4549         gint h = ghb_settings_get_int(settings, "scale_height");
4550         ghb_par_scale(ud, &w, &h, par_width, par_height);
4551
4552         gint c0, c1, c2, c3;
4553         c0 = ghb_settings_get_int(settings, "PictureTopCrop");
4554         c1 = ghb_settings_get_int(settings, "PictureBottomCrop");
4555         c2 = ghb_settings_get_int(settings, "PictureLeftCrop");
4556         c3 = ghb_settings_get_int(settings, "PictureRightCrop");
4557
4558         gdouble xscale = (gdouble)w / (gdouble)(title->width - c2 - c3);
4559         gdouble yscale = (gdouble)h / (gdouble)(title->height - c0 - c1);
4560         
4561         ghb_par_scale(ud, &dstWidth, &dstHeight, par_width, par_height);
4562         *out_width = w;
4563         *out_height = h;
4564         if (ghb_settings_get_boolean(settings, "reduce_hd_preview"))
4565         {
4566                 GdkScreen *ss;
4567                 gint s_w, s_h;
4568                 gint orig_w, orig_h;
4569                 gint factor = 80;
4570
4571                 if (ghb_settings_get_boolean(settings, "preview_fullscreen"))
4572                 {
4573                         factor = 100;
4574                 }
4575                 ss = gdk_screen_get_default();
4576                 s_w = gdk_screen_get_width(ss);
4577                 s_h = gdk_screen_get_height(ss);
4578                 orig_w = dstWidth;
4579                 orig_h = dstHeight;
4580
4581                 if (dstWidth > s_w * factor / 100)
4582                 {
4583                         dstWidth = s_w * factor / 100;
4584                         dstHeight = dstHeight * dstWidth / orig_w;
4585                 }
4586                 if (dstHeight > s_h * factor / 100)
4587                 {
4588                         dstHeight = s_h * factor / 100;
4589                         dstWidth = dstWidth * dstHeight / orig_h;
4590                 }
4591                 xscale *= (gdouble)dstWidth / orig_w;
4592                 yscale *= (gdouble)dstHeight / orig_h;
4593                 w *= (gdouble)dstWidth / orig_w;
4594                 h *= (gdouble)dstHeight / orig_h;
4595         }
4596         GdkPixbuf *scaled_preview;
4597         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
4598         if (ghb_settings_get_boolean(settings, "show_crop"))
4599         {
4600                 c0 *= yscale;
4601                 c1 *= yscale;
4602                 c2 *= xscale;
4603                 c3 *= xscale;
4604                 // Top
4605                 hash_pixbuf(scaled_preview, c2, 0, w, c0, 32, 0);
4606                 // Bottom
4607                 hash_pixbuf(scaled_preview, c2, dstHeight-c1, w, c1, 32, 0);
4608                 // Left
4609                 hash_pixbuf(scaled_preview, 0, c0, c2, h, 32, 1);
4610                 // Right
4611                 hash_pixbuf(scaled_preview, dstWidth-c3, c0, c3, h, 32, 1);
4612         }
4613         g_object_unref (preview);
4614         return scaled_preview;
4615 }
4616
4617 static void
4618 sanitize_volname(gchar *name)
4619 {
4620         gchar *a, *b;
4621
4622         a = b = name;
4623         while (*b)
4624         {
4625                 switch(*b)
4626                 {
4627                 case '<':
4628                         b++;
4629                         break;
4630                 case '>':
4631                         b++;
4632                         break;
4633                 default:
4634                         *a = *b;
4635                         a++; b++;
4636                         break;
4637                 }
4638         }
4639         *a = 0;
4640 }
4641
4642 gchar*
4643 ghb_dvd_volname(const gchar *device)
4644 {
4645         gchar *name;
4646         name = hb_dvd_name((gchar*)device);
4647         if (name != NULL && name[0] != 0)
4648         {
4649                 name = g_strdup(name);
4650                 sanitize_volname(name);
4651                 return name;
4652         }
4653         return NULL;
4654 }