OSDN Git Service

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