OSDN Git Service

make it possible to dynamically create and close multiple libhb instances
[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 static const gchar*
735 lookup_generic_string(combo_opts_t *opts, const GValue *gval)
736 {
737         gint ii;
738         gchar *str;
739         const gchar *result = "";
740
741         str = ghb_value_string(gval);
742         for (ii = 0; ii < opts->count; ii++)
743         {
744                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
745                 {
746                         result = opts->map[ii].svalue;
747                         break;
748                 }
749         }
750         g_free(str);
751         return result;
752 }
753
754 static gint
755 lookup_generic_int(combo_opts_t *opts, const GValue *gval)
756 {
757         gint ii;
758         gchar *str;
759         gint result = -1;
760
761         str = ghb_value_string(gval);
762         for (ii = 0; ii < opts->count; ii++)
763         {
764                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
765                 {
766                         result = opts->map[ii].ivalue;
767                         break;
768                 }
769         }
770         g_free(str);
771         return result;
772 }
773
774 static gdouble
775 lookup_generic_double(combo_opts_t *opts, const GValue *gval)
776 {
777         gint ii;
778         gchar *str;
779         gdouble result = -1;
780
781         str = ghb_value_string(gval);
782         for (ii = 0; ii < opts->count; ii++)
783         {
784                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
785                 {
786                         result = opts->map[ii].ivalue;
787                         break;
788                 }
789         }
790         g_free(str);
791         return result;
792 }
793
794 static const gchar*
795 lookup_generic_option(combo_opts_t *opts, const GValue *gval)
796 {
797         gint ii;
798         gchar *str;
799         const gchar *result = "";
800
801         str = ghb_value_string(gval);
802         for (ii = 0; ii < opts->count; ii++)
803         {
804                 if (strcmp(opts->map[ii].shortOpt, str) == 0)
805                 {
806                         result = opts->map[ii].option;
807                         break;
808                 }
809         }
810         g_free(str);
811         return result;
812 }
813
814 static gint
815 lookup_mix_int(const GValue *mix)
816 {
817         gint ii;
818         gchar *str;
819         gint result = 0;
820
821
822         str = ghb_value_string(mix);
823         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
824         {
825                 if (strcmp(hb_audio_mixdowns[ii].short_name, str) == 0)
826                 {
827                         result = hb_audio_mixdowns[ii].amixdown;
828                         break;
829                 }
830         }
831         g_free(str);
832         return result;
833 }
834
835 static const gchar*
836 lookup_mix_option(const GValue *mix)
837 {
838         gint ii;
839         gchar *str;
840         gchar *result = "None";
841
842
843         str = ghb_value_string(mix);
844         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
845         {
846                 if (strcmp(hb_audio_mixdowns[ii].short_name, str) == 0)
847                 {
848                         result = hb_audio_mixdowns[ii].human_readable_name;
849                         break;
850                 }
851         }
852         g_free(str);
853         return result;
854 }
855
856 static gint
857 lookup_video_rate_int(const GValue *vrate)
858 {
859         gint ii;
860         gchar *str;
861         gint result = 0;
862
863         str = ghb_value_string(vrate);
864         for (ii = 0; ii < hb_video_rates_count; ii++)
865         {
866                 if (strcmp(hb_video_rates[ii].string, str) == 0)
867                 {
868                         result = hb_video_rates[ii].rate;
869                         break;
870                 }
871         }
872         g_free(str);
873         // Default to "same as source"
874         return result;
875 }
876
877 static const gchar*
878 lookup_video_rate_option(const GValue *vrate)
879 {
880         gint ii;
881         gchar *str;
882         const gchar *result = "Same as source";
883
884         str = ghb_value_string(vrate);
885         for (ii = 0; ii < hb_video_rates_count; ii++)
886         {
887                 if (strcmp(hb_video_rates[ii].string, str) == 0)
888                 {
889                         result = hb_video_rates[ii].string;
890                         break;
891                 }
892         }
893         g_free(str);
894         // Default to "same as source"
895         return result;
896 }
897
898 static gint
899 lookup_audio_rate_int(const GValue *rate)
900 {
901         gint ii;
902         gchar *str;
903         gint result = 0;
904
905         // Coincidentally, the string "source" will return 0
906         // which is our flag to use "same as source"
907         str = ghb_value_string(rate);
908         for (ii = 0; ii < hb_audio_rates_count; ii++)
909         {
910                 if (strcmp(hb_audio_rates[ii].string, str) == 0)
911                 {
912                         result = hb_audio_rates[ii].rate;
913                         break;
914                 }
915         }
916         g_free(str);
917         return result;
918 }
919
920 static const gchar*
921 lookup_audio_rate_option(const GValue *rate)
922 {
923         gint ii;
924         gchar *str;
925         const gchar *result = "Same as source";
926
927         // Coincidentally, the string "source" will return 0
928         // which is our flag to use "same as source"
929         str = ghb_value_string(rate);
930         for (ii = 0; ii < hb_audio_rates_count; ii++)
931         {
932                 if (strcmp(hb_audio_rates[ii].string, str) == 0)
933                 {
934                         result = hb_audio_rates[ii].string;
935                         break;
936                 }
937         }
938         g_free(str);
939         return result;
940 }
941
942 gint
943 ghb_find_closest_audio_bitrate(gint codec, gint rate)
944 {
945         gint ii;
946         gint low = 32;
947         gint high = 768;
948         gint result;
949
950         if (codec == HB_ACODEC_FAAC)
951                 high = 160;
952
953         result = high;
954         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
955         {
956                 if (hb_audio_bitrates[ii].rate < low)
957                         continue;
958                 if (hb_audio_bitrates[ii].rate > high)
959                         break;
960                 if (rate <= hb_audio_bitrates[ii].rate)
961                 {
962                         result = hb_audio_bitrates[ii].rate;
963                         break;
964                 }
965         }
966         return result;
967 }
968
969 static gint
970 lookup_audio_bitrate_int(const GValue *rate)
971 {
972         gint ii;
973         gchar *str;
974         gint result = 0;
975
976         // Coincidentally, the string "source" will return 0
977         // which is our flag to use "same as source"
978         str = ghb_value_string(rate);
979         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
980         {
981                 if (strcmp(hb_audio_bitrates[ii].string, str) == 0)
982                 {
983                         result = hb_audio_bitrates[ii].rate;
984                         break;
985                 }
986         }
987         g_free(str);
988         return result;
989 }
990
991 static const gchar*
992 lookup_audio_bitrate_option(const GValue *rate)
993 {
994         gint ii;
995         gchar *str;
996         const gchar *result = "Same as source";
997
998         // Coincidentally, the string "source" will return 0
999         // which is our flag to use "same as source"
1000         str = ghb_value_string(rate);
1001         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
1002         {
1003                 if (strcmp(hb_audio_bitrates[ii].string, str) == 0)
1004                 {
1005                         result = hb_audio_bitrates[ii].string;
1006                         break;
1007                 }
1008         }
1009         g_free(str);
1010         return result;
1011 }
1012
1013 static gint
1014 lookup_audio_lang_int(const GValue *rate)
1015 {
1016         gint ii;
1017         gchar *str;
1018         gint result = 0;
1019
1020         // Coincidentally, the string "source" will return 0
1021         // which is our flag to use "same as source"
1022         str = ghb_value_string(rate);
1023         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1024         {
1025                 if (strcmp(ghb_language_table[ii].iso639_2, str) == 0)
1026                 {
1027                         result = ii;
1028                         break;
1029                 }
1030         }
1031         g_free(str);
1032         return result;
1033 }
1034
1035 static const gchar*
1036 lookup_audio_lang_option(const GValue *rate)
1037 {
1038         gint ii;
1039         gchar *str;
1040         const gchar *result = "Same as source";
1041
1042         // Coincidentally, the string "source" will return 0
1043         // which is our flag to use "same as source"
1044         str = ghb_value_string(rate);
1045         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1046         {
1047                 if (strcmp(ghb_language_table[ii].iso639_2, str) == 0)
1048                 {
1049                         if (ghb_language_table[ii].native_name[0] != 0)
1050                                 result = ghb_language_table[ii].native_name;
1051                         else
1052                                 result = ghb_language_table[ii].eng_name;
1053                         break;
1054                 }
1055         }
1056         g_free(str);
1057         return result;
1058 }
1059
1060 GValue*
1061 ghb_lookup_acodec_value(gint val)
1062 {
1063         GValue *value = NULL;
1064         gint ii;
1065
1066         for (ii = 0; ii < acodec_opts.count; ii++)
1067         {
1068                 if ((int)acodec_opts.map[ii].ivalue == val)
1069                 {
1070                         value = ghb_string_value_new(acodec_opts.map[ii].shortOpt);
1071                         break;
1072                 }
1073         }
1074         return value;
1075 }
1076
1077 static GValue*
1078 get_amix_value(gint val)
1079 {
1080         GValue *value = NULL;
1081         gint ii;
1082
1083         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1084         {
1085                 if (hb_audio_mixdowns[ii].amixdown == val)
1086                 {
1087                         value = ghb_string_value_new(hb_audio_mixdowns[ii].short_name);
1088                         break;
1089                 }
1090         }
1091         return value;
1092 }
1093
1094 // Handle for libhb.  Gets set by ghb_backend_init()
1095 static hb_handle_t * h_scan = NULL;
1096 static hb_handle_t * h_queue = NULL;
1097
1098 extern void hb_get_temporary_directory(char path[512]);
1099
1100 gchar*
1101 ghb_get_tmp_dir()
1102 {
1103         char dir[512];
1104
1105         hb_get_temporary_directory(dir);
1106         return g_strdup(dir);
1107 }
1108
1109 void
1110 ghb_hb_cleanup(gboolean partial)
1111 {
1112         char dir[512];
1113
1114         hb_get_temporary_directory(dir);
1115         del_tree(dir, !partial);
1116 }
1117
1118 gint
1119 ghb_subtitle_track_source(signal_user_data_t *ud, gint track)
1120 {
1121         gint titleindex;
1122
1123         if (track == -2)
1124                 return SRTSUB;
1125         if (track < 0)
1126                 return VOBSUB;
1127         titleindex = ghb_settings_combo_int(ud->settings, "title");
1128         if (titleindex < 0)
1129                 return VOBSUB;
1130
1131         hb_list_t  * list;
1132         hb_title_t * title;
1133         hb_subtitle_t * sub;
1134         
1135         if (h_scan == NULL) return VOBSUB;
1136         list = hb_get_titles( h_scan );
1137         if( !hb_list_count( list ) )
1138         {
1139                 /* No valid title, stop right there */
1140                 return VOBSUB;
1141         }
1142         title = hb_list_item( list, titleindex );
1143         if (title == NULL) return VOBSUB;       // Bad titleindex
1144         sub = hb_list_item( title->list_subtitle, track);
1145         if (sub != NULL)
1146                 return sub->source;
1147         else
1148                 return VOBSUB;
1149 }
1150
1151 const char*
1152 ghb_subtitle_track_source_name(signal_user_data_t *ud, gint track)
1153 {
1154         gint titleindex;
1155         const gchar * name = "Unknown";
1156
1157         if (track == -2)
1158         {
1159                 name = "SRT";
1160                 goto done;
1161         }
1162         if (track == -1)
1163         {
1164                 name = "Bitmap";
1165                 goto done;
1166         }
1167
1168         titleindex = ghb_settings_combo_int(ud->settings, "title");
1169         if (titleindex < 0)
1170                 goto done;
1171
1172         hb_list_t  * list;
1173         hb_title_t * title;
1174         hb_subtitle_t * sub;
1175         
1176         if (h_scan == NULL) 
1177                 goto done;
1178         list = hb_get_titles( h_scan );
1179         if( !hb_list_count( list ) )
1180                 goto done;
1181
1182         title = hb_list_item( list, titleindex );
1183         if (title == NULL)
1184                 goto done;
1185
1186         sub = hb_list_item( title->list_subtitle, track);
1187         if (sub != NULL)
1188         {
1189                 switch (sub->source)
1190                 {
1191                         case VOBSUB:
1192                                 name = "Bitmap";
1193                                 break;
1194                         case CC708SUB:
1195                         case CC608SUB:
1196                                 name = "Text";
1197                                 break;
1198                         case SRTSUB:
1199                                 name = "SRT";
1200                                 break;
1201                         default:
1202                                 break;
1203                 }
1204         }
1205
1206 done:
1207         return name;
1208 }
1209
1210 gchar*
1211 ghb_subtitle_track_lang(signal_user_data_t *ud, gint track)
1212 {
1213         gint titleindex;
1214
1215         titleindex = ghb_settings_combo_int(ud->settings, "title");
1216         if (titleindex < 0)
1217                 goto fail;
1218         if (track == -1)
1219                 return ghb_get_user_audio_lang(ud, titleindex, 0);
1220         if (track < 0)
1221                 goto fail;
1222
1223         hb_list_t  * list;
1224         hb_title_t * title;
1225         hb_subtitle_t * sub;
1226         
1227         if (h_scan == NULL)
1228                 goto fail;
1229
1230         list = hb_get_titles( h_scan );
1231         if( !hb_list_count( list ) )
1232         {
1233                 /* No valid title, stop right there */
1234                 goto fail;
1235         }
1236         title = hb_list_item( list, titleindex );
1237         if (title == NULL)      // Bad titleindex
1238                 goto fail;
1239         sub = hb_list_item( title->list_subtitle, track);
1240         if (sub != NULL)
1241                 return g_strdup(sub->iso639_2);
1242
1243 fail:
1244         return g_strdup("und");
1245 }
1246
1247 gint
1248 ghb_get_title_number(gint titleindex)
1249 {
1250         hb_list_t  * list;
1251         hb_title_t * title;
1252         
1253         if (h_scan == NULL) return 1;
1254         list = hb_get_titles( h_scan );
1255         if( !hb_list_count( list ) )
1256         {
1257                 /* No valid title, stop right there */
1258                 return 1;
1259         }
1260         title = hb_list_item( list, titleindex );
1261         if (title == NULL) return 1;    // Bad titleindex
1262         return title->index;
1263 }
1264
1265 static hb_audio_config_t*
1266 get_hb_audio(gint titleindex, gint track)
1267 {
1268         hb_list_t  * list;
1269         hb_title_t * title;
1270     hb_audio_config_t *audio = NULL;
1271         
1272     if (h_scan == NULL) return NULL;
1273         list = hb_get_titles( h_scan );
1274         if( !hb_list_count( list ) )
1275         {
1276                 /* No valid title, stop right there */
1277                 return NULL;
1278         }
1279     title = hb_list_item( list, titleindex );
1280         if (title == NULL) return NULL; // Bad titleindex
1281         if (!hb_list_count(title->list_audio))
1282         {
1283                 return NULL;
1284         }
1285     audio = (hb_audio_config_t *)hb_list_audio_config_item(title->list_audio, track);
1286         return audio;
1287 }
1288
1289 static gint
1290 search_rates(hb_rate_t *rates, gint rate, gint count)
1291 {
1292         gint ii;
1293         for (ii = 0; ii < count; ii++)
1294         {
1295                 if (rates[ii].rate == rate)
1296                         return ii;
1297         }
1298         return -1;
1299 }
1300
1301 static gboolean find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter);
1302
1303 static GtkListStore*
1304 get_combo_box_store(GtkBuilder *builder, const gchar *name)
1305 {
1306         GtkComboBox *combo;
1307         GtkListStore *store;
1308
1309         g_debug("get_combo_box_store() %s\n", name);
1310         // First modify the combobox model to allow greying out of options
1311         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1312         store = GTK_LIST_STORE(gtk_combo_box_get_model (combo));
1313         return store;
1314 }
1315
1316 static void
1317 grey_combo_box_item(GtkBuilder *builder, const gchar *name, gint value, gboolean grey)
1318 {
1319         GtkListStore *store;
1320         GtkTreeIter iter;
1321         
1322         store = get_combo_box_store(builder, name);
1323         if (find_combo_item_by_int(GTK_TREE_MODEL(store), value, &iter))
1324         {
1325                 gtk_list_store_set(store, &iter, 
1326                                                    1, !grey, 
1327                                                    -1);
1328         }
1329 }
1330
1331 void
1332 ghb_grey_combo_options(GtkBuilder *builder)
1333 {
1334         GtkWidget *widget;
1335         gint container, track, titleindex, acodec;
1336     hb_audio_config_t *audio = NULL;
1337         GValue *gval;
1338         
1339         widget = GHB_WIDGET (builder, "title");
1340         gval = ghb_widget_value(widget);
1341         titleindex = ghb_lookup_combo_int("title", gval);
1342         ghb_value_free(gval);
1343         widget = GHB_WIDGET (builder, "AudioTrack");
1344         gval = ghb_widget_value(widget);
1345         track = ghb_lookup_combo_int("AudioTrack", gval);
1346         ghb_value_free(gval);
1347         audio = get_hb_audio(titleindex, track);
1348         widget = GHB_WIDGET (builder, "FileFormat");
1349         gval = ghb_widget_value(widget);
1350         container = ghb_lookup_combo_int("FileFormat", gval);
1351         ghb_value_free(gval);
1352
1353         grey_combo_box_item(builder, "x264_analyse", 3, TRUE);
1354         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_FAAC, FALSE);
1355         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_LAME, FALSE);
1356         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, FALSE);
1357
1358         gboolean allow_dca = TRUE;
1359         allow_dca = (container != HB_MUX_MP4);
1360
1361         grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, FALSE);
1362         if (allow_dca)
1363                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, FALSE);
1364         else
1365                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, TRUE);
1366
1367         if (audio && audio->in.codec != HB_ACODEC_AC3)
1368         {
1369                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_AC3, TRUE);
1370         }
1371         if (audio && audio->in.codec != HB_ACODEC_DCA)
1372         {
1373                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_DCA, TRUE);
1374         }
1375         grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, FALSE);
1376
1377         widget = GHB_WIDGET (builder, "AudioEncoder");
1378         gval = ghb_widget_value(widget);
1379         acodec = ghb_lookup_combo_int("AudioEncoder", gval);
1380         ghb_value_free(gval);
1381         if (acodec != HB_ACODEC_AC3)
1382         {
1383                 grey_combo_box_item(builder, "AudioMixdown", 0, TRUE);
1384         }
1385         if (container == HB_MUX_MP4)
1386         {
1387                 grey_combo_box_item(builder, "AudioEncoder", HB_ACODEC_VORBIS, TRUE);
1388                 grey_combo_box_item(builder, "VideoEncoder", HB_VCODEC_THEORA, TRUE);
1389         }
1390
1391         gboolean allow_mono = TRUE;
1392         gboolean allow_stereo = TRUE;
1393         gboolean allow_dolby = TRUE;
1394         gboolean allow_dpl2 = TRUE;
1395         gboolean allow_6ch = TRUE;
1396         allow_mono = acodec & ~HB_ACODEC_LAME;
1397         allow_6ch = acodec & ~HB_ACODEC_LAME;
1398         if (audio)
1399         {
1400                 allow_mono = allow_mono &&
1401                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA));
1402                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1403                 allow_stereo =
1404                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1405                 allow_dolby =
1406                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1407                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1408                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1409                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1410                 allow_6ch = allow_6ch &&
1411                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1412                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1413                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1414         }
1415         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_MONO, !allow_mono);
1416         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_STEREO, !allow_stereo);
1417         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBY, !allow_dolby);
1418         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_DOLBYPLII, !allow_dpl2);
1419         grey_combo_box_item(builder, "AudioMixdown", HB_AMIXDOWN_6CH, !allow_6ch);
1420 }
1421
1422 gint
1423 ghb_get_best_audio_bitrate(gint acodec, gint br, gint channels)
1424 {
1425         if (acodec & HB_ACODEC_FAAC)
1426         {
1427         int maxbr = channels * 80;
1428                 if (br > maxbr)
1429                         br = maxbr;
1430         }
1431         return br;
1432 }
1433
1434 gint
1435 ghb_get_best_mix(gint titleindex, gint track, gint acodec, gint mix)
1436 {
1437     hb_audio_config_t *audio = NULL;
1438         gboolean allow_mono = TRUE;
1439         gboolean allow_stereo = TRUE;
1440         gboolean allow_dolby = TRUE;
1441         gboolean allow_dpl2 = TRUE;
1442         gboolean allow_6ch = TRUE;
1443         
1444         if (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
1445         {
1446                 // Audio codec pass-thru.  No mixdown
1447                 return 0;
1448         }
1449         audio = get_hb_audio(titleindex, track);
1450         if (audio)
1451         {
1452                 allow_mono =
1453                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1454                         (acodec & ~HB_ACODEC_LAME);
1455                 gint layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
1456                 allow_stereo =
1457                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
1458                 allow_dolby =
1459                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
1460                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
1461                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
1462                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
1463                 allow_6ch =
1464                         (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
1465                         (acodec & ~HB_ACODEC_LAME) &&
1466                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
1467                         (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
1468         }
1469         gboolean greater = FALSE;
1470         if (mix == 0) 
1471         {
1472                 // If no mix is specified, select the best available.
1473                 mix = HB_AMIXDOWN_6CH;
1474         }
1475         if (mix == HB_AMIXDOWN_6CH)
1476         {
1477                 greater = TRUE;
1478                 if (allow_6ch) return HB_AMIXDOWN_6CH;
1479         }
1480         if (mix == HB_AMIXDOWN_DOLBYPLII || greater)
1481         {
1482                 greater = TRUE;
1483                 if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1484         }
1485         if (mix == HB_AMIXDOWN_DOLBY || greater)
1486         {
1487                 greater = TRUE;
1488                 if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1489         }
1490         if (mix == HB_AMIXDOWN_STEREO || greater)
1491         {
1492                 greater = TRUE;
1493                 if (allow_stereo) return HB_AMIXDOWN_STEREO;
1494         }
1495         if (mix == HB_AMIXDOWN_MONO || greater)
1496         {
1497                 greater = TRUE;
1498                 if (allow_mono) return HB_AMIXDOWN_MONO;
1499         }
1500         if (allow_stereo) return HB_AMIXDOWN_STEREO;
1501         if (allow_dolby) return HB_AMIXDOWN_DOLBY;
1502         if (allow_dpl2) return HB_AMIXDOWN_DOLBYPLII;
1503         if (allow_6ch) return HB_AMIXDOWN_6CH;
1504         return 0;
1505 }
1506
1507 // Set up the model for the combo box
1508 static void
1509 init_combo_box(GtkBuilder *builder, const gchar *name)
1510 {
1511         GtkComboBox *combo;
1512         GtkListStore *store;
1513         GtkCellRenderer *cell;
1514
1515         g_debug("init_combo_box() %s\n", name);
1516         // First modify the combobox model to allow greying out of options
1517         combo = GTK_COMBO_BOX(GHB_WIDGET(builder, name));
1518         if (combo == NULL)
1519                 return;
1520         // Store contains:
1521         // 1 - String to display
1522         // 2 - bool indicating whether the entry is selectable (grey or not)
1523         // 3 - String that is used for presets
1524         // 4 - Int value determined by backend
1525         // 5 - String value determined by backend
1526         store = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_BOOLEAN, 
1527                                                            G_TYPE_STRING, G_TYPE_DOUBLE, G_TYPE_STRING);
1528         gtk_combo_box_set_model(combo, GTK_TREE_MODEL(store));
1529
1530         if (GTK_WIDGET_TYPE(combo) == GTK_TYPE_COMBO_BOX)
1531         {
1532                 gtk_cell_layout_clear(GTK_CELL_LAYOUT(combo));
1533         cell = GTK_CELL_RENDERER(gtk_cell_renderer_text_new());
1534         gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combo), cell, TRUE);
1535         gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combo), cell,
1536                 "markup", 0, "sensitive", 1, NULL);
1537         }
1538         else
1539         { // Combo box entry
1540                 gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(combo), 0);
1541         }
1542 }       
1543
1544 static void
1545 audio_samplerate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1546 {
1547         GtkTreeIter iter;
1548         GtkListStore *store;
1549         gint ii;
1550         gchar *str;
1551         
1552         g_debug("audio_samplerate_opts_set ()\n");
1553         store = get_combo_box_store(builder, name);
1554         gtk_list_store_clear(store);
1555         // Add an item for "Same As Source"
1556         gtk_list_store_append(store, &iter);
1557         gtk_list_store_set(store, &iter, 
1558                                            0, "<small>Same as source</small>", 
1559                                            1, TRUE, 
1560                                            2, "source", 
1561                                            3, 0.0, 
1562                                            4, "source", 
1563                                            -1);
1564         for (ii = 0; ii < count; ii++)
1565         {
1566                 gtk_list_store_append(store, &iter);
1567                 str = g_strdup_printf("<small>%s</small>", rates[ii].string);
1568                 gtk_list_store_set(store, &iter, 
1569                                                    0, str,
1570                                                    1, TRUE, 
1571                                                    2, rates[ii].string, 
1572                                                    3, (gdouble)rates[ii].rate, 
1573                                                    4, rates[ii].string, 
1574                                                    -1);
1575                 g_free(str);
1576         }
1577 }
1578
1579 static void
1580 video_rate_opts_set(GtkBuilder *builder, const gchar *name, hb_rate_t *rates, gint count)
1581 {
1582         GtkTreeIter iter;
1583         GtkListStore *store;
1584         gint ii;
1585         
1586         g_debug("video_rate_opts_set ()\n");
1587         store = get_combo_box_store(builder, name);
1588         gtk_list_store_clear(store);
1589         // Add an item for "Same As Source"
1590         gtk_list_store_append(store, &iter);
1591         gtk_list_store_set(store, &iter, 
1592                                            0, "Same as source", 
1593                                            1, TRUE, 
1594                                            2, "source", 
1595                                            3, 0.0, 
1596                                            4, "source", 
1597                                            -1);
1598         for (ii = 0; ii < count; ii++)
1599         {
1600                 gchar *desc = "";
1601                 gchar *option;
1602                 if (strcmp(rates[ii].string, "23.976") == 0)
1603                 {
1604                         desc = "(NTSC Film)";
1605                 }
1606                 else if (strcmp(rates[ii].string, "25") == 0)
1607                 {
1608                         desc = "(PAL Film/Video)";
1609                 }
1610                 else if (strcmp(rates[ii].string, "29.97") == 0)
1611                 {
1612                         desc = "(NTSC Video)";
1613                 }
1614                 option = g_strdup_printf ("%s %s", rates[ii].string, desc);
1615                 gtk_list_store_append(store, &iter);
1616                 gtk_list_store_set(store, &iter, 
1617                                                    0, option, 
1618                                                    1, TRUE, 
1619                                                    2, rates[ii].string, 
1620                                                    3, (gdouble)rates[ii].rate, 
1621                                                    4, rates[ii].string, 
1622                                                    -1);
1623                 g_free(option);
1624         }
1625 }
1626
1627 static void
1628 mix_opts_set(GtkBuilder *builder, const gchar *name)
1629 {
1630         GtkTreeIter iter;
1631         GtkListStore *store;
1632         gint ii;
1633         gchar *str;
1634         
1635         g_debug("mix_opts_set ()\n");
1636         store = get_combo_box_store(builder, name);
1637         gtk_list_store_clear(store);
1638         gtk_list_store_append(store, &iter);
1639         gtk_list_store_set(store, &iter, 
1640                                            0, "<small>None</small>", 
1641                                            1, TRUE, 
1642                                            2, "none", 
1643                                            3, 0.0, 
1644                                            4, "none", 
1645                                            -1);
1646         for (ii = 0; ii < hb_audio_mixdowns_count; ii++)
1647         {
1648                 gtk_list_store_append(store, &iter);
1649                 str = g_strdup_printf("<small>%s</small>",
1650                         hb_audio_mixdowns[ii].human_readable_name);
1651                 gtk_list_store_set(store, &iter, 
1652                                                    0, str,
1653                                                    1, TRUE, 
1654                                                    2, hb_audio_mixdowns[ii].short_name, 
1655                                                    3, (gdouble)hb_audio_mixdowns[ii].amixdown, 
1656                                                    4, hb_audio_mixdowns[ii].internal_name, 
1657                                                    -1);
1658                 g_free(str);
1659         }
1660 }
1661
1662 static void
1663 srt_codeset_opts_set(GtkBuilder *builder, const gchar *name)
1664 {
1665         GtkTreeIter iter;
1666         GtkListStore *store;
1667         gint ii;
1668         
1669         g_debug("srt_codeset_opts_set ()\n");
1670         store = get_combo_box_store(builder, name);
1671         gtk_list_store_clear(store);
1672         for (ii = 0; ii < SRT_TABLE_SIZE; ii++)
1673         {
1674                 gtk_list_store_append(store, &iter);
1675                 gtk_list_store_set(store, &iter, 
1676                                                    0, srt_codeset_table[ii],
1677                                                    1, TRUE, 
1678                                                    2, srt_codeset_table[ii],
1679                                                    3, (gdouble)ii, 
1680                                                    4, srt_codeset_table[ii],
1681                                                    -1);
1682         }
1683         GtkComboBoxEntry *cbe;
1684
1685         cbe = GTK_COMBO_BOX_ENTRY(GHB_WIDGET(builder, name));
1686         //gtk_combo_box_entry_set_text_column(cbe, 0);
1687 }
1688
1689 static void
1690 language_opts_set(GtkBuilder *builder, const gchar *name)
1691 {
1692         GtkTreeIter iter;
1693         GtkListStore *store;
1694         gint ii;
1695         
1696         g_debug("language_opts_set ()\n");
1697         store = get_combo_box_store(builder, name);
1698         gtk_list_store_clear(store);
1699         for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1700         {
1701                 const gchar *lang;
1702
1703                 if (ghb_language_table[ii].native_name[0] != 0)
1704                         lang = ghb_language_table[ii].native_name;
1705                 else
1706                         lang = ghb_language_table[ii].eng_name;
1707                 
1708                 gtk_list_store_append(store, &iter);
1709                 gtk_list_store_set(store, &iter, 
1710                                                    0, lang,
1711                                                    1, TRUE, 
1712                                                    2, ghb_language_table[ii].iso639_2, 
1713                                                    3, (gdouble)ii, 
1714                                                    4, ghb_language_table[ii].iso639_1, 
1715                                                    -1);
1716         }
1717 }
1718
1719 static gchar **titles = NULL;
1720
1721 void
1722 title_opts_set(GtkBuilder *builder, const gchar *name)
1723 {
1724         GtkTreeIter iter;
1725         GtkListStore *store;
1726         hb_list_t  * list = NULL;
1727         hb_title_t * title = NULL;
1728         gint ii;
1729         gint count = 0;
1730         
1731         g_debug("title_opts_set ()\n");
1732         store = get_combo_box_store(builder, name);
1733         gtk_list_store_clear(store);
1734         if (h_scan != NULL)
1735         {
1736                 list = hb_get_titles( h_scan );
1737                 count = hb_list_count( list );
1738                 if (count > 100) count = 100;
1739         }
1740         if (titles) g_strfreev(titles);
1741         if (title_opts.map) g_free(title_opts.map);
1742         if (count > 0)
1743         {
1744                 title_opts.count = count;
1745                 title_opts.map = g_malloc(count*sizeof(options_map_t));
1746                 titles = g_malloc((count+1) * sizeof(gchar*));
1747         }
1748         else
1749         {
1750                 title_opts.count = 1;
1751                 title_opts.map = g_malloc(sizeof(options_map_t));
1752                 titles = NULL;
1753         }
1754         if( count <= 0 )
1755         {
1756                 // No titles.  Fill in a default.
1757                 gtk_list_store_append(store, &iter);
1758                 gtk_list_store_set(store, &iter, 
1759                                                    0, "No Titles", 
1760                                                    1, TRUE, 
1761                                                    2, "none", 
1762                                                    3, -1.0, 
1763                                                    4, "none", 
1764                                                    -1);
1765                 title_opts.map[0].option = "No Titles";
1766                 title_opts.map[0].shortOpt = "none";
1767                 title_opts.map[0].ivalue = -1;
1768                 title_opts.map[0].svalue = "none";
1769                 return;
1770         }
1771         for (ii = 0; ii < count; ii++)
1772         {
1773                 title = (hb_title_t*)hb_list_item(list, ii);
1774                 if (title->type == HB_STREAM_TYPE)
1775                 {
1776                         if (title->duration != 0)
1777                         {
1778                                 titles[ii]  = g_strdup_printf ("%d - %02dh%02dm%02ds - %s",
1779                                         title->index, title->hours, title->minutes, title->seconds, 
1780                                         title->name);
1781                         }
1782                         else
1783                         {
1784                                 titles[ii]  = g_strdup_printf ("%d - %s", 
1785                                                                                 title->index, title->name);
1786                         }
1787                 }
1788                 else
1789                 {
1790                         if (title->duration != 0)
1791                         {
1792                                 titles[ii]  = g_strdup_printf ("%d - %02dh%02dm%02ds",
1793                                         title->index, title->hours, title->minutes, title->seconds);
1794                         }
1795                         else
1796                         {
1797                                 titles[ii]  = g_strdup_printf ("%d - Unknown Length", 
1798                                                                                 title->index);
1799                         }
1800                 }
1801                 gtk_list_store_append(store, &iter);
1802                 gtk_list_store_set(store, &iter, 
1803                                                    0, titles[ii], 
1804                                                    1, TRUE, 
1805                                                    2, titles[ii], 
1806                                                    3, (gdouble)ii, 
1807                                                    4, titles[ii], 
1808                                                    -1);
1809                 title_opts.map[ii].option = titles[ii];
1810                 title_opts.map[ii].shortOpt = titles[ii];
1811                 title_opts.map[ii].ivalue = ii;
1812                 title_opts.map[ii].svalue = titles[ii];
1813         }
1814         titles[ii] = NULL;
1815 }
1816
1817 static gboolean
1818 find_combo_item_by_int(GtkTreeModel *store, gint value, GtkTreeIter *iter)
1819 {
1820         gdouble ivalue;
1821         gboolean foundit = FALSE;
1822         
1823         if (gtk_tree_model_get_iter_first (store, iter))
1824         {
1825                 do
1826                 {
1827                         gtk_tree_model_get(store, iter, 3, &ivalue, -1);
1828                         if (value == (int)ivalue)
1829                         {
1830                                 foundit = TRUE;
1831                                 break;
1832                         }
1833                 } while (gtk_tree_model_iter_next (store, iter));
1834         }
1835         return foundit;
1836 }
1837
1838 void
1839 audio_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1840 {
1841         GtkTreeIter iter;
1842         GtkListStore *store;
1843         hb_list_t  * list = NULL;
1844         hb_title_t * title = NULL;
1845     hb_audio_config_t * audio;
1846         gint ii;
1847         gint count = 0;
1848         gchar *str;
1849         
1850         g_debug("audio_track_opts_set ()\n");
1851         store = get_combo_box_store(builder, name);
1852         gtk_list_store_clear(store);
1853         if (h_scan != NULL)
1854         {
1855                 list = hb_get_titles( h_scan );
1856             title = (hb_title_t*)hb_list_item( list, titleindex );
1857                 if (title != NULL)
1858                 {
1859                         count = hb_list_count( title->list_audio );
1860                 }
1861         }
1862         if (count > 100) count = 100;
1863         if (audio_track_opts.map) g_free(audio_track_opts.map);
1864         if (count > 0)
1865         {
1866                 audio_track_opts.count = count;
1867                 audio_track_opts.map = g_malloc(count*sizeof(options_map_t));
1868         }
1869         else
1870         {
1871                 audio_track_opts.count = 1;
1872                 audio_track_opts.map = g_malloc(sizeof(options_map_t));
1873         }
1874         if( count <= 0 )
1875         {
1876                 // No audio. set some default
1877                 gtk_list_store_append(store, &iter);
1878                 gtk_list_store_set(store, &iter, 
1879                                                    0, "<small>No Audio</small>", 
1880                                                    1, TRUE, 
1881                                                    2, "none", 
1882                                                    3, -1.0, 
1883                                                    4, "none", 
1884                                                    -1);
1885                 audio_track_opts.map[0].option = "No Audio";
1886                 audio_track_opts.map[0].shortOpt = "none";
1887                 audio_track_opts.map[0].ivalue = -1;
1888                 audio_track_opts.map[0].svalue = "none";
1889                 return;
1890         }
1891         index_str_init(count-1);
1892         for (ii = 0; ii < count; ii++)
1893         {
1894         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, ii );
1895                 gtk_list_store_append(store, &iter);
1896                 str = g_strdup_printf("<small>%s</small>", audio->lang.description);
1897                 gtk_list_store_set(store, &iter, 
1898                                                    0, str,
1899                                                    1, TRUE, 
1900                                                    2, index_str[ii], 
1901                                                    3, (gdouble)ii, 
1902                                                    4, index_str[ii], 
1903                                                    -1);
1904                 g_free(str);
1905                 audio_track_opts.map[ii].option = audio->lang.description,
1906                 audio_track_opts.map[ii].shortOpt = index_str[ii];
1907                 audio_track_opts.map[ii].ivalue = ii;
1908                 audio_track_opts.map[ii].svalue = index_str[ii];
1909         }
1910 }
1911
1912 void
1913 subtitle_track_opts_set(GtkBuilder *builder, const gchar *name, gint titleindex)
1914 {
1915         GtkTreeIter iter;
1916         GtkListStore *store;
1917         hb_list_t  * list = NULL;
1918         hb_title_t * title = NULL;
1919         hb_subtitle_t * subtitle;
1920         gint ii, count = 0;
1921         static char ** options = NULL;
1922         
1923         g_debug("subtitle_track_opts_set ()\n");
1924         store = get_combo_box_store(builder, name);
1925         gtk_list_store_clear(store);
1926         if (h_scan != NULL)
1927         {
1928                 list = hb_get_titles( h_scan );
1929             title = (hb_title_t*)hb_list_item( list, titleindex );
1930                 if (title != NULL)
1931                 {
1932                         count = hb_list_count( title->list_subtitle );
1933                 }
1934         }
1935         if (count > 100) count = 100;
1936         if (subtitle_opts.map) g_free(subtitle_opts.map);
1937         if (count > 0)
1938         {
1939                 subtitle_opts.count = count+1;
1940                 subtitle_opts.map = g_malloc((count+1)*sizeof(options_map_t));
1941         }
1942         else
1943         {
1944                 subtitle_opts.count = LANG_TABLE_SIZE+1;
1945                 subtitle_opts.map = g_malloc((LANG_TABLE_SIZE+1)*sizeof(options_map_t));
1946         }
1947         gtk_list_store_append(store, &iter);
1948         gtk_list_store_set(store, &iter, 
1949                                            0, "Foreign Audio Search", 
1950                                            1, TRUE, 
1951                                            2, "-1", 
1952                                            3, -1.0, 
1953                                            4, "auto", 
1954                                            -1);
1955         subtitle_opts.map[0].option = "Foreign Audio Search";
1956         subtitle_opts.map[0].shortOpt = "-1";
1957         subtitle_opts.map[0].ivalue = -1;
1958         subtitle_opts.map[0].svalue = "auto";
1959         if (count > 0)
1960         {
1961                 if (options != NULL)
1962                         g_strfreev(options);
1963                 options = g_malloc((count+1)*sizeof(gchar*));
1964                 index_str_init(count-1);
1965                 for (ii = 0; ii < count; ii++)
1966                 {
1967                 subtitle = (hb_subtitle_t *)hb_list_item(title->list_subtitle, ii);
1968                         // Skip subtitles that must be burned if there is already
1969                         // a burned subtitle in the list
1970                         options[ii] = g_strdup_printf("%d - %s", ii+1, subtitle->lang);
1971                         subtitle_opts.map[ii+1].option = options[ii];
1972                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
1973                         subtitle_opts.map[ii+1].ivalue = ii;
1974                         subtitle_opts.map[ii+1].svalue = subtitle->iso639_2;
1975                         gtk_list_store_append(store, &iter);
1976                         gtk_list_store_set(store, &iter, 
1977                                                 0, options[ii], 
1978                                                 1, TRUE, 
1979                                                 2, index_str[ii], 
1980                                                 3, (gdouble)ii, 
1981                                                 4, subtitle->iso639_2, 
1982                                                 -1);
1983                 }
1984                 options[count] = NULL;
1985         }
1986         else
1987         {
1988                 index_str_init(LANG_TABLE_SIZE-1);
1989                 for (ii = 0; ii < LANG_TABLE_SIZE; ii++)
1990                 {
1991                         const gchar *lang;
1992
1993                         if (ghb_language_table[ii].native_name[0] != 0)
1994                                 lang = ghb_language_table[ii].native_name;
1995                         else
1996                                 lang = ghb_language_table[ii].eng_name;
1997
1998                         subtitle_opts.map[ii+1].option = lang;
1999                         subtitle_opts.map[ii+1].shortOpt = index_str[ii];
2000                         subtitle_opts.map[ii+1].ivalue = ii;
2001                         subtitle_opts.map[ii+1].svalue = ghb_language_table[ii].iso639_2;
2002                         gtk_list_store_append(store, &iter);
2003                         gtk_list_store_set(store, &iter, 
2004                                         0, lang,
2005                                         1, TRUE, 
2006                                         2, index_str[ii],
2007                                         3, (gdouble)ii, 
2008                                         4, ghb_language_table[ii].iso639_2, 
2009                                         -1);
2010                 }
2011         }
2012 }
2013
2014 gint
2015 ghb_longest_title()
2016 {
2017         hb_list_t  * list;
2018         hb_title_t * title;
2019         gint ii;
2020         gint count = 0;
2021         guint64 longest = 0;
2022         gint titleindex = 0;
2023         
2024         g_debug("ghb_longest_title ()\n");
2025         if (h_scan == NULL) return 0;
2026         list = hb_get_titles( h_scan );
2027         count = hb_list_count( list );
2028         if (count > 100) count = 100;
2029         for (ii = 0; ii < count; ii++)
2030         {
2031                 title = (hb_title_t*)hb_list_item(list, ii);
2032                 if (title->duration > longest)
2033                 {
2034                         titleindex = ii;
2035                         longest = title->duration;
2036                 }
2037         }
2038         return titleindex;
2039 }
2040
2041 gchar*
2042 ghb_get_source_audio_lang(gint titleindex, gint track)
2043 {
2044         hb_list_t  * list;
2045         hb_title_t * title;
2046     hb_audio_config_t * audio;
2047         gchar *lang = NULL;
2048         
2049         g_debug("ghb_lookup_1st_audio_lang ()\n");
2050         if (h_scan == NULL) 
2051                 return NULL;
2052         list = hb_get_titles( h_scan );
2053     title = (hb_title_t*)hb_list_item( list, titleindex );
2054         if (title == NULL)
2055                 return NULL;
2056         if (hb_list_count( title->list_audio ) <= track)
2057                 return NULL;
2058
2059         audio = hb_list_audio_config_item(title->list_audio, track);
2060         if (audio == NULL)
2061                 return NULL;
2062
2063         lang = g_strdup(audio->lang.iso639_2);
2064         return lang;
2065 }
2066
2067 static gboolean*
2068 get_track_used(gint acodec, GHashTable *track_indices, gint count)
2069 {
2070         gboolean *used;
2071
2072         used = g_hash_table_lookup(track_indices, &acodec);
2073         if (used == NULL)
2074         {
2075                 gint *key;
2076
2077                 used = g_malloc0(count * sizeof(gboolean));
2078                 key = g_malloc(sizeof(gint));
2079                 *key = acodec;
2080                 g_hash_table_insert(track_indices, key, used);
2081         }
2082         return used;
2083 }
2084
2085 gint
2086 ghb_find_audio_track(
2087         gint titleindex, 
2088         const gchar *lang, 
2089         gint acodec,
2090         gint fallback_acodec,
2091         GHashTable *track_indices)
2092 {
2093         hb_list_t  * list;
2094         hb_title_t * title;
2095         hb_audio_config_t * audio;
2096         gint ii;
2097         gint count = 0;
2098         gint track = -1;
2099         gint max_chan = 0;
2100         gboolean *used;
2101         gboolean *passthru_used;
2102         gint try_acodec;
2103         gint passthru_acodec;
2104         gboolean passthru;
2105         
2106         g_debug("find_audio_track ()\n");
2107         if (h_scan == NULL) return -1;
2108         list = hb_get_titles( h_scan );
2109         title = (hb_title_t*)hb_list_item( list, titleindex );
2110         if (title != NULL)
2111         {
2112                 count = hb_list_count( title->list_audio );
2113         }
2114         if (count > 10) count = 10;
2115         // Try to find an item that matches the preferred language and
2116         // the passthru codec type
2117         passthru = (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)) != 0;
2118         if (passthru)
2119         {
2120                 for (ii = 0; ii < count; ii++)
2121                 {
2122                         gint channels;
2123
2124                         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2125                                                                                                         title->list_audio, ii );
2126                         passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2127                         // Is the source track use a passthru capable codec?
2128                         if (passthru_acodec == 0)
2129                                 continue;
2130                         used = get_track_used(passthru_acodec, track_indices, count);
2131                         // Has the track already been used with this codec?
2132                         if (used[ii])
2133                                 continue;
2134
2135                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2136                                                                                                         audio->in.channel_layout);
2137                         // Find a track that is not visually impaired or dirctor's
2138                         // commentary, and has the highest channel count.
2139                         if ((audio->lang.type < 2) &&
2140                                 ((strcmp(lang, audio->lang.iso639_2) == 0) ||
2141                                 (strcmp(lang, "und") == 0)))
2142                         {
2143                                 if (channels > max_chan)
2144                                 {
2145                                         track = ii;
2146                                         max_chan = channels;
2147                                 }
2148                         }
2149                 }
2150                 try_acodec = fallback_acodec;
2151         }
2152         else
2153         {
2154                 try_acodec = acodec;
2155         }
2156         if (track > -1)
2157         {
2158                 used[track] = TRUE;
2159                 return track;
2160         }
2161         // Try to find an item that matches the preferred language
2162         used = get_track_used(try_acodec, track_indices, count);
2163         for (ii = 0; ii < count; ii++)
2164         {
2165                 // Has the track already been used with this codec?
2166                 if (used[ii])
2167                         continue;
2168                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2169                                                                                                 title->list_audio, ii );
2170                 passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2171                 if (passthru_acodec && passthru)
2172                 {
2173                         passthru_used = get_track_used(passthru_acodec, track_indices, count);
2174                         // Has the track already been used with this codec for passthru?
2175                         if (passthru_used[ii])
2176                                 continue;
2177                 }
2178                 // Find a track that is not visually impaired or dirctor's commentary
2179                 if ((audio->lang.type < 2) &&
2180                         ((strcmp(lang, audio->lang.iso639_2) == 0) ||
2181                         (strcmp(lang, "und") == 0)))
2182                 {
2183                         track = ii;
2184                         break;
2185                 }
2186         }
2187         if (track > -1)
2188         {
2189                 used[track] = TRUE;
2190                 return track;
2191         }
2192         // Try to fine an item that does not match the preferred language and
2193         // matches the passthru codec type
2194         if (passthru)
2195         {
2196                 for (ii = 0; ii < count; ii++)
2197                 {
2198                         gint channels;
2199
2200                         audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2201                                                                                                         title->list_audio, ii );
2202                         passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2203                         // Is the source track use a passthru capable codec?
2204                         if (passthru_acodec == 0)
2205                                 continue;
2206                         used = get_track_used(passthru_acodec, track_indices, count);
2207                         // Has the track already been used with this codec?
2208                         if (used[ii])
2209                                 continue;
2210
2211                         channels = HB_INPUT_CH_LAYOUT_GET_DISCRETE_COUNT(
2212                                                                                                         audio->in.channel_layout);
2213                         // Find a track that is not visually impaired or dirctor's
2214                         // commentary, and has the highest channel count.
2215                         if (audio->lang.type < 2)
2216                         {
2217                                 if (channels > max_chan)
2218                                 {
2219                                         track = ii;
2220                                         max_chan = channels;
2221                                 }
2222                         }
2223                 }
2224                 try_acodec = fallback_acodec;
2225         }
2226         else
2227         {
2228                 try_acodec = acodec;
2229         }
2230         if (track > -1)
2231         {
2232                 used[track] = TRUE;
2233                 return track;
2234         }
2235         // Try to fine an item that does not match the preferred language
2236         used = get_track_used(try_acodec, track_indices, count);
2237         for (ii = 0; ii < count; ii++)
2238         {
2239                 // Has the track already been used with this codec?
2240                 if (used[ii])
2241                         continue;
2242                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2243                                                                                                         title->list_audio, ii );
2244                 passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2245                 if (passthru_acodec && passthru)
2246                 {
2247                         passthru_used = get_track_used(passthru_acodec, track_indices, count);
2248                         // Has the track already been used with this codec for passthru?
2249                         if (passthru_used[ii])
2250                                 continue;
2251                 }
2252                 // Find a track that is not visually impaired or dirctor's commentary
2253                 if (audio->lang.type < 2)
2254                 {
2255                         track = ii;
2256                         break;
2257                 }
2258         }
2259         if (track > -1)
2260         {
2261                 used[track] = TRUE;
2262                 return track;
2263         }
2264         // Last ditch, anything goes
2265         for (ii = 0; ii < count; ii++)
2266         {
2267                 audio = (hb_audio_config_t*)hb_list_audio_config_item( 
2268                                                                                                 title->list_audio, ii );
2269                 passthru_acodec = (HB_ACODEC_AC3 | HB_ACODEC_DCA) & audio->in.codec;
2270                 if (passthru_acodec && passthru)
2271                 {
2272                         passthru_used = get_track_used(passthru_acodec, track_indices, count);
2273                         // Has the track already been used with this codec for passthru?
2274                         if (passthru_used[ii])
2275                                 continue;
2276                 }
2277                 // Has the track already been used with this codec?
2278                 if (!used[ii])
2279                 {
2280                         track = ii;
2281                         break;
2282                 }
2283         }
2284         if (track > -1)
2285         {
2286                 used[track] = TRUE;
2287         }
2288         return track;
2289 }
2290
2291 gint
2292 ghb_find_pref_subtitle_track(const gchar *lang)
2293 {
2294         gint ii, count;
2295         count = subtitle_opts.count;
2296         for (ii = 0; ii < count; ii++)
2297         {
2298                 if (strcmp(lang, subtitle_opts.map[ii].svalue) == 0)
2299                 {
2300                         return subtitle_opts.map[ii].ivalue;
2301                 }
2302         }
2303         return -2;
2304 }
2305
2306 gint
2307 ghb_find_cc_track(gint titleindex)
2308 {
2309         hb_list_t  * list;
2310         hb_title_t * title;
2311         hb_subtitle_t * subtitle;
2312         gint count, ii;
2313         
2314         g_debug("ghb_find_cc_track ()\n");
2315         if (h_scan == NULL) return -2;
2316         list = hb_get_titles( h_scan );
2317         title = (hb_title_t*)hb_list_item( list, titleindex );
2318         if (title != NULL)
2319         {
2320                 count = hb_list_count( title->list_subtitle );
2321                 // Try to find an item that matches the preferred language
2322                 for (ii = 0; ii < count; ii++)
2323                 {
2324                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2325                         if (subtitle->source == CC608SUB || subtitle->source == CC708SUB)
2326                                 return ii;
2327                 }
2328         }
2329         return -2;
2330 }
2331
2332 gint
2333 ghb_find_subtitle_track(
2334         gint          titleindex, 
2335         const gchar * lang, 
2336         gboolean      burn,
2337         gboolean      force,
2338         gint          source,
2339         GHashTable  * track_indices)
2340 {
2341         hb_list_t  * list;
2342         hb_title_t * title;
2343         hb_subtitle_t * subtitle;
2344         gint count, ii;
2345         gboolean *used;
2346         
2347         g_debug("find_subtitle_track ()\n");
2348         if (strcmp(lang, "auto") == 0)
2349                 return -1;
2350         if (h_scan == NULL) return -1;
2351         list = hb_get_titles( h_scan );
2352         title = (hb_title_t*)hb_list_item( list, titleindex );
2353         if (title != NULL)
2354         {
2355                 count = hb_list_count( title->list_subtitle );
2356                 used = g_hash_table_lookup(track_indices, lang);
2357                 if (used == NULL)
2358                 {
2359                         used = g_malloc0(count * sizeof(gboolean));
2360                         g_hash_table_insert(track_indices, g_strdup(lang), used);
2361                 }
2362                 // Try to find an item that matches the preferred language and source
2363                 for (ii = 0; ii < count; ii++)
2364                 {
2365                         if (used[ii])
2366                                 continue;
2367
2368                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2369                         if (source == subtitle->source &&
2370                                 ((strcmp(lang, subtitle->iso639_2) == 0) ||
2371                                  (strcmp(lang, "und") == 0)))
2372                         {
2373                                 used[ii] = TRUE;
2374                                 return ii;
2375                         }
2376                 }
2377                 // Try to find an item that matches the preferred language
2378                 for (ii = 0; ii < count; ii++)
2379                 {
2380                         if (used[ii])
2381                                 continue;
2382
2383                 subtitle = (hb_subtitle_t*)hb_list_item( title->list_subtitle, ii );
2384                         if (((burn || force) && (subtitle->source == VOBSUB)) &&
2385                                 ((strcmp(lang, subtitle->iso639_2) == 0) ||
2386                                  (strcmp(lang, "und") == 0)))
2387                         {
2388                                 used[ii] = TRUE;
2389                                 return ii;
2390                         }
2391                 }
2392         }
2393         return -2;
2394 }
2395
2396 static void
2397 generic_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
2398 {
2399         GtkTreeIter iter;
2400         GtkListStore *store;
2401         gint ii;
2402         
2403         g_debug("generic_opts_set ()\n");
2404         if (name == NULL || opts == NULL) return;
2405         store = get_combo_box_store(builder, name);
2406         gtk_list_store_clear(store);
2407         for (ii = 0; ii < opts->count; ii++)
2408         {
2409                 gtk_list_store_append(store, &iter);
2410                 gtk_list_store_set(store, &iter, 
2411                                                    0, opts->map[ii].option, 
2412                                                    1, TRUE, 
2413                                                    2, opts->map[ii].shortOpt, 
2414                                                    3, opts->map[ii].ivalue, 
2415                                                    4, opts->map[ii].svalue, 
2416                                                    -1);
2417         }
2418 }
2419
2420 static void
2421 small_opts_set(GtkBuilder *builder, const gchar *name, combo_opts_t *opts)
2422 {
2423         GtkTreeIter iter;
2424         GtkListStore *store;
2425         gint ii;
2426         gchar *str;
2427         
2428         g_debug("generic_opts_set ()\n");
2429         if (name == NULL || opts == NULL) return;
2430         store = get_combo_box_store(builder, name);
2431         gtk_list_store_clear(store);
2432         for (ii = 0; ii < opts->count; ii++)
2433         {
2434                 gtk_list_store_append(store, &iter);
2435                 str = g_strdup_printf("<small>%s</small>", opts->map[ii].option);
2436                 gtk_list_store_set(store, &iter, 
2437                                                    0, str,
2438                                                    1, TRUE, 
2439                                                    2, opts->map[ii].shortOpt, 
2440                                                    3, opts->map[ii].ivalue, 
2441                                                    4, opts->map[ii].svalue, 
2442                                                    -1);
2443                 g_free(str);
2444         }
2445 }
2446
2447 combo_opts_t*
2448 find_combo_table(const gchar *name)
2449 {
2450         gint ii;
2451
2452         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2453         {
2454                 if (strcmp(name, combo_name_map[ii].name) == 0)
2455                 {
2456                         return combo_name_map[ii].opts;
2457                 }
2458         }
2459         return NULL;
2460 }
2461
2462 gint
2463 ghb_lookup_combo_int(const gchar *name, const GValue *gval)
2464 {
2465         if (gval == NULL)
2466                 return 0;
2467         if (strcmp(name, "AudioBitrate") == 0)
2468                 return lookup_audio_bitrate_int(gval);
2469         else if (strcmp(name, "AudioSamplerate") == 0)
2470                 return lookup_audio_rate_int(gval);
2471         else if (strcmp(name, "VideoFramerate") == 0)
2472                 return lookup_video_rate_int(gval);
2473         else if (strcmp(name, "AudioMixdown") == 0)
2474                 return lookup_mix_int(gval);
2475         else if (strcmp(name, "SrtLanguage") == 0)
2476                 return lookup_audio_lang_int(gval);
2477         else if (strcmp(name, "PreferredLanguage") == 0)
2478                 return lookup_audio_lang_int(gval);
2479         else
2480         {
2481                 return lookup_generic_int(find_combo_table(name), gval);
2482         }
2483         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2484         return 0;
2485 }
2486
2487 gdouble
2488 ghb_lookup_combo_double(const gchar *name, const GValue *gval)
2489 {
2490         if (gval == NULL)
2491                 return 0;
2492         if (strcmp(name, "AudioBitrate") == 0)
2493                 return lookup_audio_bitrate_int(gval);
2494         else if (strcmp(name, "AudioSamplerate") == 0)
2495                 return lookup_audio_rate_int(gval);
2496         else if (strcmp(name, "VideoFramerate") == 0)
2497                 return lookup_video_rate_int(gval);
2498         else if (strcmp(name, "AudioMixdown") == 0)
2499                 return lookup_mix_int(gval);
2500         else if (strcmp(name, "SrtLanguage") == 0)
2501                 return lookup_audio_lang_int(gval);
2502         else if (strcmp(name, "PreferredLanguage") == 0)
2503                 return lookup_audio_lang_int(gval);
2504         else
2505         {
2506                 return lookup_generic_double(find_combo_table(name), gval);
2507         }
2508         g_warning("ghb_lookup_combo_double() couldn't find %s", name);
2509         return 0;
2510 }
2511
2512 const gchar*
2513 ghb_lookup_combo_option(const gchar *name, const GValue *gval)
2514 {
2515         if (gval == NULL)
2516                 return NULL;
2517         if (strcmp(name, "AudioBitrate") == 0)
2518                 return lookup_audio_bitrate_option(gval);
2519         else if (strcmp(name, "AudioSamplerate") == 0)
2520                 return lookup_audio_rate_option(gval);
2521         else if (strcmp(name, "VideoFramerate") == 0)
2522                 return lookup_video_rate_option(gval);
2523         else if (strcmp(name, "AudioMixdown") == 0)
2524                 return lookup_mix_option(gval);
2525         else if (strcmp(name, "SrtLanguage") == 0)
2526                 return lookup_audio_lang_option(gval);
2527         else if (strcmp(name, "PreferredLanguage") == 0)
2528                 return lookup_audio_lang_option(gval);
2529         else
2530         {
2531                 return lookup_generic_option(find_combo_table(name), gval);
2532         }
2533         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2534         return NULL;
2535 }
2536
2537 const gchar*
2538 ghb_lookup_combo_string(const gchar *name, const GValue *gval)
2539 {
2540         if (gval == NULL)
2541                 return NULL;
2542         if (strcmp(name, "AudioBitrate") == 0)
2543                 return lookup_audio_bitrate_option(gval);
2544         else if (strcmp(name, "AudioSamplerate") == 0)
2545                 return lookup_audio_rate_option(gval);
2546         else if (strcmp(name, "VideoFramerate") == 0)
2547                 return lookup_video_rate_option(gval);
2548         else if (strcmp(name, "AudioMixdown") == 0)
2549                 return lookup_mix_option(gval);
2550         else if (strcmp(name, "SrtLanguage") == 0)
2551                 return lookup_audio_lang_option(gval);
2552         else if (strcmp(name, "PreferredLanguage") == 0)
2553                 return lookup_audio_lang_option(gval);
2554         else
2555         {
2556                 return lookup_generic_string(find_combo_table(name), gval);
2557         }
2558         g_warning("ghb_lookup_combo_int() couldn't find %s", name);
2559         return NULL;
2560 }
2561
2562 void
2563 ghb_update_ui_combo_box(
2564         signal_user_data_t *ud, 
2565         const gchar *name, 
2566         gint user_data, 
2567         gboolean all)
2568 {
2569         GtkComboBox *combo = NULL;
2570         gint signal_id;
2571         gint handler_id = 0;
2572
2573         if (name != NULL)
2574         {               
2575                 g_debug("ghb_update_ui_combo_box() %s\n", name);
2576                 // Clearing a combo box causes a rash of "changed" events, even when
2577                 // the active item is -1 (inactive).  To control things, I'm disabling
2578                 // the event till things are settled down.
2579                 combo = GTK_COMBO_BOX(GHB_WIDGET(ud->builder, name));
2580                 signal_id = g_signal_lookup("changed", GTK_TYPE_COMBO_BOX);
2581                 if (signal_id > 0)
2582                 {
2583                         // Valid signal id found.  This should always succeed.
2584                         handler_id = g_signal_handler_find ((gpointer)combo, G_SIGNAL_MATCH_ID, 
2585                                                                                                 signal_id, 0, 0, 0, 0);
2586                         if (handler_id > 0)
2587                         {
2588                                 // This should also always succeed
2589                                 g_signal_handler_block ((gpointer)combo, handler_id);
2590                         }
2591                 }
2592         }       
2593         if (all)
2594         {
2595                 audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2596                 audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2597                 video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2598                 mix_opts_set(ud->builder, "AudioMixdown");
2599                 language_opts_set(ud->builder, "SrtLanguage");
2600                 language_opts_set(ud->builder, "PreferredLanguage");
2601                 srt_codeset_opts_set(ud->builder, "SrtCodeset");
2602                 title_opts_set(ud->builder, "title");
2603                 audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2604                 subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2605                 generic_opts_set(ud->builder, "VideoQualityGranularity", &vqual_granularity_opts);
2606                 generic_opts_set(ud->builder, "PtoPType", &point_to_point_opts);
2607                 generic_opts_set(ud->builder, "WhenComplete", &when_complete_opts);
2608                 generic_opts_set(ud->builder, "PicturePAR", &par_opts);
2609                 generic_opts_set(ud->builder, "PictureModulus", &alignment_opts);
2610                 generic_opts_set(ud->builder, "LoggingLevel", &logging_opts);
2611                 generic_opts_set(ud->builder, "LogLongevity", &log_longevity_opts);
2612                 generic_opts_set(ud->builder, "check_updates", &appcast_update_opts);
2613                 generic_opts_set(ud->builder, "FileFormat", &container_opts);
2614                 generic_opts_set(ud->builder, "PictureDeinterlace", &deint_opts);
2615                 generic_opts_set(ud->builder, "PictureDetelecine", &detel_opts);
2616                 generic_opts_set(ud->builder, "PictureDecomb", &decomb_opts);
2617                 generic_opts_set(ud->builder, "PictureDenoise", &denoise_opts);
2618                 generic_opts_set(ud->builder, "VideoEncoder", &vcodec_opts);
2619                 small_opts_set(ud->builder, "AudioEncoder", &acodec_opts);
2620                 generic_opts_set(ud->builder, "x264_direct", &direct_opts);
2621                 generic_opts_set(ud->builder, "x264_b_adapt", &badapt_opts);
2622                 generic_opts_set(ud->builder, "x264_me", &me_opts);
2623                 generic_opts_set(ud->builder, "x264_subme", &subme_opts);
2624                 generic_opts_set(ud->builder, "x264_analyse", &analyse_opts);
2625                 generic_opts_set(ud->builder, "x264_trellis", &trellis_opts);
2626         }
2627         else
2628         {
2629                 if (strcmp(name, "AudioBitrate") == 0)
2630                         audio_bitrate_opts_set(ud->builder, "AudioBitrate");
2631                 else if (strcmp(name, "AudioSamplerate") == 0)
2632                         audio_samplerate_opts_set(ud->builder, "AudioSamplerate", hb_audio_rates, hb_audio_rates_count);
2633                 else if (strcmp(name, "VideoFramerate") == 0)
2634                         video_rate_opts_set(ud->builder, "VideoFramerate", hb_video_rates, hb_video_rates_count);
2635                 else if (strcmp(name, "AudioMixdown") == 0)
2636                         mix_opts_set(ud->builder, "AudioMixdown");
2637                 else if (strcmp(name, "SrtLanguage") == 0)
2638                         language_opts_set(ud->builder, "SrtLanguage");
2639                 else if (strcmp(name, "PreferredLanguage") == 0)
2640                         language_opts_set(ud->builder, "PreferredLanguage");
2641                 else if (strcmp(name, "SrtCodeset") == 0)
2642                         srt_codeset_opts_set(ud->builder, "SrtCodeset");
2643                 else if (strcmp(name, "title") == 0)
2644                         title_opts_set(ud->builder, "title");
2645                 else if (strcmp(name, "SubtitleTrack") == 0)
2646                         subtitle_track_opts_set(ud->builder, "SubtitleTrack", user_data);
2647                 else if (strcmp(name, "AudioTrack") == 0)
2648                         audio_track_opts_set(ud->builder, "AudioTrack", user_data);
2649                 else
2650                         generic_opts_set(ud->builder, name, find_combo_table(name));
2651         }
2652         if (handler_id > 0)
2653         {
2654                 g_signal_handler_unblock ((gpointer)combo, handler_id);
2655         }
2656 }
2657         
2658 static void
2659 init_ui_combo_boxes(GtkBuilder *builder)
2660 {
2661         gint ii;
2662
2663         init_combo_box(builder, "AudioBitrate");
2664         init_combo_box(builder, "AudioSamplerate");
2665         init_combo_box(builder, "VideoFramerate");
2666         init_combo_box(builder, "AudioMixdown");
2667         init_combo_box(builder, "SrtLanguage");
2668         init_combo_box(builder, "PreferredLanguage");
2669         init_combo_box(builder, "SrtCodeset");
2670         init_combo_box(builder, "title");
2671         init_combo_box(builder, "AudioTrack");
2672         for (ii = 0; combo_name_map[ii].name != NULL; ii++)
2673         {
2674                 init_combo_box(builder, combo_name_map[ii].name);
2675         }
2676 }
2677         
2678 static const char * turbo_opts = 
2679         "ref=1:subme=2:me=dia:analyse=none:trellis=0:"
2680         "no-fast-pskip=0:8x8dct=0";
2681
2682 // Construct the x264 options string
2683 // The result is allocated, so someone must free it at some point.
2684 gchar*
2685 ghb_build_x264opts_string(GValue *settings)
2686 {
2687         gchar *result;
2688         gchar *opts = ghb_settings_get_string(settings, "x264Option");
2689         if (opts != NULL)
2690         {
2691                 result = opts;
2692         }
2693         else
2694         {
2695                 result = g_strdup("");
2696         }
2697         return result;
2698 }
2699
2700 void
2701 ghb_part_duration(gint tt, gint sc, gint ec, gint *hh, gint *mm, gint *ss)
2702 {
2703         hb_list_t  * list;
2704         hb_title_t * title;
2705     hb_chapter_t * chapter;
2706         gint count, c;
2707         gint64 duration;
2708         
2709         *hh = *mm = *ss = 0;
2710         if (h_scan == NULL) return;
2711         list = hb_get_titles( h_scan );
2712     title = (hb_title_t*)hb_list_item( list, tt );
2713         if (title == NULL) return;
2714
2715         *hh = title->hours;
2716         *mm = title->minutes;
2717         *ss = title->seconds;
2718
2719         count = hb_list_count(title->list_chapter);
2720         if (sc > count) sc = count;
2721         if (ec > count) ec = count;
2722
2723         if (sc == 1 && ec == count)
2724                 return;
2725
2726         duration = 0;
2727         for (c = sc; c <= ec; c++)
2728         {
2729                 chapter = hb_list_item(title->list_chapter, c-1);
2730                 duration += chapter->duration;
2731         }
2732
2733         *hh =   duration / 90000 / 3600;
2734         *mm = ((duration / 90000) % 3600) / 60;
2735         *ss =  (duration / 90000) % 60;
2736 }
2737
2738 void
2739 ghb_get_chapter_duration(gint ti, gint ii, gint *hh, gint *mm, gint *ss)
2740 {
2741         hb_list_t  * list;
2742         hb_title_t * title;
2743     hb_chapter_t * chapter;
2744         gint count;
2745         
2746         g_debug("ghb_get_chapter_duration (title = %d)\n", ti);
2747         *hh = *mm = *ss = 0;
2748         if (h_scan == NULL) return;
2749         list = hb_get_titles( h_scan );
2750     title = (hb_title_t*)hb_list_item( list, ti );
2751         if (title == NULL) return;
2752         count = hb_list_count( title->list_chapter );
2753         if (ii >= count) return;
2754         chapter = hb_list_item(title->list_chapter, ii);
2755         if (chapter == NULL) return;
2756         *hh = chapter->hours;
2757         *mm = chapter->minutes;
2758         *ss = chapter->seconds;
2759 }
2760
2761 GValue*
2762 ghb_get_chapters(gint titleindex)
2763 {
2764         hb_list_t  * list;
2765         hb_title_t * title;
2766     hb_chapter_t * chapter;
2767         gint count, ii;
2768         GValue *chapters = NULL;
2769         
2770         g_debug("ghb_get_chapters (title = %d)\n", titleindex);
2771         if (h_scan == NULL) return NULL;
2772         list = hb_get_titles( h_scan );
2773     title = (hb_title_t*)hb_list_item( list, titleindex );
2774         if (title == NULL) return NULL;
2775         count = hb_list_count( title->list_chapter );
2776         chapters = ghb_array_value_new(count);
2777         for (ii = 0; ii < count; ii++)
2778         {
2779                 chapter = hb_list_item(title->list_chapter, ii);
2780                 if (chapter == NULL) break;
2781                 if (chapter->title == NULL || chapter->title[0] == 0)
2782                 {
2783                         gchar *str;
2784                         str = g_strdup_printf ("Chapter %2d", ii+1);
2785                         ghb_array_append(chapters, ghb_string_value_new(str));
2786                         g_free(str);
2787                 }
2788                 else 
2789                 {
2790                         ghb_array_append(chapters, ghb_string_value_new(chapter->title));
2791                 }
2792         }
2793         return chapters;
2794 }
2795
2796 gboolean
2797 ghb_ac3_in_audio_list(const GValue *audio_list)
2798 {
2799         gint count, ii;
2800
2801         count = ghb_array_len(audio_list);
2802         for (ii = 0; ii < count; ii++)
2803         {
2804                 GValue *asettings;
2805                 gint acodec;
2806
2807                 asettings = ghb_array_get_nth(audio_list, ii);
2808                 acodec = ghb_settings_combo_int(asettings, "AudioEncoder");
2809                 if (acodec & HB_ACODEC_AC3)
2810                         return TRUE;
2811         }
2812         return FALSE;
2813 }
2814
2815 static void
2816 audio_bitrate_opts_add(GtkBuilder *builder, const gchar *name, gint rate)
2817 {
2818         GtkTreeIter iter;
2819         GtkListStore *store;
2820         gchar *str;
2821         
2822         g_debug("audio_bitrate_opts_add ()\n");
2823
2824         if (rate < 8) return;
2825
2826         store = get_combo_box_store(builder, name);
2827         if (!find_combo_item_by_int(GTK_TREE_MODEL(store), rate, &iter))
2828         {
2829                 str = g_strdup_printf ("<small>%d</small>", rate);
2830                 gtk_list_store_append(store, &iter);
2831                 gtk_list_store_set(store, &iter, 
2832                                                    0, str, 
2833                                                    1, TRUE, 
2834                                                    2, str, 
2835                                                    3, (gdouble)rate, 
2836                                                    4, str, 
2837                                                    -1);
2838                 g_free(str);
2839         }
2840 }
2841
2842 static void
2843 audio_bitrate_opts_clean(
2844         GtkBuilder *builder, 
2845         const gchar *name, 
2846         gint first_rate, 
2847         gint last_rate)
2848 {
2849         GtkTreeIter iter;
2850         GtkListStore *store;
2851         gdouble ivalue;
2852         gboolean done = FALSE;
2853         gint ii = 0;
2854         guint last = (guint)last_rate;
2855         guint first = (guint)first_rate;
2856         
2857         g_debug("audio_bitrate_opts_clean ()\n");
2858         store = get_combo_box_store(builder, name);
2859         if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL(store), &iter))
2860         {
2861                 do
2862                 {
2863                         gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 3, &ivalue, -1);
2864                         if (search_rates(
2865                                 hb_audio_bitrates, ivalue, hb_audio_bitrates_count) < 0)
2866                         {
2867                                 done = !gtk_list_store_remove(store, &iter);
2868                         }
2869                         else if (ivalue < first || ivalue > last)
2870                         {
2871                                 ii++;
2872                                 gtk_list_store_set(store, &iter, 1, FALSE, -1);
2873                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2874                         }
2875                         else
2876                         {
2877                                 ii++;
2878                                 gtk_list_store_set(store, &iter, 1, TRUE, -1);
2879                                 done = !gtk_tree_model_iter_next (GTK_TREE_MODEL(store), &iter);
2880                         }
2881                 } while (!done);
2882         }
2883 }
2884
2885 static void
2886 audio_bitrate_opts_set(GtkBuilder *builder, const gchar *name)
2887 {
2888         GtkTreeIter iter;
2889         GtkListStore *store;
2890         gint ii;
2891         gchar *str;
2892         
2893         g_debug("audio_bitrate_opts_set ()\n");
2894         store = get_combo_box_store(builder, name);
2895         gtk_list_store_clear(store);
2896         for (ii = 0; ii < hb_audio_bitrates_count; ii++)
2897         {
2898                 gtk_list_store_append(store, &iter);
2899                 str = g_strdup_printf ("<small>%s</small>", 
2900                         hb_audio_bitrates[ii].string);
2901                 gtk_list_store_set(store, &iter, 
2902                                                    0, str,
2903                                                    1, TRUE, 
2904                                                    2, hb_audio_bitrates[ii].string, 
2905                                                    3, (gdouble)hb_audio_bitrates[ii].rate, 
2906                                                    4, hb_audio_bitrates[ii].string, 
2907                                                    -1);
2908                 g_free(str);
2909         }
2910 }
2911
2912 void
2913 ghb_set_passthru_bitrate_opts(GtkBuilder *builder, gint bitrate)
2914 {
2915         audio_bitrate_opts_add(builder, "AudioBitrate", bitrate);
2916 }
2917
2918 void
2919 ghb_set_default_bitrate_opts(
2920         GtkBuilder *builder, 
2921         gint first_rate, 
2922         gint last_rate)
2923 {
2924         audio_bitrate_opts_clean(builder, "AudioBitrate", first_rate, last_rate);
2925 }
2926
2927 static ghb_status_t hb_status;
2928
2929 void
2930 ghb_combo_init(signal_user_data_t *ud)
2931 {
2932         // Set up the list model for the combos
2933         init_ui_combo_boxes(ud->builder);
2934         // Populate all the combos
2935         ghb_update_ui_combo_box(ud, NULL, 0, TRUE);
2936 }
2937
2938 void
2939 ghb_backend_init(gint debug)
2940 {
2941     /* Init libhb */
2942     h_scan = hb_init( debug, 0 );
2943     h_queue = hb_init( debug, 0 );
2944 }
2945
2946 void
2947 ghb_backend_close()
2948 {
2949         hb_close(&h_queue);
2950         hb_close(&h_scan);
2951         hb_global_close();
2952 }
2953
2954 void ghb_backend_scan_stop()
2955 {
2956     hb_scan_stop( h_scan );
2957 }
2958
2959 void
2960 ghb_backend_scan(const gchar *path, gint titleindex, gint preview_count)
2961 {
2962     hb_scan( h_scan, path, titleindex, preview_count, 1 );
2963         hb_status.scan.state |= GHB_STATE_SCANNING;
2964         // initialize count and cur to something that won't cause FPE
2965         // when computing progress
2966         hb_status.scan.title_count = 1;
2967         hb_status.scan.title_cur = 0;
2968 }
2969
2970 void
2971 ghb_backend_queue_scan(const gchar *path, gint titlenum)
2972 {
2973         g_debug("ghb_backend_queue_scan()");
2974         hb_scan( h_queue, path, titlenum, 10, 0 );
2975         hb_status.queue.state |= GHB_STATE_SCANNING;
2976 }
2977
2978 gint
2979 ghb_get_scan_state()
2980 {
2981         return hb_status.scan.state;
2982 }
2983
2984 gint
2985 ghb_get_queue_state()
2986 {
2987         return hb_status.queue.state;
2988 }
2989
2990 void
2991 ghb_clear_scan_state(gint state)
2992 {
2993         hb_status.scan.state &= ~state;
2994 }
2995
2996 void
2997 ghb_clear_queue_state(gint state)
2998 {
2999         hb_status.queue.state &= ~state;
3000 }
3001
3002 void
3003 ghb_set_scan_state(gint state)
3004 {
3005         hb_status.scan.state |= state;
3006 }
3007
3008 void
3009 ghb_set_queue_state(gint state)
3010 {
3011         hb_status.queue.state |= state;
3012 }
3013
3014 void
3015 ghb_get_status(ghb_status_t *status)
3016 {
3017         memcpy(status, &hb_status, sizeof(ghb_status_t));
3018 }
3019
3020 void 
3021 ghb_track_status()
3022 {
3023     hb_state_t s_scan;
3024     hb_state_t s_queue;
3025
3026         if (h_scan == NULL) return;
3027     hb_get_state( h_scan, &s_scan );
3028         switch( s_scan.state )
3029     {
3030 #define p s_scan.param.scanning
3031         case HB_STATE_SCANNING:
3032                 {
3033                         hb_status.scan.state |= GHB_STATE_SCANNING;
3034                         hb_status.scan.title_count = p.title_count;
3035                         hb_status.scan.title_cur = p.title_cur;
3036                 } break;
3037 #undef p
3038
3039         case HB_STATE_SCANDONE:
3040         {
3041                         hb_status.scan.state &= ~GHB_STATE_SCANNING;
3042                         hb_status.scan.state |= GHB_STATE_SCANDONE;
3043         } break;
3044
3045 #define p s_scan.param.working
3046         case HB_STATE_WORKING:
3047                         hb_status.scan.state |= GHB_STATE_WORKING;
3048                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
3049                         hb_status.scan.job_cur = p.job_cur;
3050                         hb_status.scan.job_count = p.job_count;
3051                         hb_status.scan.progress = p.progress;
3052                         hb_status.scan.rate_cur = p.rate_cur;
3053                         hb_status.scan.rate_avg = p.rate_avg;
3054                         hb_status.scan.hours = p.hours;
3055                         hb_status.scan.minutes = p.minutes;
3056                         hb_status.scan.seconds = p.seconds;
3057                         hb_status.scan.unique_id = p.sequence_id & 0xFFFFFF;
3058             break;
3059 #undef p
3060
3061         case HB_STATE_PAUSED:
3062                         hb_status.scan.state |= GHB_STATE_PAUSED;
3063             break;
3064                                 
3065         case HB_STATE_MUXING:
3066         {
3067                         hb_status.scan.state |= GHB_STATE_MUXING;
3068         } break;
3069
3070 #define p s_scan.param.workdone
3071         case HB_STATE_WORKDONE:
3072                 {
3073             hb_job_t *job;
3074
3075                         hb_status.scan.state |= GHB_STATE_WORKDONE;
3076                         hb_status.scan.state &= ~GHB_STATE_MUXING;
3077                         hb_status.scan.state &= ~GHB_STATE_PAUSED;
3078                         hb_status.scan.state &= ~GHB_STATE_WORKING;
3079                         switch (p.error)
3080                         {
3081                         case HB_ERROR_NONE:
3082                                 hb_status.scan.error = GHB_ERROR_NONE;
3083                                 break;
3084                         case HB_ERROR_CANCELED:
3085                                 hb_status.scan.error = GHB_ERROR_CANCELED;
3086                                 break;
3087                         default:
3088                                 hb_status.scan.error = GHB_ERROR_FAIL;
3089                                 break;
3090                         }
3091                         // Delete all remaining jobs of this encode.
3092                         // An encode can be composed of multiple associated jobs.
3093                         // When a job is stopped, libhb removes it from the job list,
3094                         // but does not remove other jobs that may be associated with it.
3095                         // Associated jobs are taged in the sequence id.
3096             while ((job = hb_job(h_scan, 0)) != NULL) 
3097                 hb_rem( h_scan, job );
3098                 } break;
3099 #undef p
3100     }
3101     hb_get_state( h_queue, &s_queue );
3102         switch( s_queue.state )
3103     {
3104 #define p s_queue.param.scanning
3105         case HB_STATE_SCANNING:
3106                 {
3107                         hb_status.queue.state |= GHB_STATE_SCANNING;
3108                         hb_status.queue.title_count = p.title_count;
3109                         hb_status.queue.title_cur = p.title_cur;
3110                 } break;
3111 #undef p
3112
3113         case HB_STATE_SCANDONE:
3114         {
3115                         hb_status.queue.state &= ~GHB_STATE_SCANNING;
3116                         hb_status.queue.state |= GHB_STATE_SCANDONE;
3117         } break;
3118
3119 #define p s_queue.param.working
3120         case HB_STATE_WORKING:
3121                         hb_status.queue.state |= GHB_STATE_WORKING;
3122                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
3123                         hb_status.queue.state &= ~GHB_STATE_SEARCHING;
3124                         hb_status.queue.job_cur = p.job_cur;
3125                         hb_status.queue.job_count = p.job_count;
3126                         hb_status.queue.progress = p.progress;
3127                         hb_status.queue.rate_cur = p.rate_cur;
3128                         hb_status.queue.rate_avg = p.rate_avg;
3129                         hb_status.queue.hours = p.hours;
3130                         hb_status.queue.minutes = p.minutes;
3131                         hb_status.queue.seconds = p.seconds;
3132                         hb_status.queue.unique_id = p.sequence_id & 0xFFFFFF;
3133             break;
3134
3135         case HB_STATE_SEARCHING:
3136                         hb_status.queue.state |= GHB_STATE_SEARCHING;
3137                         hb_status.queue.state &= ~GHB_STATE_WORKING;
3138                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
3139                         hb_status.queue.job_cur = p.job_cur;
3140                         hb_status.queue.job_count = p.job_count;
3141                         hb_status.queue.progress = p.progress;
3142                         hb_status.queue.rate_cur = p.rate_cur;
3143                         hb_status.queue.rate_avg = p.rate_avg;
3144                         hb_status.queue.hours = p.hours;
3145                         hb_status.queue.minutes = p.minutes;
3146                         hb_status.queue.seconds = p.seconds;
3147                         hb_status.queue.unique_id = p.sequence_id & 0xFFFFFF;
3148             break;
3149 #undef p
3150
3151         case HB_STATE_PAUSED:
3152                         hb_status.queue.state |= GHB_STATE_PAUSED;
3153             break;
3154                                 
3155         case HB_STATE_MUXING:
3156         {
3157                         hb_status.queue.state |= GHB_STATE_MUXING;
3158         } break;
3159
3160 #define p s_queue.param.workdone
3161         case HB_STATE_WORKDONE:
3162                 {
3163             hb_job_t *job;
3164
3165                         hb_status.queue.state |= GHB_STATE_WORKDONE;
3166                         hb_status.queue.state &= ~GHB_STATE_MUXING;
3167                         hb_status.queue.state &= ~GHB_STATE_PAUSED;
3168                         hb_status.queue.state &= ~GHB_STATE_WORKING;
3169                         hb_status.queue.state &= ~GHB_STATE_SEARCHING;
3170                         switch (p.error)
3171                         {
3172                         case HB_ERROR_NONE:
3173                                 hb_status.queue.error = GHB_ERROR_NONE;
3174                                 break;
3175                         case HB_ERROR_CANCELED:
3176                                 hb_status.queue.error = GHB_ERROR_CANCELED;
3177                                 break;
3178                         default:
3179                                 hb_status.queue.error = GHB_ERROR_FAIL;
3180                                 break;
3181                         }
3182                         // Delete all remaining jobs of this encode.
3183                         // An encode can be composed of multiple associated jobs.
3184                         // When a job is stopped, libhb removes it from the job list,
3185                         // but does not remove other jobs that may be associated with it.
3186                         // Associated jobs are taged in the sequence id.
3187             while ((job = hb_job(h_queue, 0)) != NULL) 
3188                 hb_rem( h_queue, job );
3189                 } break;
3190 #undef p
3191     }
3192 }
3193
3194 gboolean
3195 ghb_get_title_info(ghb_title_info_t *tinfo, gint titleindex)
3196 {
3197         hb_list_t  * list;
3198         hb_title_t * title;
3199         
3200     if (h_scan == NULL) return FALSE;
3201         list = hb_get_titles( h_scan );
3202         if( !hb_list_count( list ) )
3203         {
3204                 /* No valid title, stop right there */
3205                 return FALSE;
3206         }
3207
3208         title = hb_list_item( list, titleindex );
3209         if (title == NULL) return FALSE;        // Bad titleindex
3210         tinfo->index = titleindex;
3211         tinfo->width = title->width;
3212         tinfo->height = title->height;
3213         memcpy(tinfo->crop, title->crop, 4 * sizeof(int));
3214         // Don't allow crop to 0
3215         if (title->crop[0] + title->crop[1] >= title->height)
3216                 title->crop[0] = title->crop[1] = 0;
3217         if (title->crop[2] + title->crop[3] >= title->width)
3218                 title->crop[2] = title->crop[3] = 0;
3219         tinfo->num_chapters = hb_list_count(title->list_chapter);
3220         tinfo->rate_base = title->rate_base;
3221         tinfo->rate = title->rate;
3222         hb_reduce(&(tinfo->aspect_n), &(tinfo->aspect_d), 
3223                                 title->width * title->pixel_aspect_width, 
3224                                 title->height * title->pixel_aspect_height);
3225         tinfo->hours = title->hours;
3226         tinfo->minutes = title->minutes;
3227         tinfo->seconds = title->seconds;
3228         tinfo->duration = title->duration;
3229
3230         tinfo->angle_count = title->angle_count;
3231         tinfo->path = title->path;
3232         tinfo->name = title->name;
3233         tinfo->type = title->type;
3234         return TRUE;
3235 }
3236
3237 gboolean
3238 ghb_get_audio_info(ghb_audio_info_t *ainfo, gint titleindex, gint audioindex)
3239 {
3240     hb_audio_config_t *audio;
3241         
3242         audio = get_hb_audio(titleindex, audioindex);
3243         if (audio == NULL) return FALSE; // Bad audioindex
3244         ainfo->codec = audio->in.codec;
3245         ainfo->bitrate = audio->in.bitrate;
3246         ainfo->samplerate = audio->in.samplerate;
3247         return TRUE;
3248 }
3249
3250 gboolean
3251 ghb_audio_is_passthru(gint acodec)
3252 {
3253         g_debug("ghb_audio_is_passthru () \n");
3254         return (acodec & (HB_ACODEC_AC3 | HB_ACODEC_DCA));
3255 }
3256
3257 gint
3258 ghb_get_default_acodec()
3259 {
3260         return HB_ACODEC_FAAC;
3261 }
3262
3263 static void
3264 picture_settings_deps(signal_user_data_t *ud)
3265 {
3266         gboolean autoscale, keep_aspect, enable_keep_aspect;
3267         gboolean enable_scale_width, enable_scale_height;
3268         gboolean enable_disp_width, enable_disp_height, enable_par;
3269         gint pic_par;
3270         GtkWidget *widget;
3271
3272         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
3273         if (pic_par == 1)
3274         {
3275                 ghb_ui_update(ud, "autoscale", ghb_boolean_value(TRUE));
3276                 ghb_ui_update(ud, "PictureModulus", ghb_int_value(2));
3277                 ghb_ui_update(ud, "PictureLooseCrop", ghb_boolean_value(TRUE));
3278         }
3279         enable_keep_aspect = (pic_par != 1 && pic_par != 2);
3280         if (!enable_keep_aspect)
3281         {
3282                 ghb_ui_update(ud, "PictureKeepRatio", ghb_boolean_value(TRUE));
3283         }
3284         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
3285         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
3286
3287         enable_scale_width = !autoscale && (pic_par != 1);
3288         enable_scale_height = !autoscale && (pic_par != 1);
3289         enable_disp_width = (pic_par == 3) && !keep_aspect;
3290         enable_par = (pic_par == 3) && !keep_aspect;
3291         enable_disp_height = FALSE;
3292
3293         widget = GHB_WIDGET(ud->builder, "PictureModulus");
3294         gtk_widget_set_sensitive(widget, pic_par != 1);
3295         widget = GHB_WIDGET(ud->builder, "PictureLooseCrop");
3296         gtk_widget_set_sensitive(widget, pic_par != 1);
3297         widget = GHB_WIDGET(ud->builder, "scale_width");
3298         gtk_widget_set_sensitive(widget, enable_scale_width);
3299         widget = GHB_WIDGET(ud->builder, "scale_height");
3300         gtk_widget_set_sensitive(widget, enable_scale_height);
3301         widget = GHB_WIDGET(ud->builder, "PictureDisplayWidth");
3302         gtk_widget_set_sensitive(widget, enable_disp_width);
3303         widget = GHB_WIDGET(ud->builder, "PictureDisplayHeight");
3304         gtk_widget_set_sensitive(widget, enable_disp_height);
3305         widget = GHB_WIDGET(ud->builder, "PicturePARWidth");
3306         gtk_widget_set_sensitive(widget, enable_par);
3307         widget = GHB_WIDGET(ud->builder, "PicturePARHeight");
3308         gtk_widget_set_sensitive(widget, enable_par);
3309         widget = GHB_WIDGET(ud->builder, "PictureKeepRatio");
3310         gtk_widget_set_sensitive(widget, enable_keep_aspect);
3311         widget = GHB_WIDGET(ud->builder, "autoscale");
3312         gtk_widget_set_sensitive(widget, pic_par != 1);
3313 }
3314
3315 void
3316 ghb_set_scale(signal_user_data_t *ud, gint mode)
3317 {
3318         hb_list_t  * list;
3319         hb_title_t * title;
3320         hb_job_t   * job;
3321         gboolean keep_aspect;
3322         gint pic_par;
3323         gboolean autocrop, autoscale, noscale;
3324         gint crop[4], width, height, par_width, par_height;
3325         gint crop_width, crop_height;
3326         gint aspect_n, aspect_d;
3327         gboolean keep_width = (mode & GHB_PIC_KEEP_WIDTH);
3328         gboolean keep_height = (mode & GHB_PIC_KEEP_HEIGHT);
3329         gint step;
3330         GtkWidget *widget;
3331         gint mod;
3332         gint max_width = 0;
3333         gint max_height = 0;
3334         static gboolean busy = FALSE;
3335         
3336         g_debug("ghb_set_scale ()\n");
3337         picture_settings_deps(ud);
3338         if (h_scan == NULL) return;
3339         list = hb_get_titles( h_scan );
3340         if( !hb_list_count( list ) )
3341         {
3342                 /* No valid title, stop right there */
3343                 return;
3344         }
3345         gint titleindex;
3346
3347         titleindex = ghb_settings_combo_int(ud->settings, "title");
3348     title = hb_list_item( list, titleindex );
3349         if (title == NULL) return;
3350         job   = title->job;
3351         if (job == NULL) return;
3352
3353         if (busy) return;
3354         busy = TRUE;
3355
3356         if (!ud->dont_clear_presets && (keep_width || keep_height))
3357         {
3358                 ghb_settings_set_int(ud->settings, "PictureWidth", 0);
3359                 ghb_settings_set_int(ud->settings, "PictureHeight", 0);
3360         }
3361
3362         // First configure widgets
3363         mod = ghb_settings_combo_int(ud->settings, "PictureModulus");
3364         pic_par = ghb_settings_combo_int(ud->settings, "PicturePAR");
3365         keep_aspect = ghb_settings_get_boolean(ud->settings, "PictureKeepRatio");
3366         autocrop = ghb_settings_get_boolean(ud->settings, "PictureAutoCrop");
3367         autoscale = ghb_settings_get_boolean(ud->settings, "autoscale");
3368         // "Noscale" is a flag that says we prefer to crop extra to satisfy
3369         // alignment constraints rather than scaling to satisfy them.
3370         noscale = ghb_settings_get_boolean(ud->settings, "PictureLooseCrop");
3371         // Align dimensions to either 16 or 2 pixels
3372         // The scaler crashes if the dimensions are not divisible by 2
3373         // x264 also will not accept dims that are not multiple of 2
3374         if (autoscale)
3375         {
3376                 keep_width = FALSE;
3377                 keep_height = FALSE;
3378         }
3379         // Step needs to be at least 2 because odd widths cause scaler crash
3380         step = mod;
3381         widget = GHB_WIDGET (ud->builder, "scale_width");
3382         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3383         widget = GHB_WIDGET (ud->builder, "scale_height");
3384         gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3385         if (noscale)
3386         {
3387                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3388                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3389                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3390                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3391                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3392                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3393                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3394                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), step, 16);
3395         }
3396         else
3397         {
3398                 widget = GHB_WIDGET (ud->builder, "PictureTopCrop");
3399                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3400                 widget = GHB_WIDGET (ud->builder, "PictureBottomCrop");
3401                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3402                 widget = GHB_WIDGET (ud->builder, "PictureLeftCrop");
3403                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3404                 widget = GHB_WIDGET (ud->builder, "PictureRightCrop");
3405                 gtk_spin_button_set_increments (GTK_SPIN_BUTTON(widget), 1, 16);
3406         }
3407         ghb_title_info_t tinfo;
3408         ghb_get_title_info (&tinfo, titleindex);
3409         if (autocrop)
3410         {
3411                 crop[0] = tinfo.crop[0];
3412                 crop[1] = tinfo.crop[1];
3413                 crop[2] = tinfo.crop[2];
3414                 crop[3] = tinfo.crop[3];
3415                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3416                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3417                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3418                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3419         }
3420         else
3421         {
3422                 crop[0] = ghb_settings_get_int(ud->settings, "PictureTopCrop");
3423                 crop[1] = ghb_settings_get_int(ud->settings, "PictureBottomCrop");
3424                 crop[2] = ghb_settings_get_int(ud->settings, "PictureLeftCrop");
3425                 crop[3] = ghb_settings_get_int(ud->settings, "PictureRightCrop");
3426         }
3427         if (noscale)
3428         {
3429                 gint need1, need2;
3430
3431                 // Adjust the cropping to accomplish the desired width and height
3432                 crop_width = tinfo.width - crop[2] - crop[3];
3433                 crop_height = tinfo.height - crop[0] - crop[1];
3434                 width = MOD_DOWN(crop_width, mod);
3435                 height = MOD_DOWN(crop_height, mod);
3436
3437                 need1 = (crop_height - height) / 2;
3438                 need2 = crop_height - height - need1;
3439                 crop[0] += need1;
3440                 crop[1] += need2;
3441                 need1 = (crop_width - width) / 2;
3442                 need2 = crop_width - width - need1;
3443                 crop[2] += need1;
3444                 crop[3] += need2;
3445                 ghb_ui_update(ud, "PictureTopCrop", ghb_int64_value(crop[0]));
3446                 ghb_ui_update(ud, "PictureBottomCrop", ghb_int64_value(crop[1]));
3447                 ghb_ui_update(ud, "PictureLeftCrop", ghb_int64_value(crop[2]));
3448                 ghb_ui_update(ud, "PictureRightCrop", ghb_int64_value(crop[3]));
3449         }
3450         hb_reduce(&aspect_n, &aspect_d, 
3451                                 title->width * title->pixel_aspect_width, 
3452                                 title->height * title->pixel_aspect_height);
3453         crop_width = title->width - crop[2] - crop[3];
3454         crop_height = title->height - crop[0] - crop[1];
3455         if (autoscale)
3456         {
3457                 width = crop_width;
3458                 height = crop_height;
3459         }
3460         else
3461         {
3462                 width = ghb_settings_get_int(ud->settings, "scale_width");
3463                 height = ghb_settings_get_int(ud->settings, "scale_height");
3464                 max_width = MOD_DOWN(
3465                         ghb_settings_get_int(ud->settings, "PictureWidth"), mod);
3466                 max_height = MOD_DOWN(
3467                         ghb_settings_get_int(ud->settings, "PictureHeight"), mod);
3468         }
3469         g_debug("max_width %d, max_height %d\n", max_width, max_height);
3470
3471         if (width < 16)
3472                 width = title->width - crop[2] - crop[3];
3473         if (height < 16)
3474                 height = title->height - crop[0] - crop[1];
3475
3476         width = MOD_ROUND(width, mod);
3477         height = MOD_ROUND(height, mod);
3478
3479         // Adjust dims according to max values
3480         if (max_height)
3481                 height = MIN(height, max_height);
3482         if (max_width)
3483                 width = MIN(width, max_width);
3484
3485         if (pic_par)
3486         {
3487                 job->anamorphic.mode = pic_par;
3488                 // The scaler crashes if the dimensions are not divisible by 2
3489                 // Align mod 2.  And so does something in x264_encoder_headers()
3490                 job->modulus = mod;
3491                 job->anamorphic.par_width = title->pixel_aspect_width;
3492                 job->anamorphic.par_height = title->pixel_aspect_height;
3493                 job->anamorphic.dar_width = 0;
3494                 job->anamorphic.dar_height = 0;
3495
3496                 if (keep_height && pic_par == 2)
3497                         width = ((double)height * crop_width / crop_height) + mod / 2;
3498                 job->width = width;
3499                 job->height = height;
3500                 job->maxWidth = max_width;
3501                 job->maxHeight = max_height;
3502                 job->crop[0] = crop[0]; job->crop[1] = crop[1];
3503                 job->crop[2] = crop[2]; job->crop[3] = crop[3];
3504                 if (job->anamorphic.mode == 3 && !keep_aspect)
3505                 {
3506                         job->anamorphic.keep_display_aspect = 0;
3507                         if (mode & GHB_PIC_KEEP_PAR)
3508                         {
3509                                 job->anamorphic.par_width = 
3510                                         ghb_settings_get_int(ud->settings, "PicturePARWidth");
3511                                 job->anamorphic.par_height = 
3512                                         ghb_settings_get_int(ud->settings, "PicturePARHeight");
3513                         }
3514                         else
3515                         {
3516                                 job->anamorphic.dar_width = 
3517                                         ghb_settings_get_int(ud->settings, 
3518                                                                                 "PictureDisplayWidth");
3519                                 job->anamorphic.dar_height = height;
3520                         }
3521                 }
3522                 else
3523                 {
3524                         job->anamorphic.keep_display_aspect = 1;
3525                 }
3526                 hb_set_anamorphic_size( job, &width, &height, 
3527                                                                 &par_width, &par_height );
3528                 if (job->anamorphic.mode == 3 && !keep_aspect && 
3529                         mode & GHB_PIC_KEEP_PAR)
3530                 {
3531                         // hb_set_anamorphic_size reduces the par, which we
3532                         // don't want in this case because the user is
3533                         // explicitely specifying it.
3534                         par_width = ghb_settings_get_int(ud->settings, 
3535                                                                                         "PicturePARWidth");
3536                         par_height = ghb_settings_get_int(ud->settings, 
3537                                                                                                 "PicturePARHeight");
3538                 }
3539         }
3540         else 
3541         {
3542                 job->anamorphic.mode = pic_par;
3543                 if (keep_aspect)
3544                 {
3545                         gdouble par;
3546                         gint new_width, new_height;
3547                         
3548                         // Compute pixel aspect ration.  
3549                         par = (gdouble)(title->height * aspect_n) / (title->width * aspect_d);
3550                         // Must scale so that par becomes 1:1
3551                         // Try to keep largest dimension
3552                         new_height = (crop_height * ((gdouble)width/crop_width) / par);
3553                         new_width = (crop_width * ((gdouble)height/crop_height) * par);
3554
3555                         if (max_width && new_width > max_width)
3556                         {
3557                                 height = new_height;
3558                         }
3559                         else if (max_height && new_height > max_height)
3560                         {
3561                                 width = new_width;
3562                         }
3563                         else if (keep_width)
3564                         {
3565                                 height = new_height;
3566                         }
3567                         else if (keep_height)
3568                         {
3569                                 width = new_width;
3570                         }
3571                         else if (width > new_width)
3572                         {
3573                                 height = new_height;
3574                         }
3575                         else
3576                         {
3577                                 width = new_width;
3578                         }
3579                         g_debug("new w %d h %d\n", width, height);
3580                 }
3581                 width = MOD_ROUND(width, mod);
3582                 height = MOD_ROUND(height, mod);
3583                 if (max_height)
3584                         height = MIN(height, max_height);
3585                 if (max_width)
3586                         width = MIN(width, max_width);
3587                 par_width = par_height = 1;
3588         }
3589         ghb_ui_update(ud, "scale_width", ghb_int64_value(width));
3590         ghb_ui_update(ud, "scale_height", ghb_int64_value(height));
3591
3592         gint disp_width, dar_width, dar_height;
3593         gchar *str;
3594
3595         disp_width = (gdouble)(width * par_width / par_height) + 0.5;
3596         hb_reduce(&dar_width, &dar_height, disp_width, height);
3597                 
3598         gint iaspect = dar_width * 9 / dar_height;
3599         if (dar_width > 2 * dar_height)
3600         {
3601                 str = g_strdup_printf("%.2f : 1", (gdouble)dar_width / dar_height);
3602         }
3603         else if (iaspect <= 16 && iaspect >= 15)
3604         {
3605                 str = g_strdup_printf("%.2f : 9", (gdouble)dar_width * 9 / dar_height);
3606         }
3607         else if (iaspect <= 12 && iaspect >= 11)
3608         {
3609                 str = g_strdup_printf("%.2f : 3", (gdouble)dar_width * 3 / dar_height);
3610         }
3611         else
3612         {
3613                 str = g_strdup_printf("%d : %d", dar_width, dar_height);
3614         }
3615         ghb_ui_update(ud, "display_aspect", ghb_string_value(str));
3616         g_free(str);
3617         ghb_ui_update(ud, "PicturePARWidth", ghb_int64_value(par_width));
3618         ghb_ui_update(ud, "PicturePARHeight", ghb_int64_value(par_height));
3619         ghb_ui_update(ud, "PictureDisplayWidth", ghb_int64_value(disp_width));
3620         ghb_ui_update(ud, "PictureDisplayHeight", ghb_int64_value(height));
3621         busy = FALSE;
3622 }
3623
3624 static void
3625 set_preview_job_settings(hb_job_t *job, GValue *settings)
3626 {
3627         job->crop[0] = ghb_settings_get_int(settings, "PictureTopCrop");
3628         job->crop[1] = ghb_settings_get_int(settings, "PictureBottomCrop");
3629         job->crop[2] = ghb_settings_get_int(settings, "PictureLeftCrop");
3630         job->crop[3] = ghb_settings_get_int(settings, "PictureRightCrop");
3631
3632         job->anamorphic.mode = ghb_settings_combo_int(settings, "PicturePAR");
3633         job->modulus = 
3634                 ghb_settings_combo_int(settings, "PictureModulus");
3635         job->width = ghb_settings_get_int(settings, "scale_width");
3636         job->height = ghb_settings_get_int(settings, "scale_height");
3637         if (ghb_settings_get_boolean(settings, "show_crop"))
3638         {
3639                 gdouble xscale = (gdouble)job->width / 
3640                         (gdouble)(job->title->width - job->crop[2] - job->crop[3]);
3641                 gdouble yscale = (gdouble)job->height / 
3642                         (gdouble)(job->title->height - job->crop[0] - job->crop[1]);
3643         
3644                 job->width += xscale * (job->crop[2] + job->crop[3]);
3645                 job->height += yscale * (job->crop[0] + job->crop[1]);
3646                 job->crop[0] = 0;
3647                 job->crop[1] = 0;
3648                 job->crop[2] = 0;
3649                 job->crop[3] = 0;
3650                 job->modulus = 2;
3651         }
3652
3653         gboolean decomb_deint = ghb_settings_get_boolean(settings, "PictureDecombDeinterlace");
3654         if (decomb_deint)
3655         {
3656                 gint decomb = ghb_settings_combo_int(settings, "PictureDecomb");
3657                 job->deinterlace = (decomb == 0) ? 0 : 1;
3658         }
3659         else
3660         {
3661                 gint deint = ghb_settings_combo_int(settings, "PictureDeinterlace");
3662                 job->deinterlace = (deint == 0) ? 0 : 1;
3663         }
3664
3665         gboolean keep_aspect;
3666         keep_aspect = ghb_settings_get_boolean(settings, "PictureKeepRatio");
3667         if (job->anamorphic.mode)
3668         {
3669                 job->anamorphic.par_width = job->title->pixel_aspect_width;
3670                 job->anamorphic.par_height = job->title->pixel_aspect_height;
3671                 job->anamorphic.dar_width = 0;
3672                 job->anamorphic.dar_height = 0;
3673
3674                 if (job->anamorphic.mode == 3 && !keep_aspect)
3675                 {
3676                         job->anamorphic.keep_display_aspect = 0;
3677                         job->anamorphic.par_width = 
3678                                 ghb_settings_get_int(settings, "PicturePARWidth");
3679                         job->anamorphic.par_height = 
3680                                 ghb_settings_get_int(settings, "PicturePARHeight");
3681                 }
3682                 else
3683                 {
3684                         job->anamorphic.keep_display_aspect = 1;
3685                 }
3686         }
3687 }
3688
3689 gint
3690 ghb_calculate_target_bitrate(GValue *settings, gint titleindex)
3691 {
3692         hb_list_t  * list;
3693         hb_title_t * title;
3694         hb_job_t   * job;
3695         gint size;
3696
3697         if (h_scan == NULL) return 1500;
3698         list = hb_get_titles( h_scan );
3699     title = hb_list_item( list, titleindex );
3700         if (title == NULL) return 1500;
3701         job   = title->job;
3702         if (job == NULL) return 1500;
3703         size = ghb_settings_get_int(settings, "VideoTargetSize");
3704         return hb_calc_bitrate( job, size );
3705 }
3706
3707 gboolean
3708 ghb_validate_filter_string(const gchar *str, gint max_fields)
3709 {
3710         gint fields = 0;
3711         gchar *end;
3712         gdouble val;
3713
3714         if (str == NULL || *str == 0) return TRUE;
3715         while (*str)
3716         {
3717                 val = g_strtod(str, &end);
3718                 if (str != end)
3719                 { // Found a numeric value
3720                         fields++;
3721                         // negative max_fields means infinate
3722                         if (max_fields >= 0 && fields > max_fields) return FALSE;
3723                         if (*end == 0)
3724                                 return TRUE;
3725                         if (*end != ':')
3726                                 return FALSE;
3727                         str = end + 1;
3728                 }
3729                 else
3730                         return FALSE;
3731         }
3732         return FALSE;
3733 }
3734
3735 gboolean
3736 ghb_validate_filters(signal_user_data_t *ud)
3737 {
3738         gchar *str;
3739         gint index;
3740         gchar *message;
3741
3742         gboolean decomb_deint = ghb_settings_get_boolean(ud->settings, "PictureDecombDeinterlace");
3743         // deinte
3744         index = ghb_settings_combo_int(ud->settings, "PictureDeinterlace");
3745         if (!decomb_deint && index == 1)
3746         {
3747                 str = ghb_settings_get_string(ud->settings, "PictureDeinterlaceCustom");
3748                 if (!ghb_validate_filter_string(str, -1))
3749                 {
3750                         message = g_strdup_printf(
3751                                                 "Invalid Deinterlace Settings:\n\n%s\n",
3752                                                 str);
3753                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3754                         g_free(message);
3755                         g_free(str);
3756                         return FALSE;
3757                 }
3758                 g_free(str);
3759         }
3760         // detel
3761         index = ghb_settings_combo_int(ud->settings, "PictureDetelecine");
3762         if (index == 1)
3763         {
3764                 str = ghb_settings_get_string(ud->settings, "PictureDetelecineCustom");
3765                 if (!ghb_validate_filter_string(str, -1))
3766                 {
3767                         message = g_strdup_printf(
3768                                                 "Invalid Detelecine Settings:\n\n%s\n",
3769                                                 str);
3770                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3771                         g_free(message);
3772                         g_free(str);
3773                         return FALSE;
3774                 }
3775                 g_free(str);
3776         }
3777         // decomb
3778         index = ghb_settings_combo_int(ud->settings, "PictureDecomb");
3779         if (decomb_deint && index == 1)
3780         {
3781                 str = ghb_settings_get_string(ud->settings, "PictureDecombCustom");
3782                 if (!ghb_validate_filter_string(str, -1))
3783                 {
3784                         message = g_strdup_printf(
3785                                                 "Invalid Decomb Settings:\n\n%s\n",
3786                                                 str);
3787                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3788                         g_free(message);
3789                         g_free(str);
3790                         return FALSE;
3791                 }
3792                 g_free(str);
3793         }
3794         // denois
3795         index = ghb_settings_combo_int(ud->settings, "PictureDenoise");
3796         if (index == 1)
3797         {
3798                 str = ghb_settings_get_string(ud->settings, "PictureDenoiseCustom");
3799                 if (!ghb_validate_filter_string(str, -1))
3800                 {
3801                         message = g_strdup_printf(
3802                                                 "Invalid Denoise Settings:\n\n%s\n",
3803                                                 str);
3804                         ghb_message_dialog(GTK_MESSAGE_ERROR, message, "Cancel", NULL);
3805                         g_free(str);
3806                         g_free(message);
3807                         return FALSE;
3808                 }
3809                 g_free(str);
3810         }
3811         return TRUE;
3812 }
3813
3814 gboolean
3815 ghb_validate_video(signal_user_data_t *ud)
3816 {
3817         gint vcodec, mux;
3818         gchar *message;
3819
3820         mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3821         vcodec = ghb_settings_combo_int(ud->settings, "VideoEncoder");
3822         if ((mux == HB_MUX_MP4) && (vcodec == HB_VCODEC_THEORA))
3823         {
3824                 // mp4/theora combination is not supported.
3825                 message = g_strdup_printf(
3826                                         "Theora is not supported in the MP4 container.\n\n"
3827                                         "You should choose a different video codec or container.\n"
3828                                         "If you continue, FFMPEG will be chosen for you.");
3829                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3830                 {
3831                         g_free(message);
3832                         return FALSE;
3833                 }
3834                 g_free(message);
3835                 vcodec = HB_VCODEC_FFMPEG;
3836                 ghb_ui_update(ud, "VideoEncoder", ghb_int64_value(vcodec));
3837         }
3838         return TRUE;
3839 }
3840
3841 gboolean
3842 ghb_validate_subtitles(signal_user_data_t *ud)
3843 {
3844         hb_list_t  * list;
3845         hb_title_t * title;
3846         gchar *message;
3847
3848         if (h_scan == NULL) return FALSE;
3849         list = hb_get_titles( h_scan );
3850         if( !hb_list_count( list ) )
3851         {
3852                 /* No valid title, stop right there */
3853                 g_message("No title found.\n");
3854                 return FALSE;
3855         }
3856
3857         gint titleindex;
3858
3859         titleindex = ghb_settings_combo_int(ud->settings, "title");
3860     title = hb_list_item( list, titleindex );
3861         if (title == NULL) return FALSE;
3862         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3863
3864         const GValue *slist, *settings;
3865         gint count, ii, source;
3866         gboolean burned, one_burned = FALSE;
3867
3868         slist = ghb_settings_get_value(ud->settings, "subtitle_list");
3869         count = ghb_array_len(slist);
3870         for (ii = 0; ii < count; ii++)
3871         {
3872                 settings = ghb_array_get_nth(slist, ii);
3873                 source = ghb_settings_get_int(settings, "SubtitleSource");
3874                 burned = ghb_settings_get_boolean(settings, "SubtitleBurned");
3875                 if (burned && one_burned)
3876                 {
3877                         // MP4 can only handle burned vobsubs.  make sure there isn't
3878                         // already something burned in the list
3879                         message = g_strdup_printf(
3880                         "Only one subtitle may be burned into the video.\n\n"
3881                                 "You should change your subtitle selections.\n"
3882                                 "If you continue, some subtitles will be lost.");
3883                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
3884                         {
3885                                 g_free(message);
3886                                 return FALSE;
3887                         }
3888                         g_free(message);
3889                         break;
3890                 }
3891                 else if (burned)
3892                 {
3893                         one_burned = TRUE;
3894                 }
3895                 if (!burned && mux == HB_MUX_MP4 && source == VOBSUB)
3896                 {
3897                         // MP4 can only handle burned vobsubs.  make sure there isn't
3898                         // already something burned in the list
3899                         message = g_strdup_printf(
3900                         "Your chosen container does not support soft bitmap subtitles.\n\n"
3901                                 "You should change your subtitle selections.\n"
3902                                 "If you continue, some subtitles will be lost.");
3903                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, 
3904                                 "Cancel", "Continue"))
3905                         {
3906                                 g_free(message);
3907                                 return FALSE;
3908                         }
3909                         g_free(message);
3910                         break;
3911                 }
3912                 if (source == SRTSUB)
3913                 {
3914                         gchar *filename;
3915
3916                         filename = ghb_settings_get_string(settings, "SrtFile");
3917                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
3918                         {
3919                                 message = g_strdup_printf(
3920                                 "Srt file does not exist or not a regular file.\n\n"
3921                                         "You should choose a valid file.\n"
3922                                         "If you continue, this subtitle will be ignored.");
3923                                 if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, 
3924                                         "Cancel", "Continue"))
3925                                 {
3926                                         g_free(message);
3927                                         return FALSE;
3928                                 }
3929                                 g_free(message);
3930                                 break;
3931                         }
3932                 }
3933         }
3934         return TRUE;
3935 }
3936
3937 gint
3938 ghb_select_audio_codec(signal_user_data_t *ud, gint track)
3939 {
3940         hb_list_t  * list;
3941         hb_title_t * title;
3942         hb_audio_config_t *audio;
3943
3944         if (h_scan == NULL) return -1;
3945         list = hb_get_titles( h_scan );
3946         if( !hb_list_count( list ) )
3947         {
3948                 return -1;
3949         }
3950
3951         gint titleindex;
3952
3953         titleindex = ghb_settings_combo_int(ud->settings, "title");
3954     title = hb_list_item( list, titleindex );
3955         if (title == NULL) return -1;
3956
3957         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
3958
3959         if (track < 0 || track >= hb_list_count(title->list_audio))
3960                 return -1;
3961
3962         audio = (hb_audio_config_t *) hb_list_audio_config_item(
3963                                                                         title->list_audio, track );
3964         if (mux == HB_MUX_MP4)
3965         {
3966                 if (audio->in.codec == HB_ACODEC_AC3)
3967                         return audio->in.codec;
3968                 else
3969                         return HB_ACODEC_FAAC;
3970         }
3971         else
3972         {
3973                 if (audio->in.codec == HB_ACODEC_AC3 || audio->in.codec == HB_ACODEC_DCA)
3974                         return audio->in.codec;
3975                 else
3976                         return HB_ACODEC_LAME;
3977         }
3978 }
3979
3980 const gchar*
3981 ghb_select_audio_codec_str(signal_user_data_t *ud, gint track)
3982 {
3983         gint acodec, ii;
3984
3985         acodec = ghb_select_audio_codec(ud, track);
3986         for (ii = 0; ii < acodec_opts.count; ii++)
3987         {
3988                 if (acodec_opts.map[ii].ivalue == acodec)
3989                         return acodec_opts.map[ii].option;
3990         }
3991         return "Unknown";
3992 }
3993
3994 gboolean
3995 ghb_validate_audio(signal_user_data_t *ud)
3996 {
3997         hb_list_t  * list;
3998         hb_title_t * title;
3999         gchar *message;
4000         GValue *value;
4001
4002         if (h_scan == NULL) return FALSE;
4003         list = hb_get_titles( h_scan );
4004         if( !hb_list_count( list ) )
4005         {
4006                 /* No valid title, stop right there */
4007                 g_message("No title found.\n");
4008                 return FALSE;
4009         }
4010
4011         gint titleindex;
4012
4013         titleindex = ghb_settings_combo_int(ud->settings, "title");
4014     title = hb_list_item( list, titleindex );
4015         if (title == NULL) return FALSE;
4016         gint mux = ghb_settings_combo_int(ud->settings, "FileFormat");
4017
4018         const GValue *audio_list;
4019         gint count, ii;
4020
4021         audio_list = ghb_settings_get_value(ud->settings, "audio_list");
4022         count = ghb_array_len(audio_list);
4023         for (ii = 0; ii < count; ii++)
4024         {
4025                 GValue *asettings;
4026             hb_audio_config_t *taudio;
4027
4028                 asettings = ghb_array_get_nth(audio_list, ii);
4029                 gint track = ghb_settings_combo_int(asettings, "AudioTrack");
4030                 gint codec = ghb_settings_combo_int(asettings, "AudioEncoder");
4031                 if (codec == HB_ACODEC_MASK)
4032                         continue;
4033
4034         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
4035                                                                                         title->list_audio, track );
4036                 if (!(taudio->in.codec & codec) && 
4037                         (codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)))
4038                 {
4039                         // Not supported.  AC3 is passthrough only, so input must be AC3
4040                         message = g_strdup_printf(
4041                                                 "The source does not support Pass-Thru.\n\n"
4042                                                 "You should choose a different audio codec.\n"
4043                                                 "If you continue, one will be chosen for you.");
4044                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4045                         {
4046                                 g_free(message);
4047                                 return FALSE;
4048                         }
4049                         g_free(message);
4050                         if (mux == HB_MUX_MKV)
4051                         {
4052                                 codec = HB_ACODEC_LAME;
4053                         }
4054                         else
4055                         {
4056                                 codec = HB_ACODEC_FAAC;
4057                         }
4058                         value = ghb_lookup_acodec_value(codec);
4059                         ghb_settings_take_value(asettings, "AudioEncoder", value);
4060                 }
4061                 gchar *a_unsup = NULL;
4062                 gchar *mux_s = NULL;
4063                 if (mux == HB_MUX_MP4)
4064                 { 
4065                         mux_s = "MP4";
4066                         // mp4/vorbis|DTS combination is not supported.
4067                         if (codec == HB_ACODEC_VORBIS)
4068                         {
4069                                 a_unsup = "Vorbis";
4070                                 codec = HB_ACODEC_FAAC;
4071                         }
4072                         if (codec == HB_ACODEC_DCA)
4073                         {
4074                                 a_unsup = "DTS";
4075                                 codec = HB_ACODEC_FAAC;
4076                         }
4077                 }
4078                 if (a_unsup)
4079                 {
4080                         message = g_strdup_printf(
4081                                                 "%s is not supported in the %s container.\n\n"
4082                                                 "You should choose a different audio codec.\n"
4083                                                 "If you continue, one will be chosen for you.", a_unsup, mux_s);
4084                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4085                         {
4086                                 g_free(message);
4087                                 return FALSE;
4088                         }
4089                         g_free(message);
4090                         value = ghb_lookup_acodec_value(codec);
4091                         ghb_settings_take_value(asettings, "AudioEncoder", value);
4092                 }
4093                 gint mix = ghb_settings_combo_int (asettings, "AudioMixdown");
4094                 gboolean allow_mono = TRUE;
4095                 gboolean allow_stereo = TRUE;
4096                 gboolean allow_dolby = TRUE;
4097                 gboolean allow_dpl2 = TRUE;
4098                 gboolean allow_6ch = TRUE;
4099                 allow_mono =
4100                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4101                         (codec & ~HB_ACODEC_LAME);
4102                 gint layout = taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4103                 allow_stereo =
4104                         ((layout == HB_INPUT_CH_LAYOUT_MONO && !allow_mono) || layout >= HB_INPUT_CH_LAYOUT_STEREO);
4105                 allow_dolby =
4106                         (layout == HB_INPUT_CH_LAYOUT_3F1R) || 
4107                         (layout == HB_INPUT_CH_LAYOUT_3F2R) || 
4108                         (layout == HB_INPUT_CH_LAYOUT_DOLBY);
4109                 allow_dpl2 = (layout == HB_INPUT_CH_LAYOUT_3F2R);
4110                 allow_6ch =
4111                         (taudio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4112                         (codec & ~HB_ACODEC_LAME) &&
4113                         (layout == HB_INPUT_CH_LAYOUT_3F2R) && 
4114                         (taudio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE);
4115
4116                 gchar *mix_unsup = NULL;
4117                 if (mix == HB_AMIXDOWN_MONO && !allow_mono)
4118                 {
4119                         mix_unsup = "mono";
4120                 }
4121                 if (mix == HB_AMIXDOWN_STEREO && !allow_stereo)
4122                 {
4123                         mix_unsup = "stereo";
4124                 }
4125                 if (mix == HB_AMIXDOWN_DOLBY && !allow_dolby)
4126                 {
4127                         mix_unsup = "Dolby";
4128                 }
4129                 if (mix == HB_AMIXDOWN_DOLBYPLII && !allow_dpl2)
4130                 {
4131                         mix_unsup = "Dolby Pro Logic II";
4132                 }
4133                 if (mix == HB_AMIXDOWN_6CH && !allow_6ch)
4134                 {
4135                         mix_unsup = "6 Channel";
4136                 }
4137                 if (mix_unsup)
4138                 {
4139                         message = g_strdup_printf(
4140                                                 "The source audio does not support %s mixdown.\n\n"
4141                                                 "You should choose a different mixdown.\n"
4142                                                 "If you continue, one will be chosen for you.", mix_unsup);
4143                         if (!ghb_message_dialog(GTK_MESSAGE_WARNING, message, "Cancel", "Continue"))
4144                         {
4145                                 g_free(message);
4146                                 return FALSE;
4147                         }
4148                         g_free(message);
4149                         mix = ghb_get_best_mix(titleindex, track, codec, mix);
4150                         value = get_amix_value(mix);
4151                         ghb_settings_take_value(asettings, "AudioMixdown", value);
4152                 }
4153         }
4154         return TRUE;
4155 }
4156
4157 gboolean
4158 ghb_validate_vquality(GValue *settings)
4159 {
4160         gint vcodec;
4161         gchar *message;
4162         gint min, max;
4163
4164         if (ghb_settings_get_boolean(settings, "nocheckvquality")) return TRUE;
4165         vcodec = ghb_settings_combo_int(settings, "VideoEncoder");
4166         gdouble vquality;
4167         vquality = ghb_settings_get_double(settings, "VideoQualitySlider");
4168         if (ghb_settings_get_boolean(settings, "vquality_type_constant"))
4169         {
4170                 switch (vcodec)
4171                 {
4172                         case HB_VCODEC_X264:
4173                         {
4174                                 min = 16;
4175                                 max = 30;
4176                         } break;
4177
4178                         case HB_VCODEC_FFMPEG:
4179                         {
4180                                 min = 1;
4181                                 max = 8;
4182                         } break;
4183
4184                         case HB_VCODEC_THEORA:
4185                         {
4186                                 min = 0;
4187                                 max = 63;
4188                         } break;
4189
4190                         default:
4191                         {
4192                                 min = 48;
4193                                 max = 62;
4194                         } break;
4195                 }
4196                 if (vquality < min || vquality > max)
4197                 {
4198                         message = g_strdup_printf(
4199                                                 "Interesting video quality choise: %d\n\n"
4200                                                 "Typical values range from %d to %d.\n"
4201                                                 "Are you sure you wish to use this setting?",
4202                                                 (gint)vquality, min, max);
4203                         if (!ghb_message_dialog(GTK_MESSAGE_QUESTION, message, 
4204                                                                         "Cancel", "Continue"))
4205                         {
4206                                 g_free(message);
4207                                 return FALSE;
4208                         }
4209                         g_free(message);
4210                 }
4211         }
4212         return TRUE;
4213 }
4214
4215 static void
4216 add_job(hb_handle_t *h, GValue *js, gint unique_id, gint titleindex)
4217 {
4218         hb_list_t  * list;
4219         hb_title_t * title;
4220         hb_job_t   * job;
4221         static gchar *x264opts;
4222         gint sub_id = 0;
4223         gboolean tweaks = FALSE;
4224         gchar *detel_str = NULL;
4225         gchar *decomb_str = NULL;
4226         gchar *deint_str = NULL;
4227         gchar *deblock_str = NULL;
4228         gchar *denoise_str = NULL;
4229         gchar *dest_str = NULL;
4230
4231         g_debug("add_job()\n");
4232         if (h == NULL) return;
4233         list = hb_get_titles( h );
4234         if( !hb_list_count( list ) )
4235         {
4236                 /* No valid title, stop right there */
4237                 return;
4238         }
4239
4240     title = hb_list_item( list, titleindex );
4241         if (title == NULL) return;
4242
4243         /* Set job settings */
4244         job   = title->job;
4245         if (job == NULL) return;
4246
4247         job->angle = ghb_settings_get_int(js, "angle");
4248         job->start_at_preview = ghb_settings_get_int(js, "start_frame") + 1;
4249         if (job->start_at_preview)
4250         {
4251                 job->seek_points = ghb_settings_get_int(js, "preview_count");
4252                 job->pts_to_stop = ghb_settings_get_int(js, "live_duration") * 90000LL;
4253         }
4254
4255         tweaks = ghb_settings_get_boolean(js, "allow_tweaks");
4256         job->mux = ghb_settings_combo_int(js, "FileFormat");
4257         if (job->mux == HB_MUX_MP4)
4258         {
4259                 job->largeFileSize = ghb_settings_get_boolean(js, "Mp4LargeFile");
4260                 job->mp4_optimize = ghb_settings_get_boolean(js, "Mp4HttpOptimize");
4261         }
4262         else
4263         {
4264                 job->largeFileSize = FALSE;
4265                 job->mp4_optimize = FALSE;
4266         }
4267         if (!job->start_at_preview)
4268         {
4269                 gint start, end;
4270                 gint num_chapters = hb_list_count(title->list_chapter);
4271                 gint duration = title->duration / 90000;
4272                 job->chapter_start = 1;
4273                 job->chapter_end = num_chapters;
4274
4275                 if (ghb_settings_combo_int(js, "PtoPType") == 0)
4276                 {
4277                         start = ghb_settings_get_int(js, "start_point");
4278                         end = ghb_settings_get_int(js, "end_point");
4279                         job->chapter_start = MIN( num_chapters, start );
4280                         job->chapter_end   = MAX( job->chapter_start, end );
4281
4282                 }
4283                 if (ghb_settings_combo_int(js, "PtoPType") == 1)
4284                 {
4285                         job->chapter_start = 1;
4286                         job->chapter_end = num_chapters;
4287                         start = ghb_settings_get_int(js, "start_point");
4288                         end = ghb_settings_get_int(js, "end_point");
4289                         job->pts_to_start = (int64_t)MIN(duration-1, start) * 90000;
4290                         job->pts_to_stop = (int64_t)MAX(start+1, end) * 90000 - 
4291                                                                 job->pts_to_start;
4292                 }
4293                 if (ghb_settings_combo_int(js, "PtoPType") == 2)
4294                 {
4295                         job->chapter_start = 1;
4296                         job->chapter_end = num_chapters;
4297                         start = ghb_settings_get_int(js, "start_point");
4298                         end = ghb_settings_get_int(js, "end_point");
4299                         gint64 max_frames;
4300                         max_frames = (gint64)duration * title->rate / title->rate_base;
4301                         job->frame_to_start = (int64_t)MIN(max_frames-1, start-1);
4302                         job->frame_to_stop = (int64_t)MAX(start, end-1) - 
4303                                                                  job->frame_to_start;
4304                 }
4305                 job->chapter_markers = ghb_settings_get_boolean(js, "ChapterMarkers");
4306                 if (job->chapter_start == job->chapter_end)
4307                         job->chapter_markers = 0;
4308                 if ( job->chapter_markers )
4309                 {
4310                         GValue *chapters;
4311                         GValue *chapter;
4312                         gint chap;
4313                         gint count;
4314
4315                         chapters = ghb_settings_get_value(js, "chapter_list");
4316                         count = ghb_array_len(chapters);
4317                         for(chap = 0; chap < count; chap++)
4318                         {
4319                                 hb_chapter_t * chapter_s;
4320                                 gchar *name;
4321
4322                                 name = NULL;
4323                                 chapter = ghb_array_get_nth(chapters, chap);
4324                                 name = ghb_value_string(chapter); 
4325                                 if (name == NULL)
4326                                 {
4327                                         name = g_strdup_printf ("Chapter %2d", chap+1);
4328                                 }
4329                                 chapter_s = hb_list_item( job->title->list_chapter, chap);
4330                                 strncpy(chapter_s->title, name, 1023);
4331                                 chapter_s->title[1023] = '\0';
4332                                 g_free(name);
4333                         }
4334                 }
4335         }
4336         job->crop[0] = ghb_settings_get_int(js, "PictureTopCrop");
4337         job->crop[1] = ghb_settings_get_int(js, "PictureBottomCrop");
4338         job->crop[2] = ghb_settings_get_int(js, "PictureLeftCrop");
4339         job->crop[3] = ghb_settings_get_int(js, "PictureRightCrop");
4340
4341         
4342         gboolean decomb_deint = ghb_settings_get_boolean(js, "PictureDecombDeinterlace");
4343         gint decomb = ghb_settings_combo_int(js, "PictureDecomb");
4344         gint deint = ghb_settings_combo_int(js, "PictureDeinterlace");
4345         if (!decomb_deint)
4346                 job->deinterlace = (deint != 0) ? 1 : 0;
4347         else
4348                 job->deinterlace = 0;
4349     job->grayscale   = ghb_settings_get_boolean(js, "VideoGrayScale");
4350
4351         gboolean keep_aspect;
4352         keep_aspect = ghb_settings_get_boolean(js, "PictureKeepRatio");
4353         job->anamorphic.mode = ghb_settings_combo_int(js, "PicturePAR");
4354         job->modulus = ghb_settings_combo_int(js, "PictureModulus");
4355         if (job->anamorphic.mode)
4356         {
4357                 job->anamorphic.par_width = title->pixel_aspect_width;
4358                 job->anamorphic.par_height = title->pixel_aspect_height;
4359                 job->anamorphic.dar_width = 0;
4360                 job->anamorphic.dar_height = 0;
4361
4362                 if (job->anamorphic.mode == 3 && !keep_aspect)
4363                 {
4364                         job->anamorphic.keep_display_aspect = 0;
4365                         job->anamorphic.par_width = 
4366                                 ghb_settings_get_int(js, "PicturePARWidth");
4367                         job->anamorphic.par_height = 
4368                                 ghb_settings_get_int(js, "PicturePARHeight");
4369                 }
4370                 else
4371                 {
4372                         job->anamorphic.keep_display_aspect = 1;
4373                 }
4374         }
4375
4376         /* Add selected filters */
4377         job->filters = hb_list_init();
4378         gint detel = ghb_settings_combo_int(js, "PictureDetelecine");
4379         if ( detel )
4380         {
4381                 if (detel != 1)
4382                 {
4383                         if (detel_opts.map[detel].svalue != NULL)
4384                                 detel_str = g_strdup(detel_opts.map[detel].svalue);
4385                 }
4386                 else
4387                         detel_str = ghb_settings_get_string(js, "PictureDetelecineCustom");
4388                 hb_filter_detelecine.settings = detel_str;
4389                 hb_list_add( job->filters, &hb_filter_detelecine );
4390         }
4391         if ( decomb_deint && decomb )
4392         {
4393                 if (decomb != 1)
4394                 {
4395                         if (decomb_opts.map[decomb].svalue != NULL)
4396                                 decomb_str = g_strdup(decomb_opts.map[decomb].svalue);
4397                 }
4398                 else
4399                         decomb_str = ghb_settings_get_string(js, "PictureDecombCustom");
4400                 hb_filter_decomb.settings = decomb_str;
4401                 hb_list_add( job->filters, &hb_filter_decomb );
4402         }
4403         if( job->deinterlace )
4404         {
4405                 if (deint != 1)
4406                 {
4407                         if (deint_opts.map[deint].svalue != NULL)
4408                                 deint_str = g_strdup(deint_opts.map[deint].svalue);
4409                 }
4410                 else
4411                         deint_str = ghb_settings_get_string(js, "PictureDeinterlaceCustom");
4412                 hb_filter_deinterlace.settings = deint_str;
4413                 hb_list_add( job->filters, &hb_filter_deinterlace );
4414         }
4415         gint deblock = ghb_settings_get_int(js, "PictureDeblock");
4416         if( deblock >= 5 )
4417         {
4418                 deblock_str = g_strdup_printf("%d", deblock);
4419                 hb_filter_deblock.settings = deblock_str;
4420                 hb_list_add( job->filters, &hb_filter_deblock );
4421         }
4422         gint denoise = ghb_settings_combo_int(js, "PictureDenoise");
4423         if( denoise )
4424         {
4425                 if (denoise != 1)
4426                 {
4427                         if (denoise_opts.map[denoise].svalue != NULL)
4428                                 denoise_str = g_strdup(denoise_opts.map[denoise].svalue);
4429                 }
4430                 else
4431                         denoise_str = ghb_settings_get_string(js, "PictureDenoiseCustom");
4432                 hb_filter_denoise.settings = denoise_str;
4433                 hb_list_add( job->filters, &hb_filter_denoise );
4434         }
4435         job->width = ghb_settings_get_int(js, "scale_width");
4436         job->height = ghb_settings_get_int(js, "scale_height");
4437
4438         job->vcodec = ghb_settings_combo_int(js, "VideoEncoder");
4439         if ((job->mux == HB_MUX_MP4 ) && (job->vcodec == HB_VCODEC_THEORA))
4440         {
4441                 // mp4/theora combination is not supported.
4442                 job->vcodec = HB_VCODEC_FFMPEG;
4443         }
4444         if ((job->vcodec == HB_VCODEC_X264) && (job->mux == HB_MUX_MP4))
4445         {
4446                 job->ipod_atom = ghb_settings_get_boolean(js, "Mp4iPodCompatible");
4447         }
4448         if (ghb_settings_get_boolean(js, "vquality_type_constant"))
4449         {
4450                 gdouble vquality;
4451                 vquality = ghb_settings_get_double(js, "VideoQualitySlider");
4452                 job->vquality =  vquality;
4453                 job->vbitrate = 0;
4454         }
4455         else if (ghb_settings_get_boolean(js, "vquality_type_bitrate"))
4456         {
4457                 job->vquality = -1.0;
4458                 job->vbitrate = ghb_settings_get_int(js, "VideoAvgBitrate");
4459         }
4460
4461         gint vrate = ghb_settings_combo_int(js, "VideoFramerate");
4462         if( vrate == 0 )
4463         {
4464                 job->vrate = title->rate;
4465                 job->vrate_base = title->rate_base;
4466                 job->cfr = 0;
4467         }
4468         else
4469         {
4470                 job->vrate = 27000000;
4471                 job->vrate_base = vrate;
4472                 job->cfr = 1;
4473         }
4474
4475         const GValue *audio_list;
4476         gint count, ii;
4477         gint tcount = 0;
4478         
4479         audio_list = ghb_settings_get_value(js, "audio_list");
4480         count = ghb_array_len(audio_list);
4481         for (ii = 0; ii < count; ii++)
4482         {
4483                 GValue *asettings;
4484             hb_audio_config_t audio;
4485             hb_audio_config_t *taudio;
4486
4487                 hb_audio_config_init(&audio);
4488                 asettings = ghb_array_get_nth(audio_list, ii);
4489                 audio.in.track = ghb_settings_get_int(asettings, "AudioTrack");
4490                 audio.out.track = tcount;
4491                 audio.out.codec = ghb_settings_combo_int(asettings, "AudioEncoder");
4492         taudio = (hb_audio_config_t *) hb_list_audio_config_item(
4493                                                                         title->list_audio, audio.in.track );
4494                 if (audio.out.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
4495                 {
4496                         if (!(taudio->in.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA)))
4497                         {
4498                                 // Not supported.  
4499                                 // AC3/DTS is passthrough only, so input must be AC3/DTS
4500                                 if (job->mux == HB_MUX_MKV)
4501                                 {
4502                                         audio.out.codec = HB_ACODEC_LAME;
4503                                 }
4504                                 else
4505                                 {
4506                                         audio.out.codec = HB_ACODEC_FAAC;
4507                                 }
4508                         }
4509                         else
4510                         {
4511                                 audio.out.codec &= taudio->in.codec;
4512                         }
4513                 }
4514                 if ((job->mux == HB_MUX_MP4) && 
4515                         ((audio.out.codec & HB_ACODEC_DCA) ||
4516                         (audio.out.codec & HB_ACODEC_VORBIS)))
4517                 {
4518                         // mp4/mp3|dts|vorbis combination is not supported.
4519                         audio.out.codec = HB_ACODEC_FAAC;
4520                 }
4521         audio.out.dynamic_range_compression = 
4522                         ghb_settings_get_double(asettings, "AudioTrackDRCSlider");
4523         if (audio.out.dynamic_range_compression < 1.0)
4524                 audio.out.dynamic_range_compression = 0.0;
4525
4526                 // It would be better if this were done in libhb for us, but its not yet.
4527                 if (audio.out.codec & (HB_ACODEC_AC3 | HB_ACODEC_DCA))
4528                 {
4529                         audio.out.mixdown = 0;
4530                 }
4531                 else
4532                 {
4533                         int channels;
4534
4535                         audio.out.mixdown = ghb_settings_combo_int(asettings, "AudioMixdown");
4536                         if (audio.out.mixdown == HB_AMIXDOWN_MONO)
4537                                 channels = 1;
4538                         else if (audio.out.mixdown == HB_AMIXDOWN_6CH)
4539                                 channels = 6;
4540                         else
4541                                 channels = 2;
4542
4543                         // Make sure the mixdown is valid and pick a new one if not.
4544                         audio.out.mixdown = ghb_get_best_mix(titleindex, 
4545                                 audio.in.track, audio.out.codec, audio.out.mixdown);
4546                         audio.out.bitrate = 
4547                                 ghb_settings_combo_int(asettings, "AudioBitrate");
4548                         gint srate = ghb_settings_combo_int(asettings, "AudioSamplerate");
4549                         if (srate == 0) // 0 is same as source
4550                                 audio.out.samplerate = taudio->in.samplerate;
4551                         else
4552                                 audio.out.samplerate = srate;
4553
4554                         audio.out.bitrate = ghb_get_best_audio_bitrate(
4555                                 audio.out.codec, audio.out.bitrate, channels);
4556                 }
4557
4558                 // Add it to the jobs audio list
4559         hb_audio_add( job, &audio );
4560                 tcount++;
4561         }
4562         // I was tempted to move this up with the reset of the video quality
4563         // settings, but I suspect the settings above need to be made
4564         // first in order for hb_calc_bitrate to be accurate.
4565         if (ghb_settings_get_boolean(js, "vquality_type_target"))
4566         {
4567                 gint size;
4568                 
4569                 size = ghb_settings_get_int(js, "VideoTargetSize");
4570         job->vbitrate = hb_calc_bitrate( job, size );
4571                 job->vquality = -1.0;
4572         }
4573
4574         dest_str = ghb_settings_get_string(js, "destination");
4575         job->file = dest_str;
4576
4577         const GValue *subtitle_list;
4578         gint subtitle;
4579         gboolean force, burned, def, one_burned = FALSE;
4580         
4581         ghb_settings_set_boolean(js, "subtitle_scan", FALSE);
4582         subtitle_list = ghb_settings_get_value(js, "subtitle_list");
4583         count = ghb_array_len(subtitle_list);
4584         for (ii = 0; ii < count; ii++)
4585         {
4586                 GValue *ssettings;
4587                 gint source;
4588
4589                 ssettings = ghb_array_get_nth(subtitle_list, ii);
4590
4591                 force = ghb_settings_get_boolean(ssettings, "SubtitleForced");
4592                 burned = ghb_settings_get_boolean(ssettings, "SubtitleBurned");
4593                 def = ghb_settings_get_boolean(ssettings, "SubtitleDefaultTrack");
4594                 source = ghb_settings_get_int(ssettings, "SubtitleSource");
4595
4596                 if (source == SRTSUB)
4597                 {
4598                 hb_subtitle_config_t sub_config;
4599                         gchar *filename, *lang, *code;
4600
4601                         filename = ghb_settings_get_string(ssettings, "SrtFile");
4602                         if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR))
4603                         {
4604                                 continue;
4605                         }
4606                         sub_config.offset = ghb_settings_get_int(ssettings, "SrtOffset");
4607                         lang = ghb_settings_get_string(ssettings, "SrtLanguage");
4608                         code = ghb_settings_get_string(ssettings, "SrtCodeset");
4609                         strncpy(sub_config.src_filename, filename, 128);
4610                         strncpy(sub_config.src_codeset, code, 40);
4611                         sub_config.force = 0;
4612                         sub_config.dest = PASSTHRUSUB;
4613                         sub_config.default_track = def;
4614
4615                         hb_srt_add( job, &sub_config, lang);
4616
4617                         g_free(filename);
4618                         g_free(lang);
4619                         g_free(code);
4620                         continue;
4621                 }
4622
4623                 subtitle = ghb_settings_get_int(ssettings, "SubtitleTrack");
4624                 if (subtitle == -1)
4625                 {
4626                         if (!burned && job->mux == HB_MUX_MKV)
4627                         {
4628                                 job->select_subtitle_config.dest = PASSTHRUSUB;
4629                         }
4630                         else if (!burned && job->mux == HB_MUX_MP4)
4631                         {
4632                                 // Skip any non-burned vobsubs when output is mp4
4633                                 continue;
4634                         }
4635                         else if (burned)
4636                         {
4637                                 // Only allow one subtitle to be burned into the video
4638                                 if (one_burned)
4639                                         continue;
4640                                 job->select_subtitle_config.dest = RENDERSUB;
4641                                 one_burned = TRUE;
4642                         }
4643                         job->select_subtitle_config.force = force;
4644                         job->select_subtitle_config.default_track = def;
4645                         job->indepth_scan = 1;
4646                         ghb_settings_set_boolean(js, "subtitle_scan", TRUE);
4647                 }
4648                 else if (subtitle >= 0)
4649                 {
4650                 hb_subtitle_t * subt;
4651                 hb_subtitle_config_t sub_config;
4652
4653                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
4654                         sub_config = subt->config;
4655                         if (subt != NULL)
4656                         {
4657                                 if (!burned && job->mux == HB_MUX_MKV && 
4658                                         subt->format == PICTURESUB)
4659                                 {
4660                                         sub_config.dest = PASSTHRUSUB;
4661                                 }
4662                                 else if (!burned && job->mux == HB_MUX_MP4 && 
4663                                         subt->format == PICTURESUB)
4664                                 {
4665                                         // Skip any non-burned vobsubs when output is mp4
4666                                         continue;
4667                                 }
4668                                 else if ( burned && subt->format == PICTURESUB )
4669                                 {
4670                                         // Only allow one subtitle to be burned into the video
4671                                         if (one_burned)
4672                                                 continue;
4673                                         one_burned = TRUE;
4674                                 }
4675                                 sub_config.force = force;
4676                                 sub_config.default_track = def;
4677                         hb_subtitle_add( job, &sub_config, subtitle );
4678                         }
4679                 }
4680         }
4681
4682         // TODO: libhb holds onto a reference to the x264opts and is not
4683         // finished with it until encoding the job is done.  But I can't
4684         // find a way to get at the job before it is removed in order to
4685         // free up the memory I am allocating here.
4686         // The short story is THIS LEAKS.
4687         x264opts = ghb_build_x264opts_string(js);
4688         
4689         if( *x264opts == '\0' )
4690         {
4691                 g_free(x264opts);
4692                 x264opts = NULL;
4693         }
4694
4695         if (job->indepth_scan == 1)
4696         {
4697                 // Subtitle scan. Look for subtitle matching audio language
4698
4699                 /*
4700                  * When subtitle scan is enabled do a fast pre-scan job
4701                  * which will determine which subtitles to enable, if any.
4702                  */
4703                 job->pass = -1;
4704                 job->indepth_scan = 1;
4705                 job->x264opts = NULL;
4706
4707                 /*
4708                  * Add the pre-scan job
4709                  */
4710                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4711                 hb_add( h, job );
4712         }
4713
4714         if( ghb_settings_get_boolean(js, "VideoTwoPass") &&
4715                 !ghb_settings_get_boolean(js, "vquality_type_constant"))
4716         {
4717                 /*
4718                  * If subtitle_scan is enabled then only turn it on
4719                  * for the second pass and then off again for the
4720                  * second.
4721                  */
4722                 job->pass = 1;
4723                 job->indepth_scan = 0;
4724
4725                 /*
4726                  * If turbo options have been selected then append them
4727                  * to the x264opts now (size includes one ':' and the '\0')
4728                  */
4729                 if( ghb_settings_get_boolean(js, "VideoTurboTwoPass") )
4730                 {
4731                         gchar *tmp_x264opts;
4732                         gchar *extra_opts;
4733                         gint badapt;
4734
4735                         badapt = ghb_lookup_badapt(x264opts);
4736                         if (badapt == 2)
4737                         {
4738                                 extra_opts = g_strdup_printf("%s", turbo_opts);
4739                         }
4740                         else
4741                         {
4742                                 extra_opts = g_strdup_printf("%s:weightb=0", turbo_opts);
4743                         }
4744         
4745                         if ( x264opts )
4746                         {
4747                                 tmp_x264opts = g_strdup_printf("%s:%s", x264opts, extra_opts);
4748                         } 
4749                         else 
4750                         {
4751                                 /*
4752                                  * No x264opts to modify, but apply the turbo options
4753                                  * anyway as they may be modifying defaults
4754                                  */
4755                                 tmp_x264opts = g_strdup_printf("%s", extra_opts);
4756                         }
4757                         g_free(extra_opts);
4758
4759                         job->x264opts = tmp_x264opts;
4760                 }
4761                 else
4762                 {
4763                         job->x264opts = x264opts;
4764                 }
4765                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4766                 hb_add( h, job );
4767                 //if (job->x264opts != NULL)
4768                 //      g_free(job->x264opts);
4769
4770                 job->pass = 2;
4771                 /*
4772                  * On the second pass we turn off subtitle scan so that we
4773                  * can actually encode using any subtitles that were auto
4774                  * selected in the first pass (using the whacky select-subtitle
4775                  * attribute of the job).
4776                  */
4777                 job->indepth_scan = 0;
4778                 job->x264opts = x264opts;
4779                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4780                 hb_add( h, job );
4781                 //if (job->x264opts != NULL)
4782                 //      g_free(job->x264opts);
4783         }
4784         else
4785         {
4786                 job->x264opts = x264opts;
4787                 job->indepth_scan = 0;
4788                 job->pass = 0;
4789                 job->sequence_id = (unique_id & 0xFFFFFF) | (sub_id++ << 24);
4790                 hb_add( h, job );
4791                 //if (job->x264opts != NULL)
4792                 //      g_free(job->x264opts);
4793         }
4794
4795         // clean up audio list
4796         gint num_audio_tracks = hb_list_count(job->list_audio);
4797         for(ii = 0; ii < num_audio_tracks; ii++)
4798         {
4799                 hb_audio_t *audio = (hb_audio_t*)hb_list_item(job->list_audio, 0);
4800                 hb_list_rem(job->list_audio, audio);
4801                 free(audio);
4802         }
4803
4804         // clean up subtitle list
4805         gint num_subtitle_tracks = hb_list_count(job->list_subtitle);
4806         for(ii = 0; ii < num_subtitle_tracks; ii++)
4807         {
4808                 hb_subtitle_t *subtitle = hb_list_item(job->list_subtitle, 0);
4809                 hb_list_rem(job->list_subtitle, subtitle);
4810                 free(subtitle);
4811         }
4812
4813         if (detel_str) g_free(detel_str);
4814         if (decomb_str) g_free(decomb_str);
4815         if (deint_str) g_free(deint_str);
4816         if (deblock_str) g_free(deblock_str);
4817         if (denoise_str) g_free(denoise_str);
4818         if (dest_str) g_free(dest_str);
4819 }
4820
4821 void
4822 ghb_add_job(GValue *js, gint unique_id)
4823 {
4824         // Since I'm doing a scan of the single title I want just prior 
4825         // to adding the job, there is only the one title to choose from.
4826         add_job(h_queue, js, unique_id, 0);
4827 }
4828
4829 void
4830 ghb_add_live_job(GValue *js, gint unique_id)
4831 {
4832         // Since I'm doing a scan of the single title I want just prior 
4833         // to adding the job, there is only the one title to choose from.
4834         gint titleindex = ghb_settings_combo_int(js, "title");
4835         add_job(h_scan, js, unique_id, titleindex);
4836 }
4837
4838 void
4839 ghb_remove_job(gint unique_id)
4840 {
4841     hb_job_t * job;
4842     gint ii;
4843         
4844         // Multiples passes all get the same id
4845         // remove them all.
4846         // Go backwards through list, so reordering doesn't screw me.
4847         ii = hb_count(h_queue) - 1;
4848     while ((job = hb_job(h_queue, ii--)) != NULL)
4849     {
4850         if ((job->sequence_id & 0xFFFFFF) == unique_id)
4851                         hb_rem(h_queue, job);
4852     }
4853 }
4854
4855 void
4856 ghb_start_queue()
4857 {
4858         hb_start( h_queue );
4859 }
4860
4861 void
4862 ghb_stop_queue()
4863 {
4864         hb_stop( h_queue );
4865 }
4866
4867 void
4868 ghb_start_live_encode()
4869 {
4870         hb_start( h_scan );
4871 }
4872
4873 void
4874 ghb_stop_live_encode()
4875 {
4876         hb_stop( h_scan );
4877 }
4878
4879 void
4880 ghb_pause_queue()
4881 {
4882     hb_state_t s;
4883     hb_get_state2( h_queue, &s );
4884
4885     if( s.state == HB_STATE_PAUSED )
4886     {
4887                 hb_status.queue.state &= ~GHB_STATE_PAUSED;
4888                 hb_resume( h_queue );
4889     }
4890     else
4891     {
4892                 hb_status.queue.state |= GHB_STATE_PAUSED;
4893                 hb_pause( h_queue );
4894     }
4895 }
4896
4897 static void
4898 vert_line(
4899         GdkPixbuf * pb, 
4900         guint8 r, 
4901         guint8 g, 
4902         guint8 b, 
4903         gint x, 
4904         gint y, 
4905         gint len, 
4906         gint width)
4907 {
4908         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4909         guint8 *dst;
4910         gint ii, jj;
4911         gint channels = gdk_pixbuf_get_n_channels (pb);
4912         gint stride = gdk_pixbuf_get_rowstride (pb);
4913
4914         for (jj = 0; jj < width; jj++)
4915         {
4916                 dst = pixels + y * stride + (x+jj) * channels;
4917                 for (ii = 0; ii < len; ii++)
4918                 {
4919                         dst[0] = r;
4920                         dst[1] = g;
4921                         dst[2] = b;
4922                         dst += stride;
4923                 }
4924         }
4925 }
4926
4927 static void
4928 horz_line(
4929         GdkPixbuf * pb, 
4930         guint8 r, 
4931         guint8 g, 
4932         guint8 b, 
4933         gint x, 
4934         gint y, 
4935         gint len,
4936         gint width)
4937 {
4938         guint8 *pixels = gdk_pixbuf_get_pixels (pb);
4939         guint8 *dst;
4940         gint ii, jj;
4941         gint channels = gdk_pixbuf_get_n_channels (pb);
4942         gint stride = gdk_pixbuf_get_rowstride (pb);
4943
4944         for (jj = 0; jj < width; jj++)
4945         {
4946                 dst = pixels + (y+jj) * stride + x * channels;
4947                 for (ii = 0; ii < len; ii++)
4948                 {
4949                         dst[0] = r;
4950                         dst[1] = g;
4951                         dst[2] = b;
4952                         dst += channels;
4953                 }
4954         }
4955 }
4956
4957 static void
4958 hash_pixbuf(
4959         GdkPixbuf * pb,
4960         gint        x,
4961         gint        y,
4962         gint        w,
4963         gint        h,
4964         gint        step,
4965         gint            orientation)
4966 {
4967         gint ii, jj;
4968         gint line_width = 8;
4969         struct
4970         {
4971                 guint8 r;
4972                 guint8 g;
4973                 guint8 b;
4974         } c[4] = 
4975         {{0x80, 0x80, 0x80},{0xC0, 0x80, 0x70},{0x80, 0xA0, 0x80},{0x70, 0x80, 0xA0}};
4976
4977         if (!orientation)
4978         {
4979                 // vertical lines
4980                 for (ii = x, jj = 0; ii+line_width < x+w; ii += step, jj++)
4981                 {
4982                         vert_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, ii, y, h, line_width);
4983                 }
4984         }
4985         else
4986         {
4987                 // horizontal lines
4988                 for (ii = y, jj = 0; ii+line_width < y+h; ii += step, jj++)
4989                 {
4990                         horz_line(pb, c[jj&3].r, c[jj&3].g, c[jj&3].b, x, ii, w, line_width);
4991                 }
4992         }
4993 }
4994
4995 GdkPixbuf*
4996 ghb_get_preview_image(
4997         gint titleindex, 
4998         gint index, 
4999         signal_user_data_t *ud,
5000         gint *out_width,
5001         gint *out_height)
5002 {
5003         GValue *settings;
5004         hb_title_t *title;
5005         hb_list_t  *list;
5006         
5007         settings = ud->settings;
5008         list = hb_get_titles( h_scan );
5009         if( !hb_list_count( list ) )
5010         {
5011                 /* No valid title, stop right there */
5012                 return NULL;
5013         }
5014     title = hb_list_item( list, titleindex );
5015         if (title == NULL) return NULL;
5016         if (title->job == NULL) return NULL;
5017         set_preview_job_settings(title->job, settings);
5018
5019         // hb_get_preview doesn't compensate for anamorphic, so lets
5020         // calculate scale factors
5021         gint width, height, par_width = 1, par_height = 1;
5022         gint pic_par = ghb_settings_combo_int(settings, "PicturePAR");
5023         if (pic_par)
5024         {
5025                 hb_set_anamorphic_size( title->job, &width, &height, 
5026                                                                 &par_width, &par_height );
5027         }
5028
5029         // Make sure we have a big enough buffer to receive the image from libhb
5030         gint dstWidth = title->job->width;
5031         gint dstHeight= title->job->height;
5032
5033         static guint8 *buffer = NULL;
5034         static gint bufferSize = 0;
5035         gint newSize;
5036
5037         newSize = dstWidth * dstHeight * 4;
5038         if( bufferSize < newSize )
5039         {
5040                 bufferSize = newSize;
5041                 buffer     = (guint8*) g_realloc( buffer, bufferSize );
5042         }
5043         hb_get_preview( h_scan, title, index, buffer );
5044
5045         // Create an GdkPixbuf and copy the libhb image into it, converting it from
5046         // libhb's format something suitable.
5047         
5048         // The image data returned by hb_get_preview is 4 bytes per pixel, 
5049         // BGRA format. Alpha is ignored.
5050
5051         GdkPixbuf *preview = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, dstWidth, dstHeight);
5052         guint8 *pixels = gdk_pixbuf_get_pixels (preview);
5053         
5054         guint32 *src = (guint32*)buffer;
5055         guint8 *dst = pixels;
5056
5057         gint ii, jj;
5058         gint channels = gdk_pixbuf_get_n_channels (preview);
5059         gint stride = gdk_pixbuf_get_rowstride (preview);
5060         guint8 *tmp;
5061
5062         for (ii = 0; ii < dstHeight; ii++)
5063         {
5064                 tmp = dst;
5065                 for (jj = 0; jj < dstWidth; jj++)
5066                 {
5067                         tmp[0] = src[0] >> 16;
5068                         tmp[1] = src[0] >> 8;
5069                         tmp[2] = src[0] >> 0;
5070                         tmp += channels;
5071                         src++;
5072                 }
5073                 dst += stride;
5074         }
5075         gint w = ghb_settings_get_int(settings, "scale_width");
5076         gint h = ghb_settings_get_int(settings, "scale_height");
5077         ghb_par_scale(ud, &w, &h, par_width, par_height);
5078
5079         gint c0, c1, c2, c3;
5080         c0 = ghb_settings_get_int(settings, "PictureTopCrop");
5081         c1 = ghb_settings_get_int(settings, "PictureBottomCrop");
5082         c2 = ghb_settings_get_int(settings, "PictureLeftCrop");
5083         c3 = ghb_settings_get_int(settings, "PictureRightCrop");
5084
5085         gdouble xscale = (gdouble)w / (gdouble)(title->width - c2 - c3);
5086         gdouble yscale = (gdouble)h / (gdouble)(title->height - c0 - c1);
5087         
5088         ghb_par_scale(ud, &dstWidth, &dstHeight, par_width, par_height);
5089         *out_width = w;
5090         *out_height = h;
5091         if (ghb_settings_get_boolean(settings, "reduce_hd_preview"))
5092         {
5093                 GdkScreen *ss;
5094                 gint s_w, s_h;
5095                 gint orig_w, orig_h;
5096                 gint factor = 80;
5097
5098                 if (ghb_settings_get_boolean(settings, "preview_fullscreen"))
5099                 {
5100                         factor = 100;
5101                 }
5102                 ss = gdk_screen_get_default();
5103                 s_w = gdk_screen_get_width(ss);
5104                 s_h = gdk_screen_get_height(ss);
5105                 orig_w = dstWidth;
5106                 orig_h = dstHeight;
5107
5108                 if (dstWidth > s_w * factor / 100)
5109                 {
5110                         dstWidth = s_w * factor / 100;
5111                         dstHeight = dstHeight * dstWidth / orig_w;
5112                 }
5113                 if (dstHeight > s_h * factor / 100)
5114                 {
5115                         dstHeight = s_h * factor / 100;
5116                         dstWidth = dstWidth * dstHeight / orig_h;
5117                 }
5118                 xscale *= (gdouble)dstWidth / orig_w;
5119                 yscale *= (gdouble)dstHeight / orig_h;
5120                 w *= (gdouble)dstWidth / orig_w;
5121                 h *= (gdouble)dstHeight / orig_h;
5122         }
5123         GdkPixbuf *scaled_preview;
5124         scaled_preview = gdk_pixbuf_scale_simple(preview, dstWidth, dstHeight, GDK_INTERP_HYPER);
5125         if (ghb_settings_get_boolean(settings, "show_crop"))
5126         {
5127                 c0 *= yscale;
5128                 c1 *= yscale;
5129                 c2 *= xscale;
5130                 c3 *= xscale;
5131                 // Top
5132                 hash_pixbuf(scaled_preview, c2, 0, w, c0, 32, 0);
5133                 // Bottom
5134                 hash_pixbuf(scaled_preview, c2, dstHeight-c1, w, c1, 32, 0);
5135                 // Left
5136                 hash_pixbuf(scaled_preview, 0, c0, c2, h, 32, 1);
5137                 // Right
5138                 hash_pixbuf(scaled_preview, dstWidth-c3, c0, c3, h, 32, 1);
5139         }
5140         g_object_unref (preview);
5141         return scaled_preview;
5142 }
5143
5144 static void
5145 sanitize_volname(gchar *name)
5146 {
5147         gchar *a, *b;
5148
5149         a = b = name;
5150         while (*b)
5151         {
5152                 switch(*b)
5153                 {
5154                 case '<':
5155                         b++;
5156                         break;
5157                 case '>':
5158                         b++;
5159                         break;
5160                 default:
5161                         *a = *b;
5162                         a++; b++;
5163                         break;
5164                 }
5165         }
5166         *a = 0;
5167 }
5168
5169 gchar*
5170 ghb_dvd_volname(const gchar *device)
5171 {
5172         gchar *name;
5173         name = hb_dvd_name((gchar*)device);
5174         if (name != NULL && name[0] != 0)
5175         {
5176                 name = g_strdup(name);
5177                 sanitize_volname(name);
5178                 return name;
5179         }
5180         return NULL;
5181 }