OSDN Git Service

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