OSDN Git Service

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