collect_proxy nested_clip/edl fixes
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / mwindow.C
1 /*
2  * CINELERRA
3  * Copyright (C) 1997-2014 Adam Williams <broadcast at earthling dot net>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  */
20
21 #include "aboutprefs.h"
22 #include "asset.h"
23 #include "assets.h"
24 #include "atrack.h"
25 #include "audioalsa.h"
26 #include "autos.h"
27 #include "awindowgui.h"
28 #include "awindow.h"
29 #include "batchrender.h"
30 #include "bccmodels.h"
31 #include "bcdisplayinfo.h"
32 #include "bcprogressbox.h"
33 #include "bcsignals.h"
34 #include "bctimer.h"
35 #include "bctrace.h"
36 #include "bdcreate.h"
37 #include "brender.h"
38 #include "cache.h"
39 #include "channel.h"
40 #include "channeldb.h"
41 #include "channelinfo.h"
42 #include "clip.h"
43 #include "clipedls.h"
44 #include "commercials.h"
45 #include "confirmsave.h"
46 #include "convert.h"
47 #include "cplayback.h"
48 #include "ctimebar.h"
49 #include "cwindowgui.h"
50 #include "cwindow.h"
51 #include "cwindowtool.h"
52 #include "bchash.h"
53 #include "devicedvbinput.inc"
54 #include "dvdcreate.h"
55 #include "editpanel.h"
56 #include "edl.h"
57 #include "edlsession.h"
58 #include "errorbox.h"
59 #include "fileformat.h"
60 #include "file.h"
61 #include "filesystem.h"
62 #include "filexml.h"
63 #include "floatautos.h"
64 #include "framecache.h"
65 #include "gwindow.h"
66 #include "gwindowgui.h"
67 #include "keyframegui.h"
68 #include "indexfile.h"
69 #include "intautos.h"
70 #include "interlacemodes.h"
71 #include "language.h"
72 #include "levelwindowgui.h"
73 #include "levelwindow.h"
74 #include "loadfile.inc"
75 #include "localsession.h"
76 #include "maincursor.h"
77 #include "mainerror.h"
78 #include "mainindexes.h"
79 #include "mainmenu.h"
80 #include "mainprogress.h"
81 #include "mainsession.h"
82 #include "mainundo.h"
83 #include "mbuttons.h"
84 #include "mixersalign.h"
85 #include "mutex.h"
86 #include "mwindowgui.h"
87 #include "mwindow.h"
88 #include "new.h"
89 #include "panautos.h"
90 #include "patchbay.h"
91 #include "playback3d.h"
92 #include "playbackengine.h"
93 #include "plugin.h"
94 #include "pluginserver.h"
95 #include "pluginset.h"
96 #include "preferences.h"
97 #include "proxy.h"
98 #include "record.h"
99 #include "recordmonitor.h"
100 #include "recordlabel.h"
101 #include "removefile.h"
102 #include "render.h"
103 #include "resourcethread.h"
104 #include "savefile.inc"
105 #include "samplescroll.h"
106 #include "sha1.h"
107 #include "shuttle.h"
108 #include "sighandler.h"
109 #include "splashgui.h"
110 #include "statusbar.h"
111 #include "theme.h"
112 #include "threadloader.h"
113 #include "timebar.h"
114 #include "timelinepane.h"
115 #include "tipwindow.h"
116 #include "trackcanvas.h"
117 #include "track.h"
118 #include "tracking.h"
119 #include "trackscroll.h"
120 #include "tracks.h"
121 #include "transition.h"
122 #include "transportque.h"
123 #include "vframe.h"
124 #include "vtrack.h"
125 #include "versioninfo.h"
126 #include "vicon.h"
127 #include "videodevice.inc"
128 #include "videowindow.h"
129 #include "vplayback.h"
130 #include "vwindowgui.h"
131 #include "vwindow.h"
132 #include "wavecache.h"
133 #include "wintv.h"
134 #include "wwindow.h"
135 #include "x10tv.h"
136 #include "zoombar.h"
137 #include "zwindow.h"
138 #include "zwindowgui.h"
139 #include "exportedl.h"
140
141 #include "defaultformats.h"
142 #include "ntsczones.h"
143
144 #include <stdint.h>
145 #include <stdlib.h>
146 #include <unistd.h>
147 #include <fcntl.h>
148 #include <string.h>
149 #include <sys/types.h>
150 #include <sys/stat.h>
151 #include <sys/time.h>
152 #include <sys/mman.h>
153 #include <sys/file.h>
154 #include <limits.h>
155 #include <errno.h>
156
157
158 extern "C"
159 {
160
161
162
163
164 // Hack for libdv to remove glib dependancy
165
166 // void
167 // g_log (const char    *log_domain,
168 //        int  log_level,
169 //        const char    *format,
170 //        ...)
171 // {
172 // }
173 //
174 // void
175 // g_logv (const char    *log_domain,
176 //        int  log_level,
177 //        const char    *format,
178 //        ...)
179 // {
180 // }
181 //
182
183 }
184
185 extern long cin_timezone;
186
187 ArrayList<PluginServer*>* MWindow::plugindb = 0;
188 Commercials* MWindow::commercials = 0;
189
190
191 MWindow::MWindow()
192  : Thread(1, 0, 0)
193 {
194         run_lock = new Mutex("MWindow::run_lock");
195         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
196         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
197         vwindows_lock = new Mutex("MWindow::vwindows_lock");
198         zwindows_lock = new Mutex("MWindow::zwindows_lock");
199         brender_lock = new Mutex("MWindow::brender_lock");
200         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
201
202         playback_3d = 0;
203         splash_window = 0;
204         undo = 0;
205         undo_command = COMMAND_NONE;
206         defaults = 0;
207         assets = 0;
208         //commercials = 0;
209         commercial_active = 0;
210         audio_cache = 0;
211         video_cache = 0;
212         frame_cache = 0;
213         wave_cache = 0;
214         preferences = 0;
215         session = 0;
216         theme = 0;
217         mainindexes = 0;
218         mainprogress = 0;
219         brender = 0;
220         brender_active = 0;
221         strcpy(cin_lang,"en");
222         channeldb_buz =  new ChannelDB;
223         channeldb_v4l2jpeg =  new ChannelDB;
224         plugin_guis = 0;
225         dead_plugins = 0;
226         keyframe_threads = 0;
227         create_bd = 0;
228         create_dvd = 0;
229         batch_render = 0;
230         convert_render = 0;
231         render = 0;
232         edl = 0;
233         gui = 0;
234         cwindow = 0;
235         awindow = 0;
236         gwindow = 0;
237         twindow = 0;
238         wwindow = 0;
239         lwindow = 0;
240         sighandler = 0;
241         restart_status = 0;
242         screens = 1;
243         in_destructor = 0;
244         speed_edl = 0;
245         beeper = 0;
246         redraw_tracks = 0;
247         shuttle = 0;
248         wintv = 0;
249         x10tv = 0;
250         mixers_align = 0;
251 }
252
253
254 // Need to delete brender temporary here.
255 MWindow::~MWindow()
256 {
257         run_lock->lock("MWindow::~MWindow");
258         in_destructor = 1;
259 //printf("MWindow::~MWindow %d\n", __LINE__);
260         if( wwindow && wwindow->is_running() )
261                 wwindow->close_window();
262         if( twindow && twindow->is_running() )
263                 twindow->close_window();
264         gui->remote_control->deactivate();
265         gui->record->stop();
266 #ifdef HAVE_DVB
267         gui->channel_info->stop();
268 #endif
269         delete beeper;          beeper = 0;
270         delete redraw_tracks;   redraw_tracks = 0;
271         delete create_bd;       create_bd = 0;
272         delete create_dvd;      create_dvd = 0;
273 #ifdef HAVE_SHUTTLE
274         delete shuttle;         shuttle = 0;
275 #endif
276 #ifdef HAVE_WINTV
277         delete wintv;           wintv = 0;
278 #endif
279 #ifdef HAVE_X10TV
280         delete x10tv;           x10tv = 0;
281 #endif
282         delete batch_render;    batch_render = 0;
283         delete convert_render;  convert_render = 0;
284         delete render;          render = 0;
285         delete mixers_align;    mixers_align = 0;
286         commit_commercial();
287         if( commercials && !commercials->remove_user() ) commercials = 0;
288         close_mixers();
289         if( speed_edl ) { speed_edl->remove_user();  speed_edl = 0; }
290 // Save defaults for open plugins
291         plugin_gui_lock->lock("MWindow::~MWindow");
292         for(int i = 0; i < plugin_guis->size(); i++) {
293                 plugin_guis->get(i)->hide_gui();
294                 delete_plugin(plugin_guis->get(i));
295         }
296         plugin_gui_lock->unlock();
297         hide_keyframe_guis();
298         clean_indexes();
299         save_defaults();
300 // Give up and go to a movie
301 //  cant run valgrind if this is used
302
303         gui->del_keyboard_listener(
304                 (int (BC_WindowBase::*)(BC_WindowBase *))
305                 &MWindowGUI::keyboard_listener);
306         reset_caches();
307 #if 0
308 // release the hounds
309         if( awindow && awindow->gui ) awindow->gui->close(0);
310         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
311         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
312         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
313         vwindows.remove_all_objects();
314         zwindows.remove_all_objects();
315         gui->close(0);
316         if( awindow ) awindow->join();
317         if( cwindow ) cwindow->join();
318         if( lwindow ) lwindow->join();
319         if( gwindow ) gwindow->join();
320         join();
321 #else
322 // one at a time, or nouveau chokes
323 #define close_gui(win) if( win ) { \
324   if( win->gui ) win->gui->close(0); \
325   win->join(); }
326         close_gui(awindow);
327         close_gui(cwindow);
328         close_gui(lwindow);
329         close_gui(gwindow);
330         vwindows.remove_all_objects();
331         zwindows.remove_all_objects();
332         gui->close(0);
333         join();
334 #endif
335         dead_plugins->remove_all_objects();
336 // must delete theme before destroying plugindb
337 //  theme destructor will be deleted by delete_plugins
338         delete theme;           theme = 0;
339         delete_plugins();
340         finit_error();
341         keyframe_threads->remove_all_objects();
342         colormodels.remove_all_objects();
343         delete awindow;         awindow = 0;
344         delete lwindow;         lwindow = 0;
345         delete twindow;         twindow = 0;
346         delete wwindow;         wwindow = 0;
347         delete gwindow;         gwindow = 0;
348         delete cwindow;         cwindow = 0;
349         delete gui;             gui = 0;
350         delete mainindexes;     mainindexes = 0;
351         delete mainprogress;    mainprogress = 0;
352         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
353         delete video_cache;     video_cache = 0;  // delete the cache after the assets
354         delete frame_cache;     frame_cache = 0;
355         delete wave_cache;      wave_cache = 0;
356         delete plugin_guis;     plugin_guis = 0;
357         delete dead_plugins;    dead_plugins = 0;
358         delete keyframe_threads;  keyframe_threads = 0;
359         delete undo;            undo = 0;
360         delete preferences;     preferences = 0;
361         delete exportedl;       exportedl = 0;
362         delete session;         session = 0;
363         delete defaults;        defaults = 0;
364         delete assets;          assets = 0;
365         delete splash_window;   splash_window = 0;
366         if( !edl->Garbage::remove_user() ) edl = 0;
367         delete channeldb_buz;
368         delete channeldb_v4l2jpeg;
369 // This must be last thread to exit
370         delete playback_3d;     playback_3d = 0;
371         delete dead_plugin_lock;
372         delete plugin_gui_lock;
373         delete vwindows_lock;
374         delete zwindows_lock;
375         delete brender_lock;
376         delete keyframe_gui_lock;
377         colormodels.remove_all_objects();
378         interlace_project_modes.remove_all_objects();
379         interlace_asset_modes.remove_all_objects();
380         sighandler->terminate();
381         delete sighandler;
382         delete run_lock;
383 }
384
385
386 void MWindow::quit()
387 {
388         gui->set_done(0);
389 }
390
391 void MWindow::init_error()
392 {
393         MainError::init_error(this);
394 }
395
396 void MWindow::finit_error()
397 {
398         MainError::finit_error();
399 }
400
401 void MWindow::create_defaults_path(char *string, const char *config_file)
402 {
403 // set the .bcast path
404         FileSystem fs;
405
406         sprintf(string, "%s/", File::get_config_path());
407         fs.complete_path(string);
408         if(!fs.is_dir(string))
409                 fs.create_dir(string);
410
411 // load the defaults
412         strcat(string, config_file);
413 }
414 const char *MWindow::default_std()
415 {
416         char buf[BCTEXTLEN], *p = 0;
417
418         int fd = open(TIMEZONE_NAME, O_RDONLY);
419         if( fd >= 0 ) {
420                 int l = read(fd, buf, sizeof(buf)-1);
421                 close(fd);
422                 if( l > 0 ) {
423                         if( buf[l-1] == '\n' ) --l;
424                         buf[l] = 0;
425                         p = buf;
426                 }
427         }
428         if( !p ) {
429                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
430                 if( l > 0 ) {
431                         buf[l] = 0;
432                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
433                         p += strlen(ZONEINFO_STR);
434                 }
435         }
436
437         if( p ) {
438                 for( int i=0; ntsc_zones[i]; ++i ) {
439                         if( !strcmp(ntsc_zones[i], p) )
440                                 return "NTSC";
441                 }
442         }
443
444         p = getenv("TZ");
445         if( p ) {
446                 for( int i=0; ntsc_zones[i]; ++i ) {
447                         if( !strcmp(ntsc_zones[i], p) )
448                                 return "NTSC";
449                 }
450         }
451
452 // cin_timezone: Seconds west of UTC.  240sec/deg
453         double tz_deg =  -cin_timezone / 240.;
454 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
455         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
456 }
457
458 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
459 {
460         struct formatpresets *fpr;
461
462         for(fpr = &format_presets[0]; fpr->name; fpr++)
463         {
464                 if(strcmp(_(fpr->name), preset) == 0)
465                 {
466                         session->audio_channels = fpr->audio_channels;
467                         session->audio_tracks = fpr->audio_tracks;
468                         session->sample_rate = fpr->sample_rate;
469                         session->video_channels = fpr->video_channels;
470                         session->video_tracks = fpr->video_tracks;
471                         session->frame_rate = fpr->frame_rate;
472                         session->output_w = fpr->output_w;
473                         session->output_h = fpr->output_h;
474                         session->aspect_w = fpr->aspect_w;
475                         session->aspect_h = fpr->aspect_h;
476                         session->interlace_mode = fpr->interlace_mode;
477                         session->color_model = fpr->color_model;
478                         return;
479                 }
480         }
481 }
482
483 const char *MWindow::get_preset_name(int index)
484 {
485         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
486                 return "Error";
487         return _(format_presets[index].name);
488 }
489
490
491 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
492 {
493         char path[BCTEXTLEN];
494 // Use user supplied path
495         if(config_path[0])
496                 strcpy(path, config_path);
497         else
498                 create_defaults_path(path, CONFIG_FILE);
499
500         delete defaults;
501         defaults = new BC_Hash(path);
502         defaults->load();
503 }
504
505
506 void MWindow::check_language()
507 {
508         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
509         const char *env_lang = getenv("LANGUAGE");
510         if( !env_lang ) env_lang = getenv("LC_ALL");
511         if( !env_lang ) env_lang = getenv("LANG");
512         if( !env_lang ) {
513                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
514                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
515                 env_lang = curr_lang;
516         }
517         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
518         defaults->get("LAST_LANG",last_lang);
519         if( strcmp(env_lang,last_lang)) {
520                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
521                 defaults->update("LAST_LANG",env_lang);
522                 char plugin_path[BCTEXTLEN];
523                 create_defaults_path(plugin_path, PLUGIN_FILE);
524                 ::remove(plugin_path);
525                 char ladspa_path[BCTEXTLEN];
526                 create_defaults_path(ladspa_path, LADSPA_FILE);
527                 ::remove(ladspa_path);
528                 defaults->save();
529         }
530         if( strlen(env_lang) > 1 &&
531             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
532                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
533         }
534         else
535                 strcpy(cin_lang, "en");
536 }
537
538 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
539 {
540         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
541         if( plug_dir ) {
542                 const char *dp = plug_dir;
543                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
544                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
545         }
546         strcpy(path, bp);
547         delete [] base_path;
548 }
549
550 int MWindow::load_plugin_index(MWindow *mwindow, FILE *fp, const char *plugin_dir)
551 {
552         if( !fp ) return -1;
553 // load index
554         fseek(fp, 0, SEEK_SET);
555         int ret = 0;
556         char index_line[BCTEXTLEN];
557         int index_version = -1, len = strlen(plugin_dir);
558         if( !fgets(index_line, BCTEXTLEN, fp) ||
559             sscanf(index_line, "%d", &index_version) != 1 ||
560             index_version != PLUGIN_FILE_VERSION ||
561             !fgets(index_line, BCTEXTLEN, fp) ||
562             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
563             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
564
565         ArrayList<PluginServer*> plugins;
566         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
567                 if( index_line[0] == ';' ) continue;
568                 if( index_line[0] == '#' ) continue;
569                 int type = PLUGIN_TYPE_UNKNOWN;
570                 char path[BCTEXTLEN], title[BCTEXTLEN];
571                 int64_t mtime = 0;
572                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
573                         ret = 1; continue;
574                 }
575                 PluginServer *server = 0;
576                 switch( type ) {
577                 case PLUGIN_TYPE_BUILTIN:
578                 case PLUGIN_TYPE_EXECUTABLE:
579                 case PLUGIN_TYPE_LADSPA: {
580                         char plugin_path[BCTEXTLEN];  struct stat st;
581                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
582                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
583                                 ret = 1; continue;
584                         }
585                         server = new PluginServer(mwindow, plugin_path, type);
586                         break; }
587                 case PLUGIN_TYPE_FFMPEG: {
588                         server = new_ffmpeg_server(mwindow, path);
589                         break; }
590                 case PLUGIN_TYPE_LV2: {
591                         server = new_lv2_server(mwindow, path);
592                         break; }
593                 }
594                 if( !server ) continue;
595                 plugins.append(server);
596 // Create plugin server from index entry
597                 server->set_title(title);
598                 if( server->read_table(index_line) ) {
599                         ret = 1;  continue;
600                 }
601         }
602
603         if( !ret )
604                 ret = check_plugin_index(plugins, plugin_dir, ".");
605
606         if( !ret )
607                 add_plugins(plugins);
608         else
609                 plugins.remove_all_objects();
610
611         return ret;
612 }
613
614 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
615         const char *plug_dir, const char *plug_path)
616 {
617         char plugin_path[BCTEXTLEN];
618         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
619         FileSystem fs;
620         fs.set_filter( "[*.plugin][*.so]" );
621         if( fs.update(plugin_path) )
622                 return 1;
623
624         for( int i=0; i<fs.dir_list.total; ++i ) {
625                 char fs_path[BCTEXTLEN];
626                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
627                 if( fs.is_dir(fs_path) ) {
628                         get_plugin_path(plugin_path, plug_dir, fs_path);
629                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
630                                 return 1;
631                 }
632                 else if( !plugin_exists(fs_path, plugins) )
633                         return 1;
634         }
635         return 0;
636 }
637
638
639 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
640 {
641         if( !plugindb )
642                 plugindb = new ArrayList<PluginServer*>;
643         init_ffmpeg();
644         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
645         create_defaults_path(index_path, PLUGIN_FILE);
646         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
647         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
648         FILE *fp = fopen(index_path,"a+");
649         if( !fp ) {
650                 fprintf(stderr,_("MWindow::init_plugins: "
651                         "can't open plugin index: %s\n"), index_path);
652                 return -1;
653         }
654         int fd = fileno(fp), ret = -1;
655         if( !flock(fd, LOCK_EX) ) {
656                 fseek(fp, 0, SEEK_SET);
657                 ret = load_plugin_index(mwindow, fp, plugin_path);
658         }
659         if( ret > 0 ) {
660                 ftruncate(fd, 0);
661                 fseek(fp, 0, SEEK_SET);
662                 printf("init plugin index: %s\n", plugin_path);
663                 fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
664                 fprintf(fp, "%s\n", plugin_path);
665                 init_plugin_index(mwindow, preferences, fp, plugin_path);
666                 init_ffmpeg_index(mwindow, preferences, fp);
667                 init_lv2_index(mwindow, preferences, fp);
668                 fseek(fp, 0, SEEK_SET);
669                 ret = load_plugin_index(mwindow, fp, plugin_path);
670         }
671         if( ret ) {
672                 fprintf(stderr,_("MWindow::init_plugins: "
673                         "can't %s plugin index: %s\n"),
674                         ret>0 ? _("create") : _("lock"), index_path);
675         }
676         fclose(fp);
677         return ret;
678 }
679
680 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
681 {
682 #ifdef HAVE_LADSPA
683         char *path = getenv("LADSPA_PATH");
684         char ladspa_path[BCTEXTLEN];
685         if( !path ) {
686                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
687                 path = ladspa_path;
688         }
689         for( int len=0; *path; path+=len ) {
690                 char *cp = strchr(path,':');
691                 len = !cp ? strlen(path) : cp-path;
692                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
693                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
694                 if( cp ) ++len;
695                 char *plugin_dir = FileSystem::basepath(plugin_path);
696                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
697                 create_defaults_path(index_path, LADSPA_FILE);
698                 cp = index_path + strlen(index_path);
699                 for( char *bp=plugin_path; *bp!=0; ++bp )
700                         *cp++ = *bp=='/' ? '_' : *bp;
701                 *cp = 0;
702                 FILE *fp = fopen(index_path,"a+");
703                 if( !fp ) {
704                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
705                                 "can't open ladspa plugin index: %s\n"), index_path);
706                         continue;
707                 }
708                 int fd = fileno(fp), ret = -1;
709                 if( !flock(fd, LOCK_EX) ) {
710                         fseek(fp, 0, SEEK_SET);
711                         ret = load_plugin_index(mwindow, fp, plugin_path);
712                 }
713                 if( ret > 0 ) {
714                         ftruncate(fd, 0);
715                         fseek(fp, 0, SEEK_SET);
716                         init_ladspa_index(mwindow, preferences, fp, plugin_path);
717                         fseek(fp, 0, SEEK_SET);
718                         ret = load_plugin_index(mwindow, fp, plugin_path);
719                 }
720                 if( ret ) {
721                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
722                                 "can't %s ladspa plugin index: %s\n"),
723                                 ret>0 ? _("create") : _("lock"), index_path);
724                 }
725                 fclose(fp);
726         }
727 #endif
728         return 1;
729 }
730
731 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
732         FILE *fp, const char *plugin_dir)
733 {
734         int idx = PLUGIN_IDS;
735         if( plugindb ) {
736                 for( int i=0; i<plugindb->size(); ++i ) {
737                         PluginServer *server = plugindb->get(i);
738                         if( server->dir_idx >= idx )
739                                 idx = server->dir_idx+1;
740                 }
741         }
742         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
743 }
744
745 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
746         const char *plug_dir, const char *plug_path, int &idx)
747 {
748         char plugin_path[BCTEXTLEN];
749         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
750         FileSystem fs;
751         fs.set_filter( "[*.plugin][*.so][*.dll]" );
752         int result = fs.update(plugin_path);
753         if( result || !fs.dir_list.total ) return;
754         int vis_id = idx++;
755
756         for( int i=0; i<fs.dir_list.total; ++i ) {
757                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
758                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
759                 get_plugin_path(path, plug_dir, fs_path);
760                 if( fs.is_dir(fs_path) ) {
761                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
762                         continue;
763                 }
764                 if( plugin_exists(path) ) continue;
765                 struct stat st;
766                 if( stat(fs_path, &st) ) continue;
767                 int64_t mtime = st.st_mtime;
768                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
769                 result = server.open_plugin(1, preferences, 0, 0);
770                 if( !result ) {
771                         server.write_table(fp, path, vis_id, mtime);
772                         server.close_plugin();
773                 }
774                 else if( result == PLUGINSERVER_IS_LAD ) {
775                         int lad_index = 0;
776                         for(;;) {
777                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
778                                 ladspa.set_lad_index(lad_index++);
779                                 result = ladspa.open_plugin(1, preferences, 0, 0);
780                                 if( result ) break;
781                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
782                                 ladspa.close_plugin();
783                         }
784                 }
785         }
786 }
787
788 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
789 {
790         for( int i=0; i<plugins.size(); ++i )
791                 plugindb->append(plugins[i]);
792         plugins.remove_all();
793 }
794
795 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
796 {
797         const char *dat_path = File::get_cindat_path();
798         char msg_path[BCTEXTLEN];
799         FILE *fp = 0;
800         if( BC_Resources::language[0] ) {
801                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
802                         dat_path, lang);
803                 fp = fopen(msg_path, "r");
804         }
805         if( !fp ) {
806                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
807                         dat_path);
808                 fp = fopen(msg_path, "r");
809         }
810         if( !fp ) return;
811         char text[BCTEXTLEN];
812         char *tp = text, *ep = tp + sizeof(text)-1;
813         char title[BCTEXTLEN];
814         title[0] = 0;
815         int no = 0;
816         for(;;) {
817                 ++no;  int done = 1;
818                 char line[BCTEXTLEN], *cp = line;
819                 if( fgets(line,sizeof(line)-1,fp) ) {
820                         if( *cp == '#' ) continue;
821                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
822                 }
823                 if( done ) {
824                         if( tp > text && *--tp == '\n' ) *tp = 0;
825                         if( title[0] ) {
826                                 int idx = plugins.size();
827                                 while( --idx>=0 && strcmp(plugins[idx]->title, title) );
828                                 if( idx >= 0 ) {
829                                         delete [] plugins[idx]->tip;
830                                         plugins[idx]->tip = cstrdup(text);
831                                 }
832                                 title[0] = 0;
833                         }
834                         if( done > 0 ) break;
835                         tp = text;  *tp = 0;
836                         char *dp = strchr(cp, ':');
837                         if( !dp ) {
838                                 printf("plugin tips: error on line %d\n", no);
839                                 continue;
840                         }
841                         char *bp = title;
842                         while( cp < dp ) *bp++ = *cp++;
843                         *bp = 0;
844                         ++cp;
845                 }
846
847                 while( *cp == ' ' || *cp == '\t' ) ++cp;
848                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
849         }
850         fclose(fp);
851 }
852
853 void MWindow::delete_plugins()
854 {
855         plugindb->remove_all_objects();
856         delete plugindb;
857         plugindb = 0;
858 }
859
860 void MWindow::search_plugindb(int do_audio,
861                 int do_video,
862                 int is_realtime,
863                 int is_transition,
864                 int is_theme,
865                 ArrayList<PluginServer*> &results)
866 {
867 // Get plugins
868         for(int i = 0; i < MWindow::plugindb->total; i++)
869         {
870                 PluginServer *current = MWindow::plugindb->get(i);
871
872                 if(current->audio == do_audio &&
873                         current->video == do_video &&
874                         (current->realtime == is_realtime || is_realtime < 0) &&
875                         current->transition == is_transition &&
876                         current->theme == is_theme)
877                         results.append(current);
878         }
879
880 // Alphabetize list by title
881         int done = 0;
882         while(!done)
883         {
884                 done = 1;
885
886                 for(int i = 0; i < results.total - 1; i++)
887                 {
888                         PluginServer *value1 = results[i];
889                         PluginServer *value2 = results[i + 1];
890                         if(strcmp(_(value1->title), _(value2->title)) > 0)
891                         {
892                                 done = 0;
893                                 results[i] = value2;
894                                 results[i + 1] = value1;
895                         }
896                 }
897         }
898 }
899
900 PluginServer* MWindow::scan_plugindb(char *title,
901                 int data_type)
902 {
903 //      if(data_type < 0)
904 //      {
905 //              printf("MWindow::scan_plugindb data_type < 0\n");
906 //              return 0;
907 //      }
908
909         for(int i = 0; i < plugindb->total; i++)
910         {
911                 PluginServer *server = plugindb->get(i);
912                 if(server->title &&
913                         !strcasecmp(server->title, title) &&
914                         (data_type < 0 ||
915                                 (data_type == TRACK_AUDIO && server->audio) ||
916                                 (data_type == TRACK_VIDEO && server->video)))
917                         return plugindb->get(i);
918         }
919         return 0;
920 }
921
922 // repair session files with xlated plugin titles
923 void MWindow::fix_plugin_title(char *title)
924 {
925         for(int i = 0; i < plugindb->total; i++) {
926                 PluginServer *server = plugindb->get(i);
927                 if( !server->title ) continue;
928                 const char *server_title = server->title;
929                 if( !bstrcasecmp(title, _(server_title)) ) {
930                         strcpy(title, server_title);
931                         return;
932                 }
933         }
934 }
935
936 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
937 {
938         for( int i=0; i<plugins.size(); ++i )
939                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
940         return 0;
941 }
942
943 int MWindow::plugin_exists(char *plugin_path)
944 {
945         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
946 }
947
948 void MWindow::remove_plugin_index()
949 {
950         char index_path[BCTEXTLEN];
951         MWindow::create_defaults_path(index_path, PLUGIN_FILE);
952         ::remove(index_path);
953 }
954
955 void MWindow::init_preferences()
956 {
957         preferences = new Preferences;
958         preferences->load_defaults(defaults);
959         File::setenv_path("LV2_PATH",preferences->lv2_path, 1);
960         session = new MainSession(this);
961         session->load_defaults(defaults);
962         // set x11_host, screens, window_config
963         screens = session->set_default_x11_host();
964         BC_Signals::set_trap_hook(trap_hook, this);
965         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
966         BC_Signals::set_catch_intr(preferences->trap_sigintr);
967         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
968                 BC_Trace::enable_locks();
969         }
970         else {
971                 BC_Trace::disable_locks();
972         }
973         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
974         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
975         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
976         YUV::yuv.yuv_set_colors(preferences->yuv_color_space, preferences->yuv_color_range);
977 }
978
979 void MWindow::clean_indexes()
980 {
981         FileSystem fs;
982         int total_excess;
983         long oldest = 0;
984         int oldest_item = -1;
985         int result;
986         char string[BCTEXTLEN];
987         char string2[BCTEXTLEN];
988
989 // Delete extra indexes
990         fs.set_filter("*.idx");
991         fs.complete_path(preferences->index_directory);
992         fs.update(preferences->index_directory);
993 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
994
995 // Eliminate directories
996         result = 1;
997         while(result)
998         {
999                 result = 0;
1000                 for(int i = 0; i < fs.dir_list.total && !result; i++)
1001                 {
1002                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1003                         if(fs.is_dir(string))
1004                         {
1005                                 delete fs.dir_list[i];
1006                                 fs.dir_list.remove_number(i);
1007                                 result = 1;
1008                         }
1009                 }
1010         }
1011         total_excess = fs.dir_list.total - preferences->index_count;
1012
1013 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
1014         while(total_excess > 0)
1015         {
1016 // Get oldest
1017                 for(int i = 0; i < fs.dir_list.total; i++)
1018                 {
1019                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1020
1021                         if(i == 0 || fs.get_date(string) <= oldest)
1022                         {
1023                                 oldest = fs.get_date(string);
1024                                 oldest_item = i;
1025                         }
1026                 }
1027
1028                 if(oldest_item >= 0)
1029                 {
1030 // Remove index file
1031                         fs.join_names(string,
1032                                 preferences->index_directory,
1033                                 fs.dir_list[oldest_item]->name);
1034 //printf("MWindow::clean_indexes 1 %s\n", string);
1035                         if(remove(string))
1036                                 perror("delete_indexes");
1037                         delete fs.dir_list[oldest_item];
1038                         fs.dir_list.remove_number(oldest_item);
1039
1040 // Remove table of contents if it exists
1041                         strcpy(string2, string);
1042                         char *ptr = strrchr(string2, '.');
1043                         if(ptr)
1044                         {
1045 //printf("MWindow::clean_indexes 2 %s\n", string2);
1046                                 sprintf(ptr, ".toc");
1047                                 remove(string2);
1048                                 sprintf(ptr, ".mkr");
1049                                 remove(string2);
1050                         }
1051                 }
1052
1053                 total_excess--;
1054         }
1055 }
1056
1057 void MWindow::init_awindow()
1058 {
1059         awindow = new AWindow(this);
1060         awindow->create_objects();
1061 }
1062
1063 void MWindow::init_gwindow()
1064 {
1065         gwindow = new GWindow(this);
1066         gwindow->create_objects();
1067 }
1068
1069 void MWindow::init_tipwindow()
1070 {
1071         TipWindow::load_tips(cin_lang);
1072         if( !twindow )
1073                 twindow = new TipWindow(this);
1074         twindow->start();
1075 }
1076
1077 void MWindow::show_warning(int *do_warning, const char *text)
1078 {
1079         if( do_warning && !*do_warning ) return;
1080         if( !wwindow )
1081                 wwindow = new WWindow(this);
1082         wwindow->show_warning(do_warning, text);
1083 }
1084
1085 int MWindow::wait_warning()
1086 {
1087         return wwindow->wait_result();
1088 }
1089
1090 void MWindow::init_theme()
1091 {
1092         Timer timer;
1093         theme = 0;
1094
1095         PluginServer *theme_plugin = 0;
1096         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1097                 if( plugindb->get(i)->theme &&
1098                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1099                         theme_plugin = plugindb->get(i);
1100         }
1101
1102         if( !theme_plugin )
1103                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1104                          preferences->theme);
1105
1106         const char *default_theme = DEFAULT_THEME;
1107         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1108                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1109                         default_theme);
1110                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1111                         if( plugindb->get(i)->theme &&
1112                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1113                                 theme_plugin = plugindb->get(i);
1114                 }
1115         }
1116
1117         if(!theme_plugin) {
1118                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1119                 exit(1);
1120         }
1121
1122         PluginServer *plugin = new PluginServer(*theme_plugin);
1123         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1124                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1125                         theme_plugin->title);
1126                 exit(1);
1127         }
1128
1129         theme = plugin->new_theme();
1130         theme->mwindow = this;
1131         strcpy(theme->path, plugin->path);
1132         delete plugin;
1133
1134 // Load default images & settings
1135         theme->Theme::initialize();
1136 // Load user images & settings
1137         theme->initialize();
1138 // Create menus with user colors
1139         theme->build_menus();
1140         init_menus();
1141
1142         theme->sort_image_sets();
1143         theme->check_used();
1144 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1145 }
1146
1147 void MWindow::init_3d()
1148 {
1149         playback_3d = new Playback3D(this);
1150         playback_3d->create_objects();
1151 }
1152
1153 void MWindow::init_edl()
1154 {
1155         edl = new EDL;
1156         edl->create_objects();
1157         fill_preset_defaults(default_standard, edl->session);
1158         edl->load_defaults(defaults);
1159         edl->session->brender_start = edl->session->brender_end = 0;
1160         edl->create_default_tracks();
1161         edl->tracks->update_y_pixels(theme);
1162 }
1163
1164 void MWindow::init_compositor()
1165 {
1166         cwindow = new CWindow(this);
1167         cwindow->create_objects();
1168 }
1169
1170 void MWindow::init_levelwindow()
1171 {
1172         lwindow = new LevelWindow(this);
1173         lwindow->create_objects();
1174 }
1175
1176 VWindow *MWindow::get_viewer(int start_it, int idx)
1177 {
1178         vwindows_lock->lock("MWindow::get_viewer");
1179         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1180         if( !vwindow ) idx = vwindows.size();
1181         while( !vwindow && --idx >= 0 ) {
1182                 VWindow *vwin = vwindows[idx];
1183                 if( !vwin->is_running() || !vwin->get_edl() )
1184                         vwindow = vwin;
1185         }
1186         if( !vwindow ) {
1187                 vwindow = new VWindow(this);
1188                 vwindow->load_defaults();
1189                 vwindow->create_objects();
1190                 vwindows.append(vwindow);
1191         }
1192         vwindows_lock->unlock();
1193         if( start_it ) vwindow->start();
1194         return vwindow;
1195 }
1196
1197 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1198 {
1199         zwindows_lock->lock("MWindow::get_mixer");
1200         if( !mixer ) mixer = edl->mixers.new_mixer();
1201         ZWindow *zwindow = 0;
1202         for( int i=0; !zwindow && i<zwindows.size(); ++i ) {
1203                 ZWindow *zwdw = zwindows[i];
1204                 if( zwdw->running() ) continue;
1205                 if( zwdw->idx >= 0 ) continue;
1206                 zwindow = zwindows[i];
1207         }
1208         if( !zwindow )
1209                 zwindows.append(zwindow = new ZWindow(this));
1210         zwindow->idx = mixer->idx;
1211         zwindows_lock->unlock();
1212         return zwindow;
1213 }
1214
1215 ZWindow *MWindow::get_mixer(int idx)
1216 {
1217         ZWindow *zwindow = 0;
1218         zwindows_lock->lock("MWindow::get_mixer");
1219         for( int i=0; !zwindow && i<zwindows.size(); ++i ) {
1220                 ZWindow *zwdw = zwindows[i];
1221                 if( !zwdw->running() ) continue;
1222                 if( zwdw->idx != idx ) continue;
1223                 zwindow = zwindows[i];
1224         }
1225         zwindows_lock->unlock();
1226         return zwindow;
1227 }
1228
1229 void MWindow::close_mixer(ZWindow *zwindow)
1230 {
1231         zwindows_lock->lock("MWindow::close_mixer 0");
1232         if( session->selected_zwindow >= 0 ) {
1233                 int i = zwindows.number_of(zwindow);
1234                 if( i >= 0 && i < session->selected_zwindow )
1235                         --session->selected_zwindow;
1236                 else if( i == session->selected_zwindow )
1237                         session->selected_zwindow = -1;
1238         }
1239         zwindows_lock->unlock();
1240         gui->lock_window("MWindow::close_mixer 1");
1241         gui->update_mixers(0, -1);
1242         gui->unlock_window();
1243 }
1244
1245 void MWindow::start_mixer()
1246 {
1247         Mixer *mixer = 0;
1248         ZWindow *zwindow = get_mixer(mixer);
1249         const char *title = 0;
1250
1251         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1252                 PatchGUI *patchgui = get_patchgui(track);
1253                 if( !patchgui || !patchgui->mixer ) continue;
1254                 mixer->mixer_ids.append(track->get_mixer_id());
1255                 if( !title ) title = track->title;
1256         }
1257
1258         session->selected_zwindow = -1;
1259         gui->lock_window("MWindow::start_mixer");
1260         gui->update_mixers(0, 0);
1261         gui->unlock_window();
1262
1263         zwindow->set_title(title);
1264         zwindow->start();
1265         refresh_mixers();
1266 }
1267
1268 int MWindow::mixer_track_active(Track *track)
1269 {
1270         int i = session->selected_zwindow;
1271         if( i < 0 || i >= zwindows.size() ) return 0;
1272         ZWindow *zwindow = zwindows[i];
1273         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1274         if( !mixer ) return 0;
1275         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1276         return n >= 0 ? 1 : 0;
1277 }
1278
1279 void MWindow::update_mixer_tracks()
1280 {
1281         zwindows_lock->lock("MixPatch::handle_event");
1282         int i = session->selected_zwindow;
1283         if( i >= 0 && i < zwindows.size() ) {
1284                 ZWindow *zwindow = zwindows[i];
1285                 zwindow->update_mixer_ids();
1286         }
1287         zwindows_lock->unlock();
1288 }
1289
1290 void MWindow::handle_mixers(EDL *edl, int command, int wait_tracking,
1291                 int use_inout, int toggle_audio, int loop_play, float speed)
1292 {
1293         zwindows_lock->lock("MWindow::handle_mixers");
1294         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1295                 ZWindow *zwindow = zwindows[vidx];
1296                 if( zwindow->idx < 0 ) continue;
1297                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1298                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1299                 int k = -1;
1300                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1301                         if( track->data_type != TRACK_VIDEO ) continue;
1302                         int mixer_id = track->get_mixer_id();
1303                         k = mixer->mixer_ids.size();
1304                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1305                 }
1306                 if( k < 0 ) continue;
1307                 EDL *mixer_edl = new EDL(this->edl);
1308                 mixer_edl->create_objects();
1309                 mixer_edl->copy_all(edl);
1310                 mixer_edl->remove_vwindow_edls();
1311                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1312                         k = mixer->mixer_ids.size();
1313                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1314                         if( k >= 0 ) {
1315                                 track->armed = 1;
1316                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1317                         }
1318                         else
1319                                 track->armed = track->play = 0;
1320                 }
1321                 zwindow->change_source(mixer_edl);
1322                 zwindow->handle_mixer(command, 0,
1323                                 use_inout, toggle_audio, loop_play, speed);
1324         }
1325         zwindows_lock->unlock();
1326 }
1327
1328 void MWindow::refresh_mixers(int dir)
1329 {
1330         int command = dir >= 0 ? CURRENT_FRAME : LAST_FRAME;
1331         handle_mixers(edl, command, 0, 0, 0, 0, 0);
1332 }
1333
1334 void MWindow::stop_mixers()
1335 {
1336         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1337                 ZWindow *zwindow = zwindows[vidx];
1338                 if( zwindow->idx < 0 ) continue;
1339                 zwindow->handle_mixer(STOP, 0, 0, 0, 0, 0);
1340         }
1341 }
1342
1343 void MWindow::close_mixers(int result)
1344 {
1345         ArrayList<ZWindow*> closed;
1346         zwindows_lock->lock("MWindow::close_mixers");
1347         for( int i=zwindows.size(); --i>=0; ) {
1348                 ZWindow *zwindow = zwindows[i];
1349                 if( zwindow->idx < 0 ) continue;
1350                 zwindow->idx = -1;
1351                 ZWindowGUI *zgui = zwindow->zgui;
1352                 zgui->lock_window("MWindow::select_zwindow 0");
1353                 zgui->set_done(result);
1354                 zgui->unlock_window();
1355                 closed.append(zwindow);
1356         }
1357         zwindows_lock->unlock();
1358         for( int i=0; i<closed.size(); ++i ) {
1359                 ZWindow *zwindow = closed[i];
1360                 zwindow->join();
1361         }
1362 }
1363
1364 ZWindow *MWindow::create_mixer(Indexable *indexable, double position)
1365 {
1366         ArrayList<Indexable*> new_assets;
1367         new_assets.append(indexable);
1368         Track *track = edl->tracks->last;
1369         load_assets(&new_assets, position, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 1);
1370         track = !track ? edl->tracks->first : track->next;
1371         Mixer *mixer = 0;
1372         ZWindow *zwindow = get_mixer(mixer);
1373         while( track ) {
1374                 track->play = track->armed = 0;
1375                 if( track->data_type == TRACK_VIDEO ) {
1376                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1377                 }
1378                 mixer->mixer_ids.append(track->get_mixer_id());
1379                 track = track->next;
1380         }
1381         if(  indexable->is_asset ) {
1382                 char *path = indexable->path;
1383                 char *tp = strrchr(path, '/');
1384                 if( !tp ) tp = path; else ++tp;
1385                 zwindow->set_title(tp);
1386         }
1387         else {
1388                 char *title = ((EDL*)indexable)->local_session->clip_title;
1389                 zwindow->set_title(title);
1390         }
1391         return zwindow;
1392 }
1393
1394 void MWindow::create_mixers(double position)
1395 {
1396         if( !session->drag_assets->size() &&
1397             !session->drag_clips->size() ) return;
1398         undo_before();
1399
1400         select_zwindow(0);
1401         ArrayList<ZWindow *>new_mixers;
1402
1403         for( int i=0; i<session->drag_assets->size(); ++i ) {
1404                 Indexable *indexable = session->drag_assets->get(i);
1405                 if( !indexable->have_video() ) continue;
1406                 ZWindow *zwindow = create_mixer(indexable, position);
1407                 new_mixers.append(zwindow);
1408         }
1409         for( int i=0; i<session->drag_clips->size(); ++i ) {
1410                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1411                 if( !indexable->have_video() ) continue;
1412                 ZWindow *zwindow = create_mixer(indexable, position);
1413                 new_mixers.append(zwindow);
1414         }
1415
1416         tile_mixers();
1417         for( int i=0; i<new_mixers.size(); ++i )
1418                 new_mixers[i]->start();
1419
1420         refresh_mixers();
1421         save_backup();
1422         undo_after(_("create mixers"), LOAD_ALL);
1423         restart_brender();
1424         gui->update(1, FORCE_REDRAW, 1, 1, 1, 1, 0);
1425         sync_parameters(CHANGE_ALL);
1426 }
1427
1428 void MWindow::open_mixers()
1429 {
1430         for( int i=0; i<edl->mixers.size(); ++i ) {
1431                 Mixer *mixer = edl->mixers[i];
1432                 ZWindow *zwindow = get_mixer(mixer);
1433                 zwindow->set_title(mixer->title);
1434                 zwindow->start();
1435         }
1436         refresh_mixers();
1437 }
1438
1439 int MWindow::select_zwindow(ZWindow *zwindow)
1440 {
1441         int ret = 0, n = zwindows.number_of(zwindow);
1442         if( session->selected_zwindow != n ) {
1443                 session->selected_zwindow = n;
1444                 for( int i=0; i<zwindows.size(); ++i ) {
1445                         ZWindow *zwindow = zwindows[i];
1446                         if( zwindow->idx < 0 ) continue;
1447                         ZWindowGUI *zgui = zwindow->zgui;
1448                         zgui->lock_window("MWindow::select_zwindow 0");
1449                         zwindow->highlighted = i == n ? 1 : 0;
1450                         if( zgui->draw_overlays() )
1451                                 zgui->canvas->get_canvas()->flash(1);
1452                         zgui->unlock_window();
1453                 }
1454                 ret = 1;
1455                 gui->lock_window("MWindow::select_window 1");
1456                 gui->update_mixers(0, -1);
1457                 gui->unlock_window();
1458         }
1459         return ret;
1460 }
1461
1462 void MWindow::tile_mixers()
1463 {
1464         int nz = 0;
1465         for( int i=0; i<zwindows.size(); ++i ) {
1466                 ZWindow *zwindow = zwindows[i];
1467                 if( zwindow->idx < 0 ) continue;
1468                 ++nz;
1469         }
1470         if( !nz ) return;
1471         int zn = ceil(sqrt(nz));
1472         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1473         int y1 = 1, y2 = gui->get_y();
1474         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1475         if( x1 < 0 ) x1 = 0;
1476         if( y1 < 0 ) y1 = 0;
1477         if( x2 > rw ) x2 = rw;
1478         if( y2 > rh ) y2 = rh;
1479         int dx = x2 - x1, dy = y2 - y1;
1480         int zw = dx / zn;
1481         int lt = BC_DisplayInfo::get_left_border();
1482         int top = BC_DisplayInfo::get_top_border();
1483         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1484         int bh = top + BC_DisplayInfo::get_bottom_border();
1485         int zx = 0, zy = 0;  // window origins
1486         int mw = xS(10+10), mh = yS(10+10); // canvas margins
1487         int rsz = 0, n = 0, dz = 0;
1488         int ow = edl->session->output_w, oh = edl->session->output_h;
1489         for( int i=0; i<zwindows.size(); ++i ) {
1490                 ZWindow *zwindow = zwindows[i];
1491                 if( zwindow->idx < 0 ) continue;
1492                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1493                 if( rsz < hh ) rsz = hh;
1494                 int xx = zx + x1, yy = zy + y1;
1495                 int mx = x2 - zw, my = y2 - zh;
1496                 if( xx > mx ) xx = mx;
1497                 if( yy > my ) yy = my;
1498                 xx += lt + xS(dz);  yy += top + yS(dz);
1499                 zwindow->reposition(xx,yy, ww,hh);
1500                 if( zwindow->running() ) {
1501                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1502                         gui->lock_window("MWindow::tile_mixers");
1503                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1504                         gui->unlock_window();
1505                 }
1506                 if( ++n >= zn ) {
1507                         n = 0;  rsz += bh;
1508                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1509                         rsz = 0;
1510                         zx = 0;
1511                 }
1512                 else
1513                         zx += zw;
1514         }
1515 }
1516
1517 void MWindow::set_gang_tracks(int v)
1518 {
1519         edl->session->gang_tracks = v;
1520         gui->update(1, 1, 0, 0, 1, 0, 0);
1521         gui->flush();
1522 }
1523
1524
1525 void MWindow::init_cache()
1526 {
1527         audio_cache = new CICache(preferences);
1528         video_cache = new CICache(preferences);
1529         frame_cache = new FrameCache;
1530         wave_cache = new WaveCache;
1531 }
1532
1533 void MWindow::init_channeldb()
1534 {
1535         channeldb_buz->load("channeldb_buz");
1536         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1537 }
1538
1539 void MWindow::init_menus()
1540 {
1541         char string[BCTEXTLEN];
1542
1543         // Color Models
1544         BC_CModels::to_text(string, BC_RGB888);
1545         colormodels.append(new ColormodelItem(string, BC_RGB888));
1546         BC_CModels::to_text(string, BC_RGBA8888);
1547         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1548 //      BC_CModels::to_text(string, BC_RGB161616);
1549 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1550 //      BC_CModels::to_text(string, BC_RGBA16161616);
1551 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1552         BC_CModels::to_text(string, BC_RGB_FLOAT);
1553         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1554         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1555         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1556         BC_CModels::to_text(string, BC_YUV888);
1557         colormodels.append(new ColormodelItem(string, BC_YUV888));
1558         BC_CModels::to_text(string, BC_YUVA8888);
1559         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1560 //      BC_CModels::to_text(string, BC_YUV161616);
1561 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1562 //      BC_CModels::to_text(string, BC_YUVA16161616);
1563 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1564
1565 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1566                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1567
1568 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1569                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1570
1571         // Interlacing Modes
1572         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1573
1574         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1575         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1576
1577         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1578         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1579
1580         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1581         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1582
1583         mixers_align = new MixersAlign(this);
1584 }
1585
1586 void MWindow::init_indexes()
1587 {
1588         mainindexes = new MainIndexes(this);
1589         mainindexes->start_loop();
1590 }
1591
1592 void MWindow::init_gui()
1593 {
1594         gui = new MWindowGUI(this);
1595         gui->create_objects();
1596         gui->load_defaults(defaults);
1597 }
1598
1599 void MWindow::init_signals()
1600 {
1601         sighandler = new SigHandler;
1602         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1603 ENABLE_BUFFER
1604 }
1605
1606 void MWindow::init_render()
1607 {
1608         render = new Render(this);
1609         create_bd = new CreateBD_Thread(this);
1610         create_dvd = new CreateDVD_Thread(this);
1611         batch_render = new BatchRenderThread(this);
1612 }
1613
1614 void MWindow::init_exportedl()
1615 {
1616         exportedl = new ExportEDL(this);
1617 }
1618
1619
1620 void MWindow::init_shuttle()
1621 {
1622 #ifdef HAVE_SHUTTLE
1623         int ret = Shuttle::probe();
1624         if( ret >= 0 ) {
1625                 shuttle = new Shuttle(this);
1626                 if( shuttle->read_config_file() > 0 ) {
1627                         printf("shuttle: bad config file\n");
1628                         delete shuttle;  shuttle = 0;
1629                         return;
1630                 }
1631                 shuttle->start(ret);
1632         }
1633 #endif
1634 }
1635 void MWindow::init_wintv()
1636 {
1637 #ifdef HAVE_WINTV
1638         wintv = WinTV::probe(this);
1639         if( wintv )
1640                 wintv->start();
1641 #endif
1642 }
1643 void MWindow::init_x10tv()
1644 {
1645 #ifdef HAVE_X10TV
1646         x10tv = X10TV::probe(this);
1647         if( x10tv )
1648                 x10tv->start();
1649 #endif
1650 }
1651
1652
1653 void MWindow::init_brender()
1654 {
1655         if(preferences->use_brender && !brender)
1656         {
1657                 brender_lock->lock("MWindow::init_brender 1");
1658                 brender = new BRender(this);
1659                 brender->initialize();
1660                 session->brender_end = 0;
1661                 brender_lock->unlock();
1662         }
1663         else
1664         if(!preferences->use_brender && brender)
1665         {
1666                 brender_lock->lock("MWindow::init_brender 2");
1667                 delete brender;
1668                 brender = 0;
1669                 session->brender_end = 0;
1670                 brender_lock->unlock();
1671         }
1672         brender_active = 0;
1673         stop_brender();
1674 }
1675
1676 void MWindow::restart_brender()
1677 {
1678 //printf("MWindow::restart_brender 1\n");
1679         if( !brender_active || !preferences->use_brender ) return;
1680         if( !brender ) return;
1681         brender->restart(edl);
1682 }
1683
1684 void MWindow::stop_brender()
1685 {
1686         if( !brender ) return;
1687 // cannot be holding mwindow->gui display lock
1688         brender->stop();
1689 }
1690
1691 int MWindow::brender_available(int position)
1692 {
1693         int result = 0;
1694         brender_lock->lock("MWindow::brender_available 1");
1695         if(brender && brender_active)
1696         {
1697                 if(brender->map_valid)
1698                 {
1699                         brender->map_lock->lock("MWindow::brender_available 2");
1700                         if(position < brender->map_size &&
1701                                 position >= 0)
1702                         {
1703 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1704                                 if(brender->map[position] == BRender::RENDERED)
1705                                         result = 1;
1706                         }
1707                         brender->map_lock->unlock();
1708                 }
1709         }
1710         brender_lock->unlock();
1711         return result;
1712 }
1713
1714 void MWindow::set_brender_active(int v, int update)
1715 {
1716         if( !preferences->use_brender ) v = 0;
1717         brender_active = v;
1718         gui->mainmenu->brender_active->set_checked(v);
1719         if( v != 0 ) {
1720                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1721                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1722
1723                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1724                         edl->session->brender_end = edl->tracks->total_video_length();
1725                 }
1726                 restart_brender();
1727         }
1728         else {
1729                 edl->session->brender_start = edl->session->brender_end = 0;
1730                 gui->unlock_window();
1731                 stop_brender();
1732                 gui->lock_window("MWindow::set_brender_active");
1733         }
1734         if( update ) {
1735                 gui->update_timebar(0);
1736                 gui->draw_overlays(1);
1737         }
1738 }
1739
1740 int MWindow::has_commercials()
1741 {
1742 #ifdef HAVE_COMMERCIAL
1743         return theme->use_commercials;
1744 #else
1745         return 0;
1746 #endif
1747 }
1748
1749 void MWindow::init_commercials()
1750 {
1751 #ifdef HAVE_COMMERCIAL
1752         if( !commercials ) {
1753                 commercials = new Commercials(this);
1754                 commercial_active = 0;
1755         }
1756         else
1757                 commercials->add_user();
1758 #endif
1759 }
1760
1761 void MWindow::commit_commercial()
1762 {
1763 #ifdef HAVE_COMMERCIAL
1764         if( !commercial_active ) return;
1765         commercial_active = 0;
1766         if( !commercials ) return;
1767         commercials->commitDb();
1768 #endif
1769 }
1770
1771 void MWindow::undo_commercial()
1772 {
1773 #ifdef HAVE_COMMERCIAL
1774         if( !commercial_active ) return;
1775         commercial_active = 0;
1776         if( !commercials ) return;
1777         commercials->undoDb();
1778 #endif
1779 }
1780
1781 int MWindow::put_commercial()
1782 {
1783         int result = 0;
1784 #ifdef HAVE_COMMERCIAL
1785         double start = edl->local_session->get_selectionstart();
1786         double end = edl->local_session->get_selectionend();
1787         if( start >= end ) return 0;
1788
1789         const char *errmsg = 0;
1790         int count = 0;
1791         Tracks *tracks = edl->tracks;
1792         //check it
1793         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1794                 if( track->data_type != TRACK_VIDEO ) continue;
1795                 if( !track->armed ) continue;
1796                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1797                 ++count;
1798                 int64_t units_start = track->to_units(start,0);
1799                 int64_t units_end = track->to_units(end,0);
1800                 Edits *edits = track->edits;
1801                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1802                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1803                 if(!edit1 && !edit2) continue;  // nothing selected
1804                 if(!edit2) {                    // edit2 beyond end of track
1805                         edit2 = edits->last;
1806                         units_end = edits->length();
1807                 }
1808                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1809                 Indexable *indexable = edit1->get_source();
1810                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1811         }
1812         //run it
1813         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1814                 if( track->data_type != TRACK_VIDEO ) continue;
1815                 if( !track->armed ) continue;
1816                 int64_t units_start = track->to_units(start,0);
1817                 int64_t units_end = track->to_units(end,0);
1818                 Edits *edits = track->edits;
1819                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1820                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1821                 if(!edit1 && !edit2) continue;  // nothing selected
1822                 if(!edit2) {                    // edit2 beyond end of track
1823                         edit2 = edits->last;
1824                         units_end = edits->length();
1825                 }
1826                 Indexable *indexable = edit1->get_source();
1827                 Asset *asset = (Asset *)indexable;
1828                 File *file = video_cache->check_out(asset, edl);
1829                 if( !file ) { errmsg = _("no file"); break; }
1830                 int64_t edit_length = units_end - units_start;
1831                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1832                 result = commercials->put_clip(file, edit1->channel,
1833                         track->from_units(edit_start), track->from_units(edit_length));
1834                 video_cache->check_in(asset);
1835                 if( result ) { errmsg = _("db failed"); break; }
1836         }
1837         if( errmsg ) {
1838                 char string[BCTEXTLEN];
1839                 sprintf(string, _("put_commercial: %s"), errmsg);
1840                 MainError::show_error(string);
1841                 undo_commercial();
1842                 result = 1;
1843         }
1844 #endif
1845         return result;
1846 }
1847
1848 void MWindow::stop_playback(int wait)
1849 {
1850         gui->stop_drawing();
1851
1852         cwindow->stop_playback(wait);
1853
1854         for(int i = 0; i < vwindows.size(); i++) {
1855                 VWindow *vwindow = vwindows[i];
1856                 if( !vwindow->is_running() ) continue;
1857                 vwindow->stop_playback(wait);
1858         }
1859         for(int i = 0; i < zwindows.size(); i++) {
1860                 ZWindow *zwindow = zwindows[i];
1861                 if( zwindow->idx < 0 ) continue;
1862                 zwindow->stop_playback(wait);
1863         }
1864 }
1865
1866 void MWindow::stop_transport()
1867 {
1868         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1869 }
1870
1871 void MWindow::undo_before(const char *description, void *creator)
1872 {
1873         undo->update_undo_before(description, creator);
1874 }
1875
1876 void MWindow::undo_after(const char *description, uint32_t load_flags, int changes_made)
1877 {
1878         undo->update_undo_after(description, load_flags, changes_made);
1879 }
1880
1881 void MWindow::beep(double freq, double secs, double gain)
1882 {
1883         if( !beeper ) beeper = new Beeper(this);
1884         beeper->tone(freq, secs, gain);
1885 }
1886
1887 Beeper::Beeper(MWindow *mwindow)
1888  : Thread(1, 0, 0)
1889 {
1890         this->mwindow = mwindow;
1891         audio = new AudioDevice(mwindow);
1892         playing_audio = 0;
1893         interrupted = -1;
1894 }
1895
1896 Beeper::~Beeper()
1897 {
1898         stop(0);
1899         delete audio;
1900 }
1901
1902 void Beeper::run()
1903 {
1904         int channels = 2;
1905         int64_t bfrsz = BEEP_SAMPLE_RATE;
1906         EDL *edl = mwindow->edl;
1907         EDLSession *session = edl->session;
1908         AudioOutConfig *aconfig = session->playback_config->aconfig;
1909         audio->open_output(aconfig, BEEP_SAMPLE_RATE, bfrsz, channels, 0);
1910         audio->start_playback();
1911
1912         double out0[bfrsz], out1[bfrsz], *out[2] = { out0, out1 };
1913         const double two_pi = 2*M_PI;
1914         int64_t audio_len = BEEP_SAMPLE_RATE * secs;
1915         const double dt = two_pi * freq/BEEP_SAMPLE_RATE;
1916         double th = 0;
1917
1918         audio_pos = 0;
1919         playing_audio = 1;
1920         while( !interrupted ) {
1921                 int len = audio_len - audio_pos;
1922                 if( len <= 0 ) break;
1923                 if( len > bfrsz ) len = bfrsz;
1924                 int k = audio_pos;
1925                 for( int i=0; i<len; ++i,++k,th+=dt ) {
1926                         double t = th - two_pi;
1927                         if( t >= 0 ) th = t;
1928                         out0[i] = out1[i] = sin(th) * gain;
1929                 }
1930                 audio->write_buffer(out, channels, len);
1931                 audio_pos = k;
1932         }
1933
1934         if( !interrupted )
1935                 audio->set_last_buffer();
1936         audio->stop_audio(interrupted ? 0 : 1);
1937         playing_audio = 0;
1938
1939         audio->close_all();
1940 }
1941
1942 void Beeper::start()
1943 {
1944         if( running() ) return;
1945         audio_pos = -1;
1946         interrupted = 0;
1947         Thread::start();
1948 }
1949
1950 void Beeper::stop(int wait)
1951 {
1952         if( running() && !interrupted ) {
1953                 interrupted = 1;
1954                 audio->stop_audio(wait);
1955         }
1956         Thread::join();
1957 }
1958
1959 void Beeper::tone(double freq, double secs, double gain)
1960 {
1961         stop(0);
1962         this->freq = freq;
1963         this->secs = secs;
1964         this->gain = gain;
1965         start();
1966 }
1967
1968
1969 int MWindow::load_filenames(ArrayList<char*> *filenames,
1970                 int load_mode, int edl_mode, int update_filename)
1971 {
1972         ArrayList<EDL*> new_edls;
1973         ArrayList<Asset*> new_assets;
1974         ArrayList<File*> new_files;
1975
1976 //      save_defaults();
1977         gui->start_hourglass();
1978
1979 // Need to stop playback since tracking depends on the EDL not getting
1980 // deleted.
1981         gui->unlock_window();
1982         stop_playback(1);
1983         gui->lock_window("MWindow::load_filenames 0");
1984         undo_before();
1985
1986 const int debug = 0;
1987 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1988
1989 // Define new_edls and new_assets to load
1990         int result = 0, ftype = -1;
1991
1992         for( int i=0; i<filenames->size(); ++i ) {
1993 // Get type of file
1994                 File *new_file = new File;
1995                 Asset *new_asset = new Asset(filenames->get(i));
1996                 EDL *new_edl = new EDL;
1997                 new_edl->create_objects();
1998                 new_edl->copy_session(edl, -1);
1999                 new_file->set_program(edl->session->program_no);
2000
2001                 char string[BCTEXTLEN];
2002                 sprintf(string, _("Loading %s"), new_asset->path);
2003                 gui->show_message(string);
2004
2005                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
2006
2007                 result = 1;
2008                 switch( ftype ) {
2009 // Convert media file to EDL
2010                 case FILE_OK: {
2011 // Warn about odd image dimensions
2012                         if( new_asset->video_data &&
2013                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
2014                                 eprintf(_("%s's resolution is %dx%d.\n"
2015                                         "Images with odd dimensions may not decode properly."),
2016                                         new_asset->path, new_asset->width, new_asset->height);
2017                         }
2018
2019                         if( new_asset->program >= 0 &&
2020                             edl->session->program_no != new_asset->program ) {
2021                                 eprintf(_("%s's index was built for program number %d\n"
2022                                         "Playback preference is %d.\n  Using program %d."),
2023                                         new_asset->path, new_asset->program,
2024                                         edl->session->program_no, new_asset->program);
2025                         }
2026
2027                         if( load_mode == LOADMODE_RESOURCESONLY ) {
2028                                 new_assets.append(new_asset);
2029                                 new_asset->add_user();
2030                                 result = 0;
2031                                 break;
2032                         }
2033
2034                         RecordLabels *labels = edl->session->label_cells ?
2035                                 new RecordLabels(new_file) : 0;
2036                         asset_to_edl(new_edl, new_asset, labels);
2037                         new_edls.append(new_edl);
2038                         new_edl->add_user();
2039                         delete labels;
2040
2041                         if( load_mode == LOADMODE_REPLACE ||
2042                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2043 // Set filename to nothing for assets since save EDL would overwrite them.
2044                                 set_filename("");
2045 // Reset timeline position
2046                                 for( int i=0; i<TOTAL_PANES; ++i ) {
2047                                         new_edl->local_session->view_start[i] = 0;
2048                                         new_edl->local_session->track_start[i] = 0;
2049                                 }
2050                         }
2051                         result = 0;
2052                         break; }
2053
2054                 case FILE_NOT_FOUND: {
2055                         eprintf(_("Failed to open %s"), new_asset->path);
2056                         sprintf(string, _("Failed to open %s"), new_asset->path);
2057                         gui->show_message(string, theme->message_error);
2058                         gui->update_default_message();
2059                         break; }
2060
2061 // Unknown format
2062                 case FILE_UNRECOGNIZED_CODEC: {
2063 // Test index file
2064                         { IndexFile indexfile(this, new_asset);
2065                         if( !(result = indexfile.open_index()) )
2066                                 indexfile.close_index(); }
2067
2068 // Test existing EDLs
2069                         for( int j=0; result && j<new_edls.total; ++j ) {
2070                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
2071                                 if( old_asset ) {
2072                                         new_asset->copy_from(old_asset,1);
2073                                         result = 0;
2074                                 }
2075                         }
2076                         if( result ) {
2077                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
2078                                 if( old_asset ) {
2079                                         new_asset->copy_from(old_asset,1);
2080                                         result = 0;
2081                                 }
2082                         }
2083
2084 // Prompt user
2085                         if( result ) {
2086                                 new_asset->audio_data = 1;
2087                                 new_asset->format = FILE_PCM;
2088                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
2089                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
2090                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
2091                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
2092                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
2093                                 new_asset->header = defaults->get("HEADER", 0);
2094
2095                                 FileSystem fs;
2096                                 fs.extract_name(string, new_asset->path);
2097                                 strcat(string, _("'s format couldn't be determined."));
2098                                 FileFormat fwindow(this);
2099                                 fwindow.create_objects(new_asset, string);
2100                                 result = fwindow.run_window();
2101
2102                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
2103                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
2104                                 defaults->update("AUDIO_BITS", new_asset->bits);
2105                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
2106                                 defaults->update("SIGNED_", new_asset->signed_);
2107                                 defaults->update("HEADER", new_asset->header);
2108                                 save_defaults();
2109                         }
2110 // Append to list
2111                         if( !result ) {
2112 // Recalculate length
2113                                 delete new_file;
2114                                 new_file = new File;
2115                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2116
2117                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
2118                                         RecordLabels *labels = edl->session->label_cells ?
2119                                                 new RecordLabels(new_file) : 0;
2120                                         asset_to_edl(new_edl, new_asset, labels);
2121                                         new_edls.append(new_edl);
2122                                         new_edl->add_user();
2123                                         delete labels;
2124                                 }
2125                                 else {
2126                                         new_assets.append(new_asset);
2127                                         new_asset->add_user();
2128                                 }
2129                         }
2130                         break; }
2131
2132                 case FILE_IS_XML: {
2133                         FileXML xml_file;
2134                         const char *filename = filenames->get(i);
2135                         if( xml_file.read_from_file(filename, 1) ) {
2136                                 eprintf(_("Error: unable to open:\n  %s"), filename);
2137                                 break;
2138                         }
2139                         const char *cin_version = 0;
2140                         while( !xml_file.read_tag() ) {
2141                                 if( xml_file.tag.title_is("EDL") ) {
2142                                         cin_version = xml_file.tag.get_property("VERSION");
2143                                         break;
2144                                 }
2145                         }
2146                         xml_file.rewind();
2147                         if( !cin_version ) {
2148                                 eprintf(_("XML file %s\n not from cinelerra."),filename);
2149                                 char string[BCTEXTLEN];
2150                                 sprintf(string,_("Unknown %s"), filename);
2151                                 gui->show_message(string);
2152                                 break;
2153                         }
2154                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2155                             strcmp(cin_version, "Unify") &&
2156                             strcmp(cin_version, "5.1") ) {
2157                                 eprintf(_("Warning: XML from cinelerra version %s\n"
2158                                         "Session data may be incompatible."), cin_version);
2159                         }
2160                         if( new_edl->load_xml(&xml_file, LOAD_ALL) ) {
2161                                 eprintf(_("Error: unable to load:\n  %s"), filename);
2162                                 break;
2163                         }
2164                         test_plugins(new_edl, filename);
2165                         int groups = new_edl->regroup(session->group_number);
2166                         session->group_number += groups;
2167                         switch( edl_mode ) {
2168                         case LOADMODE_EDL_CLIP: {
2169                                 strcpy(new_edl->local_session->clip_title,
2170                                         filenames->get(i));
2171                                 struct stat st;
2172                                 time_t t = !stat(filenames->get(i),&st) ?
2173                                         st.st_mtime : time(&t);
2174                                 ctime_r(&t, new_edl->local_session->clip_notes);
2175                                 switch( load_mode ) {
2176                                 case LOADMODE_REPLACE:
2177                                 case LOADMODE_REPLACE_CONCATENATE:
2178                                         strcpy(session->filename, filename);
2179                                         if( update_filename ) set_filename(filename);
2180                                         break;
2181                                 }
2182                                 result = 0;
2183                                 break; }
2184                         case LOADMODE_EDL_NESTED: {
2185                                 EDL *nested_edl = new EDL;
2186                                 nested_edl->create_objects();
2187                                 nested_edl->copy_session(edl, -1);
2188                                 nested_edl->create_nested(new_edl);
2189                                 nested_edl->set_path(filename);
2190                                 new_edl->remove_user();
2191                                 new_edl = nested_edl;
2192                                 result = 0;
2193                                 break; }
2194                         case LOADMODE_EDL_FILEREF: {
2195                                 result = create_ref(new_asset, new_edl);
2196                                 if( result ) break;
2197                                 new_assets.append(new_asset);
2198                                 new_asset->add_user();
2199                                 new_edl->remove_user();
2200                                 new_edl = new EDL;
2201                                 new_edl->create_objects();
2202                                 new_edl->copy_session(edl, -1);
2203                                 asset_to_edl(new_edl, new_asset);
2204                                 delete new_file;
2205                                 new_file = new File;
2206                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2207                                 break; }
2208                         }
2209                         if( !result ) {
2210                                 new_edls.append(new_edl);
2211                                 new_edl->add_user();
2212                         }
2213                         else
2214                                 eprintf(_("Error: Unable to load xml:\n  %s"), new_asset->path);
2215                         break; }
2216                 }
2217
2218                 new_edl->Garbage::remove_user();
2219                 new_asset->Garbage::remove_user();
2220
2221 // Store for testing index
2222                 new_files.append(new_file);
2223         }
2224
2225 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2226
2227         if(!result) {
2228                 gui->reset_default_message();
2229                 gui->default_message();
2230         }
2231
2232 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2233
2234 // Paste them.
2235 // Don't back up here.
2236         if( new_edls.size() ) {
2237 // For pasting, clear the active region
2238                 if( load_mode == LOADMODE_PASTE ) {
2239                         double start = edl->local_session->get_selectionstart();
2240                         double end = edl->local_session->get_selectionend();
2241                         if(!EQUIV(start, end))
2242                                 edl->clear(start, end,
2243                                         edl->session->labels_follow_edits,
2244                                         edl->session->plugins_follow_edits,
2245                                         edl->session->autos_follow_edits);
2246
2247                         paste_edls(&new_edls, load_mode, 0, -1,
2248                                 edl->session->labels_follow_edits,
2249                                 edl->session->plugins_follow_edits,
2250                                 edl->session->autos_follow_edits,
2251                                 0); // overwrite
2252                 }
2253                 else if( load_mode == LOADMODE_NEW_TRACKS &&
2254                          edl_mode != LOADMODE_EDL_CLIP )
2255                         paste_edls(&new_edls, load_mode, 0, -1, 0, 0, 0, 0);
2256                 else if( load_mode != LOADMODE_RESOURCESONLY ||
2257                          edl_mode == LOADMODE_EDL_CLIP )
2258                         paste_edls(&new_edls, load_mode, 0, -1, 1, 1, 1, 0);
2259                 else
2260                         paste_edls(&new_edls, LOADMODE_NOTHING, 0, -1, 0, 0, 0, 0);
2261
2262         }
2263
2264 // Add new assets to EDL and schedule assets for index building.
2265         int got_indexes = 0;
2266         for( int i=0; i<new_edls.size(); ++i ) {
2267                 EDL *new_edl = new_edls[i];
2268                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2269                         mainindexes->add_indexable(new_edl->nested_edls[j]);
2270                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2271                         got_indexes = 1;
2272                 }
2273
2274         }
2275
2276         for( int i=0; i<new_assets.size(); ++i ) {
2277                 Asset *new_asset = new_assets[i];
2278                 mainindexes->add_indexable(new_asset);
2279                 edl->assets->update(new_asset);
2280                 got_indexes = 1;
2281         }
2282
2283 // Start examining next batch of index files
2284         if(got_indexes) mainindexes->start_build();
2285
2286 // Open plugin GUIs
2287         show_plugins();
2288
2289         // opening new session
2290         if( ( load_mode == LOADMODE_REPLACE ||
2291               load_mode == LOADMODE_REPLACE_CONCATENATE ) &&
2292             (ftype != FILE_IS_XML || edl_mode != LOADMODE_EDL_CLIP) ) {
2293                 select_asset(0, 0);
2294                 edl->session->proxy_scale = 1;
2295                 edl->session->proxy_disabled_scale = 1;
2296                 edl->session->proxy_use_scaler = 0;
2297                 edl->session->proxy_auto_scale = 0;
2298                 edl->session->proxy_beep = 0;
2299                 edl->local_session->preview_start = 0;
2300                 edl->local_session->preview_end = -1;
2301                 edl->local_session->loop_playback = 0;
2302                 edl->local_session->set_selectionstart(0);
2303                 edl->local_session->set_selectionend(0);
2304                 edl->local_session->unset_inpoint();
2305                 edl->local_session-> unset_outpoint();
2306                 set_brender_active(0, 0);
2307                 fit_selection();
2308                 goto_start();
2309         }
2310
2311         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2312             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2313                 ArrayList<Indexable *> orig_idxbls;
2314                 for( int i=0; i<new_assets.size(); ++i )
2315                         orig_idxbls.append(new_assets.get(i));
2316                 for( int i=0; i<new_edls.size(); ++i ) {
2317                         EDL *new_edl = new_edls[i];
2318                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2319                                 if( track->data_type != TRACK_VIDEO ) continue;
2320                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2321                                         Indexable *idxbl = (Indexable *)edit->asset;
2322                                         if( !idxbl ) continue;
2323                                         if( !idxbl->have_video() ) continue;
2324                                         if( edit->channel != 0 ) continue; // first layer only
2325                                         orig_idxbls.append(edit->asset);
2326                                 }
2327                         }
2328                 }
2329                 gui->unlock_window(); // to update progress bar
2330                 int ret = render_proxy(orig_idxbls);
2331                 gui->lock_window("MWindow::load_filenames");
2332                 float gain = edl->session->proxy_beep;
2333                 if( ret >= 0 && gain > 0 ) {
2334                         if( ret > 0 )
2335                                 beep(2000., 1.5, gain);
2336                         else
2337                                 beep(4000., 0.25, gain);
2338                 }
2339         }
2340
2341 // need to update undo before project, since mwindow is unlocked & a new load
2342 // can begin here.  Should really prevent loading until we're done.
2343 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2344         undo_after(_("load"), LOAD_ALL);
2345
2346         for(int i = 0; i < new_edls.size(); i++)
2347         {
2348                 new_edls[i]->remove_user();
2349         }
2350 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2351
2352         new_edls.remove_all();
2353
2354         for(int i = 0; i < new_assets.size(); i++)
2355         {
2356                 new_assets[i]->Garbage::remove_user();
2357         }
2358
2359         new_assets.remove_all();
2360         new_files.remove_all_objects();
2361
2362
2363 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2364         if(load_mode == LOADMODE_REPLACE ||
2365                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2366         {
2367                 session->changes_made = 0;
2368         }
2369         else
2370         {
2371                 session->changes_made = 1;
2372         }
2373
2374         gui->stop_hourglass();
2375
2376
2377 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2378         update_project(load_mode);
2379
2380 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2381
2382         return 0;
2383 }
2384
2385 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2386 {
2387         Asset *format_asset = new Asset;
2388         format_asset->format = FILE_FFMPEG;
2389         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2390         int new_scale = edl->session->proxy_scale;
2391         ProxyRender proxy_render(this, format_asset, new_scale);
2392
2393         for( int i=0; i<new_idxbls.size(); ++i ) {
2394                 Indexable *orig = new_idxbls.get(i);
2395                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2396                 if( !proxy ) continue;
2397                 FileSystem fs;
2398                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2399                 int got_it = exists && // if proxy exists, and is newer than orig
2400                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2401                 if( got_it ) continue;
2402                 proxy_render.add_needed(orig, proxy);
2403         }
2404
2405 // render needed proxies
2406         int result = proxy_render.create_needed_proxies(new_scale);
2407         if( !result ) {
2408                 add_proxy(&proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2409         }
2410         format_asset->remove_user();
2411         return !result ? proxy_render.needed_proxies.size() : -1;
2412 }
2413
2414 int MWindow::enable_proxy()
2415 {
2416         int ret = 0;
2417         if( edl->session->proxy_scale == 1 &&
2418             edl->session->proxy_disabled_scale != 1 ) {
2419                 int new_scale = edl->session->proxy_disabled_scale;
2420                 int new_use_scaler = edl->session->proxy_use_scaler;
2421                 Asset *asset = new Asset;
2422                 asset->format = FILE_FFMPEG;
2423                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2424                 ret = to_proxy(asset, new_scale, new_use_scaler);
2425                 asset->remove_user();
2426                 if( ret > 0 ) {
2427                         float gain = edl->session->proxy_beep;
2428                         beep(2000., 1.5, gain);
2429                 }
2430                 edl->session->proxy_disabled_scale = 1;
2431                 gui->lock_window("MWindow::to_proxy");
2432                 update_project(LOADMODE_REPLACE);
2433                 gui->unlock_window();
2434         }
2435         return 1;
2436 }
2437
2438 int MWindow::disable_proxy()
2439 {
2440         if( edl->session->proxy_scale != 1 &&
2441             edl->session->proxy_disabled_scale == 1 ) {
2442                 int old_scale = edl->session->proxy_scale, new_scale = 1;
2443                 int new_use_scaler = edl->session->proxy_use_scaler;
2444                 Asset *asset = new Asset;
2445                 asset->format = FILE_FFMPEG;
2446                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2447                 to_proxy(asset, new_scale, new_use_scaler);
2448                 asset->remove_user();
2449                 edl->session->proxy_disabled_scale = old_scale;
2450                 gui->lock_window("MWindow::to_proxy");
2451                 update_project(LOADMODE_REPLACE);
2452                 gui->unlock_window();
2453         }
2454         return 1;
2455 }
2456
2457 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2458 {
2459         ArrayList<Indexable*> orig_idxbls;
2460         ArrayList<Indexable*> proxy_assets;
2461
2462         edl->Garbage::add_user();
2463         save_backup();
2464         undo_before(_("proxy"), this);
2465         int asset_scale = new_scale == 1 ? 0 :
2466                         !new_use_scaler ? 1 : new_scale;
2467         ProxyRender proxy_render(this, asset, asset_scale);
2468
2469 // revert project to original size from current size
2470 // remove all session proxy assets at the at the current proxy_scale
2471         int proxy_scale = edl->session->proxy_scale;
2472
2473         if( proxy_scale > 1 ) {
2474                 Asset *orig_asset = edl->assets->first;
2475                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2476                         char new_path[BCTEXTLEN];
2477                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2478 // test if proxy asset was already added to proxy_assets
2479                         int got_it = 0;
2480                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2481                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2482                         if( got_it ) continue;
2483                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2484                         if( !proxy_asset ) continue;
2485 // add pointer to existing EDL asset if it exists
2486 // EDL won't delete it unless it's the same pointer.
2487                         proxy_assets.append(proxy_asset);
2488                         proxy_asset->add_user();
2489                         orig_idxbls.append(orig_asset);
2490                         orig_asset->add_user();
2491                 }
2492                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2493                         EDL *orig_nested = edl->nested_edls[i];
2494                         char new_path[BCTEXTLEN];
2495                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2496 // test if proxy asset was already added to proxy_assets
2497                         int got_it = 0;
2498                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2499                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2500                         if( got_it ) continue;
2501                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2502                         if( !proxy_nested ) continue;
2503 // add pointer to existing EDL asset if it exists
2504 // EDL won't delete it unless it's the same pointer.
2505                         proxy_assets.append(proxy_nested);
2506                         proxy_nested->add_user();
2507                         orig_idxbls.append(orig_nested);
2508                         orig_nested->add_user();
2509                 }
2510
2511 // convert from the proxy assets to the original assets
2512                 edl->set_proxy(1, 0, &proxy_assets, &orig_idxbls);
2513
2514 // remove the references
2515                 for( int i=0; i<proxy_assets.size(); ++i ) {
2516                         Asset *proxy = (Asset *) proxy_assets[i];
2517                         proxy->width = proxy->actual_width;
2518                         proxy->height = proxy->actual_height;
2519                         proxy->remove_user();
2520                         edl->assets->remove_pointer(proxy);
2521                         proxy->remove_user();
2522                 }
2523                 proxy_assets.remove_all();
2524                 for( int i = 0; i < orig_idxbls.size(); i++ )
2525                         orig_idxbls[i]->remove_user();
2526                 orig_idxbls.remove_all();
2527         }
2528
2529         ArrayList<char *> confirm_paths;    // test for new files
2530         confirm_paths.set_array_delete();
2531
2532 // convert to new size if not original size
2533         if( new_scale != 1 ) {
2534                 FileSystem fs;
2535                 Asset *orig = edl->assets->first;
2536                 for( ; orig; orig=orig->next ) {
2537                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2538                         if( !proxy ) continue;
2539                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2540                         int got_it = exists && // if proxy exists, and is newer than orig
2541                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2542                         if( !got_it ) {
2543                                 if( exists ) // prompt user to overwrite
2544                                         confirm_paths.append(cstrdup(proxy->path));
2545                                 proxy_render.add_needed(orig, proxy);
2546                         }
2547                 }
2548                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2549                         EDL *orig_nested = edl->nested_edls[i];
2550                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2551                         if( !proxy ) continue;
2552                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2553                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2554                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2555                         if( !got_it ) {
2556                                 if( exists ) // prompt user to overwrite
2557                                         confirm_paths.append(cstrdup(proxy->path));
2558                                 proxy_render.add_needed(orig_nested, proxy);
2559                         }
2560                 }
2561         }
2562
2563         int result = 0;
2564 // test for existing files
2565         if( confirm_paths.size() ) {
2566                 result = ConfirmSave::test_files(this, &confirm_paths);
2567                 confirm_paths.remove_all_objects();
2568         }
2569
2570         if( !result )
2571                 result = proxy_render.create_needed_proxies(new_scale);
2572
2573         if( !result ) // resize project
2574                 edl->set_proxy(new_scale, new_use_scaler,
2575                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2576
2577         undo_after(_("proxy"), LOAD_ALL);
2578         edl->Garbage::remove_user();
2579         restart_brender();
2580
2581         return !result ? proxy_render.needed_proxies.size() : -1;
2582 }
2583
2584 void MWindow::test_plugins(EDL *new_edl, const char *path)
2585 {
2586         char string[BCTEXTLEN];
2587
2588 // Do a check whether plugins exist
2589         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2590                 for( int k=0; k<track->plugin_set.total; ++k ) {
2591                         PluginSet *plugin_set = track->plugin_set[k];
2592                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2593                                         plugin; plugin = (Plugin*)plugin->next ) {
2594                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2595 // ok we need to find it in plugindb
2596                                 PluginServer *server =
2597                                         scan_plugindb(plugin->title, track->data_type);
2598                                 if( !server || server->transition ) {
2599                                         sprintf(string,
2600         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2601           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2602                                                 "effect", _(plugin->title), path);
2603                                         MainError::show_error(string);
2604                                 }
2605                         }
2606                 }
2607
2608                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2609                         if( !edit->transition ) continue;
2610 // ok we need to find transition in plugindb
2611                         PluginServer *server =
2612                                 scan_plugindb(edit->transition->title, track->data_type);
2613                         if( !server || !server->transition ) {
2614                                 sprintf(string,
2615         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2616           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2617                                         "transition", _(edit->transition->title), path);
2618                                 MainError::show_error(string);
2619                         }
2620                 }
2621         }
2622 }
2623
2624
2625 void MWindow::init_shm(const char *pfn, int64_t min)
2626 {
2627         int64_t result = 0;
2628 // Fix shared memory
2629         FILE *fd = fopen(pfn, "r");
2630         if( fd ) {
2631                 fscanf(fd, "%jd", &result);
2632                 fclose(fd);
2633                 if( result >= min ) return;
2634         }
2635
2636         fd = fopen(pfn, "w");
2637         if( !fd ) return;
2638         fprintf(fd, "0x%jx", min);
2639         fclose(fd);
2640
2641         fd = fopen(pfn, "r");
2642         if( !fd ) {
2643                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2644                 return;
2645         }
2646
2647         fscanf(fd, "%jd", &result);
2648         fclose(fd);
2649         if( result < min ) {
2650                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2651                         "you probably need to be root, or:\n"
2652                         "as root, run: echo 0x%jx > %s\n"
2653                         "before trying to start cinelerra.\n"
2654                         "It should be at least 0x%jx for Cinelerra.\n"),
2655                         pfn, (void *)result, min, pfn, min);
2656         }
2657 }
2658
2659 void MWindow::create_objects(int want_gui,
2660         int want_new,
2661         char *config_path)
2662 {
2663         const int debug = 0;
2664         if(debug) PRINT_TRACE
2665
2666 // For some reason, init_signals must come after show_splash or the signals won't
2667 // get trapped.
2668         init_signals();
2669         if(debug) PRINT_TRACE
2670         init_3d();
2671
2672         if(debug) PRINT_TRACE
2673         show_splash();
2674
2675         if(debug) PRINT_TRACE
2676         default_standard = default_std();
2677         init_defaults(defaults, config_path);
2678         check_language();
2679         init_preferences();
2680         if(splash_window)
2681                 splash_window->update_status(_("Initializing Plugins"));
2682         init_plugins(this, preferences);
2683         if(debug) PRINT_TRACE
2684         init_ladspa_plugins(this, preferences);
2685         if(debug) PRINT_TRACE
2686         init_plugin_tips(*plugindb, cin_lang);
2687         if(splash_window)
2688                 splash_window->update_status(_("Initializing GUI"));
2689         if(debug) PRINT_TRACE
2690         init_theme();
2691
2692         if(debug) PRINT_TRACE
2693         init_error();
2694
2695         if(splash_window)
2696                 splash_window->update_status(_("Initializing Fonts"));
2697         char string[BCTEXTLEN];
2698         strcpy(string, preferences->plugin_dir);
2699         strcat(string, "/" FONT_SEARCHPATH);
2700         BC_Resources::init_fontconfig(string);
2701         if(debug) PRINT_TRACE
2702 // use if plugged
2703         init_x10tv();
2704         if( !x10tv )
2705                 init_wintv();
2706
2707 // Default project created here
2708         init_edl();
2709         if(debug) PRINT_TRACE
2710
2711         init_cache();
2712         if(debug) PRINT_TRACE
2713
2714         Timer timer;
2715
2716         init_awindow();
2717         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2718
2719         init_compositor();
2720         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2721
2722 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2723         if(session->show_vwindow)
2724                 get_viewer(1, DEFAULT_VWINDOW);
2725         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2726
2727         init_gui();
2728         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2729
2730         init_levelwindow();
2731         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2732
2733         init_indexes();
2734         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2735
2736         init_channeldb();
2737         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2738
2739         init_gwindow();
2740         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2741
2742         init_render();
2743         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2744
2745         init_shuttle();
2746         init_brender();
2747         init_exportedl();
2748         init_commercials();
2749         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2750         mainprogress = new MainProgress(this, gui);
2751         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2752         undo = new MainUndo(this);
2753
2754         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2755
2756         plugin_guis = new PluginGUIs(this);
2757         dead_plugins = new ArrayList<PluginServer*>;
2758         keyframe_threads = new ArrayList<KeyFrameThread*>;
2759
2760         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2761                 __LINE__,
2762                 vwindows.size(),
2763                 session->show_vwindow);
2764
2765 // Show all vwindows
2766 //      if(session->show_vwindow) {
2767 //              for(int j = 0; j < vwindows.size(); j++) {
2768 //                      VWindow *vwindow = vwindows[j];
2769 //                      if( !vwindow->is_running() ) continue;
2770 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2771 //                              __LINE__,
2772 //                              vwindow);
2773 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2774 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2775 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2776 //                      vwindow->gui->show_window();
2777 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2778 //                      vwindow->gui->unlock_window();
2779 //              }
2780 //      }
2781
2782
2783         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2784
2785         if(session->show_cwindow)
2786         {
2787                 cwindow->gui->lock_window("MWindow::create_objects 1");
2788                 cwindow->gui->show_window();
2789                 cwindow->gui->unlock_window();
2790         }
2791
2792         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2793         if(session->show_awindow)
2794         {
2795                 awindow->gui->lock_window("MWindow::create_objects 1");
2796                 awindow->gui->show_window();
2797                 awindow->gui->unlock_window();
2798         }
2799
2800         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2801         if(session->show_lwindow)
2802         {
2803                 lwindow->gui->lock_window("MWindow::create_objects 1");
2804                 lwindow->gui->show_window();
2805                 lwindow->gui->unlock_window();
2806         }
2807
2808         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2809                 __LINE__,
2810                 (int)timer.get_difference(),
2811                 gwindow->gui);
2812         if(session->show_gwindow)
2813         {
2814                 gwindow->gui->lock_window("MWindow::create_objects 1");
2815                 gwindow->gui->show_window();
2816                 gwindow->gui->unlock_window();
2817         }
2818
2819         if(debug) PRINT_TRACE
2820
2821         gui->lock_window("MWindow::create_objects 1");
2822         gui->mainmenu->load_defaults(defaults);
2823         gui->mainmenu->update_toggles(0);
2824         gui->update_patchbay();
2825         gui->draw_canvas(0, 0);
2826         gui->draw_cursor(1);
2827         gui->show_window();
2828         gui->raise_window();
2829         gui->unlock_window();
2830         cwindow->gui->lock_window("MWindow::create_objects 1");
2831         cwindow->gui->tool_panel->raise_tool();
2832         cwindow->gui->unlock_window();
2833         if(debug) PRINT_TRACE
2834
2835         if(preferences->use_tipwindow)
2836                 init_tipwindow();
2837         if(debug) PRINT_TRACE
2838
2839         gui->add_keyboard_listener(
2840                 (int (BC_WindowBase::*)(BC_WindowBase *))
2841                 &MWindowGUI::keyboard_listener);
2842
2843         hide_splash();
2844         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2845         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2846         if(debug) PRINT_TRACE
2847
2848         BC_WindowBase::get_resources()->vframe_shm = 1;
2849 }
2850
2851 int MWindow::uses_opengl()
2852 {
2853         if( !playback_3d || !playback_3d->running() ) return 0;
2854         PlaybackConfig *playback_config = edl->session->playback_config;
2855         return playback_config->vconfig->driver == PLAYBACK_X11_GL ? 1 : 0;
2856 }
2857
2858 void MWindow::show_splash()
2859 {
2860 #include "data/heroine_logo9_png.h"
2861         VFrame *frame = new VFramePng(heroine_logo9_png);
2862         BC_DisplayInfo dpyi;
2863         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2864         int rr = (rw < rh ? rw : rh) / 4;
2865         splash_window = new SplashGUI(frame, rr, rr);
2866         splash_window->create_objects();
2867 }
2868
2869 void MWindow::hide_splash()
2870 {
2871         if(splash_window)
2872                 delete splash_window;
2873         splash_window = 0;
2874 }
2875
2876
2877 void MWindow::start()
2878 {
2879 ENABLE_BUFFER
2880 //PRINT_TRACE
2881 //      vwindows[DEFAULT_VWINDOW]->start();
2882         awindow->start();
2883 //PRINT_TRACE
2884         cwindow->start();
2885 //PRINT_TRACE
2886         lwindow->start();
2887 //PRINT_TRACE
2888         gwindow->start();
2889 //PRINT_TRACE
2890 //      Thread::start();
2891 //PRINT_TRACE
2892         playback_3d->start();
2893 //PRINT_TRACE
2894 }
2895
2896 void MWindow::run()
2897 {
2898         run_lock->lock("MWindow::run");
2899         gui->run_window();
2900         stop_playback(1);
2901
2902         brender_lock->lock("MWindow::run 1");
2903         delete brender;         brender = 0;
2904         brender_lock->unlock();
2905
2906         interrupt_indexes();
2907         clean_indexes();
2908         save_defaults();
2909         run_lock->unlock();
2910 }
2911
2912 void MWindow::show_vwindow()
2913 {
2914         int total_running = 0;
2915         session->show_vwindow = 1;
2916
2917 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2918 // Raise all windows which are visible
2919         for(int j = 0; j < vwindows.size(); j++) {
2920                 VWindow *vwindow = vwindows[j];
2921                 if( !vwindow->is_running() ) continue;
2922                 vwindow->gui->lock_window("MWindow::show_vwindow");
2923                 vwindow->gui->show_window(0);
2924                 vwindow->gui->raise_window();
2925                 vwindow->gui->flush();
2926                 vwindow->gui->unlock_window();
2927                 total_running++;
2928         }
2929
2930 // If no windows visible
2931         if(!total_running)
2932         {
2933                 get_viewer(1, DEFAULT_VWINDOW);
2934         }
2935
2936         gui->mainmenu->show_vwindow->set_checked(1);
2937 }
2938
2939 void MWindow::show_awindow()
2940 {
2941         session->show_awindow = 1;
2942         awindow->gui->lock_window("MWindow::show_awindow");
2943         awindow->gui->show_window();
2944         awindow->gui->raise_window();
2945         awindow->gui->flush();
2946         awindow->gui->unlock_window();
2947         gui->mainmenu->show_awindow->set_checked(1);
2948 }
2949
2950 char *MWindow::get_cwindow_display()
2951 {
2952         char *x11_host = screens < 2 || session->window_config == 0 ?
2953                 session->a_x11_host : session->b_x11_host;
2954         return *x11_host ? x11_host : 0;
2955 }
2956
2957 void MWindow::show_cwindow()
2958 {
2959         session->show_cwindow = 1;
2960         cwindow->show_window();
2961         gui->mainmenu->show_cwindow->set_checked(1);
2962 }
2963
2964 void MWindow::show_gwindow()
2965 {
2966         session->show_gwindow = 1;
2967
2968         gwindow->gui->lock_window("MWindow::show_gwindow");
2969         gwindow->gui->show_window();
2970         gwindow->gui->raise_window();
2971         gwindow->gui->flush();
2972         gwindow->gui->unlock_window();
2973
2974         gui->mainmenu->show_gwindow->set_checked(1);
2975 }
2976 void MWindow::hide_gwindow()
2977 {
2978         session->show_gwindow = 0;
2979
2980         gwindow->gui->lock_window("MWindow::show_gwindow");
2981         gwindow->gui->hide_window();
2982         gwindow->gui->unlock_window();
2983 }
2984
2985 void MWindow::show_lwindow()
2986 {
2987         session->show_lwindow = 1;
2988         lwindow->gui->lock_window("MWindow::show_lwindow");
2989         lwindow->gui->show_window();
2990         lwindow->gui->raise_window();
2991         lwindow->gui->flush();
2992         lwindow->gui->unlock_window();
2993         gui->mainmenu->show_lwindow->set_checked(1);
2994 }
2995
2996 void MWindow::restore_windows()
2997 {
2998         gui->unlock_window();
2999         if( !session->show_vwindow ) {
3000                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
3001                         VWindow *vwindow = vwindows[i];
3002                         if( !vwindow || !vwindow->is_running() ) continue;
3003                         vwindow->gui->lock_window("MWindow::restore_windows");
3004                         vwindow->gui->close(1);
3005                         vwindow->gui->unlock_window();
3006                 }
3007         }
3008         else
3009                 show_vwindow();
3010
3011         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
3012                 awindow->gui->lock_window("MWindow::restore_windows");
3013                 awindow->gui->close_event();
3014                 awindow->gui->unlock_window();
3015         }
3016         else if( session->show_awindow && awindow->gui->is_hidden() )
3017                 show_awindow();
3018
3019         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
3020                 cwindow->gui->lock_window("MWindow::restore_windows");
3021                 cwindow->hide_window();
3022                 cwindow->gui->unlock_window();
3023         }
3024         else if( session->show_cwindow && cwindow->gui->is_hidden() )
3025                 cwindow->show_window();
3026
3027         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
3028                 gwindow->gui->lock_window("MWindow::restore_windows");
3029                 gwindow->gui->close_event();
3030                 gwindow->gui->unlock_window();
3031         }
3032         else if( session->show_gwindow && gwindow->gui->is_hidden() )
3033                 show_gwindow();
3034
3035         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
3036                 lwindow->gui->lock_window("MWindow::restore_windows");
3037                 lwindow->gui->close_event();
3038                 lwindow->gui->unlock_window();
3039         }
3040         else if( session->show_lwindow && lwindow->gui->is_hidden() )
3041                 show_lwindow();
3042
3043         gui->lock_window("MWindow::restore_windows");
3044         gui->focus();
3045 }
3046
3047 void MWindow::load_layout(const char *layout)
3048 {
3049         char path[BCTEXTLEN];
3050         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3051         session->load_file(path);
3052         restore_windows();
3053         gui->default_positions();
3054         save_defaults();
3055 }
3056
3057 void MWindow::save_layout(const char *layout)
3058 {
3059         char path[BCTEXTLEN];
3060         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3061         session->save_file(path);
3062 }
3063
3064 void MWindow::delete_layout(const char *layout)
3065 {
3066         char path[BCTEXTLEN];
3067         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3068         unlink(path);
3069 }
3070
3071 int MWindow::tile_windows(int window_config)
3072 {
3073         int need_reload = 0;
3074         int play_config = window_config==0 ? 0 : 1;
3075         edl->session->playback_config->load_defaults(defaults, play_config);
3076         session->default_window_positions(window_config);
3077         if( screens == 1 ) {
3078                 gui->default_positions();
3079                 sync_parameters(CHANGE_ALL);
3080         }
3081         else
3082                 need_reload = 1;
3083         return need_reload;
3084 }
3085
3086 void MWindow::toggle_loop_playback()
3087 {
3088         edl->local_session->loop_playback = !edl->local_session->loop_playback;
3089         set_loop_boundaries();
3090         save_backup();
3091
3092         gui->draw_overlays(1);
3093         sync_parameters(CHANGE_PARAMS);
3094 }
3095
3096 void MWindow::set_screens(int value)
3097 {
3098         screens = value;
3099 }
3100
3101 void MWindow::set_auto_keyframes(int value)
3102 {
3103         edl->session->auto_keyframes = value;
3104         gui->mbuttons->edit_panel->keyframe->update(value);
3105         gui->flush();
3106         cwindow->gui->lock_window("MWindow::set_auto_keyframes");
3107         cwindow->gui->flush();
3108         cwindow->gui->unlock_window();
3109 }
3110
3111 void MWindow::set_span_keyframes(int value)
3112 {
3113         edl->session->span_keyframes = value;
3114         gui->mbuttons->edit_panel->span_keyframe->update(value);
3115         gui->flush();
3116         cwindow->gui->lock_window("MWindow::set_span_keyframes");
3117         cwindow->gui->flush();
3118         cwindow->gui->unlock_window();
3119 }
3120
3121 void MWindow::set_auto_visibility(Autos *autos, int value)
3122 {
3123         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
3124                 edl->session->auto_conf->plugins = value;
3125         else if( autos->autoidx >= 0 )
3126                 edl->session->auto_conf->autos[autos->autoidx] = value;
3127         else
3128                 return;
3129
3130         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);