OSDN Git Service

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