OSDN Git Service

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