OSDN Git Service

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