OSDN Git Service

LinGui: fix some text alignment issues on the picture summary tab
[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                         options[ii] = g_strdup_printf("%d - %s (%s)", ii+1, 
2191                                 subtitle->lang, 
2192                                 ghb_subtitle_source_name(subtitle->source));
2193                         subtitle_opts.map[ii+1].option = options[ii];
2194                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
2195                         subtitle_opts.map[ii+1].ivalue = ii;
2196                         subtitle_opts.map[ii+1].svalue = subtitle->iso639_2;
2197                         gtk_list_store_append(store, &iter);
2198                         gtk_list_store_set(store, &iter, 
2199                                                 0, options[ii], 
2200                                                 1, TRUE, 
2201                                                 2, index_str[ii], 
2202                                                 3, (gdouble)ii, 
2203                                                 4, subtitle->iso639_2, 
2204                                                 -1);
2205                 }
2206                 options[count] = NULL;
2207         }
2208         else
2209         {
2210                 index_str_init(LANG_TABLE_SIZE-1);
2211                 for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
2212                 {
2213                         const gchar *lang;
2214
2215                         if (ghb_language_table[ii].native_name[0] != 0)
2216                                 lang = ghb_language_table[ii].native_name;
2217                         else
2218                                 lang = ghb_language_table[ii].eng_name;
2219
2220                         subtitle_opts.map[ii+1].option = lang;
2221                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
2222                         subtitle_opts.map[ii+1].ivalue = ii;
2223                         subtitle_opts.map[ii+1].svalue = ghb_language_table[ii].iso639_2;
2224                         gtk_list_store_append(store, &iter);
2225                         gtk_list_store_set(store, &iter, 
2226                                         0, lang,
2227                                         1, TRUE, 
2228                                         2, index_str[ii],
2229                                         3, (gdouble)ii, 
2230                                         4, ghb_language_table[ii].iso639_2, 
2231                                         -1);
2232                 }
2233         }
2234 }
2235
2236 gint
2237 ghb_longest_title()
2238 {
2239         hb_list_t  * list;
2240         hb_title_t * title;
2241         gint ii;
2242         gint count = 0;
2243         gint titleindex = 0;
2244         gint feature;
2245         
2246         g_debug("ghb_longest_title ()\n");
2247         if (h_scan == NULL) return 0;
2248         list = hb_get_titles( h_scan );
2249         count = hb_list_count( list );
2250         if (count > 100) count = 100;
2251         if (count < 1) return 0;
2252         title = (hb_title_t*)hb_list_item(list, 0);
2253         feature = title->job->feature;
2254         for (ii = 0; ii < count; ii++)
2255         {
2256                 title = (hb_title_t*)hb_list_item(list, ii);
2257                 if (title->index == feature)
2258                 {
2259                         return ii;
2260                 }
2261         }
2262         return titleindex;
2263 }
2264
2265 gchar*
2266 ghb_get_source_audio_lang(gint titleindex, gint track)
2267 {
2268         hb_list_t  * list;
2269         hb_title_t * title;
2270     hb_audio_config_t * audio;
2271         gchar *lang = NULL;
2272         
2273         g_debug("ghb_lookup_1st_audio_lang ()\n");
2274         if (h_scan == NULL) 
2275                 return NULL;
2276         list = hb_get_titles( h_scan );
2277     title = (hb_title_t*)hb_list_item( list, titleindex );
2278         if (title == NULL)
2279                 return NULL;
2280         if (hb_list_count( title->list_audio ) <= track)
2281                 return NULL;
2282
2283         audio = hb_list_audio_config_item(title->list_audio, track);
2284         if (audio == NULL)
2285                 return NULL;
2286
2287         lang = g_strdup(audio->lang.iso639_2);
2288         return lang;
2289 }
2290
2291 static gboolean*
2292 get_track_used(gint acodec, GHashTable *track_indices, gint count)
2293 {
2294         gboolean *used;
2295
2296         used = g_hash_table_lookup(track_indices, &acodec);
2297         if (used == NULL)
2298         {
2299                 gint *key;
2300
2301                 used = g_malloc0(count * sizeof(gboolean));
2302                 key = g_malloc(sizeof(gint));
2303                 *key = acodec;
2304                 g_hash_table_insert(track_indices, key, used);
2305         }
2306         return used;
2307 }
2308
2309 gint
2310 ghb_find_audio_track(
2311         gint titleindex, 
2312         const gchar *lang, 
2313         gint acodec,
2314         gint fallback_acodec,
2315         GHashTable *track_indices)
2316 {
2317         hb_list_t  * list;
2318         hb_title_t * title;
2319         hb_audio_config_t * audio;
2320         gint ii;
2321         gint count = 0;
2322         gint track = -1;
2323         gint max_chan;
2324         gboolean *used = NULL;
2325         gboolean *passthru_used;
2326         gint try_acodec;
2327         gint passthru_acodec;
2328         gboolean passthru;
2329         gint channels;
2330         
2331         g_debug("find_audio_track ()\n");
2332         if (h_scan == NULL) return -1;
2333         list = hb_get_titles( h_scan );
2334         title = (hb_title_t*)hb_list_item( list, titleindex );
2335         if (title != NULL)
2336         {
2337                 count = hb_list_count( title->list_audio );
2338         }
2339         if (count > 10) count = 10;
2340         // Try to find an item that matches the preferred language and
2341         // the passthru codec type
2342         max_chan = 0;
2343         passthru = (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)) != 0;
2344         if (passthru)
2345         {
2346                 for (ii = 0; ii < count; ii++)
2347                 {
2348                         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2349                                                                                                         title->list_audio, ii );
2350                         passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2351                         // Is the source track use a passthru capable codec?
2352                         if (passthru_acodec == 0)
2353                                 continue;
2354                         used = get_track_used(passthru_acodec, track_indices, count);
2355                         // Has the track already been used with this codec?
2356                         if (used[ii])
2357                                 continue;
2358
2359                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2360                                                                                                         audio->in.channel_layout);
2361                         // Find a track that is not visually impaired or dirctor's
2362                         // commentary, and has the highest channel count.
2363                         if ((audio->lang.type < 2) &&
2364                                 ((strcmp(lang, audio->lang.iso639_2) == 0) ||
2365                                 (strcmp(lang, "und") == 0)))
2366                         {
2367                                 if (channels > max_chan)
2368                                 {
2369                                         track = ii;
2370                                         max_chan = channels;
2371                                 }
2372                         }
2373                 }
2374                 try_acodec = fallback_acodec;
2375         }
2376         else
2377         {
2378                 try_acodec = acodec;
2379         }
2380         if (track > -1)
2381         {
2382                 used[track] = TRUE;
2383                 return track;
2384         }
2385         // Try to find an item that matches the preferred language
2386         max_chan = 0;
2387         used = get_track_used(try_acodec, track_indices, count);
2388         for (ii = 0; ii < count; ii++)
2389         {
2390                 // Has the track already been used with this codec?
2391                 if (used[ii])
2392                         continue;
2393                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2394                                                                                                 title->list_audio, ii );
2395                 passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2396                 if (passthru_acodec && passthru)
2397                 {
2398                         passthru_used = get_track_used(passthru_acodec, track_indices, count);
2399                         // Has the track already been used with this codec for passthru?
2400                         if (passthru_used[ii])
2401                                 continue;
2402                 }
2403                 channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2404                                                                                                 audio->in.channel_layout);
2405                 // Find a track that is not visually impaired or dirctor's commentary
2406                 if ((audio->lang.type < 2) &&
2407                         ((strcmp(lang, audio->lang.iso639_2) == 0) ||
2408                         (strcmp(lang, "und") == 0)))
2409                 {
2410                         if (channels > max_chan)
2411                         {
2412                                 track = ii;
2413                                 max_chan = channels;
2414                         }
2415                 }
2416         }
2417         if (track > -1)
2418         {
2419                 used[track] = TRUE;
2420                 return track;
2421         }
2422         // Try to fine an item that does not match the preferred language and
2423         // matches the passthru codec type
2424         max_chan = 0;
2425         if (passthru)
2426         {
2427                 for (ii = 0; ii < count; ii++)
2428                 {
2429                         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2430                                                                                                         title->list_audio, ii );
2431                         passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2432                         // Is the source track use a passthru capable codec?
2433                         if (passthru_acodec == 0)
2434                                 continue;
2435                         used = get_track_used(passthru_acodec, track_indices, count);
2436                         // Has the track already been used with this codec?
2437                         if (used[ii])
2438                                 continue;
2439
2440                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2441                                                                                                         audio->in.channel_layout);
2442                         // Find a track that is not visually impaired or dirctor's
2443                         // commentary, and has the highest channel count.
2444                         if (audio->lang.type < 2)
2445                         {
2446                                 if (channels > max_chan)
2447                                 {
2448                                         track = ii;
2449                                         max_chan = channels;
2450                                 }
2451                         }
2452                 }
2453                 try_acodec = fallback_acodec;
2454         }
2455         else
2456         {
2457                 try_acodec = acodec;
2458         }
2459         if (track > -1)
2460         {
2461                 used[track] = TRUE;
2462                 return track;
2463         }
2464         // Try to fine an item that does not match the preferred language
2465         max_chan = 0;
2466         used = get_track_used(try_acodec, track_indices, count);
2467         for (ii = 0; ii < count; ii++)
2468         {
2469                 // Has the track already been used with this codec?
2470                 if (used[ii])
2471                         continue;
2472                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2473                                                                                                         title->list_audio, ii );
2474                 passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2475                 channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2476                                                                                                 audio->in.channel_layout);
2477                 if (passthru_acodec && passthru)
2478                 {
2479                         passthru_used = get_track_used(passthru_acodec, track_indices, count);
2480                         // Has the track already been used with this codec for passthru?
2481                         if (passthru_used[ii])
2482                                 continue;
2483                 }
2484                 // Find a track that is not visually impaired or dirctor's commentary
2485                 if (audio->lang.type < 2)
2486                 {
2487                         if (channels > max_chan)
2488                         {
2489                                 track = ii;
2490                                 max_chan = channels;
2491                         }
2492                 }
2493         }
2494         if (track > -1)
2495         {
2496                 used[track] = TRUE;
2497                 return track;
2498         }
2499         // Last ditch, anything goes
2500         for (ii = 0; ii < count; ii++)
2501         {
2502                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2503                                                                                                 title->list_audio, ii );
2504                 passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2505                 if (passthru_acodec && passthru)
2506                 {
2507                         passthru_used = get_track_used(passthru_acodec, track_indices, count);
2508                         // Has the track already been used with this codec for passthru?
2509                         if (passthru_used[ii])
2510                                 continue;
2511                 }
2512                 // Has the track already been used with this codec?
2513                 if (!used[ii])
2514                 {
2515                         track = ii;
2516                         break;
2517                 }
2518         }
2519         if (track > -1)
2520         {
2521                 used[track] = TRUE;
2522         }
2523         return track;
2524 }
2525
2526 gint
2527 ghb_find_pref_subtitle_track(const gchar *lang)
2528 {
2529         gint ii, count;
2530         count = subtitle_opts.count;
2531         for (ii = 0; ii < count; ii++)
2532         {
2533                 if (strcmp(lang, subtitle_opts.map[ii].svalue) == 0)
2534                 {
2535                         return subtitle_opts.map[ii].ivalue;
2536                 }
2537         }
2538         return -2;
2539 }
2540
2541 gint
2542 ghb_find_cc_track(gint titleindex)
2543 {
2544         hb_list_t  * list;
2545         hb_title_t * title;
2546         hb_subtitle_t * subtitle;
2547         gint count, ii;
2548         
2549         g_debug("ghb_find_cc_track ()\n");
2550         if (h_scan == NULL) return -2;
2551         list = hb_get_titles( h_scan );
2552         title = (hb_title_t*)hb_list_item( list, titleindex );
2553         if (title != NULL)
2554         {
2555                 count = hb_list_count( title->list_subtitle );
2556                 // Try to find an item that matches the preferred language
2557                 for (ii = 0; ii < count; ii++)
2558                 {
2559                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2560                         if (subtitle->source == CC608SUB || subtitle->source == CC708SUB)
2561                                 return ii;
2562                 }
2563         }
2564         return -2;
2565 }
2566
2567 static gboolean
2568 canForce(int source)
2569 {
2570         return (source == VOBSUB);
2571 }
2572
2573 static gboolean
2574 canBurn(int source)
2575 {
2576         return (source == VOBSUB || source == SSASUB);
2577 }
2578
2579 gint
2580 ghb_find_subtitle_track(
2581         gint          titleindex, 
2582         const gchar * lang, 
2583         gboolean      burn,
2584         gboolean      force,
2585         gint          source,
2586         GHashTable  * track_indices)
2587 {
2588         hb_list_t  * list;
2589         hb_title_t * title;
2590         hb_subtitle_t * subtitle;
2591         gint count, ii;
2592         gboolean *used;
2593         
2594         g_debug("find_subtitle_track ()\n");
2595         if (strcmp(lang, "auto") == 0)
2596                 return -1;
2597         if (h_scan == NULL) return -1;
2598         list = hb_get_titles( h_scan );
2599         title = (hb_title_t*)hb_list_item( list, titleindex );
2600         if (title != NULL)
2601         {
2602                 count = hb_list_count( title->list_subtitle );
2603                 used = g_hash_table_lookup(track_indices, lang);
2604                 if (used == NULL)
2605                 {
2606                         used = g_malloc0(count * sizeof(gboolean));
2607                         g_hash_table_insert(track_indices, g_strdup(lang), used);
2608                 }
2609                 // Try to find an item that matches the preferred language and source
2610                 for (ii = 0; ii < count; ii++)
2611                 {
2612                         if (used[ii])
2613                                 continue;
2614
2615                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2616                         if (source == subtitle->source &&
2617                                 ((strcmp(lang, subtitle->iso639_2) == 0) ||
2618                                  (strcmp(lang, "und") == 0)))
2619                         {
2620                                 used[ii] = TRUE;
2621                                 return ii;
2622                         }
2623                 }
2624                 // Try to find an item that matches the preferred language
2625                 for (ii = 0; ii < count; ii++)
2626                 {
2627                         if (used[ii])
2628                                 continue;
2629
2630                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2631                         if (((!force || (force && canForce(subtitle->source))) &&
2632                                  (!burn  || (burn  &&  canBurn(subtitle->source)))) &&
2633                                 ((strcmp(lang, subtitle->iso639_2) == 0) ||
2634                                  (strcmp(lang, "und") == 0)))
2635                         {
2636                                 used[ii] = TRUE;
2637                                 return ii;
2638                         }
2639                 }
2640         }
2641         return -2;
2642 }
2643
2644 static void
2645 generic_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
2646 {
2647         GtkTreeIter iter;
2648         GtkListStore *store;
2649         gint ii;
2650         
2651         g_debug("generic_opts_set ()\n");
2652         if (name == NULL || opts == NULL) return;
2653         store = get_combo_box_store(builder, name);
2654         gtk_list_store_clear(store);
2655         for (ii = 0; ii < opts->count; ii++)
2656         {
2657                 gtk_list_store_append(store, &iter);
2658                 gtk_list_store_set(store, &iter, 
2659                                                    0, opts->map[ii].option, 
2660                                                    1, TRUE, 
2661                                                    2, opts->map[ii].shortOpt, 
2662                                                    3, opts->map[ii].ivalue, 
2663                                                    4, opts->map[ii].svalue, 
2664                                                    -1);
2665         }
2666 }
2667
2668 static void
2669 small_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
2670 {
2671         GtkTreeIter iter;
2672         GtkListStore *store;
2673         gint ii;
2674         gchar *str;
2675         
2676         g_debug("small_opts_set ()\n");
2677         if (name == NULL || opts == NULL) return;
2678         store = get_combo_box_store(builder, name);
2679         gtk_list_store_clear(store);
2680         for (ii = 0; ii < opts->count; ii++)
2681         {
2682                 gtk_list_store_append(store, &iter);
2683                 str = g_strdup_printf("<small>%s</small>", opts->map[ii].option);
2684                 gtk_list_store_set(store, &iter, 
2685                                                    0, str,
2686                                                    1, TRUE, 
2687                                                    2, opts->map[ii].shortOpt, 
2688                                                    3, opts->map[ii].ivalue, 
2689                                                    4, opts->map[ii].svalue, 
2690                                                    -1);
2691                 g_free(str);
2692         }
2693 }
2694
2695 combo_opts_t*
2696 find_combo_table(const gchar *name)
2697 {
2698         gint ii;
2699
2700         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2701         {
2702                 if (strcmp(name, combo_name_map[ii].name) == 0)
2703                 {
2704                         return combo_name_map[ii].opts;
2705                 }
2706         }
2707         return NULL;
2708 }
2709
2710 gint
2711 ghb_lookup_combo_int(const gchar *name, const GValue *gval)
2712 {
2713         if (gval == NULL)
2714                 return 0;
2715         if (strcmp(name, "AudioBitrate") == 0)
2716                 return lookup_audio_bitrate_int(gval);
2717         else if (strcmp(name, "AudioSamplerate") == 0)
2718                 return lookup_audio_rate_int(gval);
2719         else if (strcmp(name, "VideoFramerate") == 0)
2720                 return lookup_video_rate_int(gval);
2721         else if (strcmp(name, "AudioMixdown") == 0)
2722                 return lookup_mix_int(gval);
2723         else if (strcmp(name, "SrtLanguage") == 0)
2724                 return lookup_audio_lang_int(gval);
2725         else if (strcmp(name, "PreferredLanguage") == 0)
2726                 return lookup_audio_lang_int(gval);
2727         else
2728         {
2729                 return lookup_generic_int(find_combo_table(name), gval);
2730         }
2731         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2732         return 0;
2733 }
2734
2735 gdouble
2736 ghb_lookup_combo_double(const gchar *name, const GValue *gval)
2737 {
2738         if (gval == NULL)
2739                 return 0;
2740         if (strcmp(name, "AudioBitrate") == 0)
2741                 return lookup_audio_bitrate_int(gval);
2742         else if (strcmp(name, "AudioSamplerate") == 0)
2743                 return lookup_audio_rate_int(gval);
2744         else if (strcmp(name, "VideoFramerate") == 0)
2745                 return lookup_video_rate_int(gval);
2746         else if (strcmp(name, "AudioMixdown") == 0)
2747                 return lookup_mix_int(gval);
2748         else if (strcmp(name, "SrtLanguage") == 0)
2749                 return lookup_audio_lang_int(gval);
2750         else if (strcmp(name, "PreferredLanguage") == 0)
2751                 return lookup_audio_lang_int(gval);
2752         else
2753         {
2754                 return lookup_generic_double(find_combo_table(name), gval);
2755         }
2756         g_warning("ghb_lookup_combo_double() couldn't find %s", name);
2757         return 0;
2758 }
2759
2760 const gchar*
2761 ghb_lookup_combo_option(const gchar *name, const GValue *gval)
2762 {
2763         if (gval == NULL)
2764                 return NULL;
2765         if (strcmp(name, "AudioBitrate") == 0)
2766                 return lookup_audio_bitrate_option(gval);
2767         else if (strcmp(name, "AudioSamplerate") == 0)
2768                 return lookup_audio_rate_option(gval);
2769         else if (strcmp(name, "VideoFramerate") == 0)
2770                 return lookup_video_rate_option(gval);
2771         else if (strcmp(name, "AudioMixdown") == 0)
2772                 return lookup_mix_option(gval);
2773         else if (strcmp(name, "SrtLanguage") == 0)
2774                 return lookup_audio_lang_option(gval);
2775         else if (strcmp(name, "PreferredLanguage") == 0)
2776                 return lookup_audio_lang_option(gval);
2777         else
2778         {
2779                 return lookup_generic_option(find_combo_table(name), gval);
2780         }
2781         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2782         return NULL;
2783 }
2784
2785 const gchar*
2786 ghb_lookup_combo_string(const gchar *name, const GValue *gval)
2787 {
2788         if (gval == NULL)
2789                 return NULL;
2790         if (strcmp(name, "AudioBitrate") == 0)
2791                 return lookup_audio_bitrate_option(gval);
2792         else if (strcmp(name, "AudioSamplerate") == 0)
2793                 return lookup_audio_rate_option(gval);
2794         else if (strcmp(name, "VideoFramerate") == 0)
2795                 return lookup_video_rate_option(gval);
2796         else if (strcmp(name, "AudioMixdown") == 0)
2797                 return lookup_mix_string(gval);
2798         else if (strcmp(name, "SrtLanguage") == 0)
2799                 return lookup_audio_lang_option(gval);
2800         else if (strcmp(name, "PreferredLanguage") == 0)
2801                 return lookup_audio_lang_option(gval);
2802         else
2803         {
2804                 return lookup_generic_string(find_combo_table(name), gval);
2805         }
2806         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2807         return NULL;
2808 }
2809
2810 void
2811 ghb_update_ui_combo_box(
2812         signal_user_data_t *ud, 
2813         const gchar *name, 
2814         gint user_data, 
2815         gboolean all)
2816 {
2817         GtkComboBox *combo = NULL;
2818         gint signal_id;
2819         gint handler_id = 0;
2820
2821         if (name != NULL)
2822         {               
2823                 g_debug("ghb_update_ui_combo_box() %s\n", name);
2824                 // Clearing a combo box causes a rash of "changed" events, even when
2825                 // the active item is -1 (inactive).  To control things, I'm disabling
2826                 // the event till things are settled down.
2827                 combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, name));
2828                 signal_id = g_signal_lookup("changed", GTK_TYPE_COMBO_BOX);
2829                 if (signal_id > 0)
2830                 {
2831                         // Valid signal id found.  This should always succeed.
2832                         handler_id = g_signal_handler_find ((gpointer)combo, G_SIGNAL_MATCH_ID, 
2833                                                                                                 signal_id, 0, 0, 0, 0);
2834                         if (handler_id > 0)
2835                         {
2836                                 // This should also always succeed
2837                                 g_signal_handler_block ((gpointer)combo, handler_id);
2838                         }
2839                 }
2840         }       
2841         if (all)
2842         {
2843                 audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2844                 audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2845                 video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2846                 mix_opts_set(ud->builder, "AudioMixdown");
2847                 language_opts_set(ud->builder, "SrtLanguage");
2848                 language_opts_set(ud->builder, "PreferredLanguage");
2849                 srt_codeset_opts_set(ud->builder, "SrtCodeset");
2850                 title_opts_set(ud->builder, "title");
2851                 audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2852                 subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2853                 generic_opts_set(ud->builder, "VideoQualityGranularity", &vqual_granularity_opts);
2854                 generic_opts_set(ud->builder, "PtoPType", &point_to_point_opts);
2855                 generic_opts_set(ud->builder, "WhenComplete", &when_complete_opts);
2856                 generic_opts_set(ud->builder, "PicturePAR", &par_opts);
2857                 generic_opts_set(ud->builder, "PictureModulus", &alignment_opts);
2858                 generic_opts_set(ud->builder, "LoggingLevel", &logging_opts);
2859                 generic_opts_set(ud->builder, "LogLongevity", &log_longevity_opts);
2860                 generic_opts_set(ud->builder, "check_updates", &appcast_update_opts);
2861                 generic_opts_set(ud->builder, "FileFormat", &container_opts);
2862                 generic_opts_set(ud->builder, "PictureDeinterlace", &deint_opts);
2863                 generic_opts_set(ud->builder, "PictureDetelecine", &detel_opts);
2864                 generic_opts_set(ud->builder, "PictureDecomb", &decomb_opts);
2865                 generic_opts_set(ud->builder, "PictureDenoise", &denoise_opts);
2866                 generic_opts_set(ud->builder, "VideoEncoder", &vcodec_opts);
2867                 small_opts_set(ud->builder, "AudioEncoder", &acodec_opts);
2868                 small_opts_set(ud->builder, "x264_direct", &direct_opts);
2869                 small_opts_set(ud->builder, "x264_b_adapt", &badapt_opts);
2870                 small_opts_set(ud->builder, "x264_bpyramid", &bpyramid_opts);
2871                 small_opts_set(ud->builder, "x264_weighted_pframes", &weightp_opts);
2872                 small_opts_set(ud->builder, "x264_me", &me_opts);
2873                 small_opts_set(ud->builder, "x264_subme", &subme_opts);
2874                 small_opts_set(ud->builder, "x264_analyse", &analyse_opts);
2875                 small_opts_set(ud->builder, "x264_trellis", &trellis_opts);
2876         }
2877         else
2878         {
2879                 if (strcmp(name, "AudioBitrate") == 0)
2880                         audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2881                 else if (strcmp(name, "AudioSamplerate") == 0)
2882                         audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2883                 else if (strcmp(name, "VideoFramerate") == 0)
2884                         video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2885                 else if (strcmp(name, "AudioMixdown") == 0)
2886                         mix_opts_set(ud->builder, "AudioMixdown");
2887                 else if (strcmp(name, "SrtLanguage") == 0)
2888                         language_opts_set(ud->builder, "SrtLanguage");
2889                 else if (strcmp(name, "PreferredLanguage") == 0)
2890                         language_opts_set(ud->builder, "PreferredLanguage");
2891                 else if (strcmp(name, "SrtCodeset") == 0)
2892                         srt_codeset_opts_set(ud->builder, "SrtCodeset");
2893                 else if (strcmp(name, "title") == 0)
2894                         title_opts_set(ud->builder, "title");
2895                 else if (strcmp(name, "SubtitleTrack") == 0)
2896                         subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2897                 else if (strcmp(name, "AudioTrack") == 0)
2898                         audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2899                 else
2900                         generic_opts_set(ud->builder, name, find_combo_table(name));
2901         }
2902         if (handler_id > 0)
2903         {
2904                 g_signal_handler_unblock ((gpointer)combo, handler_id);
2905         }
2906 }
2907         
2908 static void
2909 init_ui_combo_boxes(GtkBuilder *builder)
2910 {
2911         gint ii;
2912
2913         init_combo_box(builder, "AudioBitrate");
2914         init_combo_box(builder, "AudioSamplerate");
2915         init_combo_box(builder, "VideoFramerate");
2916         init_combo_box(builder, "AudioMixdown");
2917         init_combo_box(builder, "SrtLanguage");
2918         init_combo_box(builder, "PreferredLanguage");
2919         init_combo_box(builder, "SrtCodeset");
2920         init_combo_box(builder, "title");
2921         init_combo_box(builder, "AudioTrack");
2922         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2923         {
2924                 init_combo_box(builder, combo_name_map[ii].name);
2925         }
2926 }
2927         
2928 static const char * turbo_opts = 
2929         "ref=1:subme=2:me=dia:analyse=none:trellis=0:"
2930         "no-fast-pskip=0:8x8dct=0";
2931
2932 // Construct the x264 options string
2933 // The result is allocated, so someone must free it at some point.
2934 gchar*
2935 ghb_build_x264opts_string(GValue *settings)
2936 {
2937         gchar *result;
2938         gchar *opts = ghb_settings_get_string(settings, "x264Option");
2939         if (opts != NULL)
2940         {
2941                 result = opts;
2942         }
2943         else
2944         {
2945                 result = g_strdup("");
2946         }
2947         return result;
2948 }
2949
2950 void
2951 ghb_part_duration(gint tt, gint sc, gint ec, gint *hh, gint *mm, gint *ss)
2952 {
2953         hb_list_t  * list;
2954         hb_title_t * title;
2955     hb_chapter_t * chapter;
2956         gint count, c;
2957         gint64 duration;
2958         
2959         *hh = *mm = *ss = 0;
2960         if (h_scan == NULL) return;
2961         list = hb_get_titles( h_scan );
2962     title = (hb_title_t*)hb_list_item( list, tt );
2963         if (title == NULL) return;
2964
2965         *hh = title->hours;
2966         *mm = title->minutes;
2967         *ss = title->seconds;
2968
2969         count = hb_list_count(title->list_chapter);
2970         if (sc > count) sc = count;
2971         if (ec > count) ec = count;
2972
2973         if (sc == 1 && ec == count)
2974                 return;
2975
2976         duration = 0;
2977         for (c = sc; c <= ec; c++)
2978         {
2979                 chapter = hb_list_item(title->list_chapter, c-1);
2980                 duration += chapter->duration;
2981         }
2982
2983         *hh =   duration / 90000 / 3600;
2984         *mm = ((duration / 90000) % 3600) / 60;
2985         *ss =  (duration / 90000) % 60;
2986 }
2987
2988 void
2989 ghb_get_chapter_duration(gint ti, gint ii, gint *hh, gint *mm, gint *ss)
2990 {
2991         hb_list_t  * list;
2992         hb_title_t * title;
2993     hb_chapter_t * chapter;
2994         gint count;
2995         
2996         g_debug("ghb_get_chapter_duration (title = %d)\n", ti);
2997         *hh = *mm = *ss = 0;
2998         if (h_scan == NULL) return;
2999         list = hb_get_titles( h_scan );
3000     title = (hb_title_t*)hb_list_item( list, ti );
3001         if (title == NULL) return;
3002         count = hb_list_count( title->list_chapter );
3003         if (ii >= count) return;
3004         chapter = hb_list_item(title->list_chapter, ii);
3005         if (chapter == NULL) return;
3006         *hh = chapter->hours;
3007         *mm = chapter->minutes;
3008         *ss = chapter->seconds;
3009 }
3010
3011 GValue*
3012 ghb_get_chapters(gint titleindex)
3013 {
3014         hb_list_t  * list;
3015         hb_title_t * title;
3016     hb_chapter_t * chapter;
3017         gint count, ii;
3018         GValue *chapters = NULL;
3019         
3020         g_debug("ghb_get_chapters (title = %d)\n", titleindex);
3021         if (h_scan == NULL) return NULL;
3022         list = hb_get_titles( h_scan );
3023     title = (hb_title_t*)hb_list_item( list, titleindex );
3024         if (title == NULL) return NULL;
3025         count = hb_list_count( title->list_chapter );
3026         chapters = ghb_array_value_new(count);
3027         for (ii = 0; ii < count; ii++)
3028         {
3029                 chapter = hb_list_item(title->list_chapter, ii);
3030                 if (chapter == NULL) break;
3031                 if (chapter->title == NULL || chapter->title[0] == 0)
3032                 {
3033                         gchar *str;
3034                         str = g_strdup_printf ("Chapter %2d", ii+1);
3035                         ghb_array_append(chapters, ghb_string_value_new(str));
3036                         g_free(str);
3037                 }
3038                 else 
3039                 {
3040                         ghb_array_append(chapters, ghb_string_value_new(chapter->title));
3041                 }
3042         }
3043         return chapters;
3044 }
3045
3046 gboolean
3047 ghb_ac3_in_audio_list(const GValue *audio_list)
3048 {
3049         gint count, ii;
3050
3051         count = ghb_array_len(audio_list);
3052         for (ii = 0; ii < count; ii++)
3053         {
3054                 GValue *asettings;
3055                 gint acodec;
3056
3057                 asettings = ghb_array_get_nth(audio_list, ii);
3058                 acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
3059                 if (acodec & HB_ACODEC_AC3)
3060                         return TRUE;
3061         }
3062         return FALSE;
3063 }
3064
3065 static void
3066 audio_bitrate_opts_add(GtkBuilder *builder, const gchar *name, gint rate)
3067 {
3068         GtkTreeIter iter;
3069         GtkListStore *store;
3070         gchar *str;
3071         
3072         g_debug("audio_bitrate_opts_add ()\n");
3073
3074         if (rate < 8) return;
3075
3076         store = get_combo_box_store(builder, name);
3077         if (!find_combo_item_by_int(GTK_TREE_MODEL(store), rate, &iter))
3078         {
3079                 str = g_strdup_printf ("<small>%d</small>", rate);
3080                 gtk_list_store_append(store, &iter);
3081                 gtk_list_store_set(store, &iter, 
3082                                                    0, str, 
3083                                                    1, TRUE, 
3084                                                    2, str, 
3085                                                    3, (gdouble)rate, 
3086                                                    4, str, 
3087                                                    -1);
3088                 g_free(str);
3089         }
3090 }
3091
3092 static void
3093 audio_bitrate_opts_clean(
3094         GtkBuilder *builder, 
3095         const gchar *name, 
3096         gint first_rate, 
3097         gint last_rate)
3098 {
3099         GtkTreeIter iter;
3100         GtkListStore *store;
3101         gdouble ivalue;
3102         gboolean done = FALSE;
3103         gint ii = 0;
3104         guint last = (guint)last_rate;
3105         guint first = (guint)first_rate;
3106         
3107         g_debug("audio_bitrate_opts_clean ()\n");
3108         store = get_combo_box_store(builder, name);
3109         if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL(store), &iter))
3110         {
3111                 do
3112                 {
3113                         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 3, &ivalue, -1);
3114                         if (search_rates(
3115                                 hb_audio_bitrates, ivalue, hb_audio_bitrates_count) < 0)
3116                         {
3117                                 done = !gtk_list_store_remove(store, &iter);
3118                         }
3119                         else if (ivalue < first || ivalue > last)
3120                         {
3121                                 ii++;
3122                                 gtk_list_store_set(store, &iter, 1, FALSE, -1);
3123                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
3124                         }
3125                         else
3126                         {
3127                                 ii++;
3128                                 gtk_list_store_set(store, &iter, 1, TRUE, -1);
3129                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
3130                         }
3131                 } while (!done);
3132         }
3133 }
3134
3135 static void
3136 audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name)
3137 {
3138         GtkTreeIter iter;
3139         GtkListStore *store;
3140         gint ii;
3141         gchar *str;
3142         
3143         g_debug("audio_bitrate_opts_set ()\n");
3144         store = get_combo_box_store(builder, name);
3145         gtk_list_store_clear(store);
3146         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
3147         {
3148                 gtk_list_store_append(store, &iter);
3149                 str = g_strdup_printf ("<small>%s</small>", 
3150                         hb_audio_bitrates[ii].string);
3151                 gtk_list_store_set(store, &iter, 
3152                                                    0, str,
3153                                                    1, TRUE, 
3154                                                    2, hb_audio_bitrates[ii].string, 
3155                                                    3, (gdouble)hb_audio_bitrates[ii].rate, 
3156                                                    4, hb_audio_bitrates[ii].string, 
3157                                                    -1);
3158                 g_free(str);
3159         }
3160 }
3161
3162 void
3163 ghb_set_passthru_bitrate_opts(GtkBuilder *builder, gint bitrate)
3164 {
3165         audio_bitrate_opts_add(builder, "AudioBitrate", bitrate);
3166 }
3167
3168 void
3169 ghb_set_default_bitrate_opts(
3170         GtkBuilder *builder, 
3171         gint first_rate, 
3172         gint last_rate)
3173 {
3174         audio_bitrate_opts_clean(builder, "AudioBitrate", first_rate, last_rate);
3175 }
3176
3177 static ghb_status_t hb_status;
3178
3179 void
3180 ghb_combo_init(signal_user_data_t *ud)
3181 {
3182         // Set up the list model for the combos
3183         init_ui_combo_boxes(ud->builder);
3184         // Populate all the combos
3185         ghb_update_ui_combo_box(ud, NULL, 0, TRUE);
3186 }
3187
3188 void
3189 ghb_backend_init(gint debug)
3190 {
3191     /* Init libhb */
3192     h_scan = hb_init( debug, 0 );
3193     h_queue = hb_init( debug, 0 );
3194 }
3195
3196 void
3197 ghb_backend_close()
3198 {
3199         hb_close(&h_queue);
3200         hb_close(&h_scan);
3201         hb_global_close();
3202 }
3203
3204 void ghb_backend_scan_stop()
3205 {
3206     hb_scan_stop( h_scan );
3207 }
3208
3209 void
3210 ghb_backend_scan(const gchar *path, gint titleindex, gint preview_count, uint64_t min_duration)
3211 {
3212     hb_scan( h_scan, path, titleindex, preview_count, 1, min_duration );
3213         hb_status.scan.state |= GHB_STATE_SCANNING;
3214         // initialize count and cur to something that won't cause FPE
3215         // when computing progress
3216         hb_status.scan.title_count = 1;
3217         hb_status.scan.title_cur = 0;
3218 }
3219
3220 void
3221 ghb_backend_queue_scan(const gchar *path, gint titlenum)
3222 {
3223         g_debug("ghb_backend_queue_scan()");
3224         hb_scan( h_queue, path, titlenum, 10, 0, 0 );
3225         hb_status.queue.state |= GHB_STATE_SCANNING;
3226 }
3227
3228 gint
3229 ghb_get_scan_state()
3230 {
3231         return hb_status.scan.state;
3232 }
3233
3234 gint
3235 ghb_get_queue_state()
3236 {
3237         return hb_status.queue.state;
3238 }
3239
3240 void
3241 ghb_clear_scan_state(gint state)
3242 {
3243         hb_status.scan.state &= ~state;
3244 }
3245
3246 void
3247 ghb_clear_queue_state(gint state)
3248 {
3249         hb_status.queue.state &= ~state;
3250 }
3251
3252 void
3253 ghb_set_scan_state(gint state)
3254 {
3255         hb_status.scan.state |= state;
3256 }
3257
3258 void
3259 ghb_set_queue_state(gint state)
3260 {
3261         hb_status.queue.state |= state;
3262 }
3263
3264 void
3265 ghb_get_status(ghb_status_t *status)
3266 {
3267         memcpy(status, &hb_status, sizeof(ghb_status_t));
3268 }
3269
3270 void 
3271 ghb_track_status()
3272 {
3273     hb_state_t s_scan;
3274     hb_state_t s_queue;
3275
3276         if (h_scan == NULL) return;
3277     hb_get_state( h_scan, &s_scan );
3278         switch( s_scan.state )
3279     {
3280 #define p s_scan.param.scanning
3281         case HB_STATE_SCANNING:
3282                 {
3283                         hb_status.scan.state |= GHB_STATE_SCANNING;
3284                         hb_status.scan.title_count = p.title_count;
3285                         hb_status.scan.title_cur = p.title_cur;
3286                 } break;
3287 #undef p
3288
3289         case HB_STATE_SCANDONE:
3290         {
3291                         hb_status.scan.state &= ~GHB_STATE_SCANNING;
3292                         hb_status.scan.state |= GHB_STATE_SCANDONE;
3293         } break;
3294
3295 #define p s_scan.param.working
3296         case HB_STATE_WORKING:
3297                         hb_status.scan.state |= GHB_STATE_WORKING;
3298                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
3299                         hb_status.scan.job_cur = p.job_cur;
3300                         hb_status.scan.job_count = p.job_count;
3301                         hb_status.scan.progress = p.progress;
3302                         hb_status.scan.rate_cur = p.rate_cur;
3303                         hb_status.scan.rate_avg = p.rate_avg;
3304                         hb_status.scan.hours = p.hours;
3305                         hb_status.scan.minutes = p.minutes;
3306                         hb_status.scan.seconds = p.seconds;
3307                         hb_status.scan.unique_id = p.sequence_id & 0xFFFFFF;
3308             break;
3309 #undef p
3310
3311         case HB_STATE_PAUSED:
3312                         hb_status.scan.state |= GHB_STATE_PAUSED;
3313             break;
3314                                 
3315         case HB_STATE_MUXING:
3316         {
3317                         hb_status.scan.state |= GHB_STATE_MUXING;
3318         } break;
3319
3320 #define p s_scan.param.workdone
3321         case HB_STATE_WORKDONE:
3322                 {
3323             hb_job_t *job;
3324
3325                         hb_status.scan.state |= GHB_STATE_WORKDONE;
3326                         hb_status.scan.state &= ~GHB_STATE_MUXING;
3327                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
3328                         hb_status.scan.state &= ~GHB_STATE_WORKING;
3329                         switch (p.error)
3330                         {
3331                         case HB_ERROR_NONE:
3332                                 hb_status.scan.error = GHB_ERROR_NONE;
3333                                 break;
3334                         case HB_ERROR_CANCELED:
3335                                 hb_status.scan.error = GHB_ERROR_CANCELED;
3336                                 break;
3337                         default:
3338                                 hb_status.scan.error = GHB_ERROR_FAIL;
3339                                 break;
3340                         }
3341                         // Delete all remaining jobs of this encode.
3342                         // An encode can be composed of multiple associated jobs.
3343                         // When a job is stopped, libhb removes it from the job list,
3344                         // but does not remove other jobs that may be associated with it.
3345                         // Associated jobs are taged in the sequence id.
3346             while ((job = hb_job(h_scan, 0)) != NULL) 
3347                 hb_rem( h_scan, job );
3348                 } break;
3349 #undef p
3350     }
3351     hb_get_state( h_queue, &s_queue );
3352         switch( s_queue.state )
3353     {
3354 #define p s_queue.param.scanning
3355         case HB_STATE_SCANNING:
3356                 {
3357                         hb_status.queue.state |= GHB_STATE_SCANNING;
3358                         hb_status.queue.title_count = p.title_count;
3359                         hb_status.queue.title_cur = p.title_cur;
3360                 } break;
3361 #undef p
3362
3363         case HB_STATE_SCANDONE:
3364         {
3365                         hb_status.queue.state &= ~GHB_STATE_SCANNING;
3366                         hb_status.queue.state |= GHB_STATE_SCANDONE;
3367         } break;
3368
3369 #define p s_queue.param.working
3370         case HB_STATE_WORKING:
3371                         hb_status.queue.state |= GHB_STATE_WORKING;
3372                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
3373                         hb_status.queue.state &= ~GHB_STATE_SEARCHING;
3374                         hb_status.queue.job_cur = p.job_cur;
3375                         hb_status.queue.job_count = p.job_count;
3376                         hb_status.queue.progress = p.progress;
3377                         hb_status.queue.rate_cur = p.rate_cur;
3378                         hb_status.queue.rate_avg = p.rate_avg;
3379                         hb_status.queue.hours = p.hours;
3380                         hb_status.queue.minutes = p.minutes;
3381                         hb_status.queue.seconds = p.seconds;
3382                         hb_status.queue.unique_id = p.sequence_id & 0xFFFFFF;
3383             break;
3384
3385         case HB_STATE_SEARCHING:
3386                         hb_status.queue.state |= GHB_STATE_SEARCHING;
3387                         hb_status.queue.state &= ~GHB_STATE_WORKING;
3388                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
3389                         hb_status.queue.job_cur = p.job_cur;
3390                         hb_status.queue.job_count = p.job_count;
3391                         hb_status.queue.progress = p.progress;
3392                         hb_status.queue.rate_cur = p.rate_cur;
3393                         hb_status.queue.rate_avg = p.rate_avg;
3394                         hb_status.queue.hours = p.hours;
3395                         hb_status.queue.minutes = p.minutes;
3396                         hb_status.queue.seconds = p.seconds;
3397                         hb_status.queue.unique_id = p.sequence_id & 0xFFFFFF;
3398             break;
3399 #undef p
3400
3401         case HB_STATE_PAUSED:
3402                         hb_status.queue.state |= GHB_STATE_PAUSED;
3403             break;
3404                                 
3405         case HB_STATE_MUXING:
3406         {
3407                         hb_status.queue.state |= GHB_STATE_MUXING;
3408         } break;
3409
3410 #define p s_queue.param.workdone
3411         case HB_STATE_WORKDONE:
3412                 {
3413             hb_job_t *job;
3414
3415                         hb_status.queue.state |= GHB_STATE_WORKDONE;
3416                         hb_status.queue.state &= ~GHB_STATE_MUXING;
3417                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
3418                         hb_status.queue.state &= ~GHB_STATE_WORKING;
3419                         hb_status.queue.state &= ~GHB_STATE_SEARCHING;
3420                         switch (p.error)
3421                         {
3422                         case HB_ERROR_NONE:
3423                                 hb_status.queue.error = GHB_ERROR_NONE;
3424                                 break;
3425                         case HB_ERROR_CANCELED:
3426                                 hb_status.queue.error = GHB_ERROR_CANCELED;
3427                                 break;
3428                         default:
3429                                 hb_status.queue.error = GHB_ERROR_FAIL;
3430                                 break;
3431                         }
3432                         // Delete all remaining jobs of this encode.
3433                         // An encode can be composed of multiple associated jobs.
3434                         // When a job is stopped, libhb removes it from the job list,
3435                         // but does not remove other jobs that may be associated with it.
3436                         // Associated jobs are taged in the sequence id.
3437             while ((job = hb_job(h_queue, 0)) != NULL) 
3438                 hb_rem( h_queue, job );
3439                 } break;
3440 #undef p
3441     }
3442 }
3443
3444 gboolean
3445 ghb_get_title_info(ghb_title_info_t *tinfo, gint titleindex)
3446 {
3447         hb_list_t  * list;
3448         hb_title_t * title;
3449         
3450     if (h_scan == NULL) return FALSE;
3451         list = hb_get_titles( h_scan );
3452         if( !hb_list_count( list ) )
3453         {
3454                 /* No valid title, stop right there */
3455                 return FALSE;
3456         }
3457
3458         title = hb_list_item( list, titleindex );
3459         if (title == NULL) return FALSE;        // Bad titleindex
3460         tinfo->index = titleindex;
3461         tinfo->width = title->width;
3462         tinfo->height = title->height;
3463         memcpy(tinfo->crop, title->crop, 4 * sizeof(int));
3464         // Don't allow crop to 0
3465         if (title->crop[0] + title->crop[1] >= title->height)
3466                 title->crop[0] = title->crop[1] = 0;
3467         if (title->crop[2] + title->crop[3] >= title->width)
3468                 title->crop[2] = title->crop[3] = 0;
3469         tinfo->num_chapters = hb_list_count(title->list_chapter);
3470         tinfo->rate_base = title->rate_base;
3471         tinfo->rate = title->rate;
3472         tinfo->interlaced = title->detected_interlacing;
3473         hb_reduce(&(tinfo->aspect_n), &(tinfo->aspect_d), 
3474                                 title->width * title->pixel_aspect_width, 
3475                                 title->height * title->pixel_aspect_height);
3476         tinfo->hours = title->hours;
3477         tinfo->minutes = title->minutes;
3478         tinfo->seconds = title->seconds;
3479         tinfo->duration = title->duration;
3480
3481         tinfo->angle_count = title->angle_count;
3482         tinfo->path = title->path;
3483         tinfo->name = title->name;
3484         tinfo->type = title->type;
3485         return TRUE;
3486 }
3487
3488 gboolean
3489 ghb_get_audio_info(ghb_audio_info_t *ainfo, gint titleindex, gint audioindex)
3490 {
3491     hb_audio_config_t *audio;
3492         
3493         audio = get_hb_audio(titleindex, audioindex);
3494         if (audio == NULL) return FALSE; // Bad audioindex
3495         ainfo->codec = audio->in.codec;
3496         ainfo->bitrate = audio->in.bitrate;
3497         ainfo->samplerate = audio->in.samplerate;
3498         return TRUE;
3499 }
3500
3501 gboolean
3502 ghb_audio_is_passthru(gint acodec)
3503 {
3504         g_debug("ghb_audio_is_passthru () \n");
3505         return (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA));
3506 }
3507
3508 gint
3509 ghb_get_default_acodec()
3510 {
3511         return HB_ACODEC_FAAC;
3512 }
3513
3514 static void
3515 picture_settings_deps(signal_user_data_t *ud)
3516 {
3517         gboolean autoscale, keep_aspect, enable_keep_aspect;
3518         gboolean enable_scale_width, enable_scale_height;
3519         gboolean enable_disp_width, enable_disp_height, enable_par;
3520         gint pic_par;
3521         GtkWidget *widget;
3522
3523         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
3524         if (pic_par == 1)
3525         {
3526                 ghb_ui_update(ud, "autoscale", ghb_boolean_value(TRUE));
3527                 ghb_ui_update(ud, "PictureModulus", ghb_int_value(2));
3528                 ghb_ui_update(ud, "PictureLooseCrop", ghb_boolean_value(TRUE));
3529         }
3530         enable_keep_aspect = (pic_par != 1 && pic_par != 2);
3531         if (!enable_keep_aspect)
3532         {
3533                 ghb_ui_update(ud, "PictureKeepRatio", ghb_boolean_value(TRUE));
3534         }
3535         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
3536         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
3537
3538         enable_scale_width = !autoscale && (pic_par != 1);
3539         enable_scale_height = !autoscale && (pic_par != 1);
3540         enable_disp_width = (pic_par == 3) && !keep_aspect;
3541         enable_par = (pic_par == 3) && !keep_aspect;
3542         enable_disp_height = FALSE;
3543
3544         widget = GHB_WIDGET(ud->builder, "PictureModulus");
3545         gtk_widget_set_sensitive(widget, pic_par != 1);
3546         widget = GHB_WIDGET(ud->builder, "PictureLooseCrop");
3547         gtk_widget_set_sensitive(widget, pic_par != 1);
3548         widget = GHB_WIDGET(ud->builder, "scale_width");
3549         gtk_widget_set_sensitive(widget, enable_scale_width);
3550         widget = GHB_WIDGET(ud->builder, "scale_height");
3551         gtk_widget_set_sensitive(widget, enable_scale_height);
3552         widget = GHB_WIDGET(ud->builder, "PictureDisplayWidth");
3553         gtk_widget_set_sensitive(widget, enable_disp_width);
3554         widget = GHB_WIDGET(ud->builder, "PictureDisplayHeight");
3555         gtk_widget_set_sensitive(widget, enable_disp_height);
3556         widget = GHB_WIDGET(ud->builder, "PicturePARWidth");
3557         gtk_widget_set_sensitive(widget, enable_par);
3558         widget = GHB_WIDGET(ud->builder, "PicturePARHeight");
3559         gtk_widget_set_sensitive(widget, enable_par);
3560         widget = GHB_WIDGET(ud->builder, "PictureKeepRatio");
3561         gtk_widget_set_sensitive(widget, enable_keep_aspect);
3562         widget = GHB_WIDGET(ud->builder, "autoscale");
3563         gtk_widget_set_sensitive(widget, pic_par != 1);
3564 }
3565
3566 void
3567 ghb_set_scale(signal_user_data_t *ud, gint mode)
3568 {
3569         hb_list_t  * list;
3570         hb_title_t * title;
3571         hb_job_t   * job;
3572         gboolean keep_aspect;
3573         gint pic_par;
3574         gboolean autocrop, autoscale, noscale;
3575         gint crop[4], width, height, par_width, par_height;
3576         gint crop_width, crop_height;
3577         gint aspect_n, aspect_d;
3578         gboolean keep_width = (mode & GHB_PIC_KEEP_WIDTH);
3579         gboolean keep_height = (mode & GHB_PIC_KEEP_HEIGHT);
3580         gint step;
3581         GtkWidget *widget;
3582         gint mod;
3583         gint max_width = 0;
3584         gint max_height = 0;
3585         
3586         g_debug("ghb_set_scale ()\n");
3587         picture_settings_deps(ud);
3588         if (h_scan == NULL) return;
3589         list = hb_get_titles( h_scan );
3590         if( !hb_list_count( list ) )
3591         {
3592                 /* No valid title, stop right there */
3593                 return;
3594         }
3595         gint titleindex;
3596
3597         titleindex = ghb_settings_combo_int(ud->settings, "title");
3598         title = hb_list_item( list, titleindex );
3599         if (title == NULL) return;
3600         job   = title->job;
3601         if (job == NULL) return;
3602
3603         if (ud->scale_busy) return;
3604         ud->scale_busy = TRUE;
3605
3606         // First configure widgets
3607         mod = ghb_settings_combo_int(ud->settings, "PictureModulus");
3608         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
3609         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
3610         autocrop = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop");
3611         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
3612         // "Noscale" is a flag that says we prefer to crop extra to satisfy
3613         // alignment constraints rather than scaling to satisfy them.
3614         noscale = ghb_settings_get_boolean(ud->settings, "PictureLooseCrop");
3615         // Align dimensions to either 16 or 2 pixels
3616         // The scaler crashes if the dimensions are not divisible by 2
3617         // x264 also will not accept dims that are not multiple of 2
3618         if (autoscale)
3619         {
3620                 keep_width = FALSE;
3621                 keep_height = FALSE;
3622         }
3623         // Step needs to be at least 2 because odd widths cause scaler crash
3624         step = mod;
3625         widget = GHB_WIDGET (ud->builder, "scale_width");
3626         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3627         widget = GHB_WIDGET (ud->builder, "scale_height");
3628         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3629         if (noscale)
3630         {
3631                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3632                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3633                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3634                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3635                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3636                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3637                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3638                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3639         }
3640         else
3641         {
3642                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3643                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3644                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3645                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3646                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3647                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3648                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3649                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3650         }
3651         ghb_title_info_t tinfo;
3652         ghb_get_title_info (&tinfo, titleindex);
3653         if (autocrop)
3654         {
3655                 crop[0] = tinfo.crop[0];
3656                 crop[1] = tinfo.crop[1];
3657                 crop[2] = tinfo.crop[2];
3658                 crop[3] = tinfo.crop[3];
3659                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3660                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3661                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3662                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3663         }
3664         else
3665         {
3666                 crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
3667                 crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
3668                 crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
3669                 crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
3670         }
3671         if (noscale)
3672         {
3673                 gint need1, need2;
3674
3675                 // Adjust the cropping to accomplish the desired width and height
3676                 crop_width = tinfo.width - crop[2] - crop[3];
3677                 crop_height = tinfo.height - crop[0] - crop[1];
3678                 width = MOD_DOWN(crop_width, mod);
3679                 height = MOD_DOWN(crop_height, mod);
3680
3681                 need1 = (crop_height - height) / 2;
3682                 need2 = crop_height - height - need1;
3683                 crop[0] += need1;
3684                 crop[1] += need2;
3685                 need1 = (crop_width - width) / 2;
3686                 need2 = crop_width - width - need1;
3687                 crop[2] += need1;
3688                 crop[3] += need2;
3689                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3690                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3691                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3692                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3693         }
3694         hb_reduce(&aspect_n, &aspect_d, 
3695                                 title->width * title->pixel_aspect_width, 
3696                                 title->height * title->pixel_aspect_height);
3697         crop_width = title->width - crop[2] - crop[3];
3698         crop_height = title->height - crop[0] - crop[1];
3699         if (autoscale)
3700         {
3701                 width = crop_width;
3702                 height = crop_height;
3703         }
3704         else
3705         {
3706                 width = ghb_settings_get_int(ud->settings, "scale_width");
3707                 height = ghb_settings_get_int(ud->settings, "scale_height");
3708                 if (mode & GHB_PIC_USE_MAX)
3709                 {
3710                         max_width = MOD_DOWN(
3711                                 ghb_settings_get_int(ud->settings, "PictureWidth"), mod);
3712                         max_height = MOD_DOWN(
3713                                 ghb_settings_get_int(ud->settings, "PictureHeight"), mod);
3714                 }
3715         }
3716         g_debug("max_width %d, max_height %d\n", max_width, max_height);
3717
3718         if (width < 16)
3719                 width = title->width - crop[2] - crop[3];
3720         if (height < 16)
3721                 height = title->height - crop[0] - crop[1];
3722
3723         width = MOD_ROUND(width, mod);
3724         height = MOD_ROUND(height, mod);
3725
3726         job->anamorphic.mode = pic_par;
3727         if (pic_par)
3728         {
3729                 // The scaler crashes if the dimensions are not divisible by 2
3730                 // Align mod 2.  And so does something in x264_encoder_headers()
3731                 job->modulus = mod;
3732                 job->anamorphic.par_width = title->pixel_aspect_width;
3733                 job->anamorphic.par_height = title->pixel_aspect_height;
3734                 job->anamorphic.dar_width = 0;
3735                 job->anamorphic.dar_height = 0;
3736
3737                 if (keep_height && pic_par == 2)
3738                         width = ((double)height * crop_width / crop_height);
3739                 job->width = width;
3740                 job->height = height;
3741                 job->maxWidth = max_width;
3742                 job->maxHeight = max_height;
3743                 job->crop[0] = crop[0]; job->crop[1] = crop[1];
3744                 job->crop[2] = crop[2]; job->crop[3] = crop[3];
3745                 if (job->anamorphic.mode == 3 && !keep_aspect)
3746                 {
3747                         job->anamorphic.keep_display_aspect = 0;
3748                         if (mode & GHB_PIC_KEEP_PAR)
3749                         {
3750                                 job->anamorphic.par_width = 
3751                                         ghb_settings_get_int(ud->settings, "PicturePARWidth");
3752                                 job->anamorphic.par_height = 
3753                                         ghb_settings_get_int(ud->settings, "PicturePARHeight");
3754                         }
3755                         else
3756                         {
3757                                 job->anamorphic.dar_width = 
3758                                         ghb_settings_get_int(ud->settings, 
3759                                                                                 "PictureDisplayWidth");
3760                                 job->anamorphic.dar_height = height;
3761                         }
3762                 }
3763                 else
3764                 {
3765                         job->anamorphic.keep_display_aspect = 1;
3766                 }
3767                 // hb_set_anamorphic_size will adjust par, dar, and width/height
3768                 // to conform to job parameters that have been set, including 
3769                 // maxWidth and maxHeight
3770                 hb_set_anamorphic_size( job, &width, &height, 
3771                                                                 &par_width, &par_height );
3772                 if (job->anamorphic.mode == 3 && !keep_aspect && 
3773                         mode & GHB_PIC_KEEP_PAR)
3774                 {
3775                         // hb_set_anamorphic_size reduces the par, which we
3776                         // don't want in this case because the user is
3777                         // explicitely specifying it.
3778                         par_width = ghb_settings_get_int(ud->settings, 
3779                                                                                         "PicturePARWidth");
3780                         par_height = ghb_settings_get_int(ud->settings, 
3781                                                                                                 "PicturePARHeight");
3782                 }
3783         }
3784         else 
3785         {
3786                 // Adjust dims according to max values
3787                 if (max_height)
3788                         height = MIN(height, max_height);
3789                 if (max_width)
3790                         width = MIN(width, max_width);
3791
3792                 if (keep_aspect)
3793                 {
3794                         gdouble par;
3795                         gint new_width, new_height;
3796                         
3797                         // Compute pixel aspect ration.  
3798                         par = (gdouble)(title->height * aspect_n) / (title->width * aspect_d);
3799                         // Must scale so that par becomes 1:1
3800                         // Try to keep largest dimension
3801                         new_height = (crop_height * ((gdouble)width/crop_width) / par);
3802                         new_width = (crop_width * ((gdouble)height/crop_height) * par);
3803
3804                         if (max_width && new_width > max_width)
3805                         {
3806                                 height = new_height;
3807                         }
3808                         else if (max_height && new_height > max_height)
3809                         {
3810                                 width = new_width;
3811                         }
3812                         else if (keep_width)
3813                         {
3814                                 height = new_height;
3815                         }
3816                         else if (keep_height)
3817                         {
3818                                 width = new_width;
3819                         }
3820                         else if (width > new_width)
3821                         {
3822                                 height = new_height;
3823                         }
3824                         else
3825                         {
3826                                 width = new_width;
3827                         }
3828                         g_debug("new w %d h %d\n", width, height);
3829                 }
3830                 width = MOD_ROUND(width, mod);
3831                 height = MOD_ROUND(height, mod);
3832                 if (max_height)
3833                         height = MIN(height, max_height);
3834                 if (max_width)
3835                         width = MIN(width, max_width);
3836                 par_width = par_height = 1;
3837         }
3838         ghb_ui_update(ud, "scale_width", ghb_int64_value(width));
3839         ghb_ui_update(ud, "scale_height", ghb_int64_value(height));
3840
3841         gint disp_width, dar_width, dar_height;
3842         gchar *str;
3843
3844         disp_width = (gdouble)(width * par_width / par_height) + 0.5;
3845         hb_reduce(&dar_width, &dar_height, disp_width, height);
3846                 
3847         gint iaspect = dar_width * 9 / dar_height;
3848         if (dar_width > 2 * dar_height)
3849         {
3850                 str = g_strdup_printf("%.2f : 1", (gdouble)dar_width / dar_height);
3851         }
3852         else if (iaspect <= 16 && iaspect >= 15)
3853         {
3854                 str = g_strdup_printf("%.2f : 9", (gdouble)dar_width * 9 / dar_height);
3855         }
3856         else if (iaspect <= 12 && iaspect >= 11)
3857         {
3858                 str = g_strdup_printf("%.2f : 3", (gdouble)dar_width * 3 / dar_height);
3859         }
3860         else
3861         {
3862                 str = g_strdup_printf("%d : %d", dar_width, dar_height);
3863         }
3864         ghb_ui_update(ud, "display_aspect", ghb_string_value(str));
3865         g_free(str);
3866         ghb_ui_update(ud, "PicturePARWidth", ghb_int64_value(par_width));
3867         ghb_ui_update(ud, "PicturePARHeight", ghb_int64_value(par_height));
3868         ghb_ui_update(ud, "PictureDisplayWidth", ghb_int64_value(disp_width));
3869         ghb_ui_update(ud, "PictureDisplayHeight", ghb_int64_value(height));
3870         ud->scale_busy = FALSE;
3871 }
3872
3873 static void
3874 set_preview_job_settings(hb_job_t *job, GValue *settings)
3875 {
3876         job->crop[0] = ghb_settings_get_int(settings, "PictureTopCrop");
3877         job->crop[1] = ghb_settings_get_int(settings, "PictureBottomCrop");
3878         job->crop[2] = ghb_settings_get_int(settings, "PictureLeftCrop");
3879         job->crop[3] = ghb_settings_get_int(settings, "PictureRightCrop");
3880
3881         job->anamorphic.mode = ghb_settings_combo_int(settings, "PicturePAR");
3882         job->modulus = 
3883                 ghb_settings_combo_int(settings, "PictureModulus");
3884         job->width = ghb_settings_get_int(settings, "scale_width");
3885         job->height = ghb_settings_get_int(settings, "scale_height");
3886         if (ghb_settings_get_boolean(settings, "show_crop"))
3887         {
3888                 gdouble xscale = (gdouble)job->width / 
3889                         (gdouble)(job->title->width - job->crop[2] - job->crop[3]);
3890                 gdouble yscale = (gdouble)job->height / 
3891                         (gdouble)(job->title->height - job->crop[0] - job->crop[1]);
3892         
3893                 job->width += xscale * (job->crop[2] + job->crop[3]);
3894                 job->height += yscale * (job->crop[0] + job->crop[1]);
3895                 job->crop[0] = 0;
3896                 job->crop[1] = 0;
3897                 job->crop[2] = 0;
3898                 job->crop[3] = 0;
3899                 job->modulus = 2;
3900         }
3901
3902         gboolean decomb_deint = ghb_settings_get_boolean(settings, "PictureDecombDeinterlace");
3903         if (decomb_deint)
3904         {
3905                 gint decomb = ghb_settings_combo_int(settings, "PictureDecomb");
3906                 job->deinterlace = (decomb == 0) ? 0 : 1;
3907         }
3908         else
3909         {
3910                 gint deint = ghb_settings_combo_int(settings, "PictureDeinterlace");
3911                 job->deinterlace = (deint == 0) ? 0 : 1;
3912         }
3913
3914         gboolean keep_aspect;
3915         keep_aspect = ghb_settings_get_boolean(settings, "PictureKeepRatio");
3916         if (job->anamorphic.mode)
3917         {
3918                 job->anamorphic.par_width = job->title->pixel_aspect_width;
3919                 job->anamorphic.par_height = job->title->pixel_aspect_height;
3920                 job->anamorphic.dar_width = 0;
3921                 job->anamorphic.dar_height = 0;
3922
3923                 if (job->anamorphic.mode == 3 && !keep_aspect)
3924                 {
3925                         job->anamorphic.keep_display_aspect = 0;
3926                         job->anamorphic.par_width = 
3927                                 ghb_settings_get_int(settings, "PicturePARWidth");
3928                         job->anamorphic.par_height = 
3929                                 ghb_settings_get_int(settings, "PicturePARHeight");
3930                 }
3931                 else
3932                 {
3933                         job->anamorphic.keep_display_aspect = 1;
3934                 }
3935         }
3936 }
3937
3938 gint
3939 ghb_calculate_target_bitrate(GValue *settings, gint titleindex)
3940 {
3941         hb_list_t  * list;
3942         hb_title_t * title;
3943         hb_job_t   * job;
3944         gint size;
3945
3946         if (h_scan == NULL) return 1500;
3947         list = hb_get_titles( h_scan );
3948     title = hb_list_item( list, titleindex );
3949         if (title == NULL) return 1500;
3950         job   = title->job;
3951         if (job == NULL) return 1500;
3952         size = ghb_settings_get_int(settings, "VideoTargetSize");
3953         return hb_calc_bitrate( job, size );
3954 }
3955
3956 gboolean
3957 ghb_validate_filter_string(const gchar *str, gint max_fields)
3958 {
3959         gint fields = 0;
3960         gchar *end;
3961         gdouble val;
3962
3963         if (str == NULL || *str == 0) return TRUE;
3964         while (*str)
3965         {
3966                 val = g_strtod(str, &end);
3967                 if (str != end)
3968                 { // Found a numeric value
3969                         fields++;
3970                         // negative max_fields means infinate
3971                         if (max_fields >= 0 && fields > max_fields) return FALSE;
3972                         if (*end == 0)
3973                                 return TRUE;
3974                         if (*end != ':')
3975                                 return FALSE;
3976                         str = end + 1;
3977                 }
3978                 else
3979                         return FALSE;
3980         }
3981         return FALSE;
3982 }
3983
3984 gboolean
3985 ghb_validate_filters(signal_user_data_t *ud)
3986 {
3987         gchar *str;
3988         gint index;
3989         gchar *message;
3990
3991         gboolean decomb_deint = ghb_settings_get_boolean(ud->settings, "PictureDecombDeinterlace");
3992         // deinte
3993         index = ghb_settings_combo_int(ud->settings, "PictureDeinterlace");
3994         if (!decomb_deint && index == 1)
3995         {
3996                 str = ghb_settings_get_string(ud->settings, "PictureDeinterlaceCustom");
3997                 if (!ghb_validate_filter_string(str, -1))
3998                 {
3999                         message = g_strdup_printf(
4000                                                 "Invalid Deinterlace Settings:\n\n%s\n",
4001                                                 str);
4002                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
4003                         g_free(message);
4004                         g_free(str);
4005                         return FALSE;
4006                 }
4007                 g_free(str);
4008         }
4009         // detel
4010         index = ghb_settings_combo_int(ud->settings, "PictureDetelecine");
4011         if (index == 1)
4012         {
4013                 str = ghb_settings_get_string(ud->settings, "PictureDetelecineCustom");
4014                 if (!ghb_validate_filter_string(str, -1))
4015                 {
4016                         message = g_strdup_printf(
4017                                                 "Invalid Detelecine Settings:\n\n%s\n",
4018                                                 str);
4019                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
4020                         g_free(message);
4021                         g_free(str);
4022                         return FALSE;
4023                 }
4024                 g_free(str);
4025         }
4026         // decomb
4027         index = ghb_settings_combo_int(ud->settings, "PictureDecomb");
4028         if (decomb_deint && index == 1)
4029         {
4030                 str = ghb_settings_get_string(ud->settings, "PictureDecombCustom");
4031                 if (!ghb_validate_filter_string(str, -1))
4032                 {
4033                         message = g_strdup_printf(
4034                                                 "Invalid Decomb Settings:\n\n%s\n",
4035                                                 str);
4036                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
4037                         g_free(message);
4038                         g_free(str);
4039                         return FALSE;
4040                 }
4041                 g_free(str);
4042         }
4043         // denois
4044         index = ghb_settings_combo_int(ud->settings, "PictureDenoise");
4045         if (index == 1)
4046         {
4047                 str = ghb_settings_get_string(ud->settings, "PictureDenoiseCustom");
4048                 if (!ghb_validate_filter_string(str, -1))
4049                 {
4050                         message = g_strdup_printf(
4051                                                 "Invalid Denoise Settings:\n\n%s\n",
4052                                                 str);
4053                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
4054                         g_free(str);
4055                         g_free(message);
4056                         return FALSE;
4057                 }
4058                 g_free(str);
4059         }
4060         return TRUE;
4061 }
4062
4063 gboolean
4064 ghb_validate_video(signal_user_data_t *ud)
4065 {
4066         gint vcodec, mux;
4067         gchar *message;
4068
4069         mux = ghb_settings_combo_int(ud->settings, "FileFormat");
4070         vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
4071         if ((mux == HB_MUX_MP4) && (vcodec == HB_VCODEC_THEORA))
4072         {
4073                 // mp4/theora combination is not supported.
4074                 message = g_strdup_printf(
4075                                         "Theora is not supported in the MP4 container.\n\n"
4076                                         "You should choose a different video codec or container.\n"
4077                                         "If you continue, FFMPEG will be chosen for you.");
4078                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4079                 {
4080                         g_free(message);
4081                         return FALSE;
4082                 }
4083                 g_free(message);
4084                 vcodec = HB_VCODEC_FFMPEG;
4085                 ghb_ui_update(ud, "VideoEncoder", ghb_int64_value(vcodec));
4086         }
4087         return TRUE;
4088 }
4089
4090 gboolean
4091 ghb_validate_subtitles(signal_user_data_t *ud)
4092 {
4093         hb_list_t  * list;
4094         hb_title_t * title;
4095         gchar *message;
4096
4097         if (h_scan == NULL) return FALSE;
4098         list = hb_get_titles( h_scan );
4099         if( !hb_list_count( list ) )
4100         {
4101                 /* No valid title, stop right there */
4102                 g_message("No title found.\n");
4103                 return FALSE;
4104         }
4105
4106         gint titleindex;
4107
4108         titleindex = ghb_settings_combo_int(ud->settings, "title");
4109     title = hb_list_item( list, titleindex );
4110         if (title == NULL) return FALSE;
4111
4112         const GValue *slist, *settings;
4113         gint count, ii, source;
4114         gboolean burned, one_burned = FALSE;
4115
4116         slist = ghb_settings_get_value(ud->settings, "subtitle_list");
4117         count = ghb_array_len(slist);
4118         for (ii = 0; ii < count; ii++)
4119         {
4120                 settings = ghb_array_get_nth(slist, ii);
4121                 source = ghb_settings_get_int(settings, "SubtitleSource");
4122                 burned = ghb_settings_get_boolean(settings, "SubtitleBurned");
4123                 if (burned && one_burned)
4124                 {
4125                         // MP4 can only handle burned vobsubs.  make sure there isn't
4126                         // already something burned in the list
4127                         message = g_strdup_printf(
4128                         "Only one subtitle may be burned into the video.\n\n"
4129                                 "You should change your subtitle selections.\n"
4130                                 "If you continue, some subtitles will be lost.");
4131                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4132                         {
4133                                 g_free(message);
4134                                 return FALSE;
4135                         }
4136                         g_free(message);
4137                         break;
4138                 }
4139                 else if (burned)
4140                 {
4141                         one_burned = TRUE;
4142                 }
4143                 if (source == SRTSUB)
4144                 {
4145                         gchar *filename;
4146
4147                         filename = ghb_settings_get_string(settings, "SrtFile");
4148                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
4149                         {
4150                                 message = g_strdup_printf(
4151                                 "Srt file does not exist or not a regular file.\n\n"
4152                                         "You should choose a valid file.\n"
4153                                         "If you continue, this subtitle will be ignored.");
4154                                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, 
4155                                         "Cancel", "Continue"))
4156                                 {
4157                                         g_free(message);
4158                                         return FALSE;
4159                                 }
4160                                 g_free(message);
4161                                 break;
4162                         }
4163                 }
4164         }
4165         return TRUE;
4166 }
4167
4168 gint
4169 ghb_select_audio_codec(signal_user_data_t *ud, gint track)
4170 {
4171         hb_list_t  * list;
4172         hb_title_t * title;
4173         hb_audio_config_t *audio;
4174
4175         if (h_scan == NULL) return -1;
4176         list = hb_get_titles( h_scan );
4177         if( !hb_list_count( list ) )
4178         {
4179                 return -1;
4180         }
4181
4182         gint titleindex;
4183
4184         titleindex = ghb_settings_combo_int(ud->settings, "title");
4185     title = hb_list_item( list, titleindex );
4186         if (title == NULL) return -1;
4187
4188         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
4189
4190         if (track < 0 || track >= hb_list_count(title->list_audio))
4191                 return -1;
4192
4193         audio = (hb_audio_config_t *) hb_list_audio_config_item(
4194                                                                         title->list_audio, track );
4195         if (mux == HB_MUX_MP4)
4196         {
4197                 if (audio->in.codec == HB_ACODEC_AC3)
4198                         return audio->in.codec;
4199                 else
4200                         return HB_ACODEC_FAAC;
4201         }
4202         else
4203         {
4204                 if (audio->in.codec == HB_ACODEC_AC3 || audio->in.codec == HB_ACODEC_DCA)
4205                         return audio->in.codec;
4206                 else
4207                         return HB_ACODEC_LAME;
4208         }
4209 }
4210
4211 const gchar*
4212 ghb_select_audio_codec_str(signal_user_data_t *ud, gint track)
4213 {
4214         gint acodec, ii;
4215
4216         acodec = ghb_select_audio_codec(ud, track);
4217         for (ii = 0; ii < acodec_opts.count; ii++)
4218         {
4219                 if (acodec_opts.map[ii].ivalue == acodec)
4220                         return acodec_opts.map[ii].option;
4221         }
4222         return "Unknown";
4223 }
4224
4225 gboolean
4226 ghb_validate_audio(signal_user_data_t *ud)
4227 {
4228         hb_list_t  * list;
4229         hb_title_t * title;
4230         gchar *message;
4231         GValue *value;
4232
4233         if (h_scan == NULL) return FALSE;
4234         list = hb_get_titles( h_scan );
4235         if( !hb_list_count( list ) )
4236         {
4237                 /* No valid title, stop right there */
4238                 g_message("No title found.\n");
4239                 return FALSE;
4240         }
4241
4242         gint titleindex;
4243
4244         titleindex = ghb_settings_combo_int(ud->settings, "title");
4245     title = hb_list_item( list, titleindex );
4246         if (title == NULL) return FALSE;
4247         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
4248
4249         const GValue *audio_list;
4250         gint count, ii;
4251
4252         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
4253         count = ghb_array_len(audio_list);
4254         for (ii = 0; ii < count; ii++)
4255         {
4256                 GValue *asettings;
4257             hb_audio_config_t *taudio;
4258
4259                 asettings = ghb_array_get_nth(audio_list, ii);
4260                 gint track = ghb_settings_combo_int(asettings, "AudioTrack");
4261                 gint codec = ghb_settings_combo_int(asettings, "AudioEncoder");
4262                 if (codec == HB_ACODEC_MASK)
4263                         continue;
4264
4265         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
4266                                                                                         title->list_audio, track );
4267                 if (!(taudio->in.codec & codec) && 
4268                         (codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)))
4269                 {
4270                         // Not supported.  AC3 is passthrough only, so input must be AC3
4271                         message = g_strdup_printf(
4272                                                 "The source does not support Pass-Thru.\n\n"
4273                                                 "You should choose a different audio codec.\n"
4274                                                 "If you continue, one will be chosen for you.");
4275                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4276                         {
4277                                 g_free(message);
4278                                 return FALSE;
4279                         }
4280                         g_free(message);
4281                         if (mux == HB_MUX_MKV)
4282                         {
4283                                 codec = HB_ACODEC_LAME;
4284                         }
4285                         else
4286                         {
4287                                 codec = HB_ACODEC_FAAC;
4288                         }
4289                         value = ghb_lookup_acodec_value(codec);
4290                         ghb_settings_take_value(asettings, "AudioEncoder", value);
4291                 }
4292                 gchar *a_unsup = NULL;
4293                 gchar *mux_s = NULL;
4294                 if (mux == HB_MUX_MP4)
4295                 { 
4296                         mux_s = "MP4";
4297                         // mp4/vorbis|DTS combination is not supported.
4298                         if (codec == HB_ACODEC_VORBIS)
4299                         {
4300                                 a_unsup = "Vorbis";
4301                                 codec = HB_ACODEC_FAAC;
4302                         }
4303                         if (codec == HB_ACODEC_DCA)
4304                         {
4305                                 a_unsup = "DTS";
4306                                 codec = HB_ACODEC_FAAC;
4307                         }
4308                 }
4309                 if (a_unsup)
4310                 {
4311                         message = g_strdup_printf(
4312                                                 "%s is not supported in the %s container.\n\n"
4313                                                 "You should choose a different audio codec.\n"
4314                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
4315                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4316                         {
4317                                 g_free(message);
4318                                 return FALSE;
4319                         }
4320                         g_free(message);
4321                         value = ghb_lookup_acodec_value(codec);
4322                         ghb_settings_take_value(asettings, "AudioEncoder", value);
4323                 }
4324                 gint mix = ghb_settings_combo_int (asettings, "AudioMixdown");
4325                 gboolean allow_mono = TRUE;
4326                 gboolean allow_stereo = TRUE;
4327                 gboolean allow_dolby = TRUE;
4328                 gboolean allow_dpl2 = TRUE;
4329                 gboolean allow_6ch = TRUE;
4330                 allow_mono = TRUE;
4331                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4332                 allow_stereo =
4333                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
4334                 allow_dolby =
4335                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
4336                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
4337                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
4338                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
4339                 allow_6ch =
4340                         (codec & ~HB_ACODEC_LAME) &&
4341                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
4342                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
4343
4344                 gchar *mix_unsup = NULL;
4345                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
4346                 {
4347                         mix_unsup = "mono";
4348                 }
4349                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
4350                 {
4351                         mix_unsup = "stereo";
4352                 }
4353                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
4354                 {
4355                         mix_unsup = "Dolby";
4356                 }
4357                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
4358                 {
4359                         mix_unsup = "Dolby Pro Logic II";
4360                 }
4361                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
4362                 {
4363                         mix_unsup = "6 Channel";
4364                 }
4365                 if (mix_unsup)
4366                 {
4367                         message = g_strdup_printf(
4368                                                 "The source audio does not support %s mixdown.\n\n"
4369                                                 "You should choose a different mixdown.\n"
4370                                                 "If you continue, one will be chosen for you.", mix_unsup);
4371                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4372                         {
4373                                 g_free(message);
4374                                 return FALSE;
4375                         }
4376                         g_free(message);
4377                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
4378                         value = get_amix_value(mix);
4379                         ghb_settings_take_value(asettings, "AudioMixdown", value);
4380                 }
4381         }
4382         return TRUE;
4383 }
4384
4385 gboolean
4386 ghb_validate_vquality(GValue *settings)
4387 {
4388         gint vcodec;
4389         gchar *message;
4390         gint min, max;
4391
4392         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
4393         vcodec = ghb_settings_combo_int(settings, "VideoEncoder");
4394         gdouble vquality;
4395         vquality = ghb_settings_get_double(settings, "VideoQualitySlider");
4396         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
4397         {
4398                 switch (vcodec)
4399                 {
4400                         case HB_VCODEC_X264:
4401                         {
4402                                 min = 16;
4403                                 max = 30;
4404                         } break;
4405
4406                         case HB_VCODEC_FFMPEG:
4407                         {
4408                                 min = 1;
4409                                 max = 8;
4410                         } break;
4411
4412                         case HB_VCODEC_THEORA:
4413                         {
4414                                 min = 0;
4415                                 max = 63;
4416                         } break;
4417
4418                         default:
4419                         {
4420                                 min = 48;
4421                                 max = 62;
4422                         } break;
4423                 }
4424                 if (vquality < min || vquality > max)
4425                 {
4426                         message = g_strdup_printf(
4427                                                 "Interesting video quality choise: %d\n\n"
4428                                                 "Typical values range from %d to %d.\n"
4429                                                 "Are you sure you wish to use this setting?",
4430                                                 (gint)vquality, min, max);
4431                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
4432                                                                         "Cancel", "Continue"))
4433                         {
4434                                 g_free(message);
4435                                 return FALSE;
4436                         }
4437                         g_free(message);
4438                 }
4439         }
4440         return TRUE;
4441 }
4442
4443 static void
4444 add_job(hb_handle_t *h, GValue *js, gint unique_id, gint titleindex)
4445 {
4446         hb_list_t  * list;
4447         hb_title_t * title;
4448         hb_job_t   * job;
4449         static gchar *x264opts;
4450         gint sub_id = 0;
4451         gboolean tweaks = FALSE;
4452         gchar *detel_str = NULL;
4453         gchar *decomb_str = NULL;
4454         gchar *deint_str = NULL;
4455         gchar *deblock_str = NULL;
4456         gchar *denoise_str = NULL;
4457         gchar *dest_str = NULL;
4458
4459         g_debug("add_job()\n");
4460         if (h == NULL) return;
4461         list = hb_get_titles( h );
4462         if( !hb_list_count( list ) )
4463         {
4464                 /* No valid title, stop right there */
4465                 return;
4466         }
4467
4468     title = hb_list_item( list, titleindex );
4469         if (title == NULL) return;
4470
4471         /* Set job settings */
4472         job   = title->job;
4473         if (job == NULL) return;
4474
4475         job->angle = ghb_settings_get_int(js, "angle");
4476         job->start_at_preview = ghb_settings_get_int(js, "start_frame") + 1;
4477         if (job->start_at_preview)
4478         {
4479                 job->seek_points = ghb_settings_get_int(js, "preview_count");
4480                 job->pts_to_stop = ghb_settings_get_int(js, "live_duration") * 90000LL;
4481         }
4482
4483         tweaks = ghb_settings_get_boolean(js, "allow_tweaks");
4484         job->mux = ghb_settings_combo_int(js, "FileFormat");
4485         if (job->mux == HB_MUX_MP4)
4486         {
4487                 job->largeFileSize = ghb_settings_get_boolean(js, "Mp4LargeFile");
4488                 job->mp4_optimize = ghb_settings_get_boolean(js, "Mp4HttpOptimize");
4489         }
4490         else
4491         {
4492                 job->largeFileSize = FALSE;
4493                 job->mp4_optimize = FALSE;
4494         }
4495         if (!job->start_at_preview)
4496         {
4497                 gint start, end;
4498                 gint num_chapters = hb_list_count(title->list_chapter);
4499                 gint duration = title->duration / 90000;
4500                 job->chapter_start = 1;
4501                 job->chapter_end = num_chapters;
4502
4503                 if (ghb_settings_combo_int(js, "PtoPType") == 0)
4504                 {
4505                         start = ghb_settings_get_int(js, "start_point");
4506                         end = ghb_settings_get_int(js, "end_point");
4507                         job->chapter_start = MIN( num_chapters, start );
4508                         job->chapter_end   = MAX( job->chapter_start, end );
4509
4510                 }
4511                 if (ghb_settings_combo_int(js, "PtoPType") == 1)
4512                 {
4513                         job->chapter_start = 1;
4514                         job->chapter_end = num_chapters;
4515                         start = ghb_settings_get_int(js, "start_point");
4516                         end = ghb_settings_get_int(js, "end_point");
4517                         job->pts_to_start = (int64_t)MIN(duration-1, start) * 90000;
4518                         job->pts_to_stop = (int64_t)MAX(start+1, end) * 90000 - 
4519                                                                 job->pts_to_start;
4520                 }
4521                 if (ghb_settings_combo_int(js, "PtoPType") == 2)
4522                 {
4523                         job->chapter_start = 1;
4524                         job->chapter_end = num_chapters;
4525                         start = ghb_settings_get_int(js, "start_point");
4526                         end = ghb_settings_get_int(js, "end_point");
4527                         gint64 max_frames;
4528                         max_frames = (gint64)duration * title->rate / title->rate_base;
4529                         job->frame_to_start = (int64_t)MIN(max_frames-1, start-1);
4530                         job->frame_to_stop = (int64_t)MAX(start, end-1) - 
4531                                                                  job->frame_to_start;
4532                 }
4533                 job->chapter_markers = ghb_settings_get_boolean(js, "ChapterMarkers");
4534                 if (job->chapter_start == job->chapter_end)
4535                         job->chapter_markers = 0;
4536                 if ( job->chapter_markers )
4537                 {
4538                         GValue *chapters;
4539                         GValue *chapter;
4540                         gint chap;
4541                         gint count;
4542
4543                         chapters = ghb_settings_get_value(js, "chapter_list");
4544                         count = ghb_array_len(chapters);
4545                         for(chap = 0; chap < count; chap++)
4546                         {
4547                                 hb_chapter_t * chapter_s;
4548                                 gchar *name;
4549
4550                                 name = NULL;
4551                                 chapter = ghb_array_get_nth(chapters, chap);
4552                                 name = ghb_value_string(chapter); 
4553                                 if (name == NULL)
4554                                 {
4555                                         name = g_strdup_printf ("Chapter %2d", chap+1);
4556                                 }
4557                                 chapter_s = hb_list_item( job->title->list_chapter, chap);
4558                                 strncpy(chapter_s->title, name, 1023);
4559                                 chapter_s->title[1023] = '\0';
4560                                 g_free(name);
4561                         }
4562                 }
4563         }
4564         job->crop[0] = ghb_settings_get_int(js, "PictureTopCrop");
4565         job->crop[1] = ghb_settings_get_int(js, "PictureBottomCrop");
4566         job->crop[2] = ghb_settings_get_int(js, "PictureLeftCrop");
4567         job->crop[3] = ghb_settings_get_int(js, "PictureRightCrop");
4568
4569         
4570         gboolean decomb_deint = ghb_settings_get_boolean(js, "PictureDecombDeinterlace");
4571         gint decomb = ghb_settings_combo_int(js, "PictureDecomb");
4572         gint deint = ghb_settings_combo_int(js, "PictureDeinterlace");
4573         if (!decomb_deint)
4574                 job->deinterlace = (deint != 0) ? 1 : 0;
4575         else
4576                 job->deinterlace = 0;
4577     job->grayscale   = ghb_settings_get_boolean(js, "VideoGrayScale");
4578
4579         gboolean keep_aspect;
4580         keep_aspect = ghb_settings_get_boolean(js, "PictureKeepRatio");
4581         job->anamorphic.mode = ghb_settings_combo_int(js, "PicturePAR");
4582         job->modulus = ghb_settings_combo_int(js, "PictureModulus");
4583         if (job->anamorphic.mode)
4584         {
4585                 job->anamorphic.par_width = title->pixel_aspect_width;
4586                 job->anamorphic.par_height = title->pixel_aspect_height;
4587                 job->anamorphic.dar_width = 0;
4588                 job->anamorphic.dar_height = 0;
4589
4590                 if (job->anamorphic.mode == 3 && !keep_aspect)
4591                 {
4592                         job->anamorphic.keep_display_aspect = 0;
4593                         job->anamorphic.par_width = 
4594                                 ghb_settings_get_int(js, "PicturePARWidth");
4595                         job->anamorphic.par_height = 
4596                                 ghb_settings_get_int(js, "PicturePARHeight");
4597                 }
4598                 else
4599                 {
4600                         job->anamorphic.keep_display_aspect = 1;
4601                 }
4602         }
4603
4604         /* Add selected filters */
4605         job->filters = hb_list_init();
4606         gint detel = ghb_settings_combo_int(js, "PictureDetelecine");
4607         if ( detel )
4608         {
4609                 if (detel != 1)
4610                 {
4611                         if (detel_opts.map[detel].svalue != NULL)
4612                                 detel_str = g_strdup(detel_opts.map[detel].svalue);
4613                 }
4614                 else
4615                         detel_str = ghb_settings_get_string(js, "PictureDetelecineCustom");
4616                 hb_filter_detelecine.settings = detel_str;
4617                 hb_list_add( job->filters, &hb_filter_detelecine );
4618         }
4619         if ( decomb_deint && decomb )
4620         {
4621                 if (decomb != 1)
4622                 {
4623                         if (decomb_opts.map[decomb].svalue != NULL)
4624                                 decomb_str = g_strdup(decomb_opts.map[decomb].svalue);
4625                 }
4626                 else
4627                         decomb_str = ghb_settings_get_string(js, "PictureDecombCustom");
4628                 hb_filter_decomb.settings = decomb_str;
4629                 hb_list_add( job->filters, &hb_filter_decomb );
4630         }
4631         if( job->deinterlace )
4632         {
4633                 if (deint != 1)
4634                 {
4635                         if (deint_opts.map[deint].svalue != NULL)
4636                                 deint_str = g_strdup(deint_opts.map[deint].svalue);
4637                 }
4638                 else
4639                         deint_str = ghb_settings_get_string(js, "PictureDeinterlaceCustom");
4640                 hb_filter_deinterlace.settings = deint_str;
4641                 hb_list_add( job->filters, &hb_filter_deinterlace );
4642         }
4643         gint deblock = ghb_settings_get_int(js, "PictureDeblock");
4644         if( deblock >= 5 )
4645         {
4646                 deblock_str = g_strdup_printf("%d", deblock);
4647                 hb_filter_deblock.settings = deblock_str;
4648                 hb_list_add( job->filters, &hb_filter_deblock );
4649         }
4650         gint denoise = ghb_settings_combo_int(js, "PictureDenoise");
4651         if( denoise )
4652         {
4653                 if (denoise != 1)
4654                 {
4655                         if (denoise_opts.map[denoise].svalue != NULL)
4656                                 denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
4657                 }
4658                 else
4659                         denoise_str = ghb_settings_get_string(js, "PictureDenoiseCustom");
4660                 hb_filter_denoise.settings = denoise_str;
4661                 hb_list_add( job->filters, &hb_filter_denoise );
4662         }
4663         job->width = ghb_settings_get_int(js, "scale_width");
4664         job->height = ghb_settings_get_int(js, "scale_height");
4665
4666         job->vcodec = ghb_settings_combo_int(js, "VideoEncoder");
4667         if ((job->mux == HB_MUX_MP4 ) && (job->vcodec == HB_VCODEC_THEORA))
4668         {
4669                 // mp4/theora combination is not supported.
4670                 job->vcodec = HB_VCODEC_FFMPEG;
4671         }
4672         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
4673         {
4674                 job->ipod_atom = ghb_settings_get_boolean(js, "Mp4iPodCompatible");
4675         }
4676         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
4677         {
4678                 gdouble vquality;
4679                 vquality = ghb_settings_get_double(js, "VideoQualitySlider");
4680                 job->vquality =  vquality;
4681                 job->vbitrate = 0;
4682         }
4683         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
4684         {
4685                 job->vquality = -1.0;
4686                 job->vbitrate = ghb_settings_get_int(js, "VideoAvgBitrate");
4687         }
4688
4689         gint vrate = ghb_settings_combo_int(js, "VideoFramerate");
4690         if( vrate == 0 )
4691         {
4692                 job->vrate = title->rate;
4693                 job->vrate_base = title->rate_base;
4694                 job->cfr = 0;
4695         }
4696         else
4697         {
4698                 job->vrate = 27000000;
4699                 job->vrate_base = vrate;
4700                 gboolean pfr = ghb_settings_get_boolean(js, "VideoFrameratePFR");
4701                 if (pfr)
4702                         job->cfr = 2;
4703                 else
4704                         job->cfr = 1;
4705         }
4706
4707         const GValue *audio_list;
4708         gint count, ii;
4709         gint tcount = 0;
4710         
4711         audio_list = ghb_settings_get_value(js, "audio_list");
4712         count = ghb_array_len(audio_list);
4713         for (ii = 0; ii < count; ii++)
4714         {
4715                 GValue *asettings;
4716             hb_audio_config_t audio;
4717             hb_audio_config_t *taudio;
4718
4719                 hb_audio_config_init(&audio);
4720                 asettings = ghb_array_get_nth(audio_list, ii);
4721                 audio.in.track = ghb_settings_get_int(asettings, "AudioTrack");
4722                 audio.out.track = tcount;
4723                 audio.out.codec = ghb_settings_combo_int(asettings, "AudioEncoder");
4724         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
4725                                                                         title->list_audio, audio.in.track );
4726                 if (audio.out.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
4727                 {
4728                         if (!(taudio->in.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)))
4729                         {
4730                                 // Not supported.  
4731                                 // AC3/DTS is passthrough only, so input must be AC3/DTS
4732                                 if (job->mux == HB_MUX_MKV)
4733                                 {
4734                                         audio.out.codec = HB_ACODEC_LAME;
4735                                 }
4736                                 else
4737                                 {
4738                                         audio.out.codec = HB_ACODEC_FAAC;
4739                                 }
4740                         }
4741                         else
4742                         {
4743                                 audio.out.codec &= taudio->in.codec;
4744                         }
4745                 }
4746                 if ((job->mux == HB_MUX_MP4) && 
4747                         ((audio.out.codec & HB_ACODEC_DCA) ||
4748                         (audio.out.codec & HB_ACODEC_VORBIS)))
4749                 {
4750                         // mp4/mp3|dts|vorbis combination is not supported.
4751                         audio.out.codec = HB_ACODEC_FAAC;
4752                 }
4753         audio.out.dynamic_range_compression = 
4754                         ghb_settings_get_double(asettings, "AudioTrackDRCSlider");
4755         if (audio.out.dynamic_range_compression < 1.0)
4756                 audio.out.dynamic_range_compression = 0.0;
4757
4758                 // It would be better if this were done in libhb for us, but its not yet.
4759                 if (audio.out.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
4760                 {
4761                         audio.out.mixdown = 0;
4762                 }
4763                 else
4764                 {
4765                         int channels;
4766
4767                         audio.out.mixdown = ghb_settings_combo_int(asettings, "AudioMixdown");
4768                         if (audio.out.mixdown == HB_AMIXDOWN_MONO)
4769                                 channels = 1;
4770                         else if (audio.out.mixdown == HB_AMIXDOWN_6CH)
4771                                 channels = 6;
4772                         else
4773                                 channels = 2;
4774
4775                         // Make sure the mixdown is valid and pick a new one if not.
4776                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
4777                                 audio.in.track, audio.out.codec, audio.out.mixdown);
4778                         audio.out.bitrate = 
4779                                 ghb_settings_combo_int(asettings, "AudioBitrate");
4780                         gint srate = ghb_settings_combo_int(asettings, "AudioSamplerate");
4781                         if (srate == 0) // 0 is same as source
4782                                 audio.out.samplerate = taudio->in.samplerate;
4783                         else
4784                                 audio.out.samplerate = srate;
4785
4786                         audio.out.bitrate = ghb_get_best_audio_bitrate(
4787                                 audio.out.codec, audio.out.bitrate, channels);
4788                 }
4789
4790                 // Add it to the jobs audio list
4791         hb_audio_add( job, &audio );
4792                 tcount++;
4793         }
4794         // I was tempted to move this up with the reset of the video quality
4795         // settings, but I suspect the settings above need to be made
4796         // first in order for hb_calc_bitrate to be accurate.
4797         if (ghb_settings_get_boolean(js, "vquality_type_target"))
4798         {
4799                 gint size;
4800                 
4801                 size = ghb_settings_get_int(js, "VideoTargetSize");
4802         job->vbitrate = hb_calc_bitrate( job, size );
4803                 job->vquality = -1.0;
4804         }
4805
4806         dest_str = ghb_settings_get_string(js, "destination");
4807         job->file = dest_str;
4808
4809         const GValue *subtitle_list;
4810         gint subtitle;
4811         gboolean force, burned, def, one_burned = FALSE;
4812         
4813         ghb_settings_set_boolean(js, "subtitle_scan", FALSE);
4814         subtitle_list = ghb_settings_get_value(js, "subtitle_list");
4815         count = ghb_array_len(subtitle_list);
4816         for (ii = 0; ii < count; ii++)
4817         {
4818                 GValue *ssettings;
4819                 gint source;
4820
4821                 ssettings = ghb_array_get_nth(subtitle_list, ii);
4822
4823                 force = ghb_settings_get_boolean(ssettings, "SubtitleForced");
4824                 burned = ghb_settings_get_boolean(ssettings, "SubtitleBurned");
4825                 def = ghb_settings_get_boolean(ssettings, "SubtitleDefaultTrack");
4826                 source = ghb_settings_get_int(ssettings, "SubtitleSource");
4827
4828                 if (source == SRTSUB)
4829                 {
4830                 hb_subtitle_config_t sub_config;
4831                         gchar *filename, *lang, *code;
4832
4833                         filename = ghb_settings_get_string(ssettings, "SrtFile");
4834                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
4835                         {
4836                                 continue;
4837                         }
4838                         sub_config.offset = ghb_settings_get_int(ssettings, "SrtOffset");
4839                         lang = ghb_settings_get_string(ssettings, "SrtLanguage");
4840                         code = ghb_settings_get_string(ssettings, "SrtCodeset");
4841                         strncpy(sub_config.src_filename, filename, 128);
4842                         strncpy(sub_config.src_codeset, code, 40);
4843                         sub_config.force = 0;
4844                         sub_config.dest = PASSTHRUSUB;
4845                         sub_config.default_track = def;
4846
4847                         hb_srt_add( job, &sub_config, lang);
4848
4849                         g_free(filename);
4850                         g_free(lang);
4851                         g_free(code);
4852                         continue;
4853                 }
4854
4855                 subtitle = ghb_settings_get_int(ssettings, "SubtitleTrack");
4856                 if (subtitle == -1)
4857                 {
4858                         if (!burned)
4859                         {
4860                                 job->select_subtitle_config.dest = PASSTHRUSUB;
4861                         }
4862                         else if (burned)
4863                         {
4864                                 // Only allow one subtitle to be burned into the video
4865                                 if (one_burned)
4866                                         continue;
4867                                 job->select_subtitle_config.dest = RENDERSUB;
4868                                 one_burned = TRUE;
4869                         }
4870                         job->select_subtitle_config.force = force;
4871                         job->select_subtitle_config.default_track = def;
4872                         job->indepth_scan = 1;
4873                         ghb_settings_set_boolean(js, "subtitle_scan", TRUE);
4874                 }
4875                 else if (subtitle >= 0)
4876                 {
4877                 hb_subtitle_t * subt;
4878                 hb_subtitle_config_t sub_config;
4879
4880                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
4881                         if (subt != NULL)
4882                         {
4883                                 sub_config = subt->config;
4884                                 if (!burned)
4885                                 {
4886                                         sub_config.dest = PASSTHRUSUB;
4887                                 }
4888                                 else if ( burned && canBurn(subt->source) )
4889                                 {
4890                                         // Only allow one subtitle to be burned into the video
4891                                         if (one_burned)
4892                                                 continue;
4893                                         sub_config.dest = RENDERSUB;
4894                                         one_burned = TRUE;
4895                                 }
4896                                 sub_config.force = force;
4897                                 sub_config.default_track = def;
4898                         hb_subtitle_add( job, &sub_config, subtitle );
4899                         }
4900                 }
4901         }
4902
4903         // TODO: libhb holds onto a reference to the x264opts and is not
4904         // finished with it until encoding the job is done.  But I can't
4905         // find a way to get at the job before it is removed in order to
4906         // free up the memory I am allocating here.
4907         // The short story is THIS LEAKS.
4908         x264opts = ghb_build_x264opts_string(js);
4909         
4910         if( *x264opts == '\0' )
4911         {
4912                 g_free(x264opts);
4913                 x264opts = NULL;
4914         }
4915
4916         if (job->indepth_scan == 1)
4917         {
4918                 // Subtitle scan. Look for subtitle matching audio language
4919
4920                 /*
4921                  * When subtitle scan is enabled do a fast pre-scan job
4922                  * which will determine which subtitles to enable, if any.
4923                  */
4924                 job->pass = -1;
4925                 job->indepth_scan = 1;
4926                 job->x264opts = NULL;
4927
4928                 /*
4929                  * Add the pre-scan job
4930                  */
4931                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4932                 hb_add( h, job );
4933         }
4934
4935         if( ghb_settings_get_boolean(js, "VideoTwoPass") &&
4936                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
4937         {
4938                 /*
4939                  * If subtitle_scan is enabled then only turn it on
4940                  * for the second pass and then off again for the
4941                  * second.
4942                  */
4943                 job->pass = 1;
4944                 job->indepth_scan = 0;
4945
4946                 /*
4947                  * If turbo options have been selected then append them
4948                  * to the x264opts now (size includes one ':' and the '\0')
4949                  */
4950                 if( ghb_settings_get_boolean(js, "VideoTurboTwoPass") )
4951                 {
4952                         gchar *tmp_x264opts;
4953                         gchar *extra_opts;
4954                         gint badapt;
4955
4956                         badapt = ghb_lookup_badapt(x264opts);
4957                         if (badapt == 2)
4958                         {
4959                                 extra_opts = g_strdup_printf("%s", turbo_opts);
4960                         }
4961                         else
4962                         {
4963                                 extra_opts = g_strdup_printf("%s:weightb=0", turbo_opts);
4964                         }
4965         
4966                         if ( x264opts )
4967                         {
4968                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, extra_opts);
4969                         } 
4970                         else 
4971                         {
4972                                 /*
4973                                  * No x264opts to modify, but apply the turbo options
4974                                  * anyway as they may be modifying defaults
4975                                  */
4976                                 tmp_x264opts = g_strdup_printf("%s", extra_opts);
4977                         }
4978                         g_free(extra_opts);
4979
4980                         job->x264opts = tmp_x264opts;
4981                 }
4982                 else
4983                 {
4984                         job->x264opts = x264opts;
4985                 }
4986                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4987                 hb_add( h, job );
4988                 //if (job->x264opts != NULL)
4989                 //      g_free(job->x264opts);
4990
4991                 job->pass = 2;
4992                 /*
4993                  * On the second pass we turn off subtitle scan so that we
4994                  * can actually encode using any subtitles that were auto
4995                  * selected in the first pass (using the whacky select-subtitle
4996                  * attribute of the job).
4997                  */
4998                 job->indepth_scan = 0;
4999                 job->x264opts = x264opts;
5000                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
5001                 hb_add( h, job );
5002                 //if (job->x264opts != NULL)
5003                 //      g_free(job->x264opts);
5004         }
5005         else
5006         {
5007                 job->x264opts = x264opts;
5008                 job->indepth_scan = 0;
5009                 job->pass = 0;
5010                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
5011                 hb_add( h, job );
5012                 //if (job->x264opts != NULL)
5013                 //      g_free(job->x264opts);
5014         }
5015
5016         // clean up audio list
5017         gint num_audio_tracks = hb_list_count(job->list_audio);
5018         for(ii = 0; ii < num_audio_tracks; ii++)
5019         {
5020                 hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
5021                 hb_list_rem(job->list_audio, audio);
5022                 free(audio);
5023         }
5024
5025         // clean up subtitle list
5026         gint num_subtitle_tracks = hb_list_count(job->list_subtitle);
5027         for(ii = 0; ii < num_subtitle_tracks; ii++)
5028         {
5029                 hb_subtitle_t *subtitle = hb_list_item(job->list_subtitle, 0);
5030                 hb_list_rem(job->list_subtitle, subtitle);
5031                 free(subtitle);
5032         }
5033
5034         if (detel_str) g_free(detel_str);
5035         if (decomb_str) g_free(decomb_str);
5036         if (deint_str) g_free(deint_str);
5037         if (deblock_str) g_free(deblock_str);
5038         if (denoise_str) g_free(denoise_str);
5039         if (dest_str) g_free(dest_str);
5040 }
5041
5042 void
5043 ghb_add_job(GValue *js, gint unique_id)
5044 {
5045         // Since I'm doing a scan of the single title I want just prior 
5046         // to adding the job, there is only the one title to choose from.
5047         add_job(h_queue, js, unique_id, 0);
5048 }
5049
5050 void
5051 ghb_add_live_job(GValue *js, gint unique_id)
5052 {
5053         // Since I'm doing a scan of the single title I want just prior 
5054         // to adding the job, there is only the one title to choose from.
5055         gint titleindex = ghb_settings_combo_int(js, "title");
5056         add_job(h_scan, js, unique_id, titleindex);
5057 }
5058
5059 void
5060 ghb_remove_job(gint unique_id)
5061 {
5062     hb_job_t * job;
5063     gint ii;
5064         
5065         // Multiples passes all get the same id
5066         // remove them all.
5067         // Go backwards through list, so reordering doesn't screw me.
5068         ii = hb_count(h_queue) - 1;
5069     while ((job = hb_job(h_queue, ii--)) != NULL)
5070     {
5071         if ((job->sequence_id & 0xFFFFFF) == unique_id)
5072                         hb_rem(h_queue, job);
5073     }
5074 }
5075
5076 void
5077 ghb_start_queue()
5078 {
5079         hb_start( h_queue );
5080 }
5081
5082 void
5083 ghb_stop_queue()
5084 {
5085         hb_stop( h_queue );
5086 }
5087
5088 void
5089 ghb_start_live_encode()
5090 {
5091         hb_start( h_scan );
5092 }
5093
5094 void
5095 ghb_stop_live_encode()
5096 {
5097         hb_stop( h_scan );
5098 }
5099
5100 void
5101 ghb_pause_queue()
5102 {
5103     hb_state_t s;
5104     hb_get_state2( h_queue, &s );
5105
5106     if( s.state == HB_STATE_PAUSED )
5107     {
5108                 hb_status.queue.state &= ~GHB_STATE_PAUSED;
5109                 hb_resume( h_queue );
5110     }
5111     else
5112     {
5113                 hb_status.queue.state |= GHB_STATE_PAUSED;
5114                 hb_pause( h_queue );
5115     }
5116 }
5117
5118 static void
5119 vert_line(
5120         GdkPixbuf * pb, 
5121         guint8 r, 
5122         guint8 g, 
5123         guint8 b, 
5124         gint x, 
5125         gint y, 
5126         gint len, 
5127         gint width)
5128 {
5129         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
5130         guint8 *dst;
5131         gint ii, jj;
5132         gint channels = gdk_pixbuf_get_n_channels (pb);
5133         gint stride = gdk_pixbuf_get_rowstride (pb);
5134
5135         for (jj = 0; jj < width; jj++)
5136         {
5137                 dst = pixels + y * stride + (x+jj) * channels;
5138                 for (ii = 0; ii < len; ii++)
5139                 {
5140                         dst[0] = r;
5141                         dst[1] = g;
5142                         dst[2] = b;
5143                         dst += stride;
5144                 }
5145         }
5146 }
5147
5148 static void
5149 horz_line(
5150         GdkPixbuf * pb, 
5151         guint8 r, 
5152         guint8 g, 
5153         guint8 b, 
5154         gint x, 
5155         gint y, 
5156         gint len,
5157         gint width)
5158 {
5159         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
5160         guint8 *dst;
5161         gint ii, jj;
5162         gint channels = gdk_pixbuf_get_n_channels (pb);
5163         gint stride = gdk_pixbuf_get_rowstride (pb);
5164
5165         for (jj = 0; jj < width; jj++)
5166         {
5167                 dst = pixels + (y+jj) * stride + x * channels;
5168                 for (ii = 0; ii < len; ii++)
5169                 {
5170                         dst[0] = r;
5171                         dst[1] = g;
5172                         dst[2] = b;
5173                         dst += channels;
5174                 }
5175         }
5176 }
5177
5178 static void
5179 hash_pixbuf(
5180         GdkPixbuf * pb,
5181         gint        x,
5182         gint        y,
5183         gint        w,
5184         gint        h,
5185         gint        step,
5186         gint            orientation)
5187 {
5188         gint ii, jj;
5189         gint line_width = 8;
5190         struct
5191         {
5192                 guint8 r;
5193                 guint8 g;
5194                 guint8 b;
5195         } c[4] = 
5196         {{0x80, 0x80, 0x80},{0xC0, 0x80, 0x70},{0x80, 0xA0, 0x80},{0x70, 0x80, 0xA0}};
5197
5198         if (!orientation)
5199         {
5200                 // vertical lines
5201                 for (ii = x, jj = 0; ii+line_width < x+w; ii += step, jj++)
5202                 {
5203                         vert_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, ii, y, h, line_width);
5204                 }
5205         }
5206         else
5207         {
5208                 // horizontal lines
5209                 for (ii = y, jj = 0; ii+line_width < y+h; ii += step, jj++)
5210                 {
5211                         horz_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, x, ii, w, line_width);
5212                 }
5213         }
5214 }
5215
5216 GdkPixbuf*
5217 ghb_get_preview_image(
5218         gint titleindex, 
5219         gint index, 
5220         signal_user_data_t *ud,
5221         gint *out_width,
5222         gint *out_height)
5223 {
5224         GValue *settings;
5225         hb_title_t *title;
5226         hb_list_t  *list;
5227         
5228         settings = ud->settings;
5229         list = hb_get_titles( h_scan );
5230         if( !hb_list_count( list ) )
5231         {
5232                 /* No valid title, stop right there */
5233                 return NULL;
5234         }
5235     title = hb_list_item( list, titleindex );
5236         if (title == NULL) return NULL;
5237         if (title->job == NULL) return NULL;
5238         set_preview_job_settings(title->job, settings);
5239
5240         // hb_get_preview doesn't compensate for anamorphic, so lets
5241         // calculate scale factors
5242         gint width, height, par_width = 1, par_height = 1;
5243         gint pic_par = ghb_settings_combo_int(settings, "PicturePAR");
5244         if (pic_par)
5245         {
5246                 hb_set_anamorphic_size( title->job, &width, &height, 
5247                                                                 &par_width, &par_height );
5248         }
5249
5250         // Make sure we have a big enough buffer to receive the image from libhb
5251         gint dstWidth = title->job->width;
5252         gint dstHeight= title->job->height;
5253
5254         static guint8 *buffer = NULL;
5255         static gint bufferSize = 0;
5256         gint newSize;
5257
5258         newSize = dstWidth * dstHeight * 4;
5259         if( bufferSize < newSize )
5260         {
5261                 bufferSize = newSize;
5262                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
5263         }
5264         hb_get_preview( h_scan, title, index, buffer );
5265
5266         // Create an GdkPixbuf and copy the libhb image into it, converting it from
5267         // libhb's format something suitable.
5268         
5269         // The image data returned by hb_get_preview is 4 bytes per pixel, 
5270         // BGRA format. Alpha is ignored.
5271
5272         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
5273         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
5274         
5275         guint32 *src = (guint32*)buffer;
5276         guint8 *dst = pixels;
5277
5278         gint ii, jj;
5279         gint channels = gdk_pixbuf_get_n_channels (preview);
5280         gint stride = gdk_pixbuf_get_rowstride (preview);
5281         guint8 *tmp;
5282
5283         for (ii = 0; ii < dstHeight; ii++)
5284         {
5285                 tmp = dst;
5286                 for (jj = 0; jj < dstWidth; jj++)
5287                 {
5288                         tmp[0] = src[0] >> 16;
5289                         tmp[1] = src[0] >> 8;
5290                         tmp[2] = src[0] >> 0;
5291                         tmp += channels;
5292                         src++;
5293                 }
5294                 dst += stride;
5295         }
5296         gint w = ghb_settings_get_int(settings, "scale_width");
5297         gint h = ghb_settings_get_int(settings, "scale_height");
5298         ghb_par_scale(ud, &w, &h, par_width, par_height);
5299
5300         gint c0, c1, c2, c3;
5301         c0 = ghb_settings_get_int(settings, "PictureTopCrop");
5302         c1 = ghb_settings_get_int(settings, "PictureBottomCrop");
5303         c2 = ghb_settings_get_int(settings, "PictureLeftCrop");
5304         c3 = ghb_settings_get_int(settings, "PictureRightCrop");
5305
5306         gdouble xscale = (gdouble)w / (gdouble)(title->width - c2 - c3);
5307         gdouble yscale = (gdouble)h / (gdouble)(title->height - c0 - c1);
5308         
5309         ghb_par_scale(ud, &dstWidth, &dstHeight, par_width, par_height);
5310         *out_width = w;
5311         *out_height = h;
5312         if (ghb_settings_get_boolean(settings, "reduce_hd_preview"))
5313         {
5314                 GdkScreen *ss;
5315                 gint s_w, s_h;
5316                 gint orig_w, orig_h;
5317                 gint factor = 80;
5318
5319                 if (ghb_settings_get_boolean(settings, "preview_fullscreen"))
5320                 {
5321                         factor = 100;
5322                 }
5323                 ss = gdk_screen_get_default();
5324                 s_w = gdk_screen_get_width(ss);
5325                 s_h = gdk_screen_get_height(ss);
5326                 orig_w = dstWidth;
5327                 orig_h = dstHeight;
5328
5329                 if (dstWidth > s_w * factor / 100)
5330                 {
5331                         dstWidth = s_w * factor / 100;
5332                         dstHeight = dstHeight * dstWidth / orig_w;
5333                 }
5334                 if (dstHeight > s_h * factor / 100)
5335                 {
5336                         dstHeight = s_h * factor / 100;
5337                         dstWidth = dstWidth * dstHeight / orig_h;
5338                 }
5339                 xscale *= (gdouble)dstWidth / orig_w;
5340                 yscale *= (gdouble)dstHeight / orig_h;
5341                 w *= (gdouble)dstWidth / orig_w;
5342                 h *= (gdouble)dstHeight / orig_h;
5343         }
5344         GdkPixbuf *scaled_preview;
5345         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
5346         if (ghb_settings_get_boolean(settings, "show_crop"))
5347         {
5348                 c0 *= yscale;
5349                 c1 *= yscale;
5350                 c2 *= xscale;
5351                 c3 *= xscale;
5352                 // Top
5353                 hash_pixbuf(scaled_preview, c2, 0, w, c0, 32, 0);
5354                 // Bottom
5355                 hash_pixbuf(scaled_preview, c2, dstHeight-c1, w, c1, 32, 0);
5356                 // Left
5357                 hash_pixbuf(scaled_preview, 0, c0, c2, h, 32, 1);
5358                 // Right
5359                 hash_pixbuf(scaled_preview, dstWidth-c3, c0, c3, h, 32, 1);
5360         }
5361         g_object_unref (preview);
5362         return scaled_preview;
5363 }
5364
5365 static void
5366 sanitize_volname(gchar *name)
5367 {
5368         gchar *a, *b;
5369
5370         a = b = name;
5371         while (*b)
5372         {
5373                 switch(*b)
5374                 {
5375                 case '<':
5376                         b++;
5377                         break;
5378                 case '>':
5379                         b++;
5380                         break;
5381                 default:
5382                         *a = *b;
5383                         a++; b++;
5384                         break;
5385                 }
5386         }
5387         *a = 0;
5388 }
5389
5390 gchar*
5391 ghb_dvd_volname(const gchar *device)
5392 {
5393         gchar *name;
5394         name = hb_dvd_name((gchar*)device);
5395         if (name != NULL && name[0] != 0)
5396         {
5397                 name = g_strdup(name);
5398                 sanitize_volname(name);
5399                 return name;
5400         }
5401         return NULL;
5402 }