OSDN Git Service

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