OSDN Git Service

LinGui: picture filter changes
[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         {"Auto Pass-Thru", "auto",    HB_ACODEC_DCA|HB_ACODEC_AC3, "auto"},
246 };
247 combo_opts_t acodec_opts =
248 {
249         sizeof(d_acodec_opts)/sizeof(options_map_t),
250         d_acodec_opts
251 };
252
253 static options_map_t d_direct_opts[] =
254 {
255         {"None",      "none",     0, "none"},
256         {"Spatial",   "spatial",  1, "spatial"},
257         {"Temporal",  "temporal", 2, "temporal"},
258         {"Automatic", "auto",     3, "auto"},
259 };
260 combo_opts_t direct_opts =
261 {
262         sizeof(d_direct_opts)/sizeof(options_map_t),
263         d_direct_opts
264 };
265
266 static options_map_t d_badapt_opts[] =
267 {
268         {"Off",             "0", 0, "0"},
269         {"Fast",            "1", 1, "1"},
270         {"Optimal",         "2", 2, "2"},
271 };
272 combo_opts_t badapt_opts =
273 {
274         sizeof(d_badapt_opts)/sizeof(options_map_t),
275         d_badapt_opts
276 };
277
278 static options_map_t d_me_opts[] =
279 {
280         {"Diamond",              "dia",  0, "dia"},
281         {"Hexagon",              "hex",  1, "hex"},
282         {"Uneven Multi-Hexagon", "umh",  2, "umh"},
283         {"Exhaustive",           "esa",  3, "esa"},
284         {"Hadamard Exhaustive",  "tesa", 4, "tesa"},
285 };
286 combo_opts_t me_opts =
287 {
288         sizeof(d_me_opts)/sizeof(options_map_t),
289         d_me_opts
290 };
291
292 static options_map_t d_subme_opts[] =
293 {
294         {"1", "1", 1, "1"},
295         {"2", "2", 2, "2"},
296         {"3", "3", 3, "3"},
297         {"4", "4", 4, "4"},
298         {"5", "5", 5, "5"},
299         {"6", "6", 6, "6"},
300         {"7", "7", 7, "7"},
301         {"8", "8", 8, "8"},
302         {"9", "9", 9, "9"},
303         {"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         else if (container == HB_MUX_AVI)
1352         {
1353                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1354                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
1355                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
1356         }
1357         else if (container == HB_MUX_OGM)
1358         {
1359                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, TRUE);
1360         }
1361
1362         gboolean allow_mono = TRUE;
1363         gboolean allow_stereo = TRUE;
1364         gboolean allow_dolby = TRUE;
1365         gboolean allow_dpl2 = TRUE;
1366         gboolean allow_6ch = TRUE;
1367         if (audio)
1368         {
1369                 allow_mono =
1370                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1371                         (acodec != HB_ACODEC_LAME);
1372                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1373                 allow_stereo =
1374                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1375                 allow_dolby =
1376                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1377                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1378                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1379                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1380                 allow_6ch =
1381                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1382                         (acodec != HB_ACODEC_LAME) &&
1383                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1384                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1385         }
1386         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_MONO, !allow_mono);
1387         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_STEREO, !allow_stereo);
1388         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBY, !allow_dolby);
1389         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBYPLII, !allow_dpl2);
1390         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_6CH, !allow_6ch);
1391 }
1392
1393 gint
1394 ghb_get_best_mix(gint titleindex, gint track, gint acodec, gint mix)
1395 {
1396     hb_audio_config_t *audio = NULL;
1397         gboolean allow_mono = TRUE;
1398         gboolean allow_stereo = TRUE;
1399         gboolean allow_dolby = TRUE;
1400         gboolean allow_dpl2 = TRUE;
1401         gboolean allow_6ch = TRUE;
1402         
1403         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1404         {
1405                 // Audio codec pass-thru.  No mixdown
1406                 return 0;
1407         }
1408         audio = get_hb_audio(titleindex, track);
1409         if (audio)
1410         {
1411                 allow_mono =
1412                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1413                         (acodec != HB_ACODEC_LAME);
1414                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1415                 allow_stereo =
1416                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1417                 allow_dolby =
1418                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1419                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1420                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1421                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1422                 allow_6ch =
1423                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1424                         (acodec != HB_ACODEC_LAME) &&
1425                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1426                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1427         }
1428         gboolean greater = FALSE;
1429         if (mix == 0) 
1430         {
1431                 // If no mix is specified, select the best available.
1432                 mix = HB_AMIXDOWN_6CH;
1433         }
1434         if (mix == HB_AMIXDOWN_6CH)
1435         {
1436                 greater = TRUE;
1437                 if (allow_6ch) return HB_AMIXDOWN_6CH;
1438         }
1439         if (mix == HB_AMIXDOWN_DOLBYPLII || greater)
1440         {
1441                 greater = TRUE;
1442                 if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1443         }
1444         if (mix == HB_AMIXDOWN_DOLBY || greater)
1445         {
1446                 greater = TRUE;
1447                 if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1448         }
1449         if (mix == HB_AMIXDOWN_STEREO || greater)
1450         {
1451                 greater = TRUE;
1452                 if (allow_stereo) return HB_AMIXDOWN_STEREO;
1453         }
1454         if (mix == HB_AMIXDOWN_MONO || greater)
1455         {
1456                 greater = TRUE;
1457                 if (allow_mono) return HB_AMIXDOWN_MONO;
1458         }
1459         if (allow_stereo) return HB_AMIXDOWN_STEREO;
1460         if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1461         if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1462         if (allow_6ch) return HB_AMIXDOWN_6CH;
1463         return 0;
1464 }
1465
1466 // Set up the model for the combo box
1467 static void
1468 init_combo_box(GtkBuilder *builder, const gchar *name)
1469 {
1470         GtkComboBox *combo;
1471         GtkListStore *store;
1472         GtkCellRenderer *cell;
1473
1474         g_debug("init_combo_box() %s\n", name);
1475         // First modify the combobox model to allow greying out of options
1476         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1477         if (combo == NULL)
1478                 return;
1479         // Store contains:
1480         // 1 - String to display
1481         // 2 - bool indicating whether the entry is selectable (grey or not)
1482         // 3 - String that is used for presets
1483         // 4 - Int value determined by backend
1484         // 5 - String value determined by backend
1485         store = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_BOOLEAN, 
1486                                                            G_TYPE_STRING, G_TYPE_DOUBLE, G_TYPE_STRING);
1487         gtk_combo_box_set_model(combo, GTK_TREE_MODEL(store));
1488
1489         if (GTK_WIDGET_TYPE(combo) == GTK_TYPE_COMBO_BOX)
1490         {
1491                 gtk_cell_layout_clear(GTK_CELL_LAYOUT(combo));
1492         cell = GTK_CELL_RENDERER(gtk_cell_renderer_text_new());
1493         gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE);
1494         gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell,
1495                 "text", 0, "sensitive", 1, NULL);
1496         }
1497         else
1498         { // Combo box entry
1499                 gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(combo), 0);
1500         }
1501 }       
1502
1503 static void
1504 audio_samplerate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1505 {
1506         GtkTreeIter iter;
1507         GtkListStore *store;
1508         gint ii;
1509         
1510         g_debug("audio_samplerate_opts_set ()\n");
1511         store = get_combo_box_store(builder, name);
1512         gtk_list_store_clear(store);
1513         // Add an item for "Same As Source"
1514         gtk_list_store_append(store, &iter);
1515         gtk_list_store_set(store, &iter, 
1516                                            0, "Same as source", 
1517                                            1, TRUE, 
1518                                            2, "source", 
1519                                            3, 0.0, 
1520                                            4, "source", 
1521                                            -1);
1522         for (ii = 0; ii < count; ii++)
1523         {
1524                 gtk_list_store_append(store, &iter);
1525                 gtk_list_store_set(store, &iter, 
1526                                                    0, rates[ii].string, 
1527                                                    1, TRUE, 
1528                                                    2, rates[ii].string, 
1529                                                    3, (gdouble)rates[ii].rate, 
1530                                                    4, rates[ii].string, 
1531                                                    -1);
1532         }
1533 }
1534
1535 static void
1536 video_rate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1537 {
1538         GtkTreeIter iter;
1539         GtkListStore *store;
1540         gint ii;
1541         
1542         g_debug("video_rate_opts_set ()\n");
1543         store = get_combo_box_store(builder, name);
1544         gtk_list_store_clear(store);
1545         // Add an item for "Same As Source"
1546         gtk_list_store_append(store, &iter);
1547         gtk_list_store_set(store, &iter, 
1548                                            0, "Same as source", 
1549                                            1, TRUE, 
1550                                            2, "source", 
1551                                            3, 0.0, 
1552                                            4, "source", 
1553                                            -1);
1554         for (ii = 0; ii < count; ii++)
1555         {
1556                 gchar *desc = "";
1557                 gchar *option;
1558                 if (strcmp(rates[ii].string, "23.976") == 0)
1559                 {
1560                         desc = "(NTSC Film)";
1561                 }
1562                 else if (strcmp(rates[ii].string, "25") == 0)
1563                 {
1564                         desc = "(PAL Film/Video)";
1565                 }
1566                 else if (strcmp(rates[ii].string, "29.97") == 0)
1567                 {
1568                         desc = "(NTSC Video)";
1569                 }
1570                 option = g_strdup_printf ("%s %s", rates[ii].string, desc);
1571                 gtk_list_store_append(store, &iter);
1572                 gtk_list_store_set(store, &iter, 
1573                                                    0, option, 
1574                                                    1, TRUE, 
1575                                                    2, rates[ii].string, 
1576                                                    3, (gdouble)rates[ii].rate, 
1577                                                    4, rates[ii].string, 
1578                                                    -1);
1579                 g_free(option);
1580         }
1581 }
1582
1583 static void
1584 mix_opts_set(GtkBuilder *builder, const gchar *name)
1585 {
1586         GtkTreeIter iter;
1587         GtkListStore *store;
1588         gint ii;
1589         
1590         g_debug("mix_opts_set ()\n");
1591         store = get_combo_box_store(builder, name);
1592         gtk_list_store_clear(store);
1593         gtk_list_store_append(store, &iter);
1594         gtk_list_store_set(store, &iter, 
1595                                            0, "None", 
1596                                            1, TRUE, 
1597                                            2, "none", 
1598                                            3, 0.0, 
1599                                            4, "none", 
1600                                            -1);
1601         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1602         {
1603                 gtk_list_store_append(store, &iter);
1604                 gtk_list_store_set(store, &iter, 
1605                                                    0, hb_audio_mixdowns[ii].human_readable_name, 
1606                                                    1, TRUE, 
1607                                                    2, hb_audio_mixdowns[ii].short_name, 
1608                                                    3, (gdouble)hb_audio_mixdowns[ii].amixdown, 
1609                                                    4, hb_audio_mixdowns[ii].internal_name, 
1610                                                    -1);
1611         }
1612 }
1613
1614 static void
1615 srt_codeset_opts_set(GtkBuilder *builder, const gchar *name)
1616 {
1617         GtkTreeIter iter;
1618         GtkListStore *store;
1619         gint ii;
1620         
1621         g_debug("srt_codeset_opts_set ()\n");
1622         store = get_combo_box_store(builder, name);
1623         gtk_list_store_clear(store);
1624         for (ii = 0; ii < SRT_TABLE_SIZE; ii++)
1625         {
1626                 gtk_list_store_append(store, &iter);
1627                 gtk_list_store_set(store, &iter, 
1628                                                    0, srt_codeset_table[ii],
1629                                                    1, TRUE, 
1630                                                    2, srt_codeset_table[ii],
1631                                                    3, (gdouble)ii, 
1632                                                    4, srt_codeset_table[ii],
1633                                                    -1);
1634         }
1635         GtkComboBoxEntry *cbe;
1636
1637         cbe = GTK_COMBO_BOX_ENTRY(GHB_WIDGET(builder, name));
1638         //gtk_combo_box_entry_set_text_column(cbe, 0);
1639 }
1640
1641 static void
1642 language_opts_set(GtkBuilder *builder, const gchar *name)
1643 {
1644         GtkTreeIter iter;
1645         GtkListStore *store;
1646         gint ii;
1647         
1648         g_debug("language_opts_set ()\n");
1649         store = get_combo_box_store(builder, name);
1650         gtk_list_store_clear(store);
1651         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1652         {
1653                 const gchar *lang;
1654
1655                 if (ghb_language_table[ii].native_name[0] != 0)
1656                         lang = ghb_language_table[ii].native_name;
1657                 else
1658                         lang = ghb_language_table[ii].eng_name;
1659                 
1660                 gtk_list_store_append(store, &iter);
1661                 gtk_list_store_set(store, &iter, 
1662                                                    0, lang,
1663                                                    1, TRUE, 
1664                                                    2, ghb_language_table[ii].iso639_2, 
1665                                                    3, (gdouble)ii, 
1666                                                    4, ghb_language_table[ii].iso639_1, 
1667                                                    -1);
1668         }
1669 }
1670
1671 static gchar **titles = NULL;
1672
1673 void
1674 title_opts_set(GtkBuilder *builder, const gchar *name)
1675 {
1676         GtkTreeIter iter;
1677         GtkListStore *store;
1678         hb_list_t  * list = NULL;
1679         hb_title_t * title = NULL;
1680         gint ii;
1681         gint count = 0;
1682         
1683         g_debug("title_opts_set ()\n");
1684         store = get_combo_box_store(builder, name);
1685         gtk_list_store_clear(store);
1686         if (h_scan != NULL)
1687         {
1688                 list = hb_get_titles( h_scan );
1689                 count = hb_list_count( list );
1690                 if (count > 100) count = 100;
1691         }
1692         if (titles) g_strfreev(titles);
1693         if (title_opts.map) g_free(title_opts.map);
1694         if (count > 0)
1695         {
1696                 title_opts.count = count;
1697                 title_opts.map = g_malloc(count*sizeof(options_map_t));
1698                 titles = g_malloc((count+1) * sizeof(gchar*));
1699         }
1700         else
1701         {
1702                 title_opts.count = 1;
1703                 title_opts.map = g_malloc(sizeof(options_map_t));
1704                 titles = NULL;
1705         }
1706         if( count <= 0 )
1707         {
1708                 // No titles.  Fill in a default.
1709                 gtk_list_store_append(store, &iter);
1710                 gtk_list_store_set(store, &iter, 
1711                                                    0, "No Titles", 
1712                                                    1, TRUE, 
1713                                                    2, "none", 
1714                                                    3, -1.0, 
1715                                                    4, "none", 
1716                                                    -1);
1717                 title_opts.map[0].option = "No Titles";
1718                 title_opts.map[0].shortOpt = "none";
1719                 title_opts.map[0].ivalue = -1;
1720                 title_opts.map[0].svalue = "none";
1721                 return;
1722         }
1723         for (ii = 0; ii < count; ii++)
1724         {
1725                 title = (hb_title_t*)hb_list_item(list, ii);
1726                 if (title->duration != 0)
1727                 {
1728                         titles[ii]  = g_strdup_printf ("%d - %02dh%02dm%02ds",
1729                                 title->index, title->hours, title->minutes, title->seconds);
1730                 }
1731                 else
1732                 {
1733                         titles[ii]  = g_strdup_printf ("%d - Unknown Length", title->index);
1734                 }
1735                 gtk_list_store_append(store, &iter);
1736                 gtk_list_store_set(store, &iter, 
1737                                                    0, titles[ii], 
1738                                                    1, TRUE, 
1739                                                    2, titles[ii], 
1740                                                    3, (gdouble)ii, 
1741                                                    4, titles[ii], 
1742                                                    -1);
1743                 title_opts.map[ii].option = titles[ii];
1744                 title_opts.map[ii].shortOpt = titles[ii];
1745                 title_opts.map[ii].ivalue = ii;
1746                 title_opts.map[ii].svalue = titles[ii];
1747         }
1748         titles[ii] = NULL;
1749 }
1750
1751 static gboolean
1752 find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter)
1753 {
1754         gdouble ivalue;
1755         gboolean foundit = FALSE;
1756         
1757         if (gtk_tree_model_get_iter_first (store, iter))
1758         {
1759                 do
1760                 {
1761                         gtk_tree_model_get(store, iter, 3, &ivalue, -1);
1762                         if (value == (int)ivalue)
1763                         {
1764                                 foundit = TRUE;
1765                                 break;
1766                         }
1767                 } while (gtk_tree_model_iter_next (store, iter));
1768         }
1769         return foundit;
1770 }
1771
1772 void
1773 audio_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1774 {
1775         GtkTreeIter iter;
1776         GtkListStore *store;
1777         hb_list_t  * list = NULL;
1778         hb_title_t * title = NULL;
1779     hb_audio_config_t * audio;
1780         gint ii;
1781         gint count = 0;
1782         
1783         g_debug("audio_track_opts_set ()\n");
1784         store = get_combo_box_store(builder, name);
1785         gtk_list_store_clear(store);
1786         if (h_scan != NULL)
1787         {
1788                 list = hb_get_titles( h_scan );
1789             title = (hb_title_t*)hb_list_item( list, titleindex );
1790                 if (title != NULL)
1791                 {
1792                         count = hb_list_count( title->list_audio );
1793                 }
1794         }
1795         if (count > 100) count = 100;
1796         if (audio_track_opts.map) g_free(audio_track_opts.map);
1797         if (count > 0)
1798         {
1799                 audio_track_opts.count = count;
1800                 audio_track_opts.map = g_malloc(count*sizeof(options_map_t));
1801         }
1802         else
1803         {
1804                 audio_track_opts.count = 1;
1805                 audio_track_opts.map = g_malloc(sizeof(options_map_t));
1806         }
1807         if( count <= 0 )
1808         {
1809                 // No audio. set some default
1810                 gtk_list_store_append(store, &iter);
1811                 gtk_list_store_set(store, &iter, 
1812                                                    0, "No Audio", 
1813                                                    1, TRUE, 
1814                                                    2, "none", 
1815                                                    3, -1.0, 
1816                                                    4, "none", 
1817                                                    -1);
1818                 audio_track_opts.map[0].option = "No Audio";
1819                 audio_track_opts.map[0].shortOpt = "none";
1820                 audio_track_opts.map[0].ivalue = -1;
1821                 audio_track_opts.map[0].svalue = "none";
1822                 return;
1823         }
1824         index_str_init(count-1);
1825         for (ii = 0; ii < count; ii++)
1826         {
1827         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, ii );
1828                 gtk_list_store_append(store, &iter);
1829                 gtk_list_store_set(store, &iter, 
1830                                                    0, audio->lang.description, 
1831                                                    1, TRUE, 
1832                                                    2, index_str[ii], 
1833                                                    3, (gdouble)ii, 
1834                                                    4, index_str[ii], 
1835                                                    -1);
1836                 audio_track_opts.map[ii].option = audio->lang.description,
1837                 audio_track_opts.map[ii].shortOpt = index_str[ii];
1838                 audio_track_opts.map[ii].ivalue = ii;
1839                 audio_track_opts.map[ii].svalue = index_str[ii];
1840         }
1841 }
1842
1843 void
1844 subtitle_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1845 {
1846         GtkTreeIter iter;
1847         GtkListStore *store;
1848         hb_list_t  * list = NULL;
1849         hb_title_t * title = NULL;
1850         hb_subtitle_t * subtitle;
1851         gint ii, count = 0;
1852         static char ** options = NULL;
1853         
1854         g_debug("subtitle_track_opts_set ()\n");
1855         store = get_combo_box_store(builder, name);
1856         gtk_list_store_clear(store);
1857         if (h_scan != NULL)
1858         {
1859                 list = hb_get_titles( h_scan );
1860             title = (hb_title_t*)hb_list_item( list, titleindex );
1861                 if (title != NULL)
1862                 {
1863                         count = hb_list_count( title->list_subtitle );
1864                 }
1865         }
1866         if (count > 100) count = 100;
1867         if (subtitle_opts.map) g_free(subtitle_opts.map);
1868         if (count > 0)
1869         {
1870                 subtitle_opts.count = count+1;
1871                 subtitle_opts.map = g_malloc((count+1)*sizeof(options_map_t));
1872         }
1873         else
1874         {
1875                 subtitle_opts.count = LANG_TABLE_SIZE+1;
1876                 subtitle_opts.map = g_malloc((LANG_TABLE_SIZE+1)*sizeof(options_map_t));
1877         }
1878         gtk_list_store_append(store, &iter);
1879         gtk_list_store_set(store, &iter, 
1880                                            0, "Foreign Audio Search", 
1881                                            1, TRUE, 
1882                                            2, "-1", 
1883                                            3, -1.0, 
1884                                            4, "auto", 
1885                                            -1);
1886         subtitle_opts.map[0].option = "Foreign Audio Search";
1887         subtitle_opts.map[0].shortOpt = "-1";
1888         subtitle_opts.map[0].ivalue = -1;
1889         subtitle_opts.map[0].svalue = "auto";
1890         if (count > 0)
1891         {
1892                 if (options != NULL)
1893                         g_strfreev(options);
1894                 options = g_malloc((count+1)*sizeof(gchar*));
1895                 index_str_init(count-1);
1896                 for (ii = 0; ii < count; ii++)
1897                 {
1898                 subtitle = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
1899                         // Skip subtitles that must be burned if there is already
1900                         // a burned subtitle in the list
1901                         options[ii] = g_strdup_printf("%d - %s", ii+1, subtitle->lang);
1902                         subtitle_opts.map[ii+1].option = options[ii];
1903                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
1904                         subtitle_opts.map[ii+1].ivalue = ii;
1905                         subtitle_opts.map[ii+1].svalue = subtitle->iso639_2;
1906                         gtk_list_store_append(store, &iter);
1907                         gtk_list_store_set(store, &iter, 
1908                                                 0, options[ii], 
1909                                                 1, TRUE, 
1910                                                 2, index_str[ii], 
1911                                                 3, (gdouble)ii, 
1912                                                 4, subtitle->iso639_2, 
1913                                                 -1);
1914                 }
1915                 options[count] = NULL;
1916         }
1917         else
1918         {
1919                 index_str_init(LANG_TABLE_SIZE-1);
1920                 for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1921                 {
1922                         const gchar *lang;
1923
1924                         if (ghb_language_table[ii].native_name[0] != 0)
1925                                 lang = ghb_language_table[ii].native_name;
1926                         else
1927                                 lang = ghb_language_table[ii].eng_name;
1928
1929                         subtitle_opts.map[ii+1].option = lang;
1930                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
1931                         subtitle_opts.map[ii+1].ivalue = ii;
1932                         subtitle_opts.map[ii+1].svalue = ghb_language_table[ii].iso639_2;
1933                         gtk_list_store_append(store, &iter);
1934                         gtk_list_store_set(store, &iter, 
1935                                         0, lang,
1936                                         1, TRUE, 
1937                                         2, index_str[ii],
1938                                         3, (gdouble)ii, 
1939                                         4, ghb_language_table[ii].iso639_2, 
1940                                         -1);
1941                 }
1942         }
1943 }
1944
1945 gint
1946 ghb_longest_title()
1947 {
1948         hb_list_t  * list;
1949         hb_title_t * title;
1950         gint ii;
1951         gint count = 0;
1952         guint64 longest = 0;
1953         gint titleindex = 0;
1954         
1955         g_debug("ghb_longest_title ()\n");
1956         if (h_scan == NULL) return 0;
1957         list = hb_get_titles( h_scan );
1958         count = hb_list_count( list );
1959         if (count > 100) count = 100;
1960         for (ii = 0; ii < count; ii++)
1961         {
1962                 title = (hb_title_t*)hb_list_item(list, ii);
1963                 if (title->duration > longest)
1964                 {
1965                         titleindex = ii;
1966                         longest = title->duration;
1967                 }
1968         }
1969         return titleindex;
1970 }
1971
1972 gchar*
1973 ghb_get_source_audio_lang(gint titleindex, gint track)
1974 {
1975         hb_list_t  * list;
1976         hb_title_t * title;
1977     hb_audio_config_t * audio;
1978         gchar *lang = NULL;
1979         
1980         g_debug("ghb_lookup_1st_audio_lang ()\n");
1981         if (h_scan == NULL) 
1982                 return NULL;
1983         list = hb_get_titles( h_scan );
1984     title = (hb_title_t*)hb_list_item( list, titleindex );
1985         if (title == NULL)
1986                 return NULL;
1987         if (hb_list_count( title->list_audio ) <= track)
1988                 return NULL;
1989
1990         audio = hb_list_audio_config_item(title->list_audio, track);
1991         if (audio == NULL)
1992                 return NULL;
1993
1994         lang = g_strdup(audio->lang.iso639_2);
1995         return lang;
1996 }
1997
1998 gint
1999 ghb_find_audio_track(
2000         gint titleindex, 
2001         const gchar *lang, 
2002         gint acodec,
2003         GHashTable *track_indices)
2004 {
2005         hb_list_t  * list;
2006         hb_title_t * title;
2007     hb_audio_config_t * audio;
2008         gint ii;
2009         gint count = 0;
2010         gint track = -1;
2011         gint max_chan = 0;
2012         gboolean *used;
2013         
2014         g_debug("find_audio_track ()\n");
2015         if (h_scan == NULL) return -1;
2016         list = hb_get_titles( h_scan );
2017     title = (hb_title_t*)hb_list_item( list, titleindex );
2018         if (title != NULL)
2019         {
2020                 count = hb_list_count( title->list_audio );
2021         }
2022         if (count > 10) count = 10;
2023         used = g_hash_table_lookup(track_indices, &acodec);
2024         if (used == NULL)
2025         {
2026                 used = g_malloc0(count * sizeof(gboolean));
2027                 g_hash_table_insert(track_indices, &acodec, used);
2028         }
2029         // Try to find an item that matches the preferred language and
2030         // the passthru codec type
2031         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
2032         {
2033                 for (ii = 0; ii < count; ii++)
2034                 {
2035                         gint channels;
2036
2037                         if (used[ii])
2038                                 continue;
2039
2040                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2041                                                                                                         title->list_audio, ii );
2042                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2043                                                                                                         audio->in.channel_layout);
2044                         // Find a track that is not visually impaired or dirctor's
2045                         // commentary, and has the highest channel count.
2046                         if ((audio->in.codec & acodec) &&
2047                                 (audio->lang.type < 2) &&
2048                                 ((strcmp(lang, audio->lang.iso639_2) == 0) ||
2049                                 (strcmp(lang, "und") == 0)))
2050                         {
2051                                 if (channels > max_chan)
2052                                 {
2053                                         track = ii;
2054                                         max_chan = channels;
2055                                 }
2056                         }
2057                 }
2058         }
2059         if (track > -1)
2060         {
2061                 used[track] = TRUE;
2062                 return track;
2063         }
2064         // Try to find an item that matches the preferred language
2065         for (ii = 0; ii < count; ii++)
2066         {
2067                 if (used[ii])
2068                         continue;
2069         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2070                                                                                                         title->list_audio, ii );
2071                 // Find a track that is not visually impaired or dirctor's commentary
2072                 if ((audio->lang.type < 2) &&
2073                         ((strcmp(lang, audio->lang.iso639_2) == 0) ||
2074                         (strcmp(lang, "und") == 0)))
2075                 {
2076                         track = ii;
2077                         break;
2078                 }
2079         }
2080         if (track > -1)
2081         {
2082                 used[track] = TRUE;
2083                 return track;
2084         }
2085         // Try to fine an item that does not match the preferred language and
2086         // matches the passthru codec type
2087         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
2088         {
2089                 for (ii = 0; ii < count; ii++)
2090                 {
2091                         gint channels;
2092
2093                         if (used[ii])
2094                                 continue;
2095
2096                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2097                                                                                                         title->list_audio, ii );
2098                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2099                                                                                                         audio->in.channel_layout);
2100                         // Find a track that is not visually impaired or dirctor's
2101                         // commentary, and has the highest channel count.
2102                         if ((audio->in.codec & acodec) &&
2103                                 (audio->lang.type < 2))
2104                         {
2105                                 if (channels > max_chan)
2106                                 {
2107                                         track = ii;
2108                                         max_chan = channels;
2109                                 }
2110                         }
2111                 }
2112         }
2113         if (track > -1)
2114         {
2115                 used[track] = TRUE;
2116                 return track;
2117         }
2118         // Try to fine an item that does not match the preferred language
2119         for (ii = 0; ii < count; ii++)
2120         {
2121                 if (used[ii])
2122                         continue;
2123         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2124                                                                                                         title->list_audio, ii );
2125                 // Find a track that is not visually impaired or dirctor's commentary
2126                 if (audio->lang.type < 2)
2127                 {
2128                         track = ii;
2129                         break;
2130                 }
2131         }
2132         if (track > -1)
2133         {
2134                 used[track] = TRUE;
2135                 return track;
2136         }
2137         // Last ditch, anything goes
2138         for (ii = 0; ii < count; ii++)
2139         {
2140         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2141                                                                                                         title->list_audio, ii );
2142                 if (!used[ii])
2143                 {
2144                         track = ii;
2145                         break;
2146                 }
2147         }
2148         if (track > -1)
2149         {
2150                 used[track] = TRUE;
2151         }
2152         return track;
2153 }
2154
2155 gint
2156 ghb_find_pref_subtitle_track(const gchar *lang)
2157 {
2158         gint ii, count;
2159         count = subtitle_opts.count;
2160         for (ii = 0; ii < count; ii++)
2161         {
2162                 if (strcmp(lang, subtitle_opts.map[ii].svalue) == 0)
2163                 {
2164                         return subtitle_opts.map[ii].ivalue;
2165                 }
2166         }
2167         return -2;
2168 }
2169
2170 gint
2171 ghb_find_cc_track(gint titleindex)
2172 {
2173         hb_list_t  * list;
2174         hb_title_t * title;
2175         hb_subtitle_t * subtitle;
2176         gint count, ii;
2177         
2178         g_debug("ghb_find_cc_track ()\n");
2179         if (h_scan == NULL) return -2;
2180         list = hb_get_titles( h_scan );
2181         title = (hb_title_t*)hb_list_item( list, titleindex );
2182         if (title != NULL)
2183         {
2184                 count = hb_list_count( title->list_subtitle );
2185                 // Try to find an item that matches the preferred language
2186                 for (ii = 0; ii < count; ii++)
2187                 {
2188                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2189                         if (subtitle->source == CC608SUB || subtitle->source == CC708SUB)
2190                                 return ii;
2191                 }
2192         }
2193         return -2;
2194 }
2195
2196 gint
2197 ghb_find_subtitle_track(
2198         gint titleindex, 
2199         const gchar *lang, 
2200         GHashTable *track_indices)
2201 {
2202         hb_list_t  * list;
2203         hb_title_t * title;
2204         hb_subtitle_t * subtitle;
2205         gint count, ii;
2206         gboolean *used;
2207         
2208         g_debug("find_subtitle_track ()\n");
2209         if (strcmp(lang, "auto") == 0)
2210                 return -1;
2211         if (h_scan == NULL) return -1;
2212         list = hb_get_titles( h_scan );
2213         title = (hb_title_t*)hb_list_item( list, titleindex );
2214         if (title != NULL)
2215         {
2216                 count = hb_list_count( title->list_subtitle );
2217                 used = g_hash_table_lookup(track_indices, lang);
2218                 if (used == NULL)
2219                 {
2220                         used = g_malloc0(count * sizeof(gboolean));
2221                         g_hash_table_insert(track_indices, g_strdup(lang), used);
2222                 }
2223                 // Try to find an item that matches the preferred language
2224                 for (ii = 0; ii < count; ii++)
2225                 {
2226                         if (used[ii])
2227                                 continue;
2228
2229                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2230                         if ((strcmp(lang, subtitle->iso639_2) == 0) ||
2231                                 (strcmp(lang, "und") == 0))
2232                         {
2233                                 used[ii] = TRUE;
2234                                 return ii;
2235                         }
2236                 }
2237         }
2238         return -2;
2239 }
2240
2241 static void
2242 generic_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
2243 {
2244         GtkTreeIter iter;
2245         GtkListStore *store;
2246         gint ii;
2247         
2248         g_debug("generic_opts_set ()\n");
2249         if (name == NULL || opts == NULL) return;
2250         store = get_combo_box_store(builder, name);
2251         gtk_list_store_clear(store);
2252         for (ii = 0; ii < opts->count; ii++)
2253         {
2254                 gtk_list_store_append(store, &iter);
2255                 gtk_list_store_set(store, &iter, 
2256                                                    0, opts->map[ii].option, 
2257                                                    1, TRUE, 
2258                                                    2, opts->map[ii].shortOpt, 
2259                                                    3, opts->map[ii].ivalue, 
2260                                                    4, opts->map[ii].svalue, 
2261                                                    -1);
2262         }
2263 }
2264
2265 combo_opts_t*
2266 find_combo_table(const gchar *name)
2267 {
2268         gint ii;
2269
2270         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2271         {
2272                 if (strcmp(name, combo_name_map[ii].name) == 0)
2273                 {
2274                         return combo_name_map[ii].opts;
2275                 }
2276         }
2277         return NULL;
2278 }
2279
2280 gint
2281 ghb_lookup_combo_int(const gchar *name, const GValue *gval)
2282 {
2283         if (gval == NULL)
2284                 return 0;
2285         if (strcmp(name, "AudioBitrate") == 0)
2286                 return lookup_audio_bitrate_int(gval);
2287         else if (strcmp(name, "AudioSamplerate") == 0)
2288                 return lookup_audio_rate_int(gval);
2289         else if (strcmp(name, "VideoFramerate") == 0)
2290                 return lookup_video_rate_int(gval);
2291         else if (strcmp(name, "AudioMixdown") == 0)
2292                 return lookup_mix_int(gval);
2293         else if (strcmp(name, "SrtLanguage") == 0)
2294                 return lookup_audio_lang_int(gval);
2295         else if (strcmp(name, "PreferredLanguage") == 0)
2296                 return lookup_audio_lang_int(gval);
2297         else
2298         {
2299                 return lookup_generic_int(find_combo_table(name), gval);
2300         }
2301         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2302         return 0;
2303 }
2304
2305 gdouble
2306 ghb_lookup_combo_double(const gchar *name, const GValue *gval)
2307 {
2308         if (gval == NULL)
2309                 return 0;
2310         if (strcmp(name, "AudioBitrate") == 0)
2311                 return lookup_audio_bitrate_int(gval);
2312         else if (strcmp(name, "AudioSamplerate") == 0)
2313                 return lookup_audio_rate_int(gval);
2314         else if (strcmp(name, "VideoFramerate") == 0)
2315                 return lookup_video_rate_int(gval);
2316         else if (strcmp(name, "AudioMixdown") == 0)
2317                 return lookup_mix_int(gval);
2318         else if (strcmp(name, "SrtLanguage") == 0)
2319                 return lookup_audio_lang_int(gval);
2320         else if (strcmp(name, "PreferredLanguage") == 0)
2321                 return lookup_audio_lang_int(gval);
2322         else
2323         {
2324                 return lookup_generic_double(find_combo_table(name), gval);
2325         }
2326         g_warning("ghb_lookup_combo_double() couldn't find %s", name);
2327         return 0;
2328 }
2329
2330 const gchar*
2331 ghb_lookup_combo_option(const gchar *name, const GValue *gval)
2332 {
2333         if (gval == NULL)
2334                 return NULL;
2335         if (strcmp(name, "AudioBitrate") == 0)
2336                 return lookup_audio_bitrate_option(gval);
2337         else if (strcmp(name, "AudioSamplerate") == 0)
2338                 return lookup_audio_rate_option(gval);
2339         else if (strcmp(name, "VideoFramerate") == 0)
2340                 return lookup_video_rate_option(gval);
2341         else if (strcmp(name, "AudioMixdown") == 0)
2342                 return lookup_mix_option(gval);
2343         else if (strcmp(name, "SrtLanguage") == 0)
2344                 return lookup_audio_lang_option(gval);
2345         else if (strcmp(name, "PreferredLanguage") == 0)
2346                 return lookup_audio_lang_option(gval);
2347         else
2348         {
2349                 return lookup_generic_option(find_combo_table(name), gval);
2350         }
2351         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2352         return NULL;
2353 }
2354
2355 const gchar*
2356 ghb_lookup_combo_string(const gchar *name, const GValue *gval)
2357 {
2358         if (gval == NULL)
2359                 return NULL;
2360         if (strcmp(name, "AudioBitrate") == 0)
2361                 return lookup_audio_bitrate_option(gval);
2362         else if (strcmp(name, "AudioSamplerate") == 0)
2363                 return lookup_audio_rate_option(gval);
2364         else if (strcmp(name, "VideoFramerate") == 0)
2365                 return lookup_video_rate_option(gval);
2366         else if (strcmp(name, "AudioMixdown") == 0)
2367                 return lookup_mix_option(gval);
2368         else if (strcmp(name, "SrtLanguage") == 0)
2369                 return lookup_audio_lang_option(gval);
2370         else if (strcmp(name, "PreferredLanguage") == 0)
2371                 return lookup_audio_lang_option(gval);
2372         else
2373         {
2374                 return lookup_generic_string(find_combo_table(name), gval);
2375         }
2376         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2377         return NULL;
2378 }
2379
2380 void
2381 ghb_update_ui_combo_box(
2382         signal_user_data_t *ud, 
2383         const gchar *name, 
2384         gint user_data, 
2385         gboolean all)
2386 {
2387         GtkComboBox *combo = NULL;
2388         gint signal_id;
2389         gint handler_id = 0;
2390
2391         if (name != NULL)
2392         {               
2393                 g_debug("ghb_update_ui_combo_box() %s\n", name);
2394                 // Clearing a combo box causes a rash of "changed" events, even when
2395                 // the active item is -1 (inactive).  To control things, I'm disabling
2396                 // the event till things are settled down.
2397                 combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, name));
2398                 signal_id = g_signal_lookup("changed", GTK_TYPE_COMBO_BOX);
2399                 if (signal_id > 0)
2400                 {
2401                         // Valid signal id found.  This should always succeed.
2402                         handler_id = g_signal_handler_find ((gpointer)combo, G_SIGNAL_MATCH_ID, 
2403                                                                                                 signal_id, 0, 0, 0, 0);
2404                         if (handler_id > 0)
2405                         {
2406                                 // This should also always succeed
2407                                 g_signal_handler_block ((gpointer)combo, handler_id);
2408                         }
2409                 }
2410         }       
2411         if (all)
2412         {
2413                 audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2414                 audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2415                 video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2416                 mix_opts_set(ud->builder, "AudioMixdown");
2417                 language_opts_set(ud->builder, "SrtLanguage");
2418                 language_opts_set(ud->builder, "PreferredLanguage");
2419                 srt_codeset_opts_set(ud->builder, "SrtCodeset");
2420                 title_opts_set(ud->builder, "title");
2421                 audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2422                 subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2423                 generic_opts_set(ud->builder, "VideoQualityGranularity", &vqual_granularity_opts);
2424                 generic_opts_set(ud->builder, "WhenComplete", &when_complete_opts);
2425                 generic_opts_set(ud->builder, "PicturePAR", &par_opts);
2426                 generic_opts_set(ud->builder, "PictureModulus", &alignment_opts);
2427                 generic_opts_set(ud->builder, "LoggingLevel", &logging_opts);
2428                 generic_opts_set(ud->builder, "LogLongevity", &log_longevity_opts);
2429                 generic_opts_set(ud->builder, "check_updates", &appcast_update_opts);
2430                 generic_opts_set(ud->builder, "FileFormat", &container_opts);
2431                 generic_opts_set(ud->builder, "PictureDeinterlace", &deint_opts);
2432                 generic_opts_set(ud->builder, "PictureDetelecine", &detel_opts);
2433                 generic_opts_set(ud->builder, "PictureDecomb", &decomb_opts);
2434                 generic_opts_set(ud->builder, "PictureDenoise", &denoise_opts);
2435                 generic_opts_set(ud->builder, "VideoEncoder", &vcodec_opts);
2436                 generic_opts_set(ud->builder, "AudioEncoder", &acodec_opts);
2437                 generic_opts_set(ud->builder, "x264_direct", &direct_opts);
2438                 generic_opts_set(ud->builder, "x264_b_adapt", &badapt_opts);
2439                 generic_opts_set(ud->builder, "x264_me", &me_opts);
2440                 generic_opts_set(ud->builder, "x264_subme", &subme_opts);
2441                 generic_opts_set(ud->builder, "x264_analyse", &analyse_opts);
2442                 generic_opts_set(ud->builder, "x264_trellis", &trellis_opts);
2443         }
2444         else
2445         {
2446                 if (strcmp(name, "AudioBitrate") == 0)
2447                         audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2448                 else if (strcmp(name, "AudioSamplerate") == 0)
2449                         audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2450                 else if (strcmp(name, "VideoFramerate") == 0)
2451                         video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2452                 else if (strcmp(name, "AudioMixdown") == 0)
2453                         mix_opts_set(ud->builder, "AudioMixdown");
2454                 else if (strcmp(name, "SrtLanguage") == 0)
2455                         language_opts_set(ud->builder, "SrtLanguage");
2456                 else if (strcmp(name, "PreferredLanguage") == 0)
2457                         language_opts_set(ud->builder, "PreferredLanguage");
2458                 else if (strcmp(name, "SrtCodeset") == 0)
2459                         srt_codeset_opts_set(ud->builder, "SrtCodeset");
2460                 else if (strcmp(name, "title") == 0)
2461                         title_opts_set(ud->builder, "title");
2462                 else if (strcmp(name, "SubtitleTrack") == 0)
2463                         subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2464                 else if (strcmp(name, "AudioTrack") == 0)
2465                         audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2466                 else
2467                         generic_opts_set(ud->builder, name, find_combo_table(name));
2468         }
2469         if (handler_id > 0)
2470         {
2471                 g_signal_handler_unblock ((gpointer)combo, handler_id);
2472         }
2473 }
2474         
2475 static void
2476 init_ui_combo_boxes(GtkBuilder *builder)
2477 {
2478         gint ii;
2479
2480         init_combo_box(builder, "AudioBitrate");
2481         init_combo_box(builder, "AudioSamplerate");
2482         init_combo_box(builder, "VideoFramerate");
2483         init_combo_box(builder, "AudioMixdown");
2484         init_combo_box(builder, "SrtLanguage");
2485         init_combo_box(builder, "PreferredLanguage");
2486         init_combo_box(builder, "SrtCodeset");
2487         init_combo_box(builder, "title");
2488         init_combo_box(builder, "AudioTrack");
2489         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2490         {
2491                 init_combo_box(builder, combo_name_map[ii].name);
2492         }
2493 }
2494         
2495 static const char * turbo_opts = 
2496         "ref=1:subme=1:me=dia:analyse=none:trellis=0:"
2497         "no-fast-pskip=0:8x8dct=0";
2498
2499 // Construct the x264 options string
2500 // The result is allocated, so someone must free it at some point.
2501 gchar*
2502 ghb_build_x264opts_string(GValue *settings)
2503 {
2504         gchar *result;
2505         gchar *opts = ghb_settings_get_string(settings, "x264Option");
2506         if (opts != NULL)
2507         {
2508                 result = opts;
2509         }
2510         else
2511         {
2512                 result = g_strdup("");
2513         }
2514         return result;
2515 }
2516
2517 void
2518 ghb_get_chapter_duration(gint ti, gint ii, gint *hh, gint *mm, gint *ss)
2519 {
2520         hb_list_t  * list;
2521         hb_title_t * title;
2522     hb_chapter_t * chapter;
2523         gint count;
2524         
2525         g_debug("ghb_get_chapter_duration (title = %d)\n", ti);
2526         *hh = *mm = *ss = 0;
2527         if (h_scan == NULL) return;
2528         list = hb_get_titles( h_scan );
2529     title = (hb_title_t*)hb_list_item( list, ti );
2530         if (title == NULL) return;
2531         count = hb_list_count( title->list_chapter );
2532         if (ii >= count) return;
2533         chapter = hb_list_item(title->list_chapter, ii);
2534         if (chapter == NULL) return;
2535         *hh = chapter->hours;
2536         *mm = chapter->minutes;
2537         *ss = chapter->seconds;
2538 }
2539
2540 GValue*
2541 ghb_get_chapters(gint titleindex)
2542 {
2543         hb_list_t  * list;
2544         hb_title_t * title;
2545     hb_chapter_t * chapter;
2546         gint count, ii;
2547         GValue *chapters = NULL;
2548         
2549         g_debug("ghb_get_chapters (title = %d)\n", titleindex);
2550         if (h_scan == NULL) return NULL;
2551         list = hb_get_titles( h_scan );
2552     title = (hb_title_t*)hb_list_item( list, titleindex );
2553         if (title == NULL) return NULL;
2554         count = hb_list_count( title->list_chapter );
2555         chapters = ghb_array_value_new(count);
2556         for (ii = 0; ii < count; ii++)
2557         {
2558                 chapter = hb_list_item(title->list_chapter, ii);
2559                 if (chapter == NULL) break;
2560                 if (chapter->title == NULL || chapter->title[0] == 0)
2561                 {
2562                         gchar *str;
2563                         str = g_strdup_printf ("Chapter %2d", ii+1);
2564                         ghb_array_append(chapters, ghb_string_value_new(str));
2565                         g_free(str);
2566                 }
2567                 else 
2568                 {
2569                         ghb_array_append(chapters, ghb_string_value_new(chapter->title));
2570                 }
2571         }
2572         return chapters;
2573 }
2574
2575 gboolean
2576 ghb_ac3_in_audio_list(const GValue *audio_list)
2577 {
2578         gint count, ii;
2579
2580         count = ghb_array_len(audio_list);
2581         for (ii = 0; ii < count; ii++)
2582         {
2583                 GValue *asettings;
2584                 gint acodec;
2585
2586                 asettings = ghb_array_get_nth(audio_list, ii);
2587                 acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
2588                 if (acodec & HB_ACODEC_AC3)
2589                         return TRUE;
2590         }
2591         return FALSE;
2592 }
2593
2594 static void
2595 audio_bitrate_opts_add(GtkBuilder *builder, const gchar *name, gint rate)
2596 {
2597         GtkTreeIter iter;
2598         GtkListStore *store;
2599         gchar *str;
2600         
2601         g_debug("audio_rate_opts_add ()\n");
2602         store = get_combo_box_store(builder, name);
2603         if (!find_combo_item_by_int(GTK_TREE_MODEL(store), rate, &iter))
2604         {
2605                 str = g_strdup_printf ("%d", rate);
2606                 gtk_list_store_append(store, &iter);
2607                 gtk_list_store_set(store, &iter, 
2608                                                    0, str, 
2609                                                    1, TRUE, 
2610                                                    2, str, 
2611                                                    3, (gdouble)rate, 
2612                                                    4, str, 
2613                                                    -1);
2614                 g_free(str);
2615         }
2616 }
2617
2618 static void
2619 audio_bitrate_opts_clean(GtkBuilder *builder, const gchar *name, gint last_rate)
2620 {
2621         GtkTreeIter iter;
2622         GtkListStore *store;
2623         gdouble ivalue;
2624         gboolean done = FALSE;
2625         gint ii = 0;
2626         guint last = (guint)last_rate;
2627         
2628         g_debug("audio_bitrate_opts_clean ()\n");
2629         store = get_combo_box_store(builder, name);
2630         if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL(store), &iter))
2631         {
2632                 do
2633                 {
2634                         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 3, &ivalue, -1);
2635                         if (search_rates(
2636                                 hb_audio_bitrates, ivalue, hb_audio_bitrates_count) < 0)
2637                         {
2638                                 done = !gtk_list_store_remove(store, &iter);
2639                         }
2640                         else if (ivalue > last)
2641                         {
2642                                 ii++;
2643                                 gtk_list_store_set(store, &iter, 1, FALSE, -1);
2644                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2645                         }
2646                         else
2647                         {
2648                                 ii++;
2649                                 gtk_list_store_set(store, &iter, 1, TRUE, -1);
2650                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2651                         }
2652                 } while (!done);
2653         }
2654 }
2655
2656 static void
2657 audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name)
2658 {
2659         GtkTreeIter iter;
2660         GtkListStore *store;
2661         gint ii;
2662         
2663         g_debug("audio_bitrate_opts_set ()\n");
2664         store = get_combo_box_store(builder, name);
2665         gtk_list_store_clear(store);
2666         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
2667         {
2668                 gtk_list_store_append(store, &iter);
2669                 gtk_list_store_set(store, &iter, 
2670                                                    0, hb_audio_bitrates[ii].string, 
2671                                                    1, TRUE, 
2672                                                    2, hb_audio_bitrates[ii].string, 
2673                                                    3, (gdouble)hb_audio_bitrates[ii].rate, 
2674                                                    4, hb_audio_bitrates[ii].string, 
2675                                                    -1);
2676         }
2677 }
2678
2679 void
2680 ghb_set_passthru_bitrate_opts(GtkBuilder *builder, gint bitrate)
2681 {
2682         audio_bitrate_opts_add(builder, "AudioBitrate", bitrate);
2683 }
2684
2685 void
2686 ghb_set_default_bitrate_opts(GtkBuilder *builder, gint last_rate)
2687 {
2688         audio_bitrate_opts_clean(builder, "AudioBitrate", last_rate);
2689 }
2690
2691 static ghb_status_t hb_status;
2692
2693 void
2694 ghb_combo_init(signal_user_data_t *ud)
2695 {
2696         // Set up the list model for the combos
2697         init_ui_combo_boxes(ud->builder);
2698         // Populate all the combos
2699         ghb_update_ui_combo_box(ud, NULL, 0, TRUE);
2700 }
2701
2702 void
2703 ghb_backend_init(gint debug)
2704 {
2705     /* Init libhb */
2706     h_scan = hb_init( debug, 0 );
2707     h_queue = hb_init( debug, 0 );
2708 }
2709
2710 void
2711 ghb_backend_close()
2712 {
2713         hb_close(&h_queue);
2714         hb_close(&h_scan);
2715 }
2716
2717 void
2718 ghb_backend_scan(const gchar *path, gint titleindex, gint preview_count)
2719 {
2720     hb_scan( h_scan, path, titleindex, preview_count, 1 );
2721         hb_status.scan.state |= GHB_STATE_SCANNING;
2722         // initialize count and cur to something that won't cause FPE
2723         // when computing progress
2724         hb_status.scan.title_count = 1;
2725         hb_status.scan.title_cur = 0;
2726 }
2727
2728 void
2729 ghb_backend_queue_scan(const gchar *path, gint titlenum)
2730 {
2731         g_debug("ghb_backend_queue_scan()");
2732         hb_scan( h_queue, path, titlenum, 10, 0 );
2733         hb_status.queue.state |= GHB_STATE_SCANNING;
2734 }
2735
2736 gint
2737 ghb_get_scan_state()
2738 {
2739         return hb_status.scan.state;
2740 }
2741
2742 gint
2743 ghb_get_queue_state()
2744 {
2745         return hb_status.queue.state;
2746 }
2747
2748 void
2749 ghb_clear_scan_state(gint state)
2750 {
2751         hb_status.scan.state &= ~state;
2752 }
2753
2754 void
2755 ghb_clear_queue_state(gint state)
2756 {
2757         hb_status.queue.state &= ~state;
2758 }
2759
2760 void
2761 ghb_set_scan_state(gint state)
2762 {
2763         hb_status.scan.state |= state;
2764 }
2765
2766 void
2767 ghb_set_queue_state(gint state)
2768 {
2769         hb_status.queue.state |= state;
2770 }
2771
2772 void
2773 ghb_get_status(ghb_status_t *status)
2774 {
2775         memcpy(status, &hb_status, sizeof(ghb_status_t));
2776 }
2777
2778 void 
2779 ghb_track_status()
2780 {
2781     hb_state_t s_scan;
2782     hb_state_t s_queue;
2783
2784         if (h_scan == NULL) return;
2785     hb_get_state( h_scan, &s_scan );
2786         switch( s_scan.state )
2787     {
2788 #define p s_scan.param.scanning
2789         case HB_STATE_SCANNING:
2790                 {
2791                         hb_status.scan.state |= GHB_STATE_SCANNING;
2792                         hb_status.scan.title_count = p.title_count;
2793                         hb_status.scan.title_cur = p.title_cur;
2794                 } break;
2795 #undef p
2796
2797         case HB_STATE_SCANDONE:
2798         {
2799                         hb_status.scan.state &= ~GHB_STATE_SCANNING;
2800                         hb_status.scan.state |= GHB_STATE_SCANDONE;
2801         } break;
2802
2803 #define p s_scan.param.working
2804         case HB_STATE_WORKING:
2805                         hb_status.scan.state |= GHB_STATE_WORKING;
2806                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
2807                         hb_status.scan.job_cur = p.job_cur;
2808                         hb_status.scan.job_count = p.job_count;
2809                         hb_status.scan.progress = p.progress;
2810                         hb_status.scan.rate_cur = p.rate_cur;
2811                         hb_status.scan.rate_avg = p.rate_avg;
2812                         hb_status.scan.hours = p.hours;
2813                         hb_status.scan.minutes = p.minutes;
2814                         hb_status.scan.seconds = p.seconds;
2815                         hb_status.scan.unique_id = p.sequence_id & 0xFFFFFF;
2816             break;
2817 #undef p
2818
2819         case HB_STATE_PAUSED:
2820                         hb_status.scan.state |= GHB_STATE_PAUSED;
2821             break;
2822                                 
2823         case HB_STATE_MUXING:
2824         {
2825                         hb_status.scan.state |= GHB_STATE_MUXING;
2826         } break;
2827
2828 #define p s_scan.param.workdone
2829         case HB_STATE_WORKDONE:
2830                 {
2831             hb_job_t *job;
2832
2833                         hb_status.scan.state |= GHB_STATE_WORKDONE;
2834                         hb_status.scan.state &= ~GHB_STATE_MUXING;
2835                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
2836                         hb_status.scan.state &= ~GHB_STATE_WORKING;
2837                         switch (p.error)
2838                         {
2839                         case HB_ERROR_NONE:
2840                                 hb_status.scan.error = GHB_ERROR_NONE;
2841                                 break;
2842                         case HB_ERROR_CANCELED:
2843                                 hb_status.scan.error = GHB_ERROR_CANCELED;
2844                                 break;
2845                         default:
2846                                 hb_status.scan.error = GHB_ERROR_FAIL;
2847                                 break;
2848                         }
2849                         // Delete all remaining jobs of this encode.
2850                         // An encode can be composed of multiple associated jobs.
2851                         // When a job is stopped, libhb removes it from the job list,
2852                         // but does not remove other jobs that may be associated with it.
2853                         // Associated jobs are taged in the sequence id.
2854             while ((job = hb_job(h_scan, 0)) != NULL) 
2855                 hb_rem( h_scan, job );
2856                 } break;
2857 #undef p
2858     }
2859     hb_get_state( h_queue, &s_queue );
2860         switch( s_queue.state )
2861     {
2862 #define p s_queue.param.scanning
2863         case HB_STATE_SCANNING:
2864                 {
2865                         hb_status.queue.state |= GHB_STATE_SCANNING;
2866                         hb_status.queue.title_count = p.title_count;
2867                         hb_status.queue.title_cur = p.title_cur;
2868                 } break;
2869 #undef p
2870
2871         case HB_STATE_SCANDONE:
2872         {
2873                         hb_status.queue.state &= ~GHB_STATE_SCANNING;
2874                         hb_status.queue.state |= GHB_STATE_SCANDONE;
2875         } break;
2876
2877 #define p s_queue.param.working
2878         case HB_STATE_WORKING:
2879                         hb_status.queue.state |= GHB_STATE_WORKING;
2880                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
2881                         hb_status.queue.job_cur = p.job_cur;
2882                         hb_status.queue.job_count = p.job_count;
2883                         hb_status.queue.progress = p.progress;
2884                         hb_status.queue.rate_cur = p.rate_cur;
2885                         hb_status.queue.rate_avg = p.rate_avg;
2886                         hb_status.queue.hours = p.hours;
2887                         hb_status.queue.minutes = p.minutes;
2888                         hb_status.queue.seconds = p.seconds;
2889                         hb_status.queue.unique_id = p.sequence_id & 0xFFFFFF;
2890             break;
2891 #undef p
2892
2893         case HB_STATE_PAUSED:
2894                         hb_status.queue.state |= GHB_STATE_PAUSED;
2895             break;
2896                                 
2897         case HB_STATE_MUXING:
2898         {
2899                         hb_status.queue.state |= GHB_STATE_MUXING;
2900         } break;
2901
2902 #define p s_queue.param.workdone
2903         case HB_STATE_WORKDONE:
2904                 {
2905             hb_job_t *job;
2906
2907                         hb_status.queue.state |= GHB_STATE_WORKDONE;
2908                         hb_status.queue.state &= ~GHB_STATE_MUXING;
2909                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
2910                         hb_status.queue.state &= ~GHB_STATE_WORKING;
2911                         switch (p.error)
2912                         {
2913                         case HB_ERROR_NONE:
2914                                 hb_status.queue.error = GHB_ERROR_NONE;
2915                                 break;
2916                         case HB_ERROR_CANCELED:
2917                                 hb_status.queue.error = GHB_ERROR_CANCELED;
2918                                 break;
2919                         default:
2920                                 hb_status.queue.error = GHB_ERROR_FAIL;
2921                                 break;
2922                         }
2923                         // Delete all remaining jobs of this encode.
2924                         // An encode can be composed of multiple associated jobs.
2925                         // When a job is stopped, libhb removes it from the job list,
2926                         // but does not remove other jobs that may be associated with it.
2927                         // Associated jobs are taged in the sequence id.
2928             while ((job = hb_job(h_queue, 0)) != NULL) 
2929                 hb_rem( h_queue, job );
2930                 } break;
2931 #undef p
2932     }
2933 }
2934
2935 gboolean
2936 ghb_get_title_info(ghb_title_info_t *tinfo, gint titleindex)
2937 {
2938         hb_list_t  * list;
2939         hb_title_t * title;
2940         
2941     if (h_scan == NULL) return FALSE;
2942         list = hb_get_titles( h_scan );
2943         if( !hb_list_count( list ) )
2944         {
2945                 /* No valid title, stop right there */
2946                 return FALSE;
2947         }
2948
2949     title = hb_list_item( list, titleindex );
2950         if (title == NULL) return FALSE;        // Bad titleindex
2951         tinfo->width = title->width;
2952         tinfo->height = title->height;
2953         memcpy(tinfo->crop, title->crop, 4 * sizeof(int));
2954         // Don't allow crop to 0
2955         if (title->crop[0] + title->crop[1] >= title->height)
2956                 title->crop[0] = title->crop[1] = 0;
2957         if (title->crop[2] + title->crop[3] >= title->width)
2958                 title->crop[2] = title->crop[3] = 0;
2959         tinfo->num_chapters = hb_list_count(title->list_chapter);
2960         tinfo->rate_base = title->rate_base;
2961         tinfo->rate = title->rate;
2962         hb_reduce(&(tinfo->aspect_n), &(tinfo->aspect_d), 
2963                                 title->width * title->pixel_aspect_width, 
2964                                 title->height * title->pixel_aspect_height);
2965         tinfo->hours = title->hours;
2966         tinfo->minutes = title->minutes;
2967         tinfo->seconds = title->seconds;
2968         tinfo->duration = title->duration;
2969
2970         tinfo->angle_count = title->angle_count;
2971         return TRUE;
2972 }
2973
2974 gboolean
2975 ghb_get_audio_info(ghb_audio_info_t *ainfo, gint titleindex, gint audioindex)
2976 {
2977     hb_audio_config_t *audio;
2978         
2979         audio = get_hb_audio(titleindex, audioindex);
2980         if (audio == NULL) return FALSE; // Bad audioindex
2981         ainfo->codec = audio->in.codec;
2982         ainfo->bitrate = audio->in.bitrate;
2983         ainfo->samplerate = audio->in.samplerate;
2984         return TRUE;
2985 }
2986
2987 gboolean
2988 ghb_audio_is_passthru(gint acodec)
2989 {
2990         g_debug("ghb_audio_is_passthru () \n");
2991         return (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA));
2992 }
2993
2994 gint
2995 ghb_get_default_acodec()
2996 {
2997         return HB_ACODEC_FAAC;
2998 }
2999
3000 static void
3001 picture_settings_deps(signal_user_data_t *ud)
3002 {
3003         gboolean autoscale, keep_aspect, enable_keep_aspect;
3004         gboolean enable_scale_width, enable_scale_height;
3005         gboolean enable_disp_width, enable_disp_height, enable_par;
3006         gint pic_par;
3007         GtkWidget *widget;
3008
3009         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
3010         if (pic_par == 1)
3011         {
3012                 ghb_ui_update(ud, "autoscale", ghb_boolean_value(TRUE));
3013                 ghb_ui_update(ud, "PictureModulus", ghb_int_value(2));
3014                 ghb_ui_update(ud, "PictureLooseCrop", ghb_boolean_value(TRUE));
3015         }
3016         enable_keep_aspect = (pic_par != 1 && pic_par != 2);
3017         if (!enable_keep_aspect)
3018         {
3019                 ghb_ui_update(ud, "PictureKeepRatio", ghb_boolean_value(TRUE));
3020         }
3021         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
3022         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
3023
3024         enable_scale_width = !autoscale && (pic_par != 1);
3025         enable_scale_height = !autoscale && (pic_par != 1);
3026         enable_disp_width = (pic_par == 3) && !keep_aspect;
3027         enable_par = (pic_par == 3) && !keep_aspect;
3028         enable_disp_height = FALSE;
3029
3030         widget = GHB_WIDGET(ud->builder, "PictureModulus");
3031         gtk_widget_set_sensitive(widget, pic_par != 1);
3032         widget = GHB_WIDGET(ud->builder, "PictureLooseCrop");
3033         gtk_widget_set_sensitive(widget, pic_par != 1);
3034         widget = GHB_WIDGET(ud->builder, "scale_width");
3035         gtk_widget_set_sensitive(widget, enable_scale_width);
3036         widget = GHB_WIDGET(ud->builder, "scale_height");
3037         gtk_widget_set_sensitive(widget, enable_scale_height);
3038         widget = GHB_WIDGET(ud->builder, "PictureDisplayWidth");
3039         gtk_widget_set_sensitive(widget, enable_disp_width);
3040         widget = GHB_WIDGET(ud->builder, "PictureDisplayHeight");
3041         gtk_widget_set_sensitive(widget, enable_disp_height);
3042         widget = GHB_WIDGET(ud->builder, "PicturePARWidth");
3043         gtk_widget_set_sensitive(widget, enable_par);
3044         widget = GHB_WIDGET(ud->builder, "PicturePARHeight");
3045         gtk_widget_set_sensitive(widget, enable_par);
3046         widget = GHB_WIDGET(ud->builder, "PictureKeepRatio");
3047         gtk_widget_set_sensitive(widget, enable_keep_aspect);
3048         widget = GHB_WIDGET(ud->builder, "autoscale");
3049         gtk_widget_set_sensitive(widget, pic_par != 1);
3050 }
3051
3052 void
3053 ghb_set_scale(signal_user_data_t *ud, gint mode)
3054 {
3055         hb_list_t  * list;
3056         hb_title_t * title;
3057         hb_job_t   * job;
3058         gboolean keep_aspect;
3059         gint pic_par;
3060         gboolean autocrop, autoscale, noscale;
3061         gint crop[4], width, height, par_width, par_height;
3062         gint crop_width, crop_height;
3063         gint aspect_n, aspect_d;
3064         gboolean keep_width = (mode & GHB_PIC_KEEP_WIDTH);
3065         gboolean keep_height = (mode & GHB_PIC_KEEP_HEIGHT);
3066         gint step;
3067         GtkWidget *widget;
3068         gint mod;
3069         gint max_width = 0;
3070         gint max_height = 0;
3071         static gboolean busy = FALSE;
3072         
3073         g_debug("ghb_set_scale ()\n");
3074         if (h_scan == NULL) return;
3075         list = hb_get_titles( h_scan );
3076         if( !hb_list_count( list ) )
3077         {
3078                 /* No valid title, stop right there */
3079                 return;
3080         }
3081         gint titleindex;
3082
3083         titleindex = ghb_settings_combo_int(ud->settings, "title");
3084     title = hb_list_item( list, titleindex );
3085         if (title == NULL) return;
3086         job   = title->job;
3087         if (job == NULL) return;
3088
3089         picture_settings_deps(ud);
3090         if (busy) return;
3091         busy = TRUE;
3092
3093         
3094         // First configure widgets
3095         mod = ghb_settings_combo_int(ud->settings, "PictureModulus");
3096         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
3097         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
3098         autocrop = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop");
3099         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
3100         // "Noscale" is a flag that says we prefer to crop extra to satisfy
3101         // alignment constraints rather than scaling to satisfy them.
3102         noscale = ghb_settings_get_boolean(ud->settings, "PictureLooseCrop");
3103         // Align dimensions to either 16 or 2 pixels
3104         // The scaler crashes if the dimensions are not divisible by 2
3105         // x264 also will not accept dims that are not multiple of 2
3106         if (autoscale)
3107         {
3108                 keep_width = FALSE;
3109                 keep_height = FALSE;
3110         }
3111         // Step needs to be at least 2 because odd widths cause scaler crash
3112         step = mod;
3113         widget = GHB_WIDGET (ud->builder, "scale_width");
3114         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3115         widget = GHB_WIDGET (ud->builder, "scale_height");
3116         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3117         if (noscale)
3118         {
3119                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3120                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3121                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3122                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3123                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3124                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3125                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3126                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3127         }
3128         else
3129         {
3130                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3131                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3132                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3133                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3134                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3135                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3136                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3137                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3138         }
3139         ghb_title_info_t tinfo;
3140         ghb_get_title_info (&tinfo, titleindex);
3141         if (autocrop)
3142         {
3143                 crop[0] = tinfo.crop[0];
3144                 crop[1] = tinfo.crop[1];
3145                 crop[2] = tinfo.crop[2];
3146                 crop[3] = tinfo.crop[3];
3147                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3148                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3149                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3150                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3151         }
3152         else
3153         {
3154                 crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
3155                 crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
3156                 crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
3157                 crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
3158         }
3159         if (noscale)
3160         {
3161                 gint need1, need2;
3162
3163                 // Adjust the cropping to accomplish the desired width and height
3164                 crop_width = tinfo.width - crop[2] - crop[3];
3165                 crop_height = tinfo.height - crop[0] - crop[1];
3166                 width = MOD_DOWN(crop_width, mod);
3167                 height = MOD_DOWN(crop_height, mod);
3168
3169                 need1 = (crop_height - height) / 2;
3170                 need2 = crop_height - height - need1;
3171                 crop[0] += need1;
3172                 crop[1] += need2;
3173                 need1 = (crop_width - width) / 2;
3174                 need2 = crop_width - width - need1;
3175                 crop[2] += need1;
3176                 crop[3] += need2;
3177                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3178                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3179                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3180                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3181         }
3182         hb_reduce(&aspect_n, &aspect_d, 
3183                                 title->width * title->pixel_aspect_width, 
3184                                 title->height * title->pixel_aspect_height);
3185         crop_width = title->width - crop[2] - crop[3];
3186         crop_height = title->height - crop[0] - crop[1];
3187         if (autoscale)
3188         {
3189                 width = crop_width;
3190                 height = crop_height;
3191         }
3192         else
3193         {
3194                 width = ghb_settings_get_int(ud->settings, "scale_width");
3195                 height = ghb_settings_get_int(ud->settings, "scale_height");
3196                 max_width = MOD_DOWN(
3197                         ghb_settings_get_int(ud->settings, "PictureWidth"), mod);
3198                 max_height = MOD_DOWN(
3199                         ghb_settings_get_int(ud->settings, "PictureHeight"), mod);
3200         }
3201         g_debug("max_width %d, max_height %d\n", max_width, max_height);
3202
3203         if (width < 16)
3204                 width = title->width - crop[2] - crop[3];
3205         if (height < 16)
3206                 height = title->height - crop[0] - crop[1];
3207
3208         width = MOD_ROUND(width, mod);
3209         height = MOD_ROUND(height, mod);
3210
3211         // Adjust dims according to max values
3212         if (max_height)
3213                 height = MIN(height, max_height);
3214         if (max_width)
3215                 width = MIN(width, max_width);
3216
3217         if (pic_par)
3218         {
3219                 job->anamorphic.mode = pic_par;
3220                 // The scaler crashes if the dimensions are not divisible by 2
3221                 // Align mod 2.  And so does something in x264_encoder_headers()
3222                 job->anamorphic.modulus = mod;
3223                 job->anamorphic.par_width = title->pixel_aspect_width;
3224                 job->anamorphic.par_height = title->pixel_aspect_height;
3225                 job->anamorphic.dar_width = 0;
3226                 job->anamorphic.dar_height = 0;
3227
3228                 if (keep_height && pic_par == 2)
3229                         width = ((double)height * crop_width / crop_height) + 0.5;
3230                 job->width = width;
3231                 job->height = height;
3232                 job->maxWidth = max_width;
3233                 job->maxHeight = max_height;
3234                 job->crop[0] = crop[0]; job->crop[1] = crop[1];
3235                 job->crop[2] = crop[2]; job->crop[3] = crop[3];
3236                 if (job->anamorphic.mode == 3 && !keep_aspect)
3237                 {
3238                         job->anamorphic.keep_display_aspect = 0;
3239                         if (mode & GHB_PIC_KEEP_PAR)
3240                         {
3241                                 job->anamorphic.par_width = 
3242                                         ghb_settings_get_int(ud->settings, "PicturePARWidth");
3243                                 job->anamorphic.par_height = 
3244                                         ghb_settings_get_int(ud->settings, "PicturePARHeight");
3245                         }
3246                         else
3247                         {
3248                                 job->anamorphic.dar_width = 
3249                                         ghb_settings_get_int(ud->settings, 
3250                                                                                 "PictureDisplayWidth");
3251                                 job->anamorphic.dar_height = height;
3252                         }
3253                 }
3254                 else
3255                 {
3256                         job->anamorphic.keep_display_aspect = 1;
3257                 }
3258                 hb_set_anamorphic_size( job, &width, &height, 
3259                                                                 &par_width, &par_height );
3260                 if (job->anamorphic.mode == 3 && !keep_aspect && 
3261                         mode & GHB_PIC_KEEP_PAR)
3262                 {
3263                         // hb_set_anamorphic_size reduces the par, which we
3264                         // don't want in this case because the user is
3265                         // explicitely specifying it.
3266                         par_width = ghb_settings_get_int(ud->settings, 
3267                                                                                         "PicturePARWidth");
3268                         par_height = ghb_settings_get_int(ud->settings, 
3269                                                                                                 "PicturePARHeight");
3270                 }
3271         }
3272         else 
3273         {
3274                 job->anamorphic.mode = pic_par;
3275                 if (keep_aspect)
3276                 {
3277                         gdouble par;
3278                         gint new_width, new_height;
3279                         
3280                         // Compute pixel aspect ration.  
3281                         par = (gdouble)(title->height * aspect_n) / (title->width * aspect_d);
3282                         // Must scale so that par becomes 1:1
3283                         // Try to keep largest dimension
3284                         new_height = (crop_height * ((gdouble)width/crop_width) / par);
3285                         new_width = (crop_width * ((gdouble)height/crop_height) * par);
3286
3287                         if (max_width && new_width > max_width)
3288                         {
3289                                 height = new_height;
3290                         }
3291                         else if (max_height && new_height > max_height)
3292                         {
3293                                 width = new_width;
3294                         }
3295                         else if (keep_width)
3296                         {
3297                                 height = new_height;
3298                         }
3299                         else if (keep_height)
3300                         {
3301                                 width = new_width;
3302                         }
3303                         else if (width > new_width)
3304                         {
3305                                 height = new_height;
3306                         }
3307                         else
3308                         {
3309                                 width = new_width;
3310                         }
3311                         g_debug("new w %d h %d\n", width, height);
3312                 }
3313                 width = MOD_ROUND(width, mod);
3314                 height = MOD_ROUND(height, mod);
3315                 if (max_height)
3316                         height = MIN(height, max_height);
3317                 if (max_width)
3318                         width = MIN(width, max_width);
3319                 par_width = par_height = 1;
3320         }
3321         ghb_ui_update(ud, "scale_width", ghb_int64_value(width));
3322         ghb_ui_update(ud, "scale_height", ghb_int64_value(height));
3323
3324         gint disp_width, dar_width, dar_height;
3325         gchar *str;
3326
3327         disp_width = (gdouble)(width * par_width / par_height) + 0.5;
3328         hb_reduce(&dar_width, &dar_height, disp_width, height);
3329                 
3330         gint iaspect = dar_width * 9 / dar_height;
3331         if (dar_width > 2 * dar_height)
3332         {
3333                 str = g_strdup_printf("%.2f : 1", (gdouble)dar_width / dar_height);
3334         }
3335         else if (iaspect <= 16 && iaspect >= 15)
3336         {
3337                 str = g_strdup_printf("%.2f : 9", (gdouble)dar_width * 9 / dar_height);
3338         }
3339         else if (iaspect <= 12 && iaspect >= 11)
3340         {
3341                 str = g_strdup_printf("%.2f : 3", (gdouble)dar_width * 3 / dar_height);
3342         }
3343         else
3344         {
3345                 str = g_strdup_printf("%d : %d", dar_width, dar_height);
3346         }
3347         ghb_ui_update(ud, "display_aspect", ghb_string_value(str));
3348         g_free(str);
3349         ghb_ui_update(ud, "PicturePARWidth", ghb_int64_value(par_width));
3350         ghb_ui_update(ud, "PicturePARHeight", ghb_int64_value(par_height));
3351         ghb_ui_update(ud, "PictureDisplayWidth", ghb_int64_value(disp_width));
3352         ghb_ui_update(ud, "PictureDisplayHeight", ghb_int64_value(height));
3353         busy = FALSE;
3354 }
3355
3356 static void
3357 set_preview_job_settings(hb_job_t *job, GValue *settings)
3358 {
3359         job->crop[0] = ghb_settings_get_int(settings, "PictureTopCrop");
3360         job->crop[1] = ghb_settings_get_int(settings, "PictureBottomCrop");
3361         job->crop[2] = ghb_settings_get_int(settings, "PictureLeftCrop");
3362         job->crop[3] = ghb_settings_get_int(settings, "PictureRightCrop");
3363
3364         job->anamorphic.mode = ghb_settings_combo_int(settings, "PicturePAR");
3365         job->anamorphic.modulus = 
3366                 ghb_settings_combo_int(settings, "PictureModulus");
3367         job->width = ghb_settings_get_int(settings, "scale_width");
3368         job->height = ghb_settings_get_int(settings, "scale_height");
3369         if (ghb_settings_get_boolean(settings, "show_crop"))
3370         {
3371                 gdouble xscale = (gdouble)job->width / 
3372                         (gdouble)(job->title->width - job->crop[2] - job->crop[3]);
3373                 gdouble yscale = (gdouble)job->height / 
3374                         (gdouble)(job->title->height - job->crop[0] - job->crop[1]);
3375         
3376                 job->width += xscale * (job->crop[2] + job->crop[3]);
3377                 job->height += yscale * (job->crop[0] + job->crop[1]);
3378                 job->crop[0] = 0;
3379                 job->crop[1] = 0;
3380                 job->crop[2] = 0;
3381                 job->crop[3] = 0;
3382                 job->anamorphic.modulus = 2;
3383         }
3384
3385         gboolean decomb_deint = ghb_settings_get_boolean(settings, "PictureDecombDeinterlace");
3386         if (decomb_deint)
3387         {
3388                 gint decomb = ghb_settings_combo_int(settings, "PictureDecomb");
3389                 job->deinterlace = (decomb == 0) ? 0 : 1;
3390         }
3391         else
3392         {
3393                 gint deint = ghb_settings_combo_int(settings, "PictureDeinterlace");
3394                 job->deinterlace = (deint == 0) ? 0 : 1;
3395         }
3396
3397         gboolean keep_aspect;
3398         keep_aspect = ghb_settings_get_boolean(settings, "PictureKeepRatio");
3399         if (job->anamorphic.mode)
3400         {
3401                 job->anamorphic.par_width = job->title->pixel_aspect_width;
3402                 job->anamorphic.par_height = job->title->pixel_aspect_height;
3403                 job->anamorphic.dar_width = 0;
3404                 job->anamorphic.dar_height = 0;
3405
3406                 if (job->anamorphic.mode == 3 && !keep_aspect)
3407                 {
3408                         job->anamorphic.keep_display_aspect = 0;
3409                         job->anamorphic.par_width = 
3410                                 ghb_settings_get_int(settings, "PicturePARWidth");
3411                         job->anamorphic.par_height = 
3412                                 ghb_settings_get_int(settings, "PicturePARHeight");
3413                 }
3414                 else
3415                 {
3416                         job->anamorphic.keep_display_aspect = 1;
3417                 }
3418         }
3419 }
3420
3421 gint
3422 ghb_calculate_target_bitrate(GValue *settings, gint titleindex)
3423 {
3424         hb_list_t  * list;
3425         hb_title_t * title;
3426         hb_job_t   * job;
3427         gint size;
3428
3429         if (h_scan == NULL) return 1500;
3430         list = hb_get_titles( h_scan );
3431     title = hb_list_item( list, titleindex );
3432         if (title == NULL) return 1500;
3433         job   = title->job;
3434         if (job == NULL) return 1500;
3435         size = ghb_settings_get_int(settings, "VideoTargetSize");
3436         return hb_calc_bitrate( job, size );
3437 }
3438
3439 gboolean
3440 ghb_validate_filter_string(const gchar *str, gint max_fields)
3441 {
3442         gint fields = 0;
3443         gchar *end;
3444         gdouble val;
3445
3446         if (str == NULL || *str == 0) return TRUE;
3447         while (*str)
3448         {
3449                 val = g_strtod(str, &end);
3450                 if (str != end)
3451                 { // Found a numeric value
3452                         fields++;
3453                         // negative max_fields means infinate
3454                         if (max_fields >= 0 && fields > max_fields) return FALSE;
3455                         if (*end == 0)
3456                                 return TRUE;
3457                         if (*end != ':')
3458                                 return FALSE;
3459                         str = end + 1;
3460                 }
3461                 else
3462                         return FALSE;
3463         }
3464         return FALSE;
3465 }
3466
3467 gboolean
3468 ghb_validate_filters(signal_user_data_t *ud)
3469 {
3470         gchar *str;
3471         gint index;
3472         gchar *message;
3473
3474         gboolean decomb_deint = ghb_settings_get_boolean(ud->settings, "PictureDecombDeinterlace");
3475         // deinte
3476         index = ghb_settings_combo_int(ud->settings, "PictureDeinterlace");
3477         if (!decomb_deint && index == 1)
3478         {
3479                 str = ghb_settings_get_string(ud->settings, "PictureDeinterlaceCustom");
3480                 if (!ghb_validate_filter_string(str, 4))
3481                 {
3482                         message = g_strdup_printf(
3483                                                 "Invalid Deinterlace Settings:\n\n%s\n",
3484                                                 str);
3485                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3486                         g_free(message);
3487                         g_free(str);
3488                         return FALSE;
3489                 }
3490                 g_free(str);
3491         }
3492         // detel
3493         index = ghb_settings_combo_int(ud->settings, "PictureDetelecine");
3494         if (index == 1)
3495         {
3496                 str = ghb_settings_get_string(ud->settings, "PictureDetelecineCustom");
3497                 if (!ghb_validate_filter_string(str, 6))
3498                 {
3499                         message = g_strdup_printf(
3500                                                 "Invalid Detelecine 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         // decomb
3510         index = ghb_settings_combo_int(ud->settings, "PictureDecomb");
3511         if (decomb_deint && index == 1)
3512         {
3513                 str = ghb_settings_get_string(ud->settings, "PictureDecombCustom");
3514                 if (!ghb_validate_filter_string(str, 15))
3515                 {
3516                         message = g_strdup_printf(
3517                                                 "Invalid Decomb 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         // denois
3527         index = ghb_settings_combo_int(ud->settings, "PictureDenoise");
3528         if (index == 1)
3529         {
3530                 str = ghb_settings_get_string(ud->settings, "PictureDenoiseCustom");
3531                 if (!ghb_validate_filter_string(str, 4))
3532                 {
3533                         message = g_strdup_printf(
3534                                                 "Invalid Denoise Settings:\n\n%s\n",
3535                                                 str);
3536                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3537                         g_free(str);
3538                         g_free(message);
3539                         return FALSE;
3540                 }
3541                 g_free(str);
3542         }
3543         return TRUE;
3544 }
3545
3546 gboolean
3547 ghb_validate_video(signal_user_data_t *ud)
3548 {
3549         gint vcodec, mux;
3550         gchar *message;
3551
3552         mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3553         vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
3554         if ((mux == HB_MUX_MP4 || mux == HB_MUX_AVI) && 
3555                 (vcodec == HB_VCODEC_THEORA))
3556         {
3557                 // mp4|avi/theora combination is not supported.
3558                 message = g_strdup_printf(
3559                                         "Theora is not supported in the MP4 and AVI containers.\n\n"
3560                                         "You should choose a different video codec or container.\n"
3561                                         "If you continue, FFMPEG will be chosen for you.");
3562                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3563                 {
3564                         g_free(message);
3565                         return FALSE;
3566                 }
3567                 g_free(message);
3568                 vcodec = HB_VCODEC_FFMPEG;
3569                 ghb_ui_update(ud, "VideoEncoder", ghb_int64_value(vcodec));
3570         }
3571         return TRUE;
3572 }
3573
3574 gboolean
3575 ghb_validate_subtitles(signal_user_data_t *ud)
3576 {
3577         hb_list_t  * list;
3578         hb_title_t * title;
3579         gchar *message;
3580
3581         if (h_scan == NULL) return FALSE;
3582         list = hb_get_titles( h_scan );
3583         if( !hb_list_count( list ) )
3584         {
3585                 /* No valid title, stop right there */
3586                 g_message("No title found.\n");
3587                 return FALSE;
3588         }
3589
3590         gint titleindex;
3591
3592         titleindex = ghb_settings_combo_int(ud->settings, "title");
3593     title = hb_list_item( list, titleindex );
3594         if (title == NULL) return FALSE;
3595         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3596
3597         const GValue *slist, *settings;
3598         gint count, ii, source;
3599         gboolean burned, one_burned = FALSE;
3600
3601         slist = ghb_settings_get_value(ud->settings, "subtitle_list");
3602         count = ghb_array_len(slist);
3603         for (ii = 0; ii < count; ii++)
3604         {
3605                 settings = ghb_array_get_nth(slist, ii);
3606                 source = ghb_settings_get_int(settings, "SubtitleSource");
3607                 burned = ghb_settings_get_boolean(settings, "SubtitleBurned");
3608                 if (burned && one_burned)
3609                 {
3610                         // MP4 can only handle burned vobsubs.  make sure there isn't
3611                         // already something burned in the list
3612                         message = g_strdup_printf(
3613                         "Only one subtitle may be burned into the video.\n\n"
3614                                 "You should change your subtitle selections.\n"
3615                                 "If you continue, some subtitles will be lost.");
3616                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3617                         {
3618                                 g_free(message);
3619                                 return FALSE;
3620                         }
3621                         g_free(message);
3622                         break;
3623                 }
3624                 else if (burned)
3625                 {
3626                         one_burned = TRUE;
3627                 }
3628                 if (!burned && mux == HB_MUX_MP4 && source == VOBSUB)
3629                 {
3630                         // MP4 can only handle burned vobsubs.  make sure there isn't
3631                         // already something burned in the list
3632                         message = g_strdup_printf(
3633                         "Your chosen container does not support soft bitmap subtitles.\n\n"
3634                                 "You should change your subtitle selections.\n"
3635                                 "If you continue, some subtitles will be lost.");
3636                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, 
3637                                 "Cancel", "Continue"))
3638                         {
3639                                 g_free(message);
3640                                 return FALSE;
3641                         }
3642                         g_free(message);
3643                         break;
3644                 }
3645                 if (source == SRTSUB)
3646                 {
3647                         gchar *filename;
3648
3649                         filename = ghb_settings_get_string(settings, "SrtFile");
3650                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
3651                         {
3652                                 message = g_strdup_printf(
3653                                 "Srt file does not exist or not a regular file.\n\n"
3654                                         "You should choose a valid file.\n"
3655                                         "If you continue, this subtitle will be ignored.");
3656                                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, 
3657                                         "Cancel", "Continue"))
3658                                 {
3659                                         g_free(message);
3660                                         return FALSE;
3661                                 }
3662                                 g_free(message);
3663                                 break;
3664                         }
3665                 }
3666         }
3667         return TRUE;
3668 }
3669
3670 gboolean
3671 ghb_validate_audio(signal_user_data_t *ud)
3672 {
3673         hb_list_t  * list;
3674         hb_title_t * title;
3675         gchar *message;
3676         GValue *value;
3677
3678         if (h_scan == NULL) return FALSE;
3679         list = hb_get_titles( h_scan );
3680         if( !hb_list_count( list ) )
3681         {
3682                 /* No valid title, stop right there */
3683                 g_message("No title found.\n");
3684                 return FALSE;
3685         }
3686
3687         gint titleindex;
3688
3689         titleindex = ghb_settings_combo_int(ud->settings, "title");
3690     title = hb_list_item( list, titleindex );
3691         if (title == NULL) return FALSE;
3692         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3693
3694         const GValue *audio_list;
3695         gint count, ii;
3696
3697         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
3698         count = ghb_array_len(audio_list);
3699         for (ii = 0; ii < count; ii++)
3700         {
3701                 GValue *asettings;
3702             hb_audio_config_t *taudio;
3703
3704                 asettings = ghb_array_get_nth(audio_list, ii);
3705                 gint track = ghb_settings_combo_int(asettings, "AudioTrack");
3706                 gint codec = ghb_settings_combo_int(asettings, "AudioEncoder");
3707         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
3708                                                                                         title->list_audio, track );
3709                 if (!(taudio->in.codec & codec) && 
3710                         (codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)))
3711                 {
3712                         // Not supported.  AC3 is passthrough only, so input must be AC3
3713                         message = g_strdup_printf(
3714                                                 "The source does not support Pass-Thru.\n\n"
3715                                                 "You should choose a different audio codec.\n"
3716                                                 "If you continue, one will be chosen for you.");
3717                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3718                         {
3719                                 g_free(message);
3720                                 return FALSE;
3721                         }
3722                         g_free(message);
3723                         if (mux == HB_MUX_AVI)
3724                         {
3725                                 codec = HB_ACODEC_LAME;
3726                         }
3727                         else
3728                         {
3729                                 codec = HB_ACODEC_FAAC;
3730                         }
3731                         value = get_acodec_value(codec);
3732                         ghb_settings_take_value(asettings, "AudioEncoder", value);
3733                 }
3734                 gchar *a_unsup = NULL;
3735                 gchar *mux_s = NULL;
3736                 if (mux == HB_MUX_MP4)
3737                 { 
3738                         mux_s = "MP4";
3739                         // mp4/mp3|vorbis combination is not supported.
3740                         if (codec == HB_ACODEC_LAME)
3741                         {
3742                                 a_unsup = "MP3";
3743                                 codec = HB_ACODEC_FAAC;
3744                         }
3745                         if (codec == HB_ACODEC_VORBIS)
3746                         {
3747                                 a_unsup = "Vorbis";
3748                                 codec = HB_ACODEC_FAAC;
3749                         }
3750                         if (codec == HB_ACODEC_DCA)
3751                         {
3752                                 a_unsup = "DTS";
3753                                 codec = HB_ACODEC_FAAC;
3754                         }
3755                 }
3756                 else if (mux == HB_MUX_AVI)
3757                 {
3758                         mux_s = "AVI";
3759                         // avi/faac|vorbis combination is not supported.
3760                         if (codec == HB_ACODEC_FAAC)
3761                         {
3762                                 a_unsup = "FAAC";
3763                                 codec = HB_ACODEC_LAME;
3764                         }
3765                         if (codec == HB_ACODEC_VORBIS)
3766                         {
3767                                 a_unsup = "Vorbis";
3768                                 codec = HB_ACODEC_LAME;
3769                         }
3770                 }
3771                 else if (mux == HB_MUX_OGM)
3772                 {
3773                         mux_s = "OGM";
3774                         // avi/faac|vorbis combination is not supported.
3775                         if (codec == HB_ACODEC_FAAC)
3776                         {
3777                                 a_unsup = "FAAC";
3778                                 codec = HB_ACODEC_VORBIS;
3779                         }
3780                         if (codec == HB_ACODEC_AC3)
3781                         {
3782                                 a_unsup = "AC-3";
3783                                 codec = HB_ACODEC_VORBIS;
3784                         }
3785                         if (codec == HB_ACODEC_DCA)
3786                         {
3787                                 a_unsup = "DTS";
3788                                 codec = HB_ACODEC_VORBIS;
3789                         }
3790                 }
3791                 if (a_unsup)
3792                 {
3793                         message = g_strdup_printf(
3794                                                 "%s is not supported in the %s container.\n\n"
3795                                                 "You should choose a different audio codec.\n"
3796                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
3797                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3798                         {
3799                                 g_free(message);
3800                                 return FALSE;
3801                         }
3802                         g_free(message);
3803                         value = get_acodec_value(codec);
3804                         ghb_settings_take_value(asettings, "AudioEncoder", value);
3805                 }
3806                 gint mix = ghb_settings_combo_int (asettings, "AudioMixdown");
3807                 gboolean allow_mono = TRUE;
3808                 gboolean allow_stereo = TRUE;
3809                 gboolean allow_dolby = TRUE;
3810                 gboolean allow_dpl2 = TRUE;
3811                 gboolean allow_6ch = TRUE;
3812                 allow_mono =
3813                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3814                         (codec != HB_ACODEC_LAME);
3815                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
3816                 allow_stereo =
3817                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
3818                 allow_dolby =
3819                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
3820                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
3821                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
3822                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
3823                 allow_6ch =
3824                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3825                         (codec != HB_ACODEC_LAME) &&
3826                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
3827                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
3828
3829                 gchar *mix_unsup = NULL;
3830                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
3831                 {
3832                         mix_unsup = "mono";
3833                 }
3834                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
3835                 {
3836                         mix_unsup = "stereo";
3837                 }
3838                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
3839                 {
3840                         mix_unsup = "Dolby";
3841                 }
3842                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
3843                 {
3844                         mix_unsup = "Dolby Pro Logic II";
3845                 }
3846                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
3847                 {
3848                         mix_unsup = "6 Channel";
3849                 }
3850                 if (mix_unsup)
3851                 {
3852                         message = g_strdup_printf(
3853                                                 "The source audio does not support %s mixdown.\n\n"
3854                                                 "You should choose a different mixdown.\n"
3855                                                 "If you continue, one will be chosen for you.", mix_unsup);
3856                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3857                         {
3858                                 g_free(message);
3859                                 return FALSE;
3860                         }
3861                         g_free(message);
3862                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
3863                         value = get_amix_value(mix);
3864                         ghb_settings_take_value(asettings, "AudioMixdown", value);
3865                 }
3866         }
3867         return TRUE;
3868 }
3869
3870 gboolean
3871 ghb_validate_vquality(GValue *settings)
3872 {
3873         gint vcodec;
3874         gchar *message;
3875         gint min, max;
3876
3877         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
3878         vcodec = ghb_settings_combo_int(settings, "VideoEncoder");
3879         gdouble vquality;
3880         vquality = ghb_settings_get_double(settings, "VideoQualitySlider");
3881         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
3882         {
3883                 switch (vcodec)
3884                 {
3885                         case HB_VCODEC_X264:
3886                         {
3887                                 min = 16;
3888                                 max = 30;
3889                         } break;
3890
3891                         case HB_VCODEC_FFMPEG:
3892                         {
3893                                 min = 1;
3894                                 max = 8;
3895                         } break;
3896
3897                         case HB_VCODEC_THEORA:
3898                         {
3899                                 min = 0;
3900                                 max = 63;
3901                         } break;
3902
3903                         default:
3904                         {
3905                                 min = 48;
3906                                 max = 62;
3907                         } break;
3908                 }
3909                 if (vquality < min || vquality > max)
3910                 {
3911                         message = g_strdup_printf(
3912                                                 "Interesting video quality choise: %d\n\n"
3913                                                 "Typical values range from %d to %d.\n"
3914                                                 "Are you sure you wish to use this setting?",
3915                                                 (gint)vquality, min, max);
3916                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
3917                                                                         "Cancel", "Continue"))
3918                         {
3919                                 g_free(message);
3920                                 return FALSE;
3921                         }
3922                         g_free(message);
3923                 }
3924         }
3925         return TRUE;
3926 }
3927
3928 static void
3929 add_job(hb_handle_t *h, GValue *js, gint unique_id, gint titleindex)
3930 {
3931         hb_list_t  * list;
3932         hb_title_t * title;
3933         hb_job_t   * job;
3934         static gchar *x264opts;
3935         gint sub_id = 0;
3936         gboolean tweaks = FALSE;
3937         gchar *detel_str = NULL;
3938         gchar *decomb_str = NULL;
3939         gchar *deint_str = NULL;
3940         gchar *deblock_str = NULL;
3941         gchar *denoise_str = NULL;
3942         gchar *dest_str = NULL;
3943
3944         g_debug("add_job()\n");
3945         if (h == NULL) return;
3946         list = hb_get_titles( h );
3947         if( !hb_list_count( list ) )
3948         {
3949                 /* No valid title, stop right there */
3950                 return;
3951         }
3952
3953     title = hb_list_item( list, titleindex );
3954         if (title == NULL) return;
3955
3956         /* Set job settings */
3957         job   = title->job;
3958         if (job == NULL) return;
3959
3960         job->start_at_preview = ghb_settings_get_int(js, "start_frame") + 1;
3961         if (job->start_at_preview)
3962         {
3963                 job->seek_points = ghb_settings_get_int(js, "preview_count");
3964                 job->pts_to_stop = ghb_settings_get_int(js, "live_duration") * 90000LL;
3965         }
3966
3967         tweaks = ghb_settings_get_boolean(js, "allow_tweaks");
3968         job->mux = ghb_settings_combo_int(js, "FileFormat");
3969         if (job->mux == HB_MUX_MP4)
3970         {
3971                 job->largeFileSize = ghb_settings_get_boolean(js, "Mp4LargeFile");
3972                 job->mp4_optimize = ghb_settings_get_boolean(js, "Mp4HttpOptimize");
3973         }
3974         else
3975         {
3976                 job->largeFileSize = FALSE;
3977                 job->mp4_optimize = FALSE;
3978         }
3979         if (!job->start_at_preview)
3980         {
3981                 gint chapter_start, chapter_end;
3982                 chapter_start = ghb_settings_get_int(js, "start_chapter");
3983                 chapter_end = ghb_settings_get_int(js, "end_chapter");
3984                 gint num_chapters = hb_list_count(title->list_chapter);
3985                 job->chapter_start = MIN( num_chapters, chapter_start );
3986                 job->chapter_end   = MAX( job->chapter_start, chapter_end );
3987
3988                 job->chapter_markers = ghb_settings_get_boolean(js, "ChapterMarkers");
3989                 if (job->chapter_start == job->chapter_end)
3990                         job->chapter_markers = 0;
3991                 if ( job->chapter_markers )
3992                 {
3993                         GValue *chapters;
3994                         GValue *chapter;
3995                         gint chap;
3996                         gint count;
3997                 
3998                         chapters = ghb_settings_get_value(js, "chapter_list");
3999                         count = ghb_array_len(chapters);
4000                         for(chap = chapter_start; chap <= chapter_end; chap++)
4001                         {
4002                                 hb_chapter_t * chapter_s;
4003                                 gchar *name;
4004                                 
4005                                 name = NULL;
4006                                 if (chap-1 < count)
4007                                 {
4008                                         chapter = ghb_array_get_nth(chapters, chap-1);
4009                                         name = ghb_value_string(chapter); 
4010                                 }
4011                                 if (name == NULL)
4012                                 {
4013                                         name = g_strdup_printf ("Chapter %2d", chap);
4014                                 }
4015                                 chapter_s = hb_list_item( job->title->list_chapter, chap - 1);
4016                                 strncpy(chapter_s->title, name, 1023);
4017                                 chapter_s->title[1023] = '\0';
4018                                 g_free(name);
4019                         }
4020                 }
4021         }
4022         job->crop[0] = ghb_settings_get_int(js, "PictureTopCrop");
4023         job->crop[1] = ghb_settings_get_int(js, "PictureBottomCrop");
4024         job->crop[2] = ghb_settings_get_int(js, "PictureLeftCrop");
4025         job->crop[3] = ghb_settings_get_int(js, "PictureRightCrop");
4026
4027         
4028         gboolean decomb_deint = ghb_settings_get_boolean(js, "PictureDecombDeinterlace");
4029         gint decomb = ghb_settings_combo_int(js, "PictureDecomb");
4030         gint deint = ghb_settings_combo_int(js, "PictureDeinterlace");
4031         if (!decomb_deint)
4032                 job->deinterlace = (deint != 0) ? 1 : 0;
4033         else
4034                 job->deinterlace = 0;
4035     job->grayscale   = ghb_settings_get_boolean(js, "VideoGrayScale");
4036
4037         gboolean keep_aspect;
4038         keep_aspect = ghb_settings_get_boolean(js, "PictureKeepRatio");
4039         job->anamorphic.mode = ghb_settings_combo_int(js, "PicturePAR");
4040         job->anamorphic.modulus = ghb_settings_combo_int(js, "PictureModulus");
4041         if (job->anamorphic.mode)
4042         {
4043                 job->anamorphic.par_width = title->pixel_aspect_width;
4044                 job->anamorphic.par_height = title->pixel_aspect_height;
4045                 job->anamorphic.dar_width = 0;
4046                 job->anamorphic.dar_height = 0;
4047
4048                 if (job->anamorphic.mode == 3 && !keep_aspect)
4049                 {
4050                         job->anamorphic.keep_display_aspect = 0;
4051                         job->anamorphic.par_width = 
4052                                 ghb_settings_get_int(js, "PicturePARWidth");
4053                         job->anamorphic.par_height = 
4054                                 ghb_settings_get_int(js, "PicturePARHeight");
4055                 }
4056                 else
4057                 {
4058                         job->anamorphic.keep_display_aspect = 1;
4059                 }
4060         }
4061
4062         /* Add selected filters */
4063         job->filters = hb_list_init();
4064         gint detel = ghb_settings_combo_int(js, "PictureDetelecine");
4065         if ( detel )
4066         {
4067                 if (detel != 1)
4068                 {
4069                         if (detel_opts.map[detel].svalue != NULL)
4070                                 detel_str = g_strdup(detel_opts.map[detel].svalue);
4071                 }
4072                 else
4073                         detel_str = ghb_settings_get_string(js, "PictureDetelecineCustom");
4074                 hb_filter_detelecine.settings = detel_str;
4075                 hb_list_add( job->filters, &hb_filter_detelecine );
4076         }
4077         if ( decomb_deint && decomb )
4078         {
4079                 if (decomb != 1)
4080                 {
4081                         if (decomb_opts.map[decomb].svalue != NULL)
4082                                 decomb_str = g_strdup(decomb_opts.map[decomb].svalue);
4083                 }
4084                 else
4085                         decomb_str = ghb_settings_get_string(js, "PictureDecombCustom");
4086                 hb_filter_decomb.settings = decomb_str;
4087                 hb_list_add( job->filters, &hb_filter_decomb );
4088         }
4089         if( job->deinterlace )
4090         {
4091                 if (deint != 1)
4092                 {
4093                         if (deint_opts.map[deint].svalue != NULL)
4094                                 deint_str = g_strdup(deint_opts.map[deint].svalue);
4095                 }
4096                 else
4097                         deint_str = ghb_settings_get_string(js, "PictureDeinterlaceCustom");
4098                 hb_filter_deinterlace.settings = deint_str;
4099                 hb_list_add( job->filters, &hb_filter_deinterlace );
4100         }
4101         gint deblock = ghb_settings_get_int(js, "PictureDeblock");
4102         if( deblock >= 5 )
4103         {
4104                 deblock_str = g_strdup_printf("%d", deblock);
4105                 hb_filter_deblock.settings = deblock_str;
4106                 hb_list_add( job->filters, &hb_filter_deblock );
4107         }
4108         gint denoise = ghb_settings_combo_int(js, "PictureDenoise");
4109         if( denoise )
4110         {
4111                 if (denoise != 1)
4112                 {
4113                         if (denoise_opts.map[denoise].svalue != NULL)
4114                                 denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
4115                 }
4116                 else
4117                         denoise_str = ghb_settings_get_string(js, "PictureDenoiseCustom");
4118                 hb_filter_denoise.settings = denoise_str;
4119                 hb_list_add( job->filters, &hb_filter_denoise );
4120         }
4121         job->width = ghb_settings_get_int(js, "scale_width");
4122         job->height = ghb_settings_get_int(js, "scale_height");
4123
4124         job->vcodec = ghb_settings_combo_int(js, "VideoEncoder");
4125         if ((job->mux == HB_MUX_MP4 || job->mux == HB_MUX_AVI) && 
4126                 (job->vcodec == HB_VCODEC_THEORA))
4127         {
4128                 // mp4|avi/theora combination is not supported.
4129                 job->vcodec = HB_VCODEC_FFMPEG;
4130         }
4131         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
4132         {
4133                 job->ipod_atom = ghb_settings_get_boolean(js, "Mp4iPodCompatible");
4134         }
4135         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
4136         {
4137                 gdouble vquality;
4138                 vquality = ghb_settings_get_double(js, "VideoQualitySlider");
4139                 job->vquality =  vquality;
4140                 job->vbitrate = 0;
4141         }
4142         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
4143         {
4144                 job->vquality = -1.0;
4145                 job->vbitrate = ghb_settings_get_int(js, "VideoAvgBitrate");
4146         }
4147
4148         gint vrate = ghb_settings_combo_int(js, "VideoFramerate");
4149         if( vrate == 0 )
4150         {
4151                 job->vrate = title->rate;
4152                 job->vrate_base = title->rate_base;
4153                 job->cfr = 0;
4154         }
4155         else
4156         {
4157                 job->vrate = 27000000;
4158                 job->vrate_base = vrate;
4159                 job->cfr = 1;
4160         }
4161
4162         // AVI container does not support variable frame rate.
4163         // OGM supports variable frame rate, but bases all timing on
4164         // DTS, which breaks when b-frames are used since it is
4165         // impossible to reconstruct PTS from DTS when the framerate
4166         // is variable.  
4167         if (job->mux == HB_MUX_AVI || job->mux == HB_MUX_OGM)
4168         {
4169                 job->cfr = 1;
4170         }
4171
4172         const GValue *audio_list;
4173         gint count, ii;
4174         gint tcount = 0;
4175         
4176         audio_list = ghb_settings_get_value(js, "audio_list");
4177         count = ghb_array_len(audio_list);
4178         for (ii = 0; ii < count; ii++)
4179         {
4180                 GValue *asettings;
4181             hb_audio_config_t audio;
4182             hb_audio_config_t *taudio;
4183
4184                 hb_audio_config_init(&audio);
4185                 asettings = ghb_array_get_nth(audio_list, ii);
4186                 audio.in.track = ghb_settings_get_int(asettings, "AudioTrack");
4187                 audio.out.track = tcount;
4188                 audio.out.codec = ghb_settings_combo_int(asettings, "AudioEncoder");
4189         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
4190                                                                         title->list_audio, audio.in.track );
4191                 if (audio.out.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
4192                 {
4193                         if (!(taudio->in.codec & audio.out.codec))
4194                         {
4195                                 // Not supported.  AC3 is passthrough only, so input must be AC3
4196                                 if (job->mux == HB_MUX_AVI)
4197                                 {
4198                                         audio.out.codec = HB_ACODEC_LAME;
4199                                 }
4200                                 else
4201                                 {
4202                                         audio.out.codec = HB_ACODEC_FAAC;
4203                                 }
4204                         }
4205                         else
4206                         {
4207                                 audio.out.codec &= taudio->in.codec;
4208                         }
4209                 }
4210                 if ((job->mux == HB_MUX_MP4) && 
4211                         ((audio.out.codec == HB_ACODEC_LAME) ||
4212                         (audio.out.codec == HB_ACODEC_VORBIS)))
4213                 {
4214                         // mp4/mp3|vorbis combination is not supported.
4215                         audio.out.codec = HB_ACODEC_FAAC;
4216                 }
4217                 if ((job->mux == HB_MUX_AVI) && 
4218                         ((audio.out.codec == HB_ACODEC_FAAC) ||
4219                         (audio.out.codec == HB_ACODEC_VORBIS)))
4220                 {
4221                         // avi/faac|vorbis combination is not supported.
4222                         audio.out.codec = HB_ACODEC_LAME;
4223                 }
4224                 if ((job->mux == HB_MUX_OGM) && 
4225                         ((audio.out.codec == HB_ACODEC_FAAC) ||
4226                         (audio.out.codec == HB_ACODEC_AC3) ||
4227                         (audio.out.codec == HB_ACODEC_DCA)))
4228                 {
4229                         // ogm/faac|ac3 combination is not supported.
4230                         audio.out.codec = HB_ACODEC_VORBIS;
4231                 }
4232         audio.out.dynamic_range_compression = 
4233                         ghb_settings_get_double(asettings, "AudioTrackDRCSlider");
4234         if (audio.out.dynamic_range_compression < 1.0)
4235                 audio.out.dynamic_range_compression = 0.0;
4236
4237                 // It would be better if this were done in libhb for us, but its not yet.
4238                 if (audio.out.codec == HB_ACODEC_AC3 || audio.out.codec == HB_ACODEC_DCA)
4239                 {
4240                         audio.out.mixdown = 0;
4241                 }
4242                 else
4243                 {
4244                         audio.out.mixdown = ghb_settings_combo_int(asettings, "AudioMixdown");
4245                         // Make sure the mixdown is valid and pick a new one if not.
4246                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
4247                                 audio.in.track, audio.out.codec, audio.out.mixdown);
4248                         audio.out.bitrate = 
4249                                 ghb_settings_combo_int(asettings, "AudioBitrate");
4250                         gint srate = ghb_settings_combo_int(asettings, "AudioSamplerate");
4251                         if (srate == 0) // 0 is same as source
4252                                 audio.out.samplerate = taudio->in.samplerate;
4253                         else
4254                                 audio.out.samplerate = srate;
4255                 }
4256
4257                 // Add it to the jobs audio list
4258         hb_audio_add( job, &audio );
4259                 tcount++;
4260         }
4261         // I was tempted to move this up with the reset of the video quality
4262         // settings, but I suspect the settings above need to be made
4263         // first in order for hb_calc_bitrate to be accurate.
4264         if (ghb_settings_get_boolean(js, "vquality_type_target"))
4265         {
4266                 gint size;
4267                 
4268                 size = ghb_settings_get_int(js, "VideoTargetSize");
4269         job->vbitrate = hb_calc_bitrate( job, size );
4270                 job->vquality = -1.0;
4271         }
4272
4273         dest_str = ghb_settings_get_string(js, "destination");
4274         job->file = dest_str;
4275         job->crf = ghb_settings_get_boolean(js, "constant_rate_factor");
4276
4277         const GValue *subtitle_list;
4278         gint subtitle;
4279         gboolean force, burned, def, one_burned = FALSE;
4280         
4281         ghb_settings_set_boolean(js, "subtitle_scan", FALSE);
4282         subtitle_list = ghb_settings_get_value(js, "subtitle_list");
4283         count = ghb_array_len(subtitle_list);
4284         for (ii = 0; ii < count; ii++)
4285         {
4286                 GValue *ssettings;
4287                 gint source;
4288
4289                 ssettings = ghb_array_get_nth(subtitle_list, ii);
4290
4291                 force = ghb_settings_get_boolean(ssettings, "SubtitleForced");
4292                 burned = ghb_settings_get_boolean(ssettings, "SubtitleBurned");
4293                 def = ghb_settings_get_boolean(ssettings, "SubtitleDefaultTrack");
4294                 source = ghb_settings_get_int(ssettings, "SubtitleSource");
4295
4296                 if (source == SRTSUB)
4297                 {
4298                 hb_subtitle_config_t sub_config;
4299                         gchar *filename, *lang, *code;
4300
4301                         filename = ghb_settings_get_string(ssettings, "SrtFile");
4302                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
4303                         {
4304                                 continue;
4305                         }
4306                         sub_config.offset = ghb_settings_get_int(ssettings, "SrtOffset");
4307                         lang = ghb_settings_get_string(ssettings, "SrtLanguage");
4308                         code = ghb_settings_get_string(ssettings, "SrtCodeset");
4309                         strncpy(sub_config.src_filename, filename, 128);
4310                         strncpy(sub_config.src_codeset, code, 40);
4311                         sub_config.force = 0;
4312                         sub_config.dest = PASSTHRUSUB;
4313                         sub_config.default_track = def;
4314
4315                         hb_srt_add( job, &sub_config, lang);
4316
4317                         g_free(filename);
4318                         g_free(lang);
4319                         g_free(code);
4320                         continue;
4321                 }
4322
4323                 subtitle = ghb_settings_get_int(ssettings, "SubtitleTrack");
4324                 if (subtitle == -1)
4325                 {
4326                         if (!burned && job->mux == HB_MUX_MKV)
4327                         {
4328                                 job->select_subtitle_config.dest = PASSTHRUSUB;
4329                         }
4330                         else if (!burned && job->mux == HB_MUX_MP4)
4331                         {
4332                                 // Skip any non-burned vobsubs when output is mp4
4333                                 continue;
4334                         }
4335                         else if (burned)
4336                         {
4337                                 // Only allow one subtitle to be burned into the video
4338                                 if (one_burned)
4339                                         continue;
4340                                 job->select_subtitle_config.dest = RENDERSUB;
4341                                 one_burned = TRUE;
4342                         }
4343                         job->select_subtitle_config.force = force;
4344                         job->select_subtitle_config.default_track = def;
4345                         job->indepth_scan = 1;
4346                         ghb_settings_set_boolean(js, "subtitle_scan", TRUE);
4347                 }
4348                 else if (subtitle >= 0)
4349                 {
4350                 hb_subtitle_t * subt;
4351                 hb_subtitle_config_t sub_config;
4352
4353                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
4354                         sub_config = subt->config;
4355                         if (subt != NULL)
4356                         {
4357                                 if (!burned && job->mux == HB_MUX_MKV && 
4358                                         subt->format == PICTURESUB)
4359                                 {
4360                                         sub_config.dest = PASSTHRUSUB;
4361                                 }
4362                                 else if (!burned && job->mux == HB_MUX_MP4 && 
4363                                         subt->format == PICTURESUB)
4364                                 {
4365                                         // Skip any non-burned vobsubs when output is mp4
4366                                         continue;
4367                                 }
4368                                 else if ( burned && subt->format == PICTURESUB )
4369                                 {
4370                                         // Only allow one subtitle to be burned into the video
4371                                         if (one_burned)
4372                                                 continue;
4373                                         one_burned = TRUE;
4374                                 }
4375                                 sub_config.force = force;
4376                                 sub_config.default_track = def;
4377                         hb_subtitle_add( job, &sub_config, subtitle );
4378                         }
4379                 }
4380         }
4381
4382         // TODO: libhb holds onto a reference to the x264opts and is not
4383         // finished with it until encoding the job is done.  But I can't
4384         // find a way to get at the job before it is removed in order to
4385         // free up the memory I am allocating here.
4386         // The short story is THIS LEAKS.
4387         x264opts = ghb_build_x264opts_string(js);
4388         
4389         if( *x264opts == '\0' )
4390         {
4391                 g_free(x264opts);
4392                 x264opts = NULL;
4393         }
4394
4395         if (job->indepth_scan == 1)
4396         {
4397                 // Subtitle scan. Look for subtitle matching audio language
4398
4399                 /*
4400                  * When subtitle scan is enabled do a fast pre-scan job
4401                  * which will determine which subtitles to enable, if any.
4402                  */
4403                 job->pass = -1;
4404                 job->indepth_scan = 1;
4405                 job->x264opts = NULL;
4406
4407                 /*
4408                  * Add the pre-scan job
4409                  */
4410                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4411                 hb_add( h, job );
4412         }
4413
4414         if( ghb_settings_get_boolean(js, "VideoTwoPass") &&
4415                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
4416         {
4417                 /*
4418                  * If subtitle_scan is enabled then only turn it on
4419                  * for the second pass and then off again for the
4420                  * second.
4421                  */
4422                 job->pass = 1;
4423                 job->indepth_scan = 0;
4424
4425                 /*
4426                  * If turbo options have been selected then append them
4427                  * to the x264opts now (size includes one ':' and the '\0')
4428                  */
4429                 if( ghb_settings_get_boolean(js, "VideoTurboTwoPass") )
4430                 {
4431                         gchar *tmp_x264opts;
4432                         gchar *extra_opts;
4433                         gint badapt;
4434
4435                         badapt = ghb_lookup_badapt(x264opts);
4436                         if (badapt == 2)
4437                         {
4438                                 extra_opts = g_strdup_printf("%s", turbo_opts);
4439                         }
4440                         else
4441                         {
4442                                 extra_opts = g_strdup_printf("%s:weightb=0", turbo_opts);
4443                         }
4444         
4445                         if ( x264opts )
4446                         {
4447                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, extra_opts);
4448                         } 
4449                         else 
4450                         {
4451                                 /*
4452                                  * No x264opts to modify, but apply the turbo options
4453                                  * anyway as they may be modifying defaults
4454                                  */
4455                                 tmp_x264opts = g_strdup_printf("%s", extra_opts);
4456                         }
4457                         g_free(extra_opts);
4458
4459                         job->x264opts = tmp_x264opts;
4460                 }
4461                 else
4462                 {
4463                         job->x264opts = x264opts;
4464                 }
4465                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4466                 hb_add( h, job );
4467                 //if (job->x264opts != NULL)
4468                 //      g_free(job->x264opts);
4469
4470                 job->pass = 2;
4471                 /*
4472                  * On the second pass we turn off subtitle scan so that we
4473                  * can actually encode using any subtitles that were auto
4474                  * selected in the first pass (using the whacky select-subtitle
4475                  * attribute of the job).
4476                  */
4477                 job->indepth_scan = 0;
4478                 job->x264opts = x264opts;
4479                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4480                 hb_add( h, job );
4481                 //if (job->x264opts != NULL)
4482                 //      g_free(job->x264opts);
4483         }
4484         else
4485         {
4486                 job->x264opts = x264opts;
4487                 job->indepth_scan = 0;
4488                 job->pass = 0;
4489                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4490                 hb_add( h, job );
4491                 //if (job->x264opts != NULL)
4492                 //      g_free(job->x264opts);
4493         }
4494
4495         // clean up audio list
4496         gint num_audio_tracks = hb_list_count(job->list_audio);
4497         for(ii = 0; ii < num_audio_tracks; ii++)
4498         {
4499                 hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
4500                 hb_list_rem(job->list_audio, audio);
4501                 free(audio);
4502         }
4503
4504         // clean up subtitle list
4505         gint num_subtitle_tracks = hb_list_count(job->list_subtitle);
4506         for(ii = 0; ii < num_subtitle_tracks; ii++)
4507         {
4508                 hb_subtitle_t *subtitle = hb_list_item(job->list_subtitle, 0);
4509                 hb_list_rem(job->list_subtitle, subtitle);
4510                 free(subtitle);
4511         }
4512
4513         if (detel_str) g_free(detel_str);
4514         if (decomb_str) g_free(decomb_str);
4515         if (deint_str) g_free(deint_str);
4516         if (deblock_str) g_free(deblock_str);
4517         if (denoise_str) g_free(denoise_str);
4518         if (dest_str) g_free(dest_str);
4519 }
4520
4521 void
4522 ghb_add_job(GValue *js, gint unique_id)
4523 {
4524         // Since I'm doing a scan of the single title I want just prior 
4525         // to adding the job, there is only the one title to choose from.
4526         add_job(h_queue, js, unique_id, 0);
4527 }
4528
4529 void
4530 ghb_add_live_job(GValue *js, gint unique_id)
4531 {
4532         // Since I'm doing a scan of the single title I want just prior 
4533         // to adding the job, there is only the one title to choose from.
4534         gint titleindex = ghb_settings_combo_int(js, "title");
4535         add_job(h_scan, js, unique_id, titleindex);
4536 }
4537
4538 void
4539 ghb_remove_job(gint unique_id)
4540 {
4541     hb_job_t * job;
4542     gint ii;
4543         
4544         // Multiples passes all get the same id
4545         // remove them all.
4546         // Go backwards through list, so reordering doesn't screw me.
4547         ii = hb_count(h_queue) - 1;
4548     while ((job = hb_job(h_queue, ii--)) != NULL)
4549     {
4550         if ((job->sequence_id & 0xFFFFFF) == unique_id)
4551                         hb_rem(h_queue, job);
4552     }
4553 }
4554
4555 void
4556 ghb_start_queue()
4557 {
4558         hb_start( h_queue );
4559 }
4560
4561 void
4562 ghb_stop_queue()
4563 {
4564         hb_stop( h_queue );
4565 }
4566
4567 void
4568 ghb_start_live_encode()
4569 {
4570         hb_start( h_scan );
4571 }
4572
4573 void
4574 ghb_stop_live_encode()
4575 {
4576         hb_stop( h_scan );
4577 }
4578
4579 void
4580 ghb_pause_queue()
4581 {
4582     hb_state_t s;
4583     hb_get_state2( h_queue, &s );
4584
4585     if( s.state == HB_STATE_PAUSED )
4586     {
4587                 hb_status.queue.state &= ~GHB_STATE_PAUSED;
4588                 hb_resume( h_queue );
4589     }
4590     else
4591     {
4592                 hb_status.queue.state |= GHB_STATE_PAUSED;
4593                 hb_pause( h_queue );
4594     }
4595 }
4596
4597 static void
4598 vert_line(
4599         GdkPixbuf * pb, 
4600         guint8 r, 
4601         guint8 g, 
4602         guint8 b, 
4603         gint x, 
4604         gint y, 
4605         gint len, 
4606         gint width)
4607 {
4608         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4609         guint8 *dst;
4610         gint ii, jj;
4611         gint channels = gdk_pixbuf_get_n_channels (pb);
4612         gint stride = gdk_pixbuf_get_rowstride (pb);
4613
4614         for (jj = 0; jj < width; jj++)
4615         {
4616                 dst = pixels + y * stride + (x+jj) * channels;
4617                 for (ii = 0; ii < len; ii++)
4618                 {
4619                         dst[0] = r;
4620                         dst[1] = g;
4621                         dst[2] = b;
4622                         dst += stride;
4623                 }
4624         }
4625 }
4626
4627 static void
4628 horz_line(
4629         GdkPixbuf * pb, 
4630         guint8 r, 
4631         guint8 g, 
4632         guint8 b, 
4633         gint x, 
4634         gint y, 
4635         gint len,
4636         gint width)
4637 {
4638         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4639         guint8 *dst;
4640         gint ii, jj;
4641         gint channels = gdk_pixbuf_get_n_channels (pb);
4642         gint stride = gdk_pixbuf_get_rowstride (pb);
4643
4644         for (jj = 0; jj < width; jj++)
4645         {
4646                 dst = pixels + (y+jj) * stride + x * channels;
4647                 for (ii = 0; ii < len; ii++)
4648                 {
4649                         dst[0] = r;
4650                         dst[1] = g;
4651                         dst[2] = b;
4652                         dst += channels;
4653                 }
4654         }
4655 }
4656
4657 static void
4658 hash_pixbuf(
4659         GdkPixbuf * pb,
4660         gint        x,
4661         gint        y,
4662         gint        w,
4663         gint        h,
4664         gint        step,
4665         gint            orientation)
4666 {
4667         gint ii, jj;
4668         gint line_width = 8;
4669         struct
4670         {
4671                 guint8 r;
4672                 guint8 g;
4673                 guint8 b;
4674         } c[4] = 
4675         {{0x80, 0x80, 0x80},{0xC0, 0x80, 0x70},{0x80, 0xA0, 0x80},{0x70, 0x80, 0xA0}};
4676
4677         if (!orientation)
4678         {
4679                 // vertical lines
4680                 for (ii = x, jj = 0; ii+line_width < x+w; ii += step, jj++)
4681                 {
4682                         vert_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, ii, y, h, line_width);
4683                 }
4684         }
4685         else
4686         {
4687                 // horizontal lines
4688                 for (ii = y, jj = 0; ii+line_width < y+h; ii += step, jj++)
4689                 {
4690                         horz_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, x, ii, w, line_width);
4691                 }
4692         }
4693 }
4694
4695 GdkPixbuf*
4696 ghb_get_preview_image(
4697         gint titleindex, 
4698         gint index, 
4699         signal_user_data_t *ud,
4700         gint *out_width,
4701         gint *out_height)
4702 {
4703         GValue *settings;
4704         hb_title_t *title;
4705         hb_list_t  *list;
4706         
4707         settings = ud->settings;
4708         list = hb_get_titles( h_scan );
4709         if( !hb_list_count( list ) )
4710         {
4711                 /* No valid title, stop right there */
4712                 return NULL;
4713         }
4714     title = hb_list_item( list, titleindex );
4715         if (title == NULL) return NULL;
4716         if (title->job == NULL) return NULL;
4717         set_preview_job_settings(title->job, settings);
4718
4719         // hb_get_preview doesn't compensate for anamorphic, so lets
4720         // calculate scale factors
4721         gint width, height, par_width = 1, par_height = 1;
4722         gint pic_par = ghb_settings_combo_int(settings, "PicturePAR");
4723         if (pic_par)
4724         {
4725                 hb_set_anamorphic_size( title->job, &width, &height, 
4726                                                                 &par_width, &par_height );
4727         }
4728
4729         // Make sure we have a big enough buffer to receive the image from libhb
4730         gint dstWidth = title->job->width;
4731         gint dstHeight= title->job->height;
4732
4733         static guint8 *buffer = NULL;
4734         static gint bufferSize = 0;
4735         gint newSize;
4736
4737         newSize = dstWidth * dstHeight * 4;
4738         if( bufferSize < newSize )
4739         {
4740                 bufferSize = newSize;
4741                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
4742         }
4743         hb_get_preview( h_scan, title, index, buffer );
4744
4745         // Create an GdkPixbuf and copy the libhb image into it, converting it from
4746         // libhb's format something suitable.
4747         
4748         // The image data returned by hb_get_preview is 4 bytes per pixel, 
4749         // BGRA format. Alpha is ignored.
4750
4751         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
4752         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
4753         
4754         guint32 *src = (guint32*)buffer;
4755         guint8 *dst = pixels;
4756
4757         gint ii, jj;
4758         gint channels = gdk_pixbuf_get_n_channels (preview);
4759         gint stride = gdk_pixbuf_get_rowstride (preview);
4760         guint8 *tmp;
4761
4762         for (ii = 0; ii < dstHeight; ii++)
4763         {
4764                 tmp = dst;
4765                 for (jj = 0; jj < dstWidth; jj++)
4766                 {
4767                         tmp[0] = src[0] >> 16;
4768                         tmp[1] = src[0] >> 8;
4769                         tmp[2] = src[0] >> 0;
4770                         tmp += channels;
4771                         src++;
4772                 }
4773                 dst += stride;
4774         }
4775         gint w = ghb_settings_get_int(settings, "scale_width");
4776         gint h = ghb_settings_get_int(settings, "scale_height");
4777         ghb_par_scale(ud, &w, &h, par_width, par_height);
4778
4779         gint c0, c1, c2, c3;
4780         c0 = ghb_settings_get_int(settings, "PictureTopCrop");
4781         c1 = ghb_settings_get_int(settings, "PictureBottomCrop");
4782         c2 = ghb_settings_get_int(settings, "PictureLeftCrop");
4783         c3 = ghb_settings_get_int(settings, "PictureRightCrop");
4784
4785         gdouble xscale = (gdouble)w / (gdouble)(title->width - c2 - c3);
4786         gdouble yscale = (gdouble)h / (gdouble)(title->height - c0 - c1);
4787         
4788         ghb_par_scale(ud, &dstWidth, &dstHeight, par_width, par_height);
4789         *out_width = w;
4790         *out_height = h;
4791         if (ghb_settings_get_boolean(settings, "reduce_hd_preview"))
4792         {
4793                 GdkScreen *ss;
4794                 gint s_w, s_h;
4795                 gint orig_w, orig_h;
4796                 gint factor = 80;
4797
4798                 if (ghb_settings_get_boolean(settings, "preview_fullscreen"))
4799                 {
4800                         factor = 100;
4801                 }
4802                 ss = gdk_screen_get_default();
4803                 s_w = gdk_screen_get_width(ss);
4804                 s_h = gdk_screen_get_height(ss);
4805                 orig_w = dstWidth;
4806                 orig_h = dstHeight;
4807
4808                 if (dstWidth > s_w * factor / 100)
4809                 {
4810                         dstWidth = s_w * factor / 100;
4811                         dstHeight = dstHeight * dstWidth / orig_w;
4812                 }
4813                 if (dstHeight > s_h * factor / 100)
4814                 {
4815                         dstHeight = s_h * factor / 100;
4816                         dstWidth = dstWidth * dstHeight / orig_h;
4817                 }
4818                 xscale *= (gdouble)dstWidth / orig_w;
4819                 yscale *= (gdouble)dstHeight / orig_h;
4820                 w *= (gdouble)dstWidth / orig_w;
4821                 h *= (gdouble)dstHeight / orig_h;
4822         }
4823         GdkPixbuf *scaled_preview;
4824         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
4825         if (ghb_settings_get_boolean(settings, "show_crop"))
4826         {
4827                 c0 *= yscale;
4828                 c1 *= yscale;
4829                 c2 *= xscale;
4830                 c3 *= xscale;
4831                 // Top
4832                 hash_pixbuf(scaled_preview, c2, 0, w, c0, 32, 0);
4833                 // Bottom
4834                 hash_pixbuf(scaled_preview, c2, dstHeight-c1, w, c1, 32, 0);
4835                 // Left
4836                 hash_pixbuf(scaled_preview, 0, c0, c2, h, 32, 1);
4837                 // Right
4838                 hash_pixbuf(scaled_preview, dstWidth-c3, c0, c3, h, 32, 1);
4839         }
4840         g_object_unref (preview);
4841         return scaled_preview;
4842 }
4843
4844 static void
4845 sanitize_volname(gchar *name)
4846 {
4847         gchar *a, *b;
4848
4849         a = b = name;
4850         while (*b)
4851         {
4852                 switch(*b)
4853                 {
4854                 case '<':
4855                         b++;
4856                         break;
4857                 case '>':
4858                         b++;
4859                         break;
4860                 default:
4861                         *a = *b;
4862                         a++; b++;
4863                         break;
4864                 }
4865         }
4866         *a = 0;
4867 }
4868
4869 gchar*
4870 ghb_dvd_volname(const gchar *device)
4871 {
4872         gchar *name;
4873         name = hb_dvd_name((gchar*)device);
4874         if (name != NULL && name[0] != 0)
4875         {
4876                 name = g_strdup(name);
4877                 sanitize_volname(name);
4878                 return name;
4879         }
4880         return NULL;
4881 }