OSDN Git Service

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