OSDN Git Service

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