bunch-o compiler bitch'n
[goodguy/history.git] / cinelerra-5.1 / cinelerra / bdcreate.C
1 #include "asset.h"
2 #include "bchash.h"
3 #include "bdcreate.h"
4 #include "clip.h"
5 #include "edl.h"
6 #include "edit.h"
7 #include "edits.h"
8 #include "edlsession.h"
9 #include "file.h"
10 #include "filexml.h"
11 #include "interlacemodes.h"
12 #include "keyframe.h"
13 #include "labels.h"
14 #include "mainerror.h"
15 #include "mainundo.h"
16 #include "mwindow.h"
17 #include "mwindowgui.h"
18 #include "plugin.h"
19 #include "pluginset.h"
20 #include "preferences.h"
21 #include "rescale.h"
22 #include "track.h"
23 #include "tracks.h"
24
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <sys/stat.h>
29 #include <sys/statfs.h>
30
31 // BD Creation
32
33 // selected by timezone
34 #define BD_1920x1080_2997i      0
35 #define BD_1920x1080_25i        3
36
37 static struct bd_format {
38         const char *name;
39         int w, h;
40         double framerate;
41         int wide, interlaced;
42 } bd_formats[] = {
43 // framerates are frames, not fields, per second, *=not standard
44         { "1920x1080 29.97i",   1920,1080, 29.97,  1, ILACE_MODE_TOP_FIRST },
45         { "1920x1080 29.97p*",  1920,1080, 29.97,  1, ILACE_MODE_NOTINTERLACED },
46         { "1920x1080 24p",      1920,1080, 24.,    1, ILACE_MODE_NOTINTERLACED },
47         { "1920x1080 25i",      1920,1080, 25.,    1, ILACE_MODE_TOP_FIRST },
48         { "1920x1080 23.976p",  1920,1080, 23.976, 1, ILACE_MODE_NOTINTERLACED },
49         { "1440x1080 29.97i",   1440,1080, 29.97, -1, ILACE_MODE_TOP_FIRST },
50         { "1440x1080 25i",      1440,1080, 25.,   -1, ILACE_MODE_TOP_FIRST },
51         { "1440x1080 24p",      1440,1080, 24.,   -1, ILACE_MODE_NOTINTERLACED },
52         { "1440x1080 23.976p",  1440,1080, 23.976,-1, ILACE_MODE_NOTINTERLACED },
53         { "1280x720  59.94p",   1280,720,  59.94,  1, ILACE_MODE_NOTINTERLACED },
54         { "1280x720  50p",      1280,720,  50.,    1, ILACE_MODE_NOTINTERLACED },
55         { "1280x720  24p",      1280,720,  24.,    1, ILACE_MODE_NOTINTERLACED },
56         { "1280x720  23.976p",  1280,720,  23.976, 1, ILACE_MODE_NOTINTERLACED },
57         { "720x576   25i",       720,576,  25.,    0, ILACE_MODE_BOTTOM_FIRST },
58         { "720x576   25p*",      720,576,  25.,    0, ILACE_MODE_NOTINTERLACED },
59         { "720x480   29.97i",    720,480,  29.97,  0, ILACE_MODE_BOTTOM_FIRST },
60         { "720x480   29.97p*",   720,480,  29.97,  0, ILACE_MODE_NOTINTERLACED },
61 };
62
63 const int64_t CreateBD_Thread::BD_SIZE = 25000000000;
64 const int CreateBD_Thread::BD_STREAMS = 1;
65 const int CreateBD_Thread::BD_WIDTH = 1920;
66 const int CreateBD_Thread::BD_HEIGHT = 1080;
67 const double CreateBD_Thread::BD_WIDE_ASPECT_WIDTH = 16.;
68 const double CreateBD_Thread::BD_WIDE_ASPECT_HEIGHT = 9.;
69 const double CreateBD_Thread::BD_ASPECT_WIDTH = 4.;
70 const double CreateBD_Thread::BD_ASPECT_HEIGHT = 3.;
71 const double CreateBD_Thread::BD_FRAMERATE = 24000. / 1001.;
72 //const int CreateBD_Thread::BD_MAX_BITRATE = 40000000;
73 const int CreateBD_Thread::BD_MAX_BITRATE = 10000000;
74 const int CreateBD_Thread::BD_CHANNELS = 2;
75 const int CreateBD_Thread::BD_WIDE_CHANNELS = 6;
76 const double CreateBD_Thread::BD_SAMPLERATE = 48000;
77 const double CreateBD_Thread::BD_KAUDIO_RATE = 192;
78 const int CreateBD_Thread::BD_INTERLACE_MODE = ILACE_MODE_NOTINTERLACED;
79
80 CreateBD_MenuItem::CreateBD_MenuItem(MWindow *mwindow)
81  : BC_MenuItem(_("BD Render..."), _("Ctrl-d"), 'd')
82 {
83         set_ctrl(1);
84         this->mwindow = mwindow;
85 }
86
87 int CreateBD_MenuItem::handle_event()
88 {
89         mwindow->create_bd->start();
90         return 1;
91 }
92
93
94 CreateBD_Thread::CreateBD_Thread(MWindow *mwindow)
95  : BC_DialogThread()
96 {
97         this->mwindow = mwindow;
98         this->gui = 0;
99         this->use_deinterlace = 0;
100         this->use_scale = Rescale::none;
101         this->use_histogram = 0;
102         this->use_inverse_telecine = 0;
103         this->use_wide_audio = 0;
104         this->use_resize_tracks = 0;
105         this->use_label_chapters = 0;
106
107         this->bd_size = BD_SIZE;
108         this->bd_width = BD_WIDTH;
109         this->bd_height = BD_HEIGHT;
110         this->bd_aspect_width = BD_WIDE_ASPECT_WIDTH;
111         this->bd_aspect_height = BD_WIDE_ASPECT_HEIGHT;
112         this->bd_framerate = BD_FRAMERATE;
113         this->bd_samplerate = BD_SAMPLERATE;
114         this->bd_max_bitrate = BD_MAX_BITRATE;
115         this->bd_kaudio_rate = BD_KAUDIO_RATE;
116         this->max_w = this->max_h = 0;
117 }
118
119 CreateBD_Thread::~CreateBD_Thread()
120 {
121         close_window();
122 }
123
124 int CreateBD_Thread::get_udfs_mount(char *udfs, char *mopts, char *mntpt)
125 {
126         int ret = 0;
127 // default: mount -t udf -o loop $1/bd.udfs $1/udfs
128         strcpy(udfs,"$1/bd.udfs");
129         strcpy(mopts,"-t udf -o loop $1/bd.udfs ");
130         strcpy(mntpt,"$1/udfs");
131         const char *home = getenv("HOME");
132         if( !home ) return ret;
133         FILE *fp = fopen("/etc/fstab","r");
134         if( !fp ) return ret;
135         int len = strlen(home);
136         char line[BCTEXTLEN], typ[BCTEXTLEN], file[BCTEXTLEN];
137         char mpnt[BCTEXTLEN], opts[BCTEXTLEN];
138         while( fgets(line,sizeof(line),fp) ) {
139 // search "/etc/fstab" for: $HOME/img_file $HOME/bluray udf noauto,loop,rw,user
140                 if( line[0] == '#' || line[0] == ';' ) continue;
141                 if( sscanf(line,"%s %s %s %s ", &file[0], &mpnt[0], &typ[0], &opts[0]) != 4 )
142                         continue;
143                 if( strcmp("udf", typ) ) continue;
144                 if( strncmp(home, file, len) || file[len] != '/' ) continue;
145                 if( strncmp(home, mpnt, len) ) continue;
146                 if( strcmp(&mpnt[len], "/bluray") ) continue;
147                 int loop = 0, user = 0, rw = 0, noauto = 0;
148                 char *op = opts, *ep = op + sizeof(opts)-1;
149                 while( op < ep && *op ) {
150                         char opt[BCTEXTLEN], *cp = opt;
151                         while( op < ep && *op && (*cp=*op++)!=',' ) ++cp;
152                         *cp = 0;
153                         if( !strcmp("loop", opt) ) loop = 1;
154                         else if( !strcmp("user", opt) ) user = 1;
155                         else if( !strcmp("noauto", opt) ) noauto = 1;
156                         else if( !strcmp("rw", opt) ) rw = 1;
157                 }
158                 if( loop && user && rw && noauto ) {
159                         strcpy(udfs, file);
160                         strcpy(mopts, "");
161                         strcpy(mntpt, mpnt);
162                         ret = 1;
163                         break;
164                 }
165         }
166         fclose(fp);
167         return ret;
168 }
169
170 int CreateBD_Thread::create_bd_jobs(ArrayList<BatchRenderJob*> *jobs, const char *asset_dir)
171 {
172         EDL *edl = mwindow->edl;
173         if( !edl || !edl->session ) {
174                 char msg[BCTEXTLEN];
175                 sprintf(msg, _("No EDL/Session"));
176                 MainError::show_error(msg);
177                 return 1;
178         }
179         EDLSession *session = edl->session;
180
181         double total_length = edl->tracks->total_length();
182         if( total_length <= 0 ) {
183                 char msg[BCTEXTLEN];
184                 sprintf(msg, _("No content: %s"), asset_title);
185                 MainError::show_error(msg);
186                 return 1;
187         }
188
189         if( mkdir(asset_dir, 0777) ) {
190                 char err[BCTEXTLEN], msg[BCTEXTLEN];
191                 strerror_r(errno, err, sizeof(err));
192                 sprintf(msg, _("Unable to create directory: %s\n-- %s"), asset_dir, err);
193                 MainError::show_error(msg);
194                 return 1;
195         }
196
197         double old_samplerate = session->sample_rate;
198         double old_framerate = session->frame_rate;
199
200         session->video_channels = BD_STREAMS;
201         session->video_tracks = BD_STREAMS;
202         session->frame_rate = bd_framerate;
203         session->output_w = bd_width;
204         session->output_h = bd_height;
205         session->aspect_w = bd_aspect_width;
206         session->aspect_h = bd_aspect_height;
207         session->sample_rate = bd_samplerate;
208         session->audio_channels = session->audio_tracks =
209                 use_wide_audio ? BD_WIDE_CHANNELS : BD_CHANNELS;
210         session->interlace_mode = bd_interlace_mode;
211
212         char script_filename[BCTEXTLEN];
213         sprintf(script_filename, "%s/bd.sh", asset_dir);
214         int fd = open(script_filename, O_WRONLY+O_CREAT+O_TRUNC, 0755);
215         FILE *fp = fdopen(fd, "w");
216         if( !fp ) {
217                 char err[BCTEXTLEN], msg[BCTEXTLEN];
218                 strerror_r(errno, err, sizeof(err));
219                 sprintf(msg, _("Unable to save: %s\n-- %s"), script_filename, err);
220                 MainError::show_error(msg);
221                 return 1;
222         }
223         char udfs[BCTEXTLEN], mopts[BCTEXTLEN], mntpt[BCTEXTLEN];
224         int is_usr_mnt = get_udfs_mount(udfs, mopts, mntpt);
225         const char *exec_path = File::get_cinlib_path();
226         fprintf(fp,"#!/bin/bash -ex\n");
227         fprintf(fp,"PATH=$PATH:%s\n",exec_path);
228         fprintf(fp,"mkdir -p $1/udfs\n");
229         fprintf(fp,"sz=`du -sb $1/bd.m2ts | sed -e 's/[ \t].*//'`\n");
230         fprintf(fp,"blks=$((sz/2048 + 4096))\n");
231         fprintf(fp,"rm -f %s\n", udfs);
232         fprintf(fp,"mkudffs %s $blks\n", udfs);
233         fprintf(fp,"mount %s%s\n", mopts, mntpt);
234         fprintf(fp,"bdwrite %s $1/bd.m2ts\n",mntpt);
235         fprintf(fp,"umount %s\n",mntpt);
236         if( is_usr_mnt )
237                 fprintf(fp,"mv -f %s $1/bd.udfs\n", udfs);
238         fprintf(fp,"echo To burn bluray, load writable media and run:\n");
239         fprintf(fp,"echo for WORM: growisofs -dvd-compat -Z /dev/bd=$1/bd.udfs\n");
240         fprintf(fp,"echo for RW:   dd if=$1/bd.udfs of=/dev/bd bs=2048000\n");
241         fprintf(fp,"kill $$\n");
242         fprintf(fp,"\n");
243         fclose(fp);
244
245         if( use_wide_audio ) {
246                 session->audio_channels = session->audio_tracks = BD_WIDE_CHANNELS;
247                 session->achannel_positions[0] = 90;
248                 session->achannel_positions[1] = 150;
249                 session->achannel_positions[2] = 30;
250                 session->achannel_positions[3] = 210;
251                 session->achannel_positions[4] = 330;
252                 session->achannel_positions[5] = 270;
253                 if( edl->tracks->recordable_audio_tracks() == BD_WIDE_CHANNELS )
254                         mwindow->remap_audio(MWindow::AUDIO_1_TO_1);
255         }
256         else {
257                 session->audio_channels = session->audio_tracks = BD_CHANNELS;
258                 session->achannel_positions[0] = 180;
259                 session->achannel_positions[1] = 0;
260                 if( edl->tracks->recordable_audio_tracks() == BD_WIDE_CHANNELS )
261                         mwindow->remap_audio(MWindow::AUDIO_5_1_TO_2);
262         }
263
264         double new_samplerate = session->sample_rate;
265         double new_framerate = session->frame_rate;
266         edl->retrack();
267         edl->rechannel();
268         edl->resample(old_samplerate, new_samplerate, TRACK_AUDIO);
269         edl->resample(old_framerate, new_framerate, TRACK_VIDEO);
270
271         int64_t aud_size = ((bd_kaudio_rate * total_length)/8 + 1000-1) * 1000;
272         int64_t vid_size = bd_size*0.96 - aud_size;
273         int64_t vid_bitrate = (vid_size * 8) / total_length;
274         vid_bitrate /= 1000;  vid_bitrate *= 1000;
275         if( vid_bitrate > bd_max_bitrate ) vid_bitrate = bd_max_bitrate;
276
277         char xml_filename[BCTEXTLEN];
278         sprintf(xml_filename, "%s/bd.xml", asset_dir);
279         FileXML xml_file;
280         edl->save_xml(&xml_file, xml_filename, 0, 0);
281         xml_file.terminate_string();
282         if( xml_file.write_to_file(xml_filename) ) {
283                 char msg[BCTEXTLEN];
284                 sprintf(msg, _("Unable to save: %s"), xml_filename);
285                 MainError::show_error(msg);
286                 return 1;
287         }
288
289         BatchRenderJob *job = new BatchRenderJob(mwindow->preferences);
290         jobs->append(job);
291         strcpy(&job->edl_path[0], xml_filename);
292         Asset *asset = job->asset;
293
294         asset->layers = BD_STREAMS;
295         asset->frame_rate = session->frame_rate;
296         asset->width = session->output_w;
297         asset->height = session->output_h;
298         asset->aspect_ratio = session->aspect_w / session->aspect_h;
299         asset->interlace_mode = session->interlace_mode;
300
301         char option_path[BCTEXTLEN];
302         sprintf(&asset->path[0],"%s/bd.m2ts", asset_dir);
303         asset->format = FILE_FFMPEG;
304         strcpy(asset->fformat, "m2ts");
305
306         asset->audio_data = 1;
307         strcpy(asset->acodec, "bluray.m2ts");
308         //mwindow->defaults->get("DEFAULT_BLURAY_ACODEC", asset->acodec);
309         FFMPEG::set_option_path(option_path, "audio/%s", asset->acodec);
310         FFMPEG::load_options(option_path, asset->ff_audio_options,
311                          sizeof(asset->ff_audio_options));
312         asset->ff_audio_bitrate = bd_kaudio_rate * 1000;
313
314         asset->video_data = 1;
315         strcpy(asset->vcodec, "bluray.m2ts");
316         //mwindow->defaults->get("DEFAULT_BLURAY_VCODEC", asset->vcodec);
317         FFMPEG::set_option_path(option_path, "video/%s", asset->vcodec);
318         FFMPEG::load_options(option_path, asset->ff_video_options,
319                  sizeof(asset->ff_video_options));
320         const char *opts = 0;
321         switch( asset->interlace_mode ) {
322         case ILACE_MODE_TOP_FIRST:    opts = ":tff\n";  break;
323         case ILACE_MODE_BOTTOM_FIRST: opts = ":bff\n";  break;
324         }
325         if( opts ) {
326                 int len = strlen(asset->ff_video_options);
327                 char *cp = asset->ff_video_options + len-1;
328                 strncpy(cp, opts, sizeof(asset->ff_video_options)-len);
329         }
330         asset->ff_video_bitrate = vid_bitrate;
331         asset->ff_video_quality = -1;
332
333         job = new BatchRenderJob(mwindow->preferences);
334         jobs->append(job);
335         job->edl_path[0] = '@';
336         strcpy(&job->edl_path[1], script_filename);
337         strcpy(&job->asset->path[0], asset_dir);
338
339         return 0;
340 }
341
342 void CreateBD_Thread::handle_close_event(int result)
343 {
344         if( result ) return;
345         mwindow->defaults->update("WORK_DIRECTORY", tmp_path);
346         mwindow->batch_render->load_defaults(mwindow->defaults);
347         mwindow->undo->update_undo_before();
348         KeyFrame keyframe;  char data[BCTEXTLEN];
349         if( use_deinterlace ) {
350                 sprintf(data,"<DEINTERLACE MODE=1>");
351                 keyframe.set_data(data);
352                 insert_video_plugin("Deinterlace", &keyframe);
353         }
354         if( use_inverse_telecine ) {
355                 sprintf(data,"<IVTC FRAME_OFFSET=0 FIRST_FIELD=0 "
356                         "AUTOMATIC=1 AUTO_THRESHOLD=2.0e+00 PATTERN=2>");
357                 keyframe.set_data(data);
358                 insert_video_plugin("Inverse Telecine", &keyframe);
359         }
360         if( use_scale != Rescale::none ) {
361                 double bd_aspect = bd_aspect_height > 0 ? bd_aspect_width / bd_aspect_height : 1;
362
363                 Tracks *tracks = mwindow->edl->tracks;
364                 for( Track *vtrk=tracks->first; vtrk; vtrk=vtrk->next ) {
365                         if( vtrk->data_type != TRACK_VIDEO ) continue;
366                         if( !vtrk->record ) continue;
367                         vtrk->expand_view = 1;
368                         PluginSet *plugin_set = new PluginSet(mwindow->edl, vtrk);
369                         vtrk->plugin_set.append(plugin_set);
370                         Edits *edits = vtrk->edits;
371                         for( Edit *edit=edits->first; edit; edit=edit->next ) {
372                                 Indexable *indexable = edit->get_source();
373                                 if( !indexable ) continue;
374                                 Rescale in(indexable);
375                                 Rescale out(bd_width, bd_height, bd_aspect);
376                                 float src_w, src_h, dst_w, dst_h;
377                                 in.rescale(out,use_scale, src_w,src_h, dst_w,dst_h);
378                                 sprintf(data,"<SCALERATIO TYPE=%d"
379                                         " IN_W=%d IN_H=%d IN_ASPECT_RATIO=%f"
380                                         " OUT_W=%d OUT_H=%d OUT_ASPECT_RATIO=%f"
381                                         " SRC_X=%f SRC_Y=%f SRC_W=%f SRC_H=%f"
382                                         " DST_X=%f DST_Y=%f DST_W=%f DST_H=%f>", use_scale,
383                                         in.w, in.h, in.aspect, out.w, out.h, out.aspect,
384                                         0., 0., src_w, src_h, 0., 0., dst_w, dst_h);
385                                 keyframe.set_data(data);
386                                 plugin_set->insert_plugin(_("Scale Ratio"),
387                                         edit->startproject, edit->length,
388                                         PLUGIN_STANDALONE, 0, &keyframe, 0);
389                         }
390                         vtrk->optimize();
391                 }
392         }
393         if( use_resize_tracks )
394                 resize_tracks();
395         if( use_histogram ) {
396 #if 0
397                 sprintf(data, "<HISTOGRAM OUTPUT_MIN_0=0 OUTPUT_MAX_0=1 "
398                         "OUTPUT_MIN_1=0 OUTPUT_MAX_1=1 "
399                         "OUTPUT_MIN_2=0 OUTPUT_MAX_2=1 "
400                         "OUTPUT_MIN_3=0 OUTPUT_MAX_3=1 "
401                         "AUTOMATIC=0 THRESHOLD=9.0-01 PLOT=0 SPLIT=0>"
402                         "<POINTS></POINTS><POINTS></POINTS><POINTS></POINTS>"
403                         "<POINTS><POINT X=6.0e-02 Y=0>"
404                                 "<POINT X=9.4e-01 Y=1></POINTS>");
405 #else
406                 sprintf(data, "<HISTOGRAM AUTOMATIC=0 THRESHOLD=1.0e-01 "
407                         "PLOT=0 SPLIT=0 W=440 H=500 PARADE=0 MODE=3 "
408                         "LOW_OUTPUT_0=0 HIGH_OUTPUT_0=1 LOW_INPUT_0=0 HIGH_INPUT_0=1 GAMMA_0=1 "
409                         "LOW_OUTPUT_1=0 HIGH_OUTPUT_1=1 LOW_INPUT_1=0 HIGH_INPUT_1=1 GAMMA_1=1 "
410                         "LOW_OUTPUT_2=0 HIGH_OUTPUT_2=1 LOW_INPUT_2=0 HIGH_INPUT_2=1 GAMMA_2=1 "
411                         "LOW_OUTPUT_3=0 HIGH_OUTPUT_3=1 LOW_INPUT_3=0.044 HIGH_INPUT_3=0.956 "
412                         "GAMMA_3=1>");
413 #endif
414                 keyframe.set_data(data);
415                 insert_video_plugin("Histogram", &keyframe);
416         }
417
418         char asset_dir[BCTEXTLEN], jobs_path[BCTEXTLEN];
419         snprintf(asset_dir, sizeof(asset_dir), "%s/%s", tmp_path, asset_title);
420         snprintf(jobs_path, sizeof(jobs_path), "%s/bd.jobs", asset_dir);
421         mwindow->batch_render->reset(jobs_path);
422         int ret = create_bd_jobs(&mwindow->batch_render->jobs, asset_dir);
423         mwindow->undo->update_undo_after(_("create bd"), LOAD_ALL);
424         mwindow->resync_guis();
425         if( ret ) return;
426         mwindow->batch_render->save_jobs();
427         mwindow->batch_render->start();
428 }
429
430 BC_Window* CreateBD_Thread::new_gui()
431 {
432         strcpy(tmp_path, "/tmp");
433         mwindow->defaults->get("WORK_DIRECTORY", tmp_path);
434         memset(asset_title,0,sizeof(asset_title));
435         time_t dt;      time(&dt);
436         struct tm dtm;  localtime_r(&dt, &dtm);
437         sprintf(asset_title, "bd_%02d%02d%02d-%02d%02d%02d",
438                 dtm.tm_year+1900, dtm.tm_mon+1, dtm.tm_mday,
439                 dtm.tm_hour, dtm.tm_min, dtm.tm_sec);
440         use_deinterlace = 0;
441         use_scale = Rescale::none;
442         use_histogram = 0;
443         use_inverse_telecine = 0;
444         use_wide_audio = 0;
445         use_resize_tracks = 0;
446         use_label_chapters = 0;
447         use_standard = !strcmp(mwindow->default_std(),"NTSC") ?
448                  BD_1920x1080_2997i : BD_1920x1080_25i;
449         bd_size = BD_SIZE;
450         bd_width = BD_WIDTH;
451         bd_height = BD_HEIGHT;
452         bd_aspect_width = BD_WIDE_ASPECT_WIDTH;
453         bd_aspect_height = BD_WIDE_ASPECT_HEIGHT;
454         bd_framerate = BD_FRAMERATE;
455         bd_samplerate = BD_SAMPLERATE;
456         bd_max_bitrate = BD_MAX_BITRATE;
457         bd_kaudio_rate = BD_KAUDIO_RATE;
458         bd_interlace_mode = BD_INTERLACE_MODE;
459         max_w = 0; max_h = 0;
460
461         int has_standard = -1;
462         if( mwindow->edl ) {
463                 EDLSession *session = mwindow->edl->session;
464 // match the session to any known standard
465                 for( int i=0; i<(int)(sizeof(bd_formats)/sizeof(bd_formats[0])); ++i ) {
466                         if( !EQUIV(session->frame_rate, bd_formats[i].framerate) ) continue;
467                         if( session->output_w != bd_formats[i].w ) continue;
468                         if( session->output_h != bd_formats[i].h ) continue;
469                         has_standard = i;  break;
470                 }
471         }
472         if( has_standard >= 0 )
473                 use_standard = has_standard;
474
475         option_presets();
476         int scr_x = mwindow->gui->get_screen_x(0, -1);
477         int scr_w = mwindow->gui->get_screen_w(0, -1);
478         int scr_h = mwindow->gui->get_screen_h(0, -1);
479         int w = 500, h = 280;
480         int x = scr_x + scr_w/2 - w/2, y = scr_h/2 - h/2;
481
482         gui = new CreateBD_GUI(this, x, y, w, h);
483         gui->create_objects();
484
485         if( getuid() != 0 ) {
486                 mwindow->show_warning(
487                         &mwindow->preferences->bd_warn_root,
488                         _("Must be root to mount UDFS images\n"));
489         }
490         return gui;
491 }
492
493
494 CreateBD_OK::CreateBD_OK(CreateBD_GUI *gui, int x, int y)
495  : BC_OKButton(x, y)
496 {
497         this->gui = gui;
498         set_tooltip(_("end setup, start batch render"));
499 }
500
501 CreateBD_OK::~CreateBD_OK()
502 {
503 }
504
505 int CreateBD_OK::button_press_event()
506 {
507         if(get_buttonpress() == 1 && is_event_win() && cursor_inside()) {
508                 gui->set_done(0);
509                 return 1;
510         }
511         return 0;
512 }
513
514 int CreateBD_OK::keypress_event()
515 {
516         return 0;
517 }
518
519
520 CreateBD_Cancel::CreateBD_Cancel(CreateBD_GUI *gui, int x, int y)
521  : BC_CancelButton(x, y)
522 {
523         this->gui = gui;
524 }
525
526 CreateBD_Cancel::~CreateBD_Cancel()
527 {
528 }
529
530 int CreateBD_Cancel::button_press_event()
531 {
532         if(get_buttonpress() == 1 && is_event_win() && cursor_inside()) {
533                 gui->set_done(1);
534                 return 1;
535         }
536         return 0;
537 }
538
539
540 CreateBD_DiskSpace::CreateBD_DiskSpace(CreateBD_GUI *gui, int x, int y)
541  : BC_Title(x, y, "", MEDIUMFONT, GREEN)
542 {
543         this->gui = gui;
544 }
545
546 CreateBD_DiskSpace::~CreateBD_DiskSpace()
547 {
548 }
549
550 int64_t CreateBD_DiskSpace::tmp_path_space()
551 {
552         const char *path = gui->thread->tmp_path;
553         if( access(path,R_OK+W_OK) ) return 0;
554         struct statfs sfs;
555         if( statfs(path, &sfs) ) return 0;
556         return (int64_t)sfs.f_bsize * sfs.f_bfree;
557 }
558
559 void CreateBD_DiskSpace::update()
560 {
561         static const char *suffix[] = { "", "KB", "MB", "GB", "TB", "PB" };
562         int64_t disk_space = tmp_path_space();
563         double media_size = 100e9, msz = 0, m = 1;
564         char sfx[BCSTRLEN];
565         if( sscanf(gui->media_size->get_text(), "%lf%s", &msz, sfx) == 2 ) {
566                 int i = sizeof(suffix)/sizeof(suffix[0]);
567                 while( --i >= 0 && strcmp(sfx, suffix[i]) );
568                 while( --i >= 0 ) m *= 1000;
569                 media_size = msz * m;
570         }
571         int color = disk_space < media_size*2 ? RED : GREEN;
572         int i = 0;
573         for( int64_t space=disk_space; i<5 && (space/=1000)>0; disk_space=space, ++i );
574         char text[BCTEXTLEN];
575         sprintf(text, "%s%3jd%s", _("disk space: "), disk_space, suffix[i]);
576         gui->disk_space->BC_Title::update(text);
577         gui->disk_space->set_color(color);
578 }
579
580 CreateBD_TmpPath::CreateBD_TmpPath(CreateBD_GUI *gui, int x, int y, int w)
581  : BC_TextBox(x, y, w, 1, -(int)sizeof(gui->thread->tmp_path),
582                 gui->thread->tmp_path, 1, MEDIUMFONT)
583 {
584         this->gui = gui;
585 }
586
587 CreateBD_TmpPath::~CreateBD_TmpPath()
588 {
589 }
590
591 int CreateBD_TmpPath::handle_event()
592 {
593         get_text();
594         gui->disk_space->update();
595         return 1;
596 }
597
598
599 CreateBD_AssetTitle::CreateBD_AssetTitle(CreateBD_GUI *gui, int x, int y, int w)
600  : BC_TextBox(x, y, w, 1, -(int)sizeof(gui->thread->asset_title),
601                 gui->thread->asset_title, 1, MEDIUMFONT)
602 {
603         this->gui = gui;
604 }
605
606 CreateBD_AssetTitle::~CreateBD_AssetTitle()
607 {
608 }
609
610 int CreateBD_AssetTitle::handle_event()
611 {
612         get_text();
613         return 1;
614 }
615
616 CreateBD_Deinterlace::CreateBD_Deinterlace(CreateBD_GUI *gui, int x, int y)
617  : BC_CheckBox(x, y, &gui->thread->use_deinterlace, _("Deinterlace"))
618 {
619         this->gui = gui;
620 }
621
622 CreateBD_Deinterlace::~CreateBD_Deinterlace()
623 {
624 }
625
626 int CreateBD_Deinterlace::handle_event()
627 {
628         if( get_value() ) {
629                 gui->need_inverse_telecine->set_value(0);
630                 gui->thread->use_inverse_telecine = 0;
631         }
632         return BC_CheckBox::handle_event();
633 }
634
635
636 CreateBD_InverseTelecine::CreateBD_InverseTelecine(CreateBD_GUI *gui, int x, int y)
637  : BC_CheckBox(x, y, &gui->thread->use_inverse_telecine, _("Inverse Telecine"))
638 {
639         this->gui = gui;
640 }
641
642 CreateBD_InverseTelecine::~CreateBD_InverseTelecine()
643 {
644 }
645
646 int CreateBD_InverseTelecine::handle_event()
647 {
648         if( get_value() ) {
649                 gui->need_deinterlace->set_value(0);
650                 gui->thread->use_deinterlace = 0;
651         }
652         return BC_CheckBox::handle_event();
653 }
654
655
656 CreateBD_ResizeTracks::CreateBD_ResizeTracks(CreateBD_GUI *gui, int x, int y)
657  : BC_CheckBox(x, y, &gui->thread->use_resize_tracks, _("Resize Tracks"))
658 {
659         this->gui = gui;
660 }
661
662 CreateBD_ResizeTracks::~CreateBD_ResizeTracks()
663 {
664 }
665
666
667 CreateBD_Histogram::CreateBD_Histogram(CreateBD_GUI *gui, int x, int y)
668  : BC_CheckBox(x, y, &gui->thread->use_histogram, _("Histogram"))
669 {
670         this->gui = gui;
671 }
672
673 CreateBD_Histogram::~CreateBD_Histogram()
674 {
675 }
676
677 CreateBD_LabelChapters::CreateBD_LabelChapters(CreateBD_GUI *gui, int x, int y)
678  : BC_CheckBox(x, y, &gui->thread->use_label_chapters, _("Chapters at Labels"))
679 {
680         this->gui = gui;
681 }
682
683 CreateBD_LabelChapters::~CreateBD_LabelChapters()
684 {
685 }
686
687 CreateBD_WideAudio::CreateBD_WideAudio(CreateBD_GUI *gui, int x, int y)
688  : BC_CheckBox(x, y, &gui->thread->use_wide_audio, _("Audio 5.1"))
689 {
690         this->gui = gui;
691 }
692
693 CreateBD_WideAudio::~CreateBD_WideAudio()
694 {
695 }
696
697
698 CreateBD_GUI::CreateBD_GUI(CreateBD_Thread *thread, int x, int y, int w, int h)
699  : BC_Window(_(PROGRAM_NAME ": Create BD"), x, y, w, h, 50, 50, 1, 0, 1)
700 {
701         this->thread = thread;
702         at_x = at_y = tmp_x = tmp_y = 0;
703         ok_x = ok_y = ok_w = ok_h = 0;
704         cancel_x = cancel_y = cancel_w = cancel_h = 0;
705         asset_title = 0;
706         tmp_path = 0;
707         btmp_path = 0;
708         disk_space = 0;
709         standard = 0;
710         scale = 0;
711         need_deinterlace = 0;
712         need_inverse_telecine = 0;
713         need_resize_tracks = 0;
714         need_histogram = 0;
715         non_standard = 0;
716         need_wide_audio = 0;
717         need_label_chapters = 0;
718         ok = 0;
719         cancel = 0;
720 }
721
722 CreateBD_GUI::~CreateBD_GUI()
723 {
724 }
725
726 void CreateBD_GUI::create_objects()
727 {
728         lock_window("CreateBD_GUI::create_objects");
729         int pady = BC_TextBox::calculate_h(this, MEDIUMFONT, 0, 1) + 5;
730         int padx = BC_Title::calculate_w(this, (char*)"X", MEDIUMFONT);
731         int x = padx/2, y = pady/2;
732         BC_Title *title = new BC_Title(x, y, _("Title:"), MEDIUMFONT, YELLOW);
733         add_subwindow(title);
734         at_x = x + title->get_w();  at_y = y;
735         asset_title = new CreateBD_AssetTitle(this, at_x, at_y, get_w()-at_x-10);
736         add_subwindow(asset_title);
737         y += title->get_h() + pady/2;
738         title = new BC_Title(x, y, _("Work path:"), MEDIUMFONT, YELLOW);
739         add_subwindow(title);
740         tmp_x = x + title->get_w();  tmp_y = y;
741         tmp_path = new CreateBD_TmpPath(this, tmp_x, tmp_y,  get_w()-tmp_x-35);
742         add_subwindow(tmp_path);
743         btmp_path = new BrowseButton(thread->mwindow->theme, this, tmp_path,
744                 tmp_x+tmp_path->get_w(), tmp_y, "/tmp",
745                 _("Work path"), _("Select a Work directory:"), 1);
746         add_subwindow(btmp_path);
747         y += title->get_h() + pady/2;
748         disk_space = new CreateBD_DiskSpace(this, x, y);
749         add_subwindow(disk_space);
750         int x0 = get_w() - 170;
751         title = new BC_Title(x0, y, _("Media:"), MEDIUMFONT, YELLOW);
752         add_subwindow(title);
753         int x1 =  x0+title->get_w()+padx;
754         media_size = new CreateBD_MediaSize(this, x1, y);
755         media_size->create_objects();
756         media_sizes.append(new BC_ListBoxItem("25GB"));
757         media_sizes.append(new BC_ListBoxItem("50GB"));
758         media_size->update_list(&media_sizes);
759         media_size->update(media_sizes[0]->get_text());
760         disk_space->update();
761         y += disk_space->get_h() + pady/2;
762         title = new BC_Title(x, y, _("Format:"), MEDIUMFONT, YELLOW);
763         add_subwindow(title);
764         standard = new CreateBD_Format(this, title->get_w() + padx, y);
765         add_subwindow(standard);
766         standard->create_objects();
767         standard->set_text(bd_formats[thread->use_standard].name);
768         x0 -= 30;
769         title = new BC_Title(x0, y, _("Scale:"), MEDIUMFONT, YELLOW);
770         add_subwindow(title);
771         x1 = x0+title->get_w()+padx;
772         scale = new CreateBD_Scale(this, x1, y);
773         add_subwindow(scale);
774         scale->create_objects();
775         y += standard->get_h() + pady/2;
776         need_deinterlace = new CreateBD_Deinterlace(this, x, y);
777         add_subwindow(need_deinterlace);
778         x1 = x + 170; //, x2 = x1 + 150;
779         need_inverse_telecine = new CreateBD_InverseTelecine(this, x1, y);
780         add_subwindow(need_inverse_telecine);
781         y += need_deinterlace->get_h() + pady/2;
782         need_histogram = new CreateBD_Histogram(this, x, y);
783         add_subwindow(need_histogram);
784         need_wide_audio = new CreateBD_WideAudio(this, x1, y);
785         add_subwindow(need_wide_audio);
786         y += need_histogram->get_h() + pady/2;
787         non_standard = new BC_Title(x, y+5, "", MEDIUMFONT, RED);
788         add_subwindow(non_standard);
789         need_resize_tracks = new CreateBD_ResizeTracks(this, x1, y);
790         add_subwindow(need_resize_tracks);
791 //      need_label_chapters = new CreateBD_LabelChapters(this, x2, y);
792 //      add_subwindow(need_label_chapters);
793         ok_w = BC_OKButton::calculate_w();
794         ok_h = BC_OKButton::calculate_h();
795         ok_x = 10;
796         ok_y = get_h() - ok_h - 10;
797         ok = new CreateBD_OK(this, ok_x, ok_y);
798         add_subwindow(ok);
799         cancel_w = BC_CancelButton::calculate_w();
800         cancel_h = BC_CancelButton::calculate_h();
801         cancel_x = get_w() - cancel_w - 10,
802         cancel_y = get_h() - cancel_h - 10;
803         cancel = new CreateBD_Cancel(this, cancel_x, cancel_y);
804         add_subwindow(cancel);
805         show_window();
806         unlock_window();
807 }
808
809 int CreateBD_GUI::resize_event(int w, int h)
810 {
811         asset_title->reposition_window(at_x, at_y, get_w()-at_x-10);
812         tmp_path->reposition_window(tmp_x, tmp_y,  get_w()-tmp_x-35);
813         btmp_path->reposition_window(tmp_x+tmp_path->get_w(), tmp_y);
814         ok_y = h - ok_h - 10;
815         ok->reposition_window(ok_x, ok_y);
816         cancel_x = w - cancel_w - 10,
817         cancel_y = h - cancel_h - 10;
818         cancel->reposition_window(cancel_x, cancel_y);
819         return 0;
820 }
821
822 int CreateBD_GUI::translation_event()
823 {
824         return 1;
825 }
826
827 int CreateBD_GUI::close_event()
828 {
829         set_done(1);
830         return 1;
831 }
832
833 void CreateBD_GUI::update()
834 {
835         scale->set_value(thread->use_scale);
836         need_deinterlace->set_value(thread->use_deinterlace);
837         need_inverse_telecine->set_value(thread->use_inverse_telecine);
838         need_resize_tracks->set_value(thread->use_resize_tracks);
839         need_histogram->set_value(thread->use_histogram);
840         need_wide_audio->set_value(thread->use_wide_audio);
841 //      need_label_chapters->set_value(thread->use_label_chapters);
842 }
843
844 int CreateBD_Thread::
845 insert_video_plugin(const char *title, KeyFrame *default_keyframe)
846 {
847         Tracks *tracks = mwindow->edl->tracks;
848         for( Track *vtrk=tracks->first; vtrk; vtrk=vtrk->next ) {
849                 if( vtrk->data_type != TRACK_VIDEO ) continue;
850                 if( !vtrk->record ) continue;
851                 vtrk->expand_view = 1;
852                 PluginSet *plugin_set = new PluginSet(mwindow->edl, vtrk);
853                 vtrk->plugin_set.append(plugin_set);
854                 Edits *edits = vtrk->edits;
855                 for( Edit *edit=edits->first; edit; edit=edit->next ) {
856                         plugin_set->insert_plugin(_(title),
857                                 edit->startproject, edit->length,
858                                 PLUGIN_STANDALONE, 0, default_keyframe, 0);
859                 }
860                 vtrk->optimize();
861         }
862         return 0;
863 }
864
865 int CreateBD_Thread::
866 resize_tracks()
867 {
868         Tracks *tracks = mwindow->edl->tracks;
869         int trk_w = max_w, trk_h = max_h;
870         if( trk_w < bd_width ) trk_w = bd_width;
871         if( trk_h < bd_height ) trk_h = bd_height;
872         for( Track *vtrk=tracks->first; vtrk; vtrk=vtrk->next ) {
873                 if( vtrk->data_type != TRACK_VIDEO ) continue;
874                 if( !vtrk->record ) continue;
875                 vtrk->track_w = trk_w;
876                 vtrk->track_h = trk_h;
877         }
878         return 0;
879 }
880
881 int CreateBD_Thread::
882 option_presets()
883 {
884 // reset only probed options
885         use_deinterlace = 0;
886         use_scale = Rescale::none;
887         use_resize_tracks = 0;
888         use_wide_audio = 0;
889         use_label_chapters = 0;
890
891         if( !mwindow->edl ) return 1;
892
893         bd_width = bd_formats[use_standard].w;
894         bd_height = bd_formats[use_standard].h;
895         bd_framerate = bd_formats[use_standard].framerate;
896         int wide = bd_formats[use_standard].wide;
897         bd_aspect_width  = wide < 0 ? 1. :
898                 wide > 0 ? BD_WIDE_ASPECT_WIDTH  : BD_ASPECT_WIDTH;
899         bd_aspect_height = wide < 0 ? 1. :
900                 wide > 0 ? BD_WIDE_ASPECT_HEIGHT : BD_ASPECT_HEIGHT;
901         bd_interlace_mode = bd_formats[use_standard].interlaced;
902         double bd_aspect = bd_aspect_width / bd_aspect_height;
903
904         Tracks *tracks = mwindow->edl->tracks;
905         max_w = 0;  max_h = 0;
906         int has_deinterlace = 0, has_scale = 0;
907         for( Track *trk=tracks->first; trk; trk=trk->next ) {
908                 if( !trk->record ) continue;
909                 Edits *edits = trk->edits;
910                 switch( trk->data_type ) {
911                 case TRACK_VIDEO:
912                         for( Edit *edit=edits->first; edit; edit=edit->next ) {
913                                 if( edit->silence() ) continue;
914                                 Indexable *indexable = edit->get_source();
915                                 int w = indexable->get_w();
916                                 if( w > max_w ) max_w = w;
917                                 if( w != bd_width ) use_scale = Rescale::scaled;
918                                 int h = indexable->get_h();
919                                 if( h > max_h ) max_h = h;
920                                 if( h != bd_height ) use_scale = Rescale::scaled;
921                                 float aw, ah;
922                                 MWindow::create_aspect_ratio(aw, ah, w, h);
923                                 double aspect = ah > 0 ? aw / ah : 1;
924                                 if( wide >= 0 && !EQUIV(aspect, bd_aspect) )
925                                         use_scale = Rescale::scaled;
926                         }
927                         for( int i=0; i<trk->plugin_set.size(); ++i ) {
928                                 for(Plugin *plugin = (Plugin*)trk->plugin_set[i]->first;
929                                                 plugin;
930                                                 plugin = (Plugin*)plugin->next) {
931                                         if( !strcmp(plugin->title, _("Deinterlace")) )
932                                                 has_deinterlace = 1;
933                                         if( !strcmp(plugin->title, _("Auto Scale")) ||
934                                             !strcmp(plugin->title, _("Scale Ratio")) ||
935                                             !strcmp(plugin->title, _("Scale")) )
936                                                 has_scale = 1;
937                                 }
938                         }
939                         break;
940                 }
941         }
942         if( has_scale )
943                 use_scale = Rescale::none;
944         if( use_scale != Rescale::none ) {
945                 if( max_w != bd_width ) use_resize_tracks = 1;
946                 if( max_h != bd_height ) use_resize_tracks = 1;
947         }
948         for( Track *trk=tracks->first; trk && !use_resize_tracks; trk=trk->next ) {
949                 if( !trk->record ) continue;
950                 switch( trk->data_type ) {
951                 case TRACK_VIDEO:
952                         if( trk->track_w != max_w ) use_resize_tracks = 1;
953                         if( trk->track_h != max_h ) use_resize_tracks = 1;
954                         break;
955                 }
956         }
957         if( !has_deinterlace && max_h > 2*bd_height ) use_deinterlace = 1;
958         // Labels *labels = mwindow->edl->labels;
959         // use_label_chapters = labels && labels->first ? 1 : 0;
960
961         if( tracks->recordable_audio_tracks() == BD_WIDE_CHANNELS )
962                 use_wide_audio = 1;
963
964         return 0;
965 }
966
967
968 CreateBD_FormatItem::CreateBD_FormatItem(CreateBD_Format *popup,
969                 int standard, const char *name)
970  : BC_MenuItem(name)
971 {
972         this->popup = popup;
973         this->standard = standard;
974 }
975
976 CreateBD_FormatItem::~CreateBD_FormatItem()
977 {
978 }
979
980 int CreateBD_FormatItem::handle_event()
981 {
982         const char *text = get_text();
983         int standard = this->standard;
984         if( standard < 0 ) {
985                 BC_SubMenu *submenu = get_submenu();
986                 CreateBD_FormatItem *sub_item0 =
987                         (CreateBD_FormatItem *)submenu->get_item(0);
988                 standard = sub_item0->standard;
989                 text = sub_item0->get_text();
990         }
991         popup->gui->thread->use_standard = standard;
992         popup->set_text(text);
993         int n = strlen(text)-1;
994         int not_standard = n >= 0 && text[n] == '*' ? 1 : 0;
995         popup->gui->non_standard->update(not_standard ? _("* non-standard format") : "", 0);
996         return popup->handle_event();
997 }
998
999
1000 CreateBD_Format::CreateBD_Format(CreateBD_GUI *gui, int x, int y)
1001  : BC_PopupMenu(x, y, 180, bd_formats[gui->thread->use_standard].name, 1)
1002 {
1003         this->gui = gui;
1004 }
1005
1006 CreateBD_Format::~CreateBD_Format()
1007 {
1008 }
1009
1010 void CreateBD_Format::create_objects()
1011 {
1012         BC_SubMenu *submenu = 0;
1013         CreateBD_FormatItem *item = 0;
1014         int ww = 0, hh = 0;
1015         for( int i=0; i<(int)(sizeof(bd_formats)/sizeof(bd_formats[0])); ++i ) {
1016                 if( ww != bd_formats[i].w || hh != bd_formats[i].h ) {
1017                         ww = bd_formats[i].w;  hh = bd_formats[i].h;
1018                         char string[BCSTRLEN];
1019                         sprintf(string, "%dx%d", ww,hh);
1020                         add_item(item = new CreateBD_FormatItem(this, -1, string));
1021                         item->add_submenu(submenu = new BC_SubMenu());
1022                 }
1023                 submenu->add_submenuitem(new CreateBD_FormatItem(this, i, bd_formats[i].name));
1024         }
1025 }
1026
1027 int CreateBD_Format::handle_event()
1028 {
1029         gui->thread->option_presets();
1030         gui->update();
1031         return 1;
1032 }
1033
1034
1035 CreateBD_ScaleItem::CreateBD_ScaleItem(CreateBD_Scale *popup,
1036                 int scale, const char *text)
1037  : BC_MenuItem(text)
1038 {
1039         this->popup = popup;
1040         this->scale = scale;
1041 }
1042
1043 CreateBD_ScaleItem::~CreateBD_ScaleItem()
1044 {
1045 }
1046
1047 int CreateBD_ScaleItem::handle_event()
1048 {
1049         popup->gui->thread->use_scale = scale;
1050         popup->set_value(scale);
1051         return popup->handle_event();
1052 }
1053
1054
1055 CreateBD_Scale::CreateBD_Scale(CreateBD_GUI *gui, int x, int y)
1056  : BC_PopupMenu(x, y, 100, "", 1)
1057 {
1058         this->gui = gui;
1059 }
1060
1061 CreateBD_Scale::~CreateBD_Scale()
1062 {
1063 }
1064
1065 void CreateBD_Scale::create_objects()
1066 {
1067
1068         for( int i=0; i<(int)Rescale::n_scale_types; ++i ) {
1069                 add_item(new CreateBD_ScaleItem(this, i, Rescale::scale_types[i]));
1070         }
1071         set_value(gui->thread->use_scale);
1072 }
1073
1074 int CreateBD_Scale::handle_event()
1075 {
1076         gui->update();
1077         return 1;
1078 }
1079
1080
1081 CreateBD_MediaSize::CreateBD_MediaSize(CreateBD_GUI *gui, int x, int y)
1082  : BC_PopupTextBox(gui, 0, 0, x, y, 70,50)
1083 {
1084         this->gui = gui;
1085 }
1086
1087 CreateBD_MediaSize::~CreateBD_MediaSize()
1088 {
1089 }
1090
1091 int CreateBD_MediaSize::handle_event()
1092 {
1093         gui->disk_space->update();
1094         return 1;
1095 }
1096