OSDN Git Service

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