OSDN Git Service

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