OSDN Git Service

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