OSDN Git Service

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