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