OSDN Git Service

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