OSDN Git Service

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