OSDN Git Service

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