OSDN Git Service

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