OSDN Git Service

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