OSDN Git Service

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