OSDN Git Service

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