OSDN Git Service

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