Exciting new Alt/h help key provided by sge (Georgy) with many thanks!
[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         clean_backups();
300         save_defaults();
301 // Give up and go to a movie
302 //  cant run valgrind if this is used
303
304         gui->del_keyboard_listener(
305                 (int (BC_WindowBase::*)(BC_WindowBase *))
306                 &MWindowGUI::keyboard_listener);
307         reset_caches(0);
308 #if 0
309 // release the hounds
310         if( awindow && awindow->gui ) awindow->gui->close(0);
311         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
312         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
313         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
314         vwindows.remove_all_objects();
315         zwindows.remove_all_objects();
316         gui->close(0);
317         if( awindow ) awindow->join();
318         if( cwindow ) cwindow->join();
319         if( lwindow ) lwindow->join();
320         if( gwindow ) gwindow->join();
321         join();
322 #else
323 // one at a time, or nouveau chokes
324 #define close_gui(win) if( win ) { \
325   if( win->gui ) win->gui->close(0); \
326   win->join(); }
327         close_gui(awindow);
328         close_gui(cwindow);
329         close_gui(lwindow);
330         close_gui(gwindow);
331         vwindows.remove_all_objects();
332         zwindows.remove_all_objects();
333         gui->close(0);
334         join();
335 #endif
336         dead_plugins->remove_all_objects();
337 // must delete theme before destroying plugindb
338 //  theme destructor will be deleted by delete_plugins
339         delete theme;           theme = 0;
340         delete_plugins();
341         finit_error();
342         keyframe_threads->remove_all_objects();
343         colormodels.remove_all_objects();
344         delete awindow;         awindow = 0;
345         delete lwindow;         lwindow = 0;
346         delete twindow;         twindow = 0;
347         delete wwindow;         wwindow = 0;
348         delete gwindow;         gwindow = 0;
349         delete cwindow;         cwindow = 0;
350         delete gui;             gui = 0;
351         delete mainindexes;     mainindexes = 0;
352         delete mainprogress;    mainprogress = 0;
353  // delete the caches after the assets
354         if( audio_cache ) { audio_cache->remove_user();  audio_cache = 0; }
355         if( video_cache ) { video_cache->remove_user();  video_cache = 0; }
356         delete frame_cache;     frame_cache = 0;
357         delete wave_cache;      wave_cache = 0;
358         delete plugin_guis;     plugin_guis = 0;
359         delete dead_plugins;    dead_plugins = 0;
360         delete keyframe_threads;  keyframe_threads = 0;
361         delete undo;            undo = 0;
362         delete preferences;     preferences = 0;
363         delete exportedl;       exportedl = 0;
364         delete session;         session = 0;
365         delete defaults;        defaults = 0;
366         delete assets;          assets = 0;
367         delete splash_window;   splash_window = 0;
368         if( !edl->Garbage::remove_user() ) edl = 0;
369         delete channeldb_buz;
370         delete channeldb_v4l2jpeg;
371 // This must be last thread to exit
372         delete playback_3d;     playback_3d = 0;
373         delete dead_plugin_lock;
374         delete plugin_gui_lock;
375         delete vwindows_lock;
376         delete zwindows_lock;
377         delete brender_lock;
378         delete keyframe_gui_lock;
379         colormodels.remove_all_objects();
380         interlace_project_modes.remove_all_objects();
381         interlace_asset_modes.remove_all_objects();
382         sighandler->terminate();
383         delete sighandler;
384         delete run_lock;
385 }
386
387
388 void MWindow::quit()
389 {
390         gui->set_done(0);
391 }
392
393 void MWindow::init_error()
394 {
395         MainError::init_error(this);
396 }
397
398 void MWindow::finit_error()
399 {
400         MainError::finit_error();
401 }
402
403 void MWindow::create_defaults_path(char *string, const char *config_file)
404 {
405 // set the .bcast path
406         FileSystem fs;
407
408         sprintf(string, "%s/", File::get_config_path());
409         fs.complete_path(string);
410         if(!fs.is_dir(string))
411                 fs.create_dir(string);
412
413 // load the defaults
414         strcat(string, config_file);
415 }
416 const char *MWindow::default_std()
417 {
418         char buf[BCTEXTLEN], *p = 0;
419
420         int fd = open(TIMEZONE_NAME, O_RDONLY);
421         if( fd >= 0 ) {
422                 int l = read(fd, buf, sizeof(buf)-1);
423                 close(fd);
424                 if( l > 0 ) {
425                         if( buf[l-1] == '\n' ) --l;
426                         buf[l] = 0;
427                         p = buf;
428                 }
429         }
430         if( !p ) {
431                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
432                 if( l > 0 ) {
433                         buf[l] = 0;
434                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
435                         p += strlen(ZONEINFO_STR);
436                 }
437         }
438
439         if( p ) {
440                 for( int i=0; ntsc_zones[i]; ++i ) {
441                         if( !strcmp(ntsc_zones[i], p) )
442                                 return "NTSC";
443                 }
444         }
445
446         p = getenv("TZ");
447         if( p ) {
448                 for( int i=0; ntsc_zones[i]; ++i ) {
449                         if( !strcmp(ntsc_zones[i], p) )
450                                 return "NTSC";
451                 }
452         }
453
454 // cin_timezone: Seconds west of UTC.  240sec/deg
455         double tz_deg =  -cin_timezone / 240.;
456 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
457         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
458 }
459
460 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
461 {
462         struct formatpresets *fpr;
463
464         for(fpr = &format_presets[0]; fpr->name; fpr++)
465         {
466                 if(strcmp(_(fpr->name), preset) == 0)
467                 {
468                         session->audio_channels = fpr->audio_channels;
469                         session->audio_tracks = fpr->audio_tracks;
470                         session->sample_rate = fpr->sample_rate;
471                         session->video_channels = fpr->video_channels;
472                         session->video_tracks = fpr->video_tracks;
473                         session->frame_rate = fpr->frame_rate;
474                         session->output_w = fpr->output_w;
475                         session->output_h = fpr->output_h;
476                         session->aspect_w = fpr->aspect_w;
477                         session->aspect_h = fpr->aspect_h;
478                         session->interlace_mode = fpr->interlace_mode;
479                         session->color_model = fpr->color_model;
480                         return;
481                 }
482         }
483 }
484
485 const char *MWindow::get_preset_name(int index)
486 {
487         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
488                 return "Error";
489         return _(format_presets[index].name);
490 }
491
492
493 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
494 {
495         char path[BCTEXTLEN];
496 // Use user supplied path
497         if(config_path[0])
498                 strcpy(path, config_path);
499         else
500                 create_defaults_path(path, CONFIG_FILE);
501
502         delete defaults;
503         defaults = new BC_Hash(path);
504         defaults->load();
505 }
506
507
508 void MWindow::check_language()
509 {
510         char pref_locale[BCSTRLEN];
511         strcpy(pref_locale, DEFAULT_LOCALE);
512         defaults->get("LOCALE",pref_locale);
513 // set LANGUAGE if pref locale != sys
514         if( strcmp(pref_locale, DEFAULT_LOCALE) )
515                 setenv("LANGUAGE", pref_locale, 1);
516
517         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
518         const char *env_lang = getenv("LANGUAGE");
519         if( !env_lang ) env_lang = getenv("LC_ALL");
520         if( !env_lang ) env_lang = getenv("LANG");
521         if( !env_lang ) {
522                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
523                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
524                 env_lang = curr_lang;
525         }
526         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
527         defaults->get("LAST_LANG",last_lang);
528         if( strcmp(env_lang,last_lang)) {
529                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
530                 defaults->update("LAST_LANG",env_lang);
531                 char plugin_path[BCTEXTLEN];
532                 create_defaults_path(plugin_path, PLUGIN_FILE);
533                 ::remove(plugin_path);
534                 char ladspa_path[BCTEXTLEN];
535                 create_defaults_path(ladspa_path, LADSPA_FILE);
536                 ::remove(ladspa_path);
537                 defaults->save();
538         }
539         if( strlen(env_lang) > 1 &&
540             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
541                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
542         }
543         else
544                 strcpy(cin_lang, "en");
545 }
546
547 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
548 {
549         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
550         if( plug_dir ) {
551                 const char *dp = plug_dir;
552                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
553                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
554         }
555         strcpy(path, bp);
556         delete [] base_path;
557 }
558
559 int MWindow::load_plugin_index(MWindow *mwindow, FILE *fp, const char *plugin_dir)
560 {
561         if( !fp ) return -1;
562 // load index
563         fseek(fp, 0, SEEK_SET);
564         int ret = 0;
565         char index_line[BCTEXTLEN];
566         int index_version = -1, len = strlen(plugin_dir);
567         if( !fgets(index_line, BCTEXTLEN, fp) ||
568             sscanf(index_line, "%d", &index_version) != 1 ||
569             index_version != PLUGIN_FILE_VERSION ||
570             !fgets(index_line, BCTEXTLEN, fp) ||
571             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
572             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
573
574         ArrayList<PluginServer*> plugins;
575         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
576                 if( index_line[0] == ';' ) continue;
577                 if( index_line[0] == '#' ) continue;
578                 int type = PLUGIN_TYPE_UNKNOWN;
579                 char path[BCTEXTLEN], title[BCTEXTLEN];
580                 int64_t mtime = 0;
581                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
582                         ret = 1; continue;
583                 }
584                 PluginServer *server = 0;
585                 switch( type ) {
586                 case PLUGIN_TYPE_BUILTIN:
587                 case PLUGIN_TYPE_EXECUTABLE:
588                 case PLUGIN_TYPE_LADSPA: {
589                         char plugin_path[BCTEXTLEN];  struct stat st;
590                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
591                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
592                                 ret = 1; continue;
593                         }
594                         server = new PluginServer(mwindow, plugin_path, type);
595                         break; }
596                 case PLUGIN_TYPE_FFMPEG: {
597                         server = new_ffmpeg_server(mwindow, path);
598                         break; }
599                 case PLUGIN_TYPE_LV2: {
600                         server = new_lv2_server(mwindow, path);
601                         break; }
602                 }
603                 if( !server ) continue;
604                 plugins.append(server);
605 // Create plugin server from index entry
606                 server->set_title(title);
607                 if( server->read_table(index_line) ) {
608                         ret = 1;  continue;
609                 }
610         }
611
612         if( !ret )
613                 ret = check_plugin_index(plugins, plugin_dir, ".");
614
615         if( !ret )
616                 add_plugins(plugins);
617         else
618                 plugins.remove_all_objects();
619
620         return ret;
621 }
622
623 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
624         const char *plug_dir, const char *plug_path)
625 {
626         char plugin_path[BCTEXTLEN];
627         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
628         FileSystem fs;
629         fs.set_filter( "[*.plugin][*.so]" );
630         if( fs.update(plugin_path) )
631                 return 1;
632
633         for( int i=0; i<fs.dir_list.total; ++i ) {
634                 char fs_path[BCTEXTLEN];
635                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
636                 if( fs.is_dir(fs_path) ) {
637                         get_plugin_path(plugin_path, plug_dir, fs_path);
638                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
639                                 return 1;
640                 }
641                 else if( !plugin_exists(fs_path, plugins) )
642                         return 1;
643         }
644         return 0;
645 }
646
647
648 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
649 {
650         if( !plugindb )
651                 plugindb = new ArrayList<PluginServer*>;
652         init_ffmpeg();
653         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
654         create_defaults_path(index_path, PLUGIN_FILE);
655         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
656         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
657         FILE *fp = fopen(index_path,"a+");
658         if( !fp ) {
659                 fprintf(stderr,_("MWindow::init_plugins: "
660                         "can't open plugin index: %s\n"), index_path);
661                 return -1;
662         }
663         int fd = fileno(fp), ret = -1;
664         if( !flock(fd, LOCK_EX) ) {
665                 fseek(fp, 0, SEEK_SET);
666                 ret = load_plugin_index(mwindow, fp, plugin_path);
667         }
668         if( ret > 0 ) {
669                 ftruncate(fd, 0);
670                 fseek(fp, 0, SEEK_SET);
671                 printf("init plugin index: %s\n", plugin_path);
672                 fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
673                 fprintf(fp, "%s\n", plugin_path);
674                 init_plugin_index(mwindow, preferences, fp, plugin_path);
675                 init_ffmpeg_index(mwindow, preferences, fp);
676                 init_lv2_index(mwindow, preferences, fp);
677                 fseek(fp, 0, SEEK_SET);
678                 ret = load_plugin_index(mwindow, fp, plugin_path);
679         }
680         if( ret ) {
681                 fprintf(stderr,_("MWindow::init_plugins: "
682                         "can't %s plugin index: %s\n"),
683                         ret>0 ? _("create") : _("lock"), index_path);
684         }
685         fclose(fp);
686         return ret;
687 }
688
689 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
690 {
691 #ifdef HAVE_LADSPA
692         char *path = getenv("LADSPA_PATH");
693         char ladspa_path[BCTEXTLEN];
694         if( !path ) {
695                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
696                 path = ladspa_path;
697         }
698         for( int len=0; *path; path+=len ) {
699                 char *cp = strchr(path,':');
700                 len = !cp ? strlen(path) : cp-path;
701                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
702                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
703                 if( cp ) ++len;
704                 char *plugin_dir = FileSystem::basepath(plugin_path);
705                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
706                 create_defaults_path(index_path, LADSPA_FILE);
707                 cp = index_path + strlen(index_path);
708                 for( char *bp=plugin_path; *bp!=0; ++bp )
709                         *cp++ = *bp=='/' ? '_' : *bp;
710                 *cp = 0;
711                 FILE *fp = fopen(index_path,"a+");
712                 if( !fp ) {
713                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
714                                 "can't open ladspa plugin index: %s\n"), index_path);
715                         continue;
716                 }
717                 int fd = fileno(fp), ret = -1;
718                 if( !flock(fd, LOCK_EX) ) {
719                         fseek(fp, 0, SEEK_SET);
720                         ret = load_plugin_index(mwindow, fp, plugin_path);
721                 }
722                 if( ret > 0 ) {
723                         ftruncate(fd, 0);
724                         fseek(fp, 0, SEEK_SET);
725                         init_ladspa_index(mwindow, preferences, fp, plugin_path);
726                         fseek(fp, 0, SEEK_SET);
727                         ret = load_plugin_index(mwindow, fp, plugin_path);
728                 }
729                 if( ret ) {
730                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
731                                 "can't %s ladspa plugin index: %s\n"),
732                                 ret>0 ? _("create") : _("lock"), index_path);
733                 }
734                 fclose(fp);
735         }
736 #endif
737         return 1;
738 }
739
740 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
741         FILE *fp, const char *plugin_dir)
742 {
743         int idx = PLUGIN_IDS;
744         if( plugindb ) {
745                 for( int i=0; i<plugindb->size(); ++i ) {
746                         PluginServer *server = plugindb->get(i);
747                         if( server->dir_idx >= idx )
748                                 idx = server->dir_idx+1;
749                 }
750         }
751         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
752 }
753
754 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
755         const char *plug_dir, const char *plug_path, int &idx)
756 {
757         char plugin_path[BCTEXTLEN];
758         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
759         FileSystem fs;
760         fs.set_filter( "[*.plugin][*.so][*.dll]" );
761         int result = fs.update(plugin_path);
762         if( result || !fs.dir_list.total ) return;
763         int vis_id = idx++;
764
765         for( int i=0; i<fs.dir_list.total; ++i ) {
766                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
767                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
768                 get_plugin_path(path, plug_dir, fs_path);
769                 if( fs.is_dir(fs_path) ) {
770                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
771                         continue;
772                 }
773                 if( plugin_exists(path) ) continue;
774                 struct stat st;
775                 if( stat(fs_path, &st) ) continue;
776                 int64_t mtime = st.st_mtime;
777                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
778                 result = server.open_plugin(1, preferences, 0, 0);
779                 if( !result ) {
780                         server.write_table(fp, path, vis_id, mtime);
781                         server.close_plugin();
782                 }
783                 else if( result == PLUGINSERVER_IS_LAD ) {
784                         int lad_index = 0;
785                         for(;;) {
786                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
787                                 ladspa.set_lad_index(lad_index++);
788                                 result = ladspa.open_plugin(1, preferences, 0, 0);
789                                 if( result ) break;
790                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
791                                 ladspa.close_plugin();
792                         }
793                 }
794         }
795 }
796
797 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
798 {
799         for( int i=0; i<plugins.size(); ++i )
800                 plugindb->append(plugins[i]);
801         plugins.remove_all();
802 }
803
804 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
805 {
806         const char *dat_path = File::get_cindat_path();
807         char msg_path[BCTEXTLEN];
808         FILE *fp = 0;
809         if( BC_Resources::language[0] ) {
810                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
811                         dat_path, lang);
812                 fp = fopen(msg_path, "r");
813         }
814         if( !fp ) {
815                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
816                         dat_path);
817                 fp = fopen(msg_path, "r");
818         }
819         if( !fp ) return;
820         char text[BCTEXTLEN];
821         char *tp = text, *ep = tp + sizeof(text)-1;
822         char title[BCTEXTLEN];
823         title[0] = 0;
824         int no = 0;
825         for(;;) {
826                 ++no;  int done = 1;
827                 char line[BCTEXTLEN], *cp = line;
828                 if( fgets(line,sizeof(line)-1,fp) ) {
829                         if( *cp == '#' ) continue;
830                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
831                 }
832                 if( done ) {
833                         if( tp > text && *--tp == '\n' ) *tp = 0;
834                         if( title[0] ) {
835                                 int idx = plugins.size();
836                                 while( --idx>=0 && strcmp(plugins[idx]->title, title) );
837                                 if( idx >= 0 ) {
838                                         delete [] plugins[idx]->tip;
839                                         plugins[idx]->tip = cstrdup(text);
840                                 }
841                                 title[0] = 0;
842                         }
843                         if( done > 0 ) break;
844                         tp = text;  *tp = 0;
845                         char *dp = strchr(cp, ':');
846                         if( !dp ) {
847                                 printf("plugin tips: error on line %d\n", no);
848                                 continue;
849                         }
850                         char *bp = title;
851                         while( cp < dp ) *bp++ = *cp++;
852                         *bp = 0;
853                         ++cp;
854                 }
855
856                 while( *cp == ' ' || *cp == '\t' ) ++cp;
857                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
858         }
859         fclose(fp);
860 }
861
862 void MWindow::delete_plugins()
863 {
864         plugindb->remove_all_objects();
865         delete plugindb;
866         plugindb = 0;
867 }
868
869 void MWindow::search_plugindb(int do_audio,
870                 int do_video,
871                 int is_realtime,
872                 int is_transition,
873                 int is_theme,
874                 ArrayList<PluginServer*> &results)
875 {
876 // Get plugins
877         for(int i = 0; i < MWindow::plugindb->total; i++)
878         {
879                 PluginServer *current = MWindow::plugindb->get(i);
880
881                 if(current->audio == do_audio &&
882                         current->video == do_video &&
883                         (current->realtime == is_realtime || is_realtime < 0) &&
884                         current->transition == is_transition &&
885                         current->theme == is_theme)
886                         results.append(current);
887         }
888
889 // Alphabetize list by title
890         int done = 0;
891         while(!done)
892         {
893                 done = 1;
894
895                 for(int i = 0; i < results.total - 1; i++)
896                 {
897                         PluginServer *value1 = results[i];
898                         PluginServer *value2 = results[i + 1];
899                         if(strcmp(_(value1->title), _(value2->title)) > 0)
900                         {
901                                 done = 0;
902                                 results[i] = value2;
903                                 results[i + 1] = value1;
904                         }
905                 }
906         }
907 }
908
909 PluginServer* MWindow::scan_plugindb(char *title,
910                 int data_type)
911 {
912 //      if(data_type < 0)
913 //      {
914 //              printf("MWindow::scan_plugindb data_type < 0\n");
915 //              return 0;
916 //      }
917
918         for(int i = 0; i < plugindb->total; i++)
919         {
920                 PluginServer *server = plugindb->get(i);
921                 if(server->title &&
922                         !strcasecmp(server->title, title) &&
923                         (data_type < 0 ||
924                                 (data_type == TRACK_AUDIO && server->audio) ||
925                                 (data_type == TRACK_VIDEO && server->video)))
926                         return plugindb->get(i);
927         }
928         return 0;
929 }
930
931 // repair session files with xlated plugin titles
932 void MWindow::fix_plugin_title(char *title)
933 {
934         for(int i = 0; i < plugindb->total; i++) {
935                 PluginServer *server = plugindb->get(i);
936                 if( !server->title ) continue;
937                 const char *server_title = server->title;
938                 if( !bstrcasecmp(title, _(server_title)) ) {
939                         strcpy(title, server_title);
940                         return;
941                 }
942         }
943 }
944
945 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
946 {
947         for( int i=0; i<plugins.size(); ++i )
948                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
949         return 0;
950 }
951
952 int MWindow::plugin_exists(char *plugin_path)
953 {
954         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
955 }
956
957 void MWindow::remove_plugin_index()
958 {
959         char index_path[BCTEXTLEN];
960         MWindow::create_defaults_path(index_path, PLUGIN_FILE);
961         ::remove(index_path);
962 }
963
964 void MWindow::init_preferences()
965 {
966         preferences = new Preferences;
967         preferences->load_defaults(defaults);
968         File::setenv_path("LV2_PATH",preferences->lv2_path, 1);
969         session = new MainSession(this);
970         session->load_defaults(defaults);
971         // set x11_host, screens, window_config
972         screens = session->set_default_x11_host();
973         BC_Signals::set_trap_hook(trap_hook, this);
974         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
975         BC_Signals::set_catch_intr(preferences->trap_sigintr);
976         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
977                 BC_Trace::enable_locks();
978         }
979         else {
980                 BC_Trace::disable_locks();
981         }
982         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
983         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
984         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
985         YUV::yuv.yuv_set_colors(preferences->yuv_color_space, preferences->yuv_color_range);
986 }
987
988 void MWindow::clean_backups()
989 {
990     FileSystem fs;
991     int total_excess;
992     long oldest = 0;
993     int oldest_item = -1;
994     char string[BCTEXTLEN];
995
996 // Delete extra backups
997     fs.set_filter("backup*.prev_*");
998     fs.complete_path(preferences->index_directory);
999     fs.update(preferences->index_directory);
1000
1001     // set to 50 for now
1002     // total_excess = fs.dir_list.total - preferences->index_count;
1003     total_excess = fs.dir_list.total - 50;
1004     printf("Total excess of backups: %i \n", total_excess);
1005
1006 //printf("MWindow::clean_backups 1 %d\n", fs.dir_list.total);
1007
1008     while(total_excess > 0)
1009     {
1010 // Get oldest
1011        for(int i = 0; i < fs.dir_list.total; i++)
1012        {
1013            fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1014
1015            if(i == 0 || fs.get_date(string) <= oldest)
1016            {
1017                oldest = fs.get_date(string);
1018                oldest_item = i;
1019            }
1020        }
1021
1022        if(oldest_item >= 0)
1023        {
1024 // Remove backup file
1025            fs.join_names(string,
1026                preferences->index_directory,
1027                fs.dir_list[oldest_item]->name);
1028 //printf("MWindow::clean_backups 1 %s\n", string);
1029            if(remove(string))
1030                perror("delete_backups");
1031            delete fs.dir_list[oldest_item];
1032            fs.dir_list.remove_number(oldest_item);
1033
1034        }
1035
1036        total_excess--;
1037     }
1038 }
1039
1040 void MWindow::clean_indexes()
1041 {
1042         FileSystem fs;
1043         int total_excess;
1044         long oldest = 0;
1045         int oldest_item = -1;
1046         int result;
1047         char string[BCTEXTLEN];
1048         char string2[BCTEXTLEN];
1049
1050 // Delete extra indexes
1051         fs.set_filter("*.idx");
1052         fs.complete_path(preferences->index_directory);
1053         fs.update(preferences->index_directory);
1054 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
1055
1056 // Eliminate directories
1057         result = 1;
1058         while(result)
1059         {
1060                 result = 0;
1061                 for(int i = 0; i < fs.dir_list.total && !result; i++)
1062                 {
1063                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1064                         if(fs.is_dir(string))
1065                         {
1066                                 delete fs.dir_list[i];
1067                                 fs.dir_list.remove_number(i);
1068                                 result = 1;
1069                         }
1070                 }
1071         }
1072         total_excess = fs.dir_list.total - preferences->index_count;
1073
1074 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
1075         while(total_excess > 0)
1076         {
1077 // Get oldest
1078                 for(int i = 0; i < fs.dir_list.total; i++)
1079                 {
1080                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1081
1082                         if(i == 0 || fs.get_date(string) <= oldest)
1083                         {
1084                                 oldest = fs.get_date(string);
1085                                 oldest_item = i;
1086                         }
1087                 }
1088
1089                 if(oldest_item >= 0)
1090                 {
1091 // Remove index file
1092                         fs.join_names(string,
1093                                 preferences->index_directory,
1094                                 fs.dir_list[oldest_item]->name);
1095 //printf("MWindow::clean_indexes 1 %s\n", string);
1096                         if(remove(string))
1097                                 perror("delete_indexes");
1098                         delete fs.dir_list[oldest_item];
1099                         fs.dir_list.remove_number(oldest_item);
1100
1101 // Remove table of contents if it exists
1102                         strcpy(string2, string);
1103                         char *ptr = strrchr(string2, '.');
1104                         if(ptr)
1105                         {
1106 //printf("MWindow::clean_indexes 2 %s\n", string2);
1107                                 sprintf(ptr, ".toc");
1108                                 remove(string2);
1109                                 sprintf(ptr, ".mkr");
1110                                 remove(string2);
1111                         }
1112                 }
1113
1114                 total_excess--;
1115         }
1116 }
1117
1118 void MWindow::init_awindow()
1119 {
1120         awindow = new AWindow(this);
1121         awindow->create_objects();
1122 }
1123
1124 void MWindow::init_gwindow()
1125 {
1126         gwindow = new GWindow(this);
1127         gwindow->create_objects();
1128 }
1129
1130 void MWindow::init_tipwindow()
1131 {
1132         TipWindow::load_tips(cin_lang);
1133         if( !twindow )
1134                 twindow = new TipWindow(this);
1135         twindow->start();
1136 }
1137
1138 void MWindow::show_warning(int *do_warning, const char *text)
1139 {
1140         if( do_warning && !*do_warning ) return;
1141         if( !wwindow )
1142                 wwindow = new WWindow(this);
1143         wwindow->show_warning(do_warning, text);
1144 }
1145
1146 int MWindow::wait_warning()
1147 {
1148         return wwindow->wait_result();
1149 }
1150
1151 void MWindow::init_theme()
1152 {
1153         Timer timer;
1154         theme = 0;
1155
1156         PluginServer *theme_plugin = 0;
1157         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1158                 if( plugindb->get(i)->theme &&
1159                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1160                         theme_plugin = plugindb->get(i);
1161         }
1162
1163         if( !theme_plugin )
1164                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1165                          preferences->theme);
1166
1167         const char *default_theme = DEFAULT_THEME;
1168         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1169                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1170                         default_theme);
1171                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1172                         if( plugindb->get(i)->theme &&
1173                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1174                                 theme_plugin = plugindb->get(i);
1175                 }
1176         }
1177
1178         if(!theme_plugin) {
1179                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1180                 exit(1);
1181         }
1182
1183         PluginServer *plugin = new PluginServer(*theme_plugin);
1184         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1185                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1186                         theme_plugin->title);
1187                 exit(1);
1188         }
1189
1190         theme = plugin->new_theme();
1191         theme->mwindow = this;
1192         strcpy(theme->path, plugin->path);
1193         delete plugin;
1194
1195 // Load default images & settings
1196         theme->Theme::initialize();
1197 // Load user images & settings
1198         theme->initialize();
1199 // Create menus with user colors
1200         theme->build_menus();
1201         init_menus();
1202
1203         theme->sort_image_sets();
1204         theme->check_used();
1205 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1206 }
1207
1208 void MWindow::init_3d()
1209 {
1210         playback_3d = new Playback3D(this);
1211         playback_3d->create_objects();
1212 }
1213
1214 void MWindow::init_edl()
1215 {
1216         edl = new EDL;
1217         edl->create_objects();
1218         fill_preset_defaults(default_standard, edl->session);
1219         edl->load_defaults(defaults);
1220         edl->session->brender_start = edl->session->brender_end = 0;
1221         edl->create_default_tracks();
1222         edl->tracks->update_y_pixels(theme);
1223 }
1224
1225 void MWindow::init_compositor()
1226 {
1227         cwindow = new CWindow(this);
1228         cwindow->create_objects();
1229 }
1230
1231 void MWindow::init_levelwindow()
1232 {
1233         lwindow = new LevelWindow(this);
1234         lwindow->create_objects();
1235 }
1236
1237 VWindow *MWindow::get_viewer(int start_it, int idx)
1238 {
1239         vwindows_lock->lock("MWindow::get_viewer");
1240         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1241         if( !vwindow ) idx = vwindows.size();
1242         while( !vwindow && --idx >= 0 ) {
1243                 VWindow *vwin = vwindows[idx];
1244                 if( !vwin->is_running() || !vwin->get_edl() )
1245                         vwindow = vwin;
1246         }
1247         if( !vwindow ) {
1248                 vwindow = new VWindow(this);
1249                 vwindow->load_defaults();
1250                 vwindow->create_objects();
1251                 vwindows.append(vwindow);
1252         }
1253         vwindows_lock->unlock();
1254         if( start_it ) vwindow->start();
1255         return vwindow;
1256 }
1257
1258 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1259 {
1260         zwindows_lock->lock("MWindow::get_mixer");
1261         if( !mixer ) mixer = edl->mixers.new_mixer();
1262         ZWindow *zwindow = 0;
1263         for( int i=0; !zwindow && i<zwindows.size(); ++i ) {
1264                 ZWindow *zwdw = zwindows[i];
1265                 if( zwdw->running() ) continue;
1266                 if( zwdw->idx >= 0 ) continue;
1267                 zwindow = zwindows[i];
1268         }
1269         if( !zwindow )
1270                 zwindows.append(zwindow = new ZWindow(this));
1271         zwindow->idx = mixer->idx;
1272         zwindows_lock->unlock();
1273         return zwindow;
1274 }
1275
1276 ZWindow *MWindow::get_mixer(int idx)
1277 {
1278         ZWindow *zwindow = 0;
1279         zwindows_lock->lock("MWindow::get_mixer");
1280         for( int i=0; !zwindow && i<zwindows.size(); ++i ) {
1281                 ZWindow *zwdw = zwindows[i];
1282                 if( !zwdw->running() ) continue;
1283                 if( zwdw->idx != idx ) continue;
1284                 zwindow = zwindows[i];
1285         }
1286         zwindows_lock->unlock();
1287         return zwindow;
1288 }
1289
1290 void MWindow::close_mixer(ZWindow *zwindow)
1291 {
1292         zwindows_lock->lock("MWindow::close_mixer 0");
1293         if( session->selected_zwindow >= 0 ) {
1294                 int i = zwindows.number_of(zwindow);
1295                 if( i >= 0 && i < session->selected_zwindow )
1296                         --session->selected_zwindow;
1297                 else if( i == session->selected_zwindow )
1298                         session->selected_zwindow = -1;
1299         }
1300         zwindows_lock->unlock();
1301         gui->lock_window("MWindow::close_mixer 1");
1302         gui->update_mixers(0, -1);
1303         gui->unlock_window();
1304 }
1305
1306 void MWindow::start_mixer()
1307 {
1308         Mixer *mixer = 0;
1309         ZWindow *zwindow = get_mixer(mixer);
1310         const char *title = 0;
1311
1312         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1313                 PatchGUI *patchgui = get_patchgui(track);
1314                 if( !patchgui || !patchgui->mixer ) continue;
1315                 mixer->mixer_ids.append(track->get_mixer_id());
1316                 if( !title ) title = track->title;
1317         }
1318
1319         session->selected_zwindow = -1;
1320         gui->lock_window("MWindow::start_mixer");
1321         gui->update_mixers(0, 0);
1322         gui->unlock_window();
1323
1324         zwindow->set_title(title);
1325         zwindow->start();
1326         refresh_mixers();
1327 }
1328
1329 int MWindow::mixer_track_active(Track *track)
1330 {
1331         int i = session->selected_zwindow;
1332         if( i < 0 || i >= zwindows.size() ) return 0;
1333         ZWindow *zwindow = zwindows[i];
1334         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1335         if( !mixer ) return 0;
1336         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1337         return n >= 0 ? 1 : 0;
1338 }
1339
1340 void MWindow::update_mixer_tracks()
1341 {
1342         zwindows_lock->lock("MixPatch::handle_event");
1343         int i = session->selected_zwindow;
1344         if( i >= 0 && i < zwindows.size() ) {
1345                 ZWindow *zwindow = zwindows[i];
1346                 zwindow->update_mixer_ids();
1347         }
1348         zwindows_lock->unlock();
1349 }
1350
1351 void MWindow::handle_mixers(EDL *edl, int command, int wait_tracking,
1352                 int use_inout, int toggle_audio, int loop_play, float speed)
1353 {
1354         zwindows_lock->lock("MWindow::handle_mixers");
1355         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1356                 ZWindow *zwindow = zwindows[vidx];
1357                 if( zwindow->idx < 0 ) continue;
1358                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1359                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1360                 int k = -1;
1361                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1362                         if( track->data_type != TRACK_VIDEO ) continue;
1363                         int mixer_id = track->get_mixer_id();
1364                         k = mixer->mixer_ids.size();
1365                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1366                 }
1367                 if( k < 0 ) continue;
1368                 EDL *mixer_edl = new EDL(this->edl);
1369                 mixer_edl->create_objects();
1370                 mixer_edl->copy_all(edl);
1371                 mixer_edl->remove_vwindow_edls();
1372                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1373                         k = mixer->mixer_ids.size();
1374                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1375                         if( k >= 0 ) {
1376                                 track->armed = 1;
1377                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1378                         }
1379                         else
1380                                 track->armed = track->play = 0;
1381                 }
1382                 zwindow->change_source(mixer_edl);
1383                 zwindow->handle_mixer(command, 0,
1384                                 use_inout, toggle_audio, loop_play, speed);
1385         }
1386         zwindows_lock->unlock();
1387 }
1388
1389 void MWindow::refresh_mixers(int dir)
1390 {
1391         int command = dir >= 0 ? CURRENT_FRAME : LAST_FRAME;
1392         handle_mixers(edl, command, 0, 0, 0, 0, 0);
1393 }
1394
1395 void MWindow::stop_mixers()
1396 {
1397         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1398                 ZWindow *zwindow = zwindows[vidx];
1399                 if( zwindow->idx < 0 ) continue;
1400                 zwindow->handle_mixer(STOP, 0, 0, 0, 0, 0);
1401         }
1402 }
1403
1404 void MWindow::close_mixers(int result)
1405 {
1406         ArrayList<ZWindow*> closed;
1407         zwindows_lock->lock("MWindow::close_mixers");
1408         for( int i=zwindows.size(); --i>=0; ) {
1409                 ZWindow *zwindow = zwindows[i];
1410                 if( zwindow->idx < 0 ) continue;
1411                 zwindow->idx = -1;
1412                 ZWindowGUI *zgui = zwindow->zgui;
1413                 zgui->lock_window("MWindow::select_zwindow 0");
1414                 zgui->set_done(result);
1415                 zgui->unlock_window();
1416                 closed.append(zwindow);
1417         }
1418         zwindows_lock->unlock();
1419         for( int i=0; i<closed.size(); ++i ) {
1420                 ZWindow *zwindow = closed[i];
1421                 zwindow->join();
1422         }
1423 }
1424
1425 ZWindow *MWindow::create_mixer(Indexable *indexable, double position)
1426 {
1427         ArrayList<Indexable*> new_assets;
1428         new_assets.append(indexable);
1429         Track *track = edl->tracks->last;
1430         load_assets(&new_assets, position, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 1);
1431         track = !track ? edl->tracks->first : track->next;
1432         Mixer *mixer = 0;
1433         ZWindow *zwindow = get_mixer(mixer);
1434         while( track ) {
1435                 track->play = track->armed = 0;
1436                 if( track->data_type == TRACK_VIDEO ) {
1437                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1438                 }
1439                 mixer->mixer_ids.append(track->get_mixer_id());
1440                 track = track->next;
1441         }
1442         if(  indexable->is_asset ) {
1443                 char *path = indexable->path;
1444                 char *tp = strrchr(path, '/');
1445                 if( !tp ) tp = path; else ++tp;
1446                 zwindow->set_title(tp);
1447         }
1448         else {
1449                 char *title = ((EDL*)indexable)->local_session->clip_title;
1450                 zwindow->set_title(title);
1451         }
1452         return zwindow;
1453 }
1454
1455 void MWindow::create_mixers(double position)
1456 {
1457         if( !session->drag_assets->size() &&
1458             !session->drag_clips->size() ) return;
1459         undo_before();
1460
1461         select_zwindow(0);
1462         ArrayList<ZWindow *>new_mixers;
1463
1464         for( int i=0; i<session->drag_assets->size(); ++i ) {
1465                 Indexable *indexable = session->drag_assets->get(i);
1466                 if( !indexable->have_video() ) continue;
1467                 ZWindow *zwindow = create_mixer(indexable, position);
1468                 new_mixers.append(zwindow);
1469         }
1470         for( int i=0; i<session->drag_clips->size(); ++i ) {
1471                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1472                 if( !indexable->have_video() ) continue;
1473                 ZWindow *zwindow = create_mixer(indexable, position);
1474                 new_mixers.append(zwindow);
1475         }
1476
1477         tile_mixers();
1478         for( int i=0; i<new_mixers.size(); ++i )
1479                 new_mixers[i]->start();
1480
1481         refresh_mixers();
1482         save_backup();
1483         undo_after(_("create mixers"), LOAD_ALL);
1484         restart_brender();
1485         gui->update(1, FORCE_REDRAW, 1, 1, 1, 1, 0);
1486         sync_parameters(CHANGE_ALL);
1487 }
1488
1489 void MWindow::open_mixers()
1490 {
1491         for( int i=0; i<edl->mixers.size(); ++i ) {
1492                 Mixer *mixer = edl->mixers[i];
1493                 ZWindow *zwindow = get_mixer(mixer);
1494                 zwindow->set_title(mixer->title);
1495                 zwindow->start();
1496         }
1497         refresh_mixers();
1498 }
1499
1500 int MWindow::select_zwindow(ZWindow *zwindow)
1501 {
1502         int ret = 0, n = zwindows.number_of(zwindow);
1503         if( session->selected_zwindow != n ) {
1504                 session->selected_zwindow = n;
1505                 for( int i=0; i<zwindows.size(); ++i ) {
1506                         ZWindow *zwindow = zwindows[i];
1507                         if( zwindow->idx < 0 ) continue;
1508                         ZWindowGUI *zgui = zwindow->zgui;
1509                         zgui->lock_window("MWindow::select_zwindow 0");
1510                         zwindow->highlighted = i == n ? 1 : 0;
1511                         if( zgui->draw_overlays() )
1512                                 zgui->canvas->get_canvas()->flash(1);
1513                         zgui->unlock_window();
1514                 }
1515                 ret = 1;
1516                 gui->lock_window("MWindow::select_window 1");
1517                 gui->update_mixers(0, -1);
1518                 gui->unlock_window();
1519         }
1520         return ret;
1521 }
1522
1523 void MWindow::tile_mixers()
1524 {
1525         int x1 = session->tile_mixers_x;
1526         int y1 = session->tile_mixers_y;
1527         int x2 = x1 + session->tile_mixers_w;
1528         int y2 = y1 + session->tile_mixers_h;
1529         tile_mixers(x1, y1, x2, y2);
1530 }
1531
1532 void MWindow::tile_mixers(int x1, int y1, int x2, int y2)
1533 {
1534         if( x1 == x2 || y1 == y2 ) {
1535 // use top left quadrent
1536                 int sw = gui->get_screen_w(1, -1);
1537                 int sh = gui->get_screen_w(1, -1);
1538                 x1 = 1;     y1 = 1;
1539                 x2 = sw/2;  y2 = sh/2;
1540         }
1541         else {
1542                 if( x1 > x2 ) { int t = x1;  x1 = x2;  x2 = t; }
1543                 if( y1 > y2 ) { int t = y1;  y1 = y2;  y2 = t; }
1544         }
1545         int ow = edl->session->output_w, oh = edl->session->output_h;
1546         int nz = 0;
1547         for( int i=0; i<zwindows.size(); ++i ) {
1548                 ZWindow *zwindow = zwindows[i];
1549                 if( zwindow->idx < 0 ) continue;
1550                 ++nz;
1551         }
1552         if( !nz ) return;
1553         int lt = BC_DisplayInfo::get_left_border();
1554         int top = BC_DisplayInfo::get_top_border();
1555         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1556         int bh = top + BC_DisplayInfo::get_bottom_border();
1557         int mw = xS(10+10), mh = yS(10+10); // canvas margins
1558         int dx = x2 - x1, dy = y2 - y1;
1559         int64_t sz = dx * dy, best_r = sz;
1560         int bx = 1, by = nz;
1561         for( int nx=1; nx<=nz; ++nx ) {
1562                 int ny = ceil((double)nz / nx);
1563                 int zw = dx / nx;
1564                 int ww = zw - bw;
1565                 int hh = (ww - mw) * oh / ow + mh;
1566                 int zh = hh + bh;
1567                 int64_t za = zw*nx * zh*ny;
1568                 int64_t r = sz - za;
1569                 if( r < 0 ) continue;
1570                 if( r >= best_r ) continue;
1571                 best_r = r;
1572                 bx = nx;  by = ny;
1573         }
1574         for( int ny=1; ny<=nz; ++ny ) {
1575                 int nx = ceil((double)nz / ny);
1576                 int zh = dy / ny;
1577                 int hh = zh - bh;
1578                 int ww = (hh - mh) * ow / oh + mw;
1579                 int zw = ww + bw;
1580                 int64_t za = zw*nx * zh*ny;
1581                 int64_t r = sz - za;
1582                 if( r < 0 ) continue;
1583                 if( r >= best_r ) continue;
1584                 best_r = r;
1585                 bx = nx;  by = ny;
1586         }
1587         int zw, zh, ww, hh;
1588         if( bx < by ) {
1589                 zh = dy / by;
1590                 hh = zh - bh;
1591                 ww = (hh - mh) * ow / oh + mw;
1592                 zw = ww + bw;
1593         }
1594         else {
1595                 zw = dx / bx;
1596                 ww = zw - bw;
1597                 hh = (ww - mw) * oh / ow + mh;
1598                 zh = hh + bh;
1599         }
1600
1601         int zx = 0, zy = 0;  // window origins
1602         int n = 0;
1603         for( int i=0; i<zwindows.size(); ++i ) {
1604                 ZWindow *zwindow = zwindows[i];
1605                 if( zwindow->idx < 0 ) continue;
1606                 int xx = zx + x1, yy = zy + y1;
1607                 int mx = x2 - zw, my = y2 - zh;
1608                 if( xx > mx ) xx = mx;
1609                 if( yy > my ) yy = my;
1610                 zwindow->reposition(xx,yy, ww,hh);
1611                 if( zwindow->running() ) {
1612                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1613                         gui->lock_window("MWindow::tile_mixers");
1614                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1615                         gui->unlock_window();
1616                 }
1617                 if( ++n >= bx ) {
1618                         zx = 0;  zy += zh;
1619                         n = 0;
1620                 }
1621                 else
1622                         zx += zw;
1623         }
1624 }
1625
1626 void MWindow::set_gang_tracks(int v)
1627 {
1628         edl->local_session->gang_tracks = v;
1629         sync_parameters(CHANGE_PARAMS);
1630         gui->update(1, 1, 0, 0, 1, 0, 0);
1631         gui->flush();
1632 }
1633
1634
1635 void MWindow::init_cache()
1636 {
1637         audio_cache = new CICache(preferences);
1638         video_cache = new CICache(preferences);
1639         frame_cache = new FrameCache;
1640         wave_cache = new WaveCache;
1641 }
1642
1643 void MWindow::init_channeldb()
1644 {
1645         channeldb_buz->load("channeldb_buz");
1646         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1647 }
1648
1649 void MWindow::init_menus()
1650 {
1651         char string[BCTEXTLEN];
1652
1653         // Color Models
1654         BC_CModels::to_text(string, BC_RGB888);
1655         colormodels.append(new ColormodelItem(string, BC_RGB888));
1656         BC_CModels::to_text(string, BC_RGBA8888);
1657         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1658 //      BC_CModels::to_text(string, BC_RGB161616);
1659 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1660 //      BC_CModels::to_text(string, BC_RGBA16161616);
1661 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1662         BC_CModels::to_text(string, BC_RGB_FLOAT);
1663         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1664         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1665         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1666         BC_CModels::to_text(string, BC_YUV888);
1667         colormodels.append(new ColormodelItem(string, BC_YUV888));
1668         BC_CModels::to_text(string, BC_YUVA8888);
1669         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1670 //      BC_CModels::to_text(string, BC_YUV161616);
1671 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1672 //      BC_CModels::to_text(string, BC_YUVA16161616);
1673 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1674
1675 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1676                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1677
1678 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1679                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1680
1681         // Interlacing Modes
1682         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1683
1684         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1685         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1686
1687         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1688         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1689
1690         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1691         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1692
1693         mixers_align = new MixersAlign(this);
1694 }
1695
1696 void MWindow::init_indexes()
1697 {
1698         mainindexes = new MainIndexes(this);
1699         mainindexes->start_loop();
1700 }
1701
1702 void MWindow::init_gui()
1703 {
1704         gui = new MWindowGUI(this);
1705         gui->create_objects();
1706         gui->load_defaults(defaults);
1707 }
1708
1709 void MWindow::init_signals()
1710 {
1711         sighandler = new SigHandler;
1712         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1713 ENABLE_BUFFER
1714 }
1715
1716 void MWindow::init_render()
1717 {
1718         render = new Render(this);
1719         create_bd = new CreateBD_Thread(this);
1720         create_dvd = new CreateDVD_Thread(this);
1721         batch_render = new BatchRenderThread(this);
1722 }
1723
1724 void MWindow::init_exportedl()
1725 {
1726         exportedl = new ExportEDL(this);
1727 }
1728
1729
1730 void MWindow::init_shuttle()
1731 {
1732 #ifdef HAVE_SHUTTLE
1733         int ret = Shuttle::probe();
1734         if( ret >= 0 ) {
1735                 shuttle = new Shuttle(this);
1736                 if( shuttle->read_config_file() > 0 ) {
1737                         printf("shuttle: bad config file\n");
1738                         delete shuttle;  shuttle = 0;
1739                         return;
1740                 }
1741                 shuttle->start(ret);
1742         }
1743 #endif
1744 }
1745 void MWindow::init_wintv()
1746 {
1747 #ifdef HAVE_WINTV
1748         wintv = WinTV::probe(this);
1749         if( wintv )
1750                 wintv->start();
1751 #endif
1752 }
1753 void MWindow::init_x10tv()
1754 {
1755 #ifdef HAVE_X10TV
1756         x10tv = X10TV::probe(this);
1757         if( x10tv )
1758                 x10tv->start();
1759 #endif
1760 }
1761
1762
1763 void MWindow::init_brender()
1764 {
1765         if(preferences->use_brender && !brender)
1766         {
1767                 brender_lock->lock("MWindow::init_brender 1");
1768                 brender = new BRender(this);
1769                 brender->initialize();
1770                 session->brender_end = 0;
1771                 brender_lock->unlock();
1772         }
1773         else
1774         if(!preferences->use_brender && brender)
1775         {
1776                 brender_lock->lock("MWindow::init_brender 2");
1777                 delete brender;
1778                 brender = 0;
1779                 session->brender_end = 0;
1780                 brender_lock->unlock();
1781         }
1782         brender_active = 0;
1783         stop_brender();
1784 }
1785
1786 void MWindow::restart_brender()
1787 {
1788 //printf("MWindow::restart_brender 1\n");
1789         if( !brender_active || !preferences->use_brender ) return;
1790         if( !brender ) return;
1791         brender->restart(edl);
1792 }
1793
1794 void MWindow::stop_brender()
1795 {
1796         if( !brender ) return;
1797 // cannot be holding mwindow->gui display lock
1798         brender->stop();
1799 }
1800
1801 int MWindow::brender_available(int position)
1802 {
1803         int result = 0;
1804         brender_lock->lock("MWindow::brender_available 1");
1805         if(brender && brender_active)
1806         {
1807                 if(brender->map_valid)
1808                 {
1809                         brender->map_lock->lock("MWindow::brender_available 2");
1810                         if(position < brender->map_size &&
1811                                 position >= 0)
1812                         {
1813 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1814                                 if(brender->map[position] == BRender::RENDERED)
1815                                         result = 1;
1816                         }
1817                         brender->map_lock->unlock();
1818                 }
1819         }
1820         brender_lock->unlock();
1821         return result;
1822 }
1823
1824 void MWindow::set_brender_active(int v, int update)
1825 {
1826         if( !preferences->use_brender ) v = 0;
1827         brender_active = v;
1828         gui->mainmenu->brender_active->set_checked(v);
1829         if( v != 0 ) {
1830                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1831                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1832
1833                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1834                         edl->session->brender_end = edl->tracks->total_video_length();
1835                 }
1836                 restart_brender();
1837         }
1838         else {
1839                 edl->session->brender_start = edl->session->brender_end = 0;
1840                 gui->unlock_window();
1841                 stop_brender();
1842                 gui->lock_window("MWindow::set_brender_active");
1843         }
1844         if( update ) {
1845                 gui->update_timebar(0);
1846                 gui->draw_overlays(1);
1847         }
1848 }
1849
1850 int MWindow::has_commercials()
1851 {
1852 #ifdef HAVE_COMMERCIAL
1853         return theme->use_commercials;
1854 #else
1855         return 0;
1856 #endif
1857 }
1858
1859 void MWindow::init_commercials()
1860 {
1861 #ifdef HAVE_COMMERCIAL
1862         if( !commercials ) {
1863                 commercials = new Commercials(this);
1864                 commercial_active = 0;
1865         }
1866         else
1867                 commercials->add_user();
1868 #endif
1869 }
1870
1871 void MWindow::commit_commercial()
1872 {
1873 #ifdef HAVE_COMMERCIAL
1874         if( !commercial_active ) return;
1875         commercial_active = 0;
1876         if( !commercials ) return;
1877         commercials->commitDb();
1878 #endif
1879 }
1880
1881 void MWindow::undo_commercial()
1882 {
1883 #ifdef HAVE_COMMERCIAL
1884         if( !commercial_active ) return;
1885         commercial_active = 0;
1886         if( !commercials ) return;
1887         commercials->undoDb();
1888 #endif
1889 }
1890
1891 int MWindow::put_commercial()
1892 {
1893         int result = 0;
1894 #ifdef HAVE_COMMERCIAL
1895         double start = edl->local_session->get_selectionstart();
1896         double end = edl->local_session->get_selectionend();
1897         if( start >= end ) return 0;
1898
1899         const char *errmsg = 0;
1900         int count = 0;
1901         Tracks *tracks = edl->tracks;
1902         //check it
1903         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1904                 if( track->data_type != TRACK_VIDEO ) continue;
1905                 if( !track->armed ) continue;
1906                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1907                 ++count;
1908                 int64_t units_start = track->to_units(start,0);
1909                 int64_t units_end = track->to_units(end,0);
1910                 Edits *edits = track->edits;
1911                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1912                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1913                 if(!edit1 && !edit2) continue;  // nothing selected
1914                 if(!edit2) {                    // edit2 beyond end of track
1915                         edit2 = edits->last;
1916                         units_end = edits->length();
1917                 }
1918                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1919                 Indexable *indexable = edit1->get_source();
1920                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1921         }
1922         //run it
1923         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1924                 if( track->data_type != TRACK_VIDEO ) continue;
1925                 if( !track->armed ) continue;
1926                 int64_t units_start = track->to_units(start,0);
1927                 int64_t units_end = track->to_units(end,0);
1928                 Edits *edits = track->edits;
1929                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1930                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1931                 if(!edit1 && !edit2) continue;  // nothing selected
1932                 if(!edit2) {                    // edit2 beyond end of track
1933                         edit2 = edits->last;
1934                         units_end = edits->length();
1935                 }
1936                 Indexable *indexable = edit1->get_source();
1937                 Asset *asset = (Asset *)indexable;
1938                 File *file = video_cache->check_out(asset, edl);
1939                 if( !file ) { errmsg = _("no file"); break; }
1940                 int64_t edit_length = units_end - units_start;
1941                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1942                 result = commercials->put_clip(file, edit1->channel,
1943                         track->from_units(edit_start), track->from_units(edit_length));
1944                 video_cache->check_in(asset);
1945                 if( result ) { errmsg = _("db failed"); break; }
1946         }
1947         if( errmsg ) {
1948                 char string[BCTEXTLEN];
1949                 sprintf(string, _("put_commercial: %s"), errmsg);
1950                 MainError::show_error(string);
1951                 undo_commercial();
1952                 result = 1;
1953         }
1954 #endif
1955         return result;
1956 }
1957
1958 void MWindow::stop_playback(int wait)
1959 {
1960         gui->stop_drawing();
1961
1962         cwindow->stop_playback(wait);
1963
1964         for(int i = 0; i < vwindows.size(); i++) {
1965                 VWindow *vwindow = vwindows[i];
1966                 if( !vwindow->is_running() ) continue;
1967                 vwindow->stop_playback(wait);
1968         }
1969         for(int i = 0; i < zwindows.size(); i++) {
1970                 ZWindow *zwindow = zwindows[i];
1971                 if( zwindow->idx < 0 ) continue;
1972                 zwindow->stop_playback(wait);
1973         }
1974 }
1975
1976 void MWindow::stop_transport()
1977 {
1978         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1979 }
1980
1981 void MWindow::undo_before(const char *description, void *creator)
1982 {
1983         undo->update_undo_before(description, creator);
1984 }
1985
1986 void MWindow::undo_after(const char *description, uint32_t load_flags, int changes_made)
1987 {
1988         undo->update_undo_after(description, load_flags, changes_made);
1989 }
1990
1991 void MWindow::beep(double freq, double secs, double gain)
1992 {
1993         if( !beeper ) beeper = new Beeper(this);
1994         beeper->tone(freq, secs, gain);
1995 }
1996
1997 Beeper::Beeper(MWindow *mwindow)
1998  : Thread(1, 0, 0)
1999 {
2000         this->mwindow = mwindow;
2001         audio = new AudioDevice(mwindow);
2002         playing_audio = 0;
2003         interrupted = -1;
2004 }
2005
2006 Beeper::~Beeper()
2007 {
2008         stop(0);
2009         delete audio;
2010 }
2011
2012 void Beeper::run()
2013 {
2014         int channels = 2;
2015         int64_t bfrsz = BEEP_SAMPLE_RATE;
2016         EDL *edl = mwindow->edl;
2017         EDLSession *session = edl->session;
2018         AudioOutConfig *aconfig = session->playback_config->aconfig;
2019         audio->open_output(aconfig, BEEP_SAMPLE_RATE, bfrsz, channels, 0);
2020         audio->start_playback();
2021
2022         double out0[bfrsz], out1[bfrsz], *out[2] = { out0, out1 };
2023         const double two_pi = 2*M_PI;
2024         int64_t audio_len = BEEP_SAMPLE_RATE * secs;
2025         const double dt = two_pi * freq/BEEP_SAMPLE_RATE;
2026         double th = 0;
2027
2028         audio_pos = 0;
2029         playing_audio = 1;
2030         while( !interrupted ) {
2031                 int len = audio_len - audio_pos;
2032                 if( len <= 0 ) break;
2033                 if( len > bfrsz ) len = bfrsz;
2034                 int k = audio_pos;
2035                 for( int i=0; i<len; ++i,++k,th+=dt ) {
2036                         double t = th - two_pi;
2037                         if( t >= 0 ) th = t;
2038                         out0[i] = out1[i] = sin(th) * gain;
2039                 }
2040                 audio->write_buffer(out, channels, len);
2041                 audio_pos = k;
2042         }
2043
2044         if( !interrupted )
2045                 audio->set_last_buffer();
2046         audio->stop_audio(interrupted ? 0 : 1);
2047         playing_audio = 0;
2048
2049         audio->close_all();
2050 }
2051
2052 void Beeper::start()
2053 {
2054         if( running() ) return;
2055         audio_pos = -1;
2056         interrupted = 0;
2057         Thread::start();
2058 }
2059
2060 void Beeper::stop(int wait)
2061 {
2062         if( running() && !interrupted ) {
2063                 interrupted = 1;
2064                 audio->stop_audio(wait);
2065         }
2066         Thread::join();
2067 }
2068
2069 void Beeper::tone(double freq, double secs, double gain)
2070 {
2071         stop(0);
2072         this->freq = freq;
2073         this->secs = secs;
2074         this->gain = gain;
2075         start();
2076 }
2077
2078
2079 int MWindow::load_filenames(ArrayList<char*> *filenames,
2080                 int load_mode, int edl_mode, int update_filename)
2081 {
2082         ArrayList<EDL*> new_edls;
2083         ArrayList<Asset*> new_assets;
2084         ArrayList<File*> new_files;
2085
2086 //      save_defaults();
2087         gui->start_hourglass();
2088
2089 // Need to stop playback since tracking depends on the EDL not getting
2090 // deleted.
2091         gui->unlock_window();
2092         stop_playback(1);
2093         gui->lock_window("MWindow::load_filenames 0");
2094         undo_before();
2095
2096 const int debug = 0;
2097 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2098
2099 // Define new_edls and new_assets to load
2100         int result = 0, ftype = -1;
2101
2102         for( int i=0; i<filenames->size(); ++i ) {
2103 // Get type of file
2104                 File *new_file = new File;
2105                 Asset *new_asset = new Asset(filenames->get(i));
2106                 EDL *new_edl = new EDL;
2107                 new_edl->create_objects();
2108                 new_edl->copy_session(edl, -1);
2109                 new_file->set_program(edl->session->program_no);
2110
2111                 char string[BCTEXTLEN];
2112                 sprintf(string, _("Loading %s"), new_asset->path);
2113                 gui->show_message(string);
2114
2115                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
2116
2117                 result = 1;
2118                 switch( ftype ) {
2119 // Convert media file to EDL
2120                 case FILE_OK: {
2121 // Warn about odd image dimensions
2122                         if( new_asset->video_data &&
2123                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
2124                                 eprintf(_("%s's resolution is %dx%d.\n"
2125                                         "Images with odd dimensions may not decode properly."),
2126                                         new_asset->path, new_asset->width, new_asset->height);
2127                         }
2128
2129                         if( new_asset->program >= 0 &&
2130                             edl->session->program_no != new_asset->program ) {
2131                                 eprintf(_("%s's index was built for program number %d\n"
2132                                         "Playback preference is %d.\n  Using program %d."),
2133                                         new_asset->path, new_asset->program,
2134                                         edl->session->program_no, new_asset->program);
2135                         }
2136
2137                         if( load_mode == LOADMODE_RESOURCESONLY ) {
2138                                 new_assets.append(new_asset);
2139                                 new_asset->add_user();
2140                                 result = 0;
2141                                 break;
2142                         }
2143
2144                         RecordLabels *labels = edl->session->label_cells ?
2145                                 new RecordLabels(new_file) : 0;
2146                         asset_to_edl(new_edl, new_asset, labels);
2147                         new_edls.append(new_edl);
2148                         new_edl->add_user();
2149                         delete labels;
2150
2151                         if( load_mode == LOADMODE_REPLACE ||
2152                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2153 // Set filename to nothing for assets since save EDL would overwrite them.
2154                                 set_filename("");
2155 // Reset timeline position
2156                                 for( int i=0; i<TOTAL_PANES; ++i ) {
2157                                         new_edl->local_session->view_start[i] = 0;
2158                                         new_edl->local_session->track_start[i] = 0;
2159                                 }
2160                         }
2161                         result = 0;
2162                         break; }
2163
2164                 case FILE_NOT_FOUND: {
2165                         eprintf(_("Failed to open %s"), new_asset->path);
2166                         sprintf(string, _("Failed to open %s"), new_asset->path);
2167                         gui->show_message(string, theme->message_error);
2168                         gui->update_default_message();
2169                         break; }
2170
2171 // Unknown format
2172                 case FILE_UNRECOGNIZED_CODEC: {
2173 // Test index file
2174                         { IndexFile indexfile(this, new_asset);
2175                         if( !(result = indexfile.open_index()) )
2176                                 indexfile.close_index(); }
2177
2178 // Test existing EDLs
2179                         for( int j=0; result && j<new_edls.total; ++j ) {
2180                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
2181                                 if( old_asset ) {
2182                                         new_asset->copy_from(old_asset,1);
2183                                         result = 0;
2184                                 }
2185                         }
2186                         if( result ) {
2187                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
2188                                 if( old_asset ) {
2189                                         new_asset->copy_from(old_asset,1);
2190                                         result = 0;
2191                                 }
2192                         }
2193
2194 // Prompt user
2195                         if( result ) {
2196                                 new_asset->audio_data = 1;
2197                                 new_asset->format = FILE_PCM;
2198                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
2199                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
2200                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
2201                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
2202                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
2203                                 new_asset->header = defaults->get("HEADER", 0);
2204
2205                                 FileSystem fs;
2206                                 fs.extract_name(string, new_asset->path);
2207                                 strcat(string, _("'s format couldn't be determined."));
2208                                 FileFormat fwindow(this);
2209                                 fwindow.create_objects(new_asset, string);
2210                                 result = fwindow.run_window();
2211
2212                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
2213                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
2214                                 defaults->update("AUDIO_BITS", new_asset->bits);
2215                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
2216                                 defaults->update("SIGNED_", new_asset->signed_);
2217                                 defaults->update("HEADER", new_asset->header);
2218                                 save_defaults();
2219                         }
2220 // Append to list
2221                         if( !result ) {
2222 // Recalculate length
2223                                 delete new_file;
2224                                 new_file = new File;
2225                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2226
2227                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
2228                                         RecordLabels *labels = edl->session->label_cells ?
2229                                                 new RecordLabels(new_file) : 0;
2230                                         asset_to_edl(new_edl, new_asset, labels);
2231                                         new_edls.append(new_edl);
2232                                         new_edl->add_user();
2233                                         delete labels;
2234                                 }
2235                                 else {
2236                                         new_assets.append(new_asset);
2237                                         new_asset->add_user();
2238                                 }
2239                         }
2240                         break; }
2241
2242                 case FILE_IS_XML: {
2243                         FileXML xml_file;
2244                         const char *filename = filenames->get(i);
2245                         if( xml_file.read_from_file(filename, 1) ) {
2246                                 eprintf(_("Error: unable to open:\n  %s"), filename);
2247                                 break;
2248                         }
2249                         const char *cin_version = 0;
2250                         while( !xml_file.read_tag() ) {
2251                                 if( xml_file.tag.title_is("EDL") ) {
2252                                         cin_version = xml_file.tag.get_property("VERSION");
2253                                         break;
2254                                 }
2255                         }
2256                         xml_file.rewind();
2257                         if( !cin_version ) {
2258                                 eprintf(_("XML file %s\n not from cinelerra."),filename);
2259                                 char string[BCTEXTLEN];
2260                                 sprintf(string,_("Unknown %s"), filename);
2261                                 gui->show_message(string);
2262                                 break;
2263                         }
2264                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2265                             strcmp(cin_version, "Unify") &&
2266                             strcmp(cin_version, "5.1") ) {
2267                                 eprintf(_("Warning: XML from cinelerra version %s\n"
2268                                         "Session data may be incompatible."), cin_version);
2269                         }
2270                         if( new_edl->load_xml(&xml_file, LOAD_ALL) ) {
2271                                 eprintf(_("Error: unable to load:\n  %s"), filename);
2272                                 break;
2273                         }
2274                         test_plugins(new_edl, filename);
2275                         int groups = new_edl->regroup(session->group_number);
2276                         session->group_number += groups;
2277                         switch( edl_mode ) {
2278                         case LOADMODE_EDL_CLIP: {
2279                                 strcpy(new_edl->local_session->clip_title,
2280                                         filenames->get(i));
2281                                 struct stat st;
2282                                 time_t t = !stat(filenames->get(i),&st) ?
2283                                         st.st_mtime : time(&t);
2284                                 ctime_r(&t, new_edl->local_session->clip_notes);
2285                                 switch( load_mode ) {
2286                                 case LOADMODE_REPLACE:
2287                                 case LOADMODE_REPLACE_CONCATENATE:
2288                                         strcpy(session->filename, filename);
2289                                         if( update_filename ) set_filename(filename);
2290                                         break;
2291                                 }
2292                                 result = 0;
2293                                 break; }
2294                         case LOADMODE_EDL_NESTED: {
2295                                 EDL *nested_edl = new EDL;
2296                                 nested_edl->create_objects();
2297                                 nested_edl->copy_session(edl, -1);
2298                                 nested_edl->create_nested(new_edl);
2299                                 nested_edl->set_path(filename);
2300                                 new_edl->remove_user();
2301                                 new_edl = nested_edl;
2302                                 result = 0;
2303                                 break; }
2304                         case LOADMODE_EDL_FILEREF: {
2305                                 result = create_ref(new_asset, new_edl);
2306                                 if( result ) break;
2307                                 new_assets.append(new_asset);
2308                                 new_asset->add_user();
2309                                 new_edl->remove_user();
2310                                 new_edl = new EDL;
2311                                 new_edl->create_objects();
2312                                 new_edl->copy_session(edl, -1);
2313                                 asset_to_edl(new_edl, new_asset);
2314                                 delete new_file;
2315                                 new_file = new File;
2316                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2317                                 break; }
2318                         }
2319                         if( !result ) {
2320                                 new_edls.append(new_edl);
2321                                 new_edl->add_user();
2322                         }
2323                         else
2324                                 eprintf(_("Error: Unable to load xml:\n  %s"), new_asset->path);
2325                         break; }
2326                 }
2327
2328                 new_edl->Garbage::remove_user();
2329                 new_asset->Garbage::remove_user();
2330
2331 // Store for testing index
2332                 new_files.append(new_file);
2333         }
2334
2335 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2336
2337         if(!result) {
2338                 gui->reset_default_message();
2339                 gui->default_message();
2340         }
2341
2342 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2343
2344 // Paste them.
2345 // Don't back up here.
2346         if( new_edls.size() ) {
2347 // For pasting, clear the active region
2348                 if( load_mode == LOADMODE_PASTE ) {
2349                         double start = edl->local_session->get_selectionstart();
2350                         double end = edl->local_session->get_selectionend();
2351                         if(!EQUIV(start, end))
2352                                 edl->clear(start, end,
2353                                         edl->session->labels_follow_edits,
2354                                         edl->session->plugins_follow_edits,
2355                                         edl->session->autos_follow_edits);
2356
2357                         paste_edls(&new_edls, load_mode, 0, -1,
2358                                 edl->session->labels_follow_edits,
2359                                 edl->session->plugins_follow_edits,
2360                                 edl->session->autos_follow_edits,
2361                                 0); // overwrite
2362                 }
2363                 else if( load_mode == LOADMODE_NEW_TRACKS &&
2364                          edl_mode != LOADMODE_EDL_CLIP )
2365                         paste_edls(&new_edls, load_mode, 0, -1, 0, 0, 0, 0);
2366                 else if( load_mode != LOADMODE_RESOURCESONLY ||
2367                          edl_mode == LOADMODE_EDL_CLIP )
2368                         paste_edls(&new_edls, load_mode, 0, -1, 1, 1, 1, 0);
2369                 else
2370                         paste_edls(&new_edls, LOADMODE_NOTHING, 0, -1, 0, 0, 0, 0);
2371
2372         }
2373
2374 // Add new assets to EDL and schedule assets for index building.
2375         int got_indexes = 0;
2376         for( int i=0; i<new_edls.size(); ++i ) {
2377                 EDL *new_edl = new_edls[i];
2378                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2379                         mainindexes->add_indexable(new_edl->nested_edls[j]);
2380                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2381                         got_indexes = 1;
2382                 }
2383
2384         }
2385
2386         for( int i=0; i<new_assets.size(); ++i ) {
2387                 Asset *new_asset = new_assets[i];
2388                 mainindexes->add_indexable(new_asset);
2389                 edl->assets->update(new_asset);
2390                 got_indexes = 1;
2391         }
2392
2393 // Start examining next batch of index files
2394         if(got_indexes) mainindexes->start_build();
2395
2396 // reload renderengine edl or the plugin guis will flip out
2397         sync_parameters(CHANGE_ALL);
2398 // Open plugin GUIs
2399         show_plugins();
2400
2401         // opening new session
2402         if( ( load_mode == LOADMODE_REPLACE ||
2403               load_mode == LOADMODE_REPLACE_CONCATENATE ) &&
2404             (ftype != FILE_IS_XML || edl_mode != LOADMODE_EDL_CLIP) ) {
2405                 select_asset(0, 0);
2406                 edl->session->proxy_state = PROXY_INACTIVE;
2407                 edl->session->proxy_scale = 1;
2408                 edl->session->proxy_disabled_scale = 1;
2409                 edl->session->proxy_use_scaler = 0;
2410                 edl->session->proxy_auto_scale = 0;
2411                 edl->session->proxy_beep = 0;
2412                 edl->local_session->preview_start = 0;
2413                 edl->local_session->preview_end = -1;
2414                 edl->local_session->loop_playback = 0;
2415                 edl->local_session->set_selectionstart(0);
2416                 edl->local_session->set_selectionend(0);
2417                 edl->local_session->unset_inpoint();
2418                 edl->local_session-> unset_outpoint();
2419                 set_brender_active(0, 0);
2420                 fit_selection();
2421                 goto_start();
2422         }
2423
2424         if( edl->session->proxy_state != PROXY_INACTIVE && edl->session->proxy_auto_scale &&
2425             load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) {
2426                 ArrayList<Indexable *> orig_idxbls;
2427                 for( int i=0; i<new_assets.size(); ++i )
2428                         orig_idxbls.append(new_assets.get(i));
2429                 for( int i=0; i<new_edls.size(); ++i ) {
2430                         EDL *new_edl = new_edls[i];
2431                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2432                                 if( track->data_type != TRACK_VIDEO ) continue;
2433                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2434                                         Indexable *idxbl = (Indexable *)edit->asset;
2435                                         if( !idxbl ) continue;
2436                                         if( !idxbl->have_video() ) continue;
2437                                         if( edit->channel != 0 ) continue; // first layer only
2438                                         orig_idxbls.append(edit->asset);
2439                                 }
2440                         }
2441                 }
2442                 gui->unlock_window(); // to update progress bar
2443                 int ret = render_proxy(orig_idxbls);
2444                 gui->lock_window("MWindow::load_filenames");
2445                 float gain = edl->session->proxy_beep;
2446                 if( ret >= 0 && gain > 0 ) {
2447                         if( ret > 0 )
2448                                 beep(2000., 1.5, gain);
2449                         else
2450                                 beep(4000., 0.25, gain);
2451                 }
2452         }
2453
2454 // need to update undo before project, since mwindow is unlocked & a new load
2455 // can begin here.  Should really prevent loading until we're done.
2456 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2457         undo_after(_("load"), LOAD_ALL);
2458
2459         for(int i = 0; i < new_edls.size(); i++)
2460         {
2461                 new_edls[i]->remove_user();
2462         }
2463 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2464
2465         new_edls.remove_all();
2466
2467         for(int i = 0; i < new_assets.size(); i++)
2468         {
2469                 new_assets[i]->Garbage::remove_user();
2470         }
2471
2472         new_assets.remove_all();
2473         new_files.remove_all_objects();
2474
2475
2476 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2477         if(load_mode == LOADMODE_REPLACE ||
2478                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2479         {
2480                 session->changes_made = 0;
2481         }
2482         else
2483         {
2484                 session->changes_made = 1;
2485         }
2486
2487         gui->stop_hourglass();
2488
2489
2490 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2491         update_project(load_mode);
2492
2493 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2494
2495         return 0;
2496 }
2497
2498 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2499 {
2500         Asset *format_asset = new Asset;
2501         format_asset->format = FILE_FFMPEG;
2502         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2503         int new_scale = edl->session->proxy_scale;
2504         ProxyRender proxy_render(this, format_asset, new_scale);
2505
2506         for( int i=0; i<new_idxbls.size(); ++i ) {
2507                 Indexable *orig = new_idxbls.get(i);
2508                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2509                 if( !proxy ) continue;
2510                 FileSystem fs;
2511                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2512                 int got_it = exists && // if proxy exists, and is newer than orig
2513                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2514                 if( got_it ) continue;
2515                 proxy_render.add_needed(orig, proxy);
2516         }
2517
2518 // render needed proxies
2519         int result = proxy_render.create_needed_proxies(new_scale);
2520         if( !result ) {
2521                 add_proxy(&proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2522         }
2523         format_asset->remove_user();
2524         return !result ? proxy_render.needed_proxies.size() : -1;
2525 }
2526
2527 int MWindow::enable_proxy()
2528 {
2529         int ret = 0;
2530         if( edl->session->proxy_state == PROXY_DISABLED ) {
2531                 int new_scale = edl->session->proxy_disabled_scale;
2532                 int new_use_scaler = edl->session->proxy_use_scaler;
2533                 Asset *asset = new Asset;
2534                 asset->format = FILE_FFMPEG;
2535                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2536                 ret = to_proxy(asset, new_scale, new_use_scaler);
2537                 asset->remove_user();
2538                 if( ret > 0 ) {
2539                         float gain = edl->session->proxy_beep;
2540                         beep(2000., 1.5, gain);
2541                 }
2542                 edl->session->proxy_disabled_scale = 1;
2543                 edl->session->proxy_state = PROXY_ACTIVE;
2544                 gui->lock_window("MWindow::to_proxy");
2545                 update_project(LOADMODE_REPLACE);
2546                 gui->unlock_window();
2547         }
2548         return 1;
2549 }
2550
2551 int MWindow::disable_proxy()
2552 {
2553         if( edl->session->proxy_state == PROXY_ACTIVE ) {
2554                 int old_scale = edl->session->proxy_scale, new_scale = 0;
2555                 int new_use_scaler = edl->session->proxy_use_scaler;
2556                 Asset *asset = new Asset;
2557                 asset->format = FILE_FFMPEG;
2558                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2559                 to_proxy(asset, new_scale, new_use_scaler);
2560                 asset->remove_user();
2561                 edl->session->proxy_state = PROXY_DISABLED;
2562                 edl->session->proxy_disabled_scale = old_scale;
2563                 gui->lock_window("MWindow::to_proxy");
2564                 update_project(LOADMODE_REPLACE);
2565                 gui->unlock_window();
2566         }
2567         return 1;
2568 }
2569
2570 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2571 {
2572         ArrayList<Indexable*> orig_idxbls;
2573         ArrayList<Indexable*> proxy_assets;
2574
2575         edl->Garbage::add_user();
2576         save_backup();
2577         undo_before(_("proxy"), this);
2578         int asset_scale = !new_scale ? 0 :
2579                         !new_use_scaler ? 1 : new_scale;
2580         ProxyRender proxy_render(this, asset, asset_scale);
2581
2582 // revert project to original size from current size
2583 // remove all session proxy assets at the at the current proxy_scale
2584         int proxy_scale = edl->session->proxy_scale;
2585
2586         if( edl->session->proxy_state == PROXY_ACTIVE ) {
2587                 Asset *orig_asset = edl->assets->first;
2588                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2589                         char new_path[BCTEXTLEN];
2590                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2591 // test if proxy asset was already added to proxy_assets
2592                         int got_it = 0;
2593                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2594                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2595                         if( got_it ) continue;
2596                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2597                         if( !proxy_asset ) continue;
2598 // add pointer to existing EDL asset if it exists
2599 // EDL won't delete it unless it's the same pointer.
2600                         proxy_assets.append(proxy_asset);
2601                         proxy_asset->add_user();
2602                         orig_idxbls.append(orig_asset);
2603                         orig_asset->add_user();
2604                 }
2605                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2606                         EDL *orig_nested = edl->nested_edls[i];
2607                         char new_path[BCTEXTLEN];
2608                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2609 // test if proxy asset was already added to proxy_assets
2610                         int got_it = 0;
2611                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2612                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2613                         if( got_it ) continue;
2614                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2615                         if( !proxy_nested ) continue;
2616 // add pointer to existing EDL asset if it exists
2617 // EDL won't delete it unless it's the same pointer.
2618                         proxy_assets.append(proxy_nested);
2619                         proxy_nested->add_user();
2620                         orig_idxbls.append(orig_nested);
2621                         orig_nested->add_user();
2622                 }
2623
2624 // convert from the proxy assets to the original assets
2625                 edl->set_proxy(0, 0, &proxy_assets, &orig_idxbls);
2626
2627 // remove the references
2628                 for( int i=0; i<proxy_assets.size(); ++i ) {
2629                         Asset *proxy = (Asset *) proxy_assets[i];
2630                         proxy->width = proxy->actual_width;
2631                         proxy->height = proxy->actual_height;
2632                         proxy->remove_user();
2633                         edl->assets->remove_pointer(proxy);
2634                         proxy->remove_user();
2635                 }
2636                 proxy_assets.remove_all();
2637                 for( int i = 0; i < orig_idxbls.size(); i++ )
2638                         orig_idxbls[i]->remove_user();
2639                 orig_idxbls.remove_all();
2640         }
2641
2642         ArrayList<char *> confirm_paths;    // test for new files
2643         confirm_paths.set_array_delete();
2644
2645 // convert to new size if not original size
2646         if( new_scale ) {
2647                 FileSystem fs;
2648                 Asset *orig = edl->assets->first;
2649                 for( ; orig; orig=orig->next ) {
2650                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2651                         if( !proxy ) continue;
2652                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2653                         int got_it = exists && // if proxy exists, and is newer than orig
2654                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2655                         if( !got_it ) {
2656                                 if( exists ) // prompt user to overwrite
2657                                         confirm_paths.append(cstrdup(proxy->path));
2658                                 proxy_render.add_needed(orig, proxy);
2659                         }
2660                 }
2661                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2662                         EDL *orig_nested = edl->nested_edls[i];
2663                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2664                         if( !proxy ) continue;
2665                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2666                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2667                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2668                         if( !got_it ) {
2669                                 if( exists ) // prompt user to overwrite
2670                                         confirm_paths.append(cstrdup(proxy->path));
2671                                 proxy_render.add_needed(orig_nested, proxy);
2672                         }
2673                 }
2674                 edl->session->proxy_state = PROXY_ACTIVE;
2675         }
2676         else
2677                 edl->session->proxy_state = PROXY_INACTIVE;
2678
2679         int result = 0;
2680 // test for existing files
2681         if( confirm_paths.size() ) {
2682                 result = ConfirmSave::test_files(this, &confirm_paths);
2683                 confirm_paths.remove_all_objects();
2684         }
2685
2686         if( !result && new_scale )
2687                 result = proxy_render.create_needed_proxies(new_scale);
2688
2689         if( !result ) { // resize project
2690                 edl->set_proxy(new_scale, new_use_scaler,
2691                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2692         }
2693         undo_after(_("proxy"), LOAD_ALL);
2694         edl->Garbage::remove_user();
2695         restart_brender();
2696
2697         return !result ? proxy_render.needed_proxies.size() : -1;
2698 }
2699
2700 void MWindow::test_plugins(EDL *new_edl, const char *path)
2701 {
2702         char string[BCTEXTLEN];
2703
2704 // Do a check whether plugins exist
2705         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2706                 for( int k=0; k<track->plugin_set.total; ++k ) {
2707                         PluginSet *plugin_set = track->plugin_set[k];
2708                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2709                                         plugin; plugin = (Plugin*)plugin->next ) {
2710                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2711 // ok we need to find it in plugindb
2712                                 PluginServer *server =
2713                                         scan_plugindb(plugin->title, track->data_type);
2714                                 if( !server || server->transition ) {
2715                                         sprintf(string,
2716         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2717           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2718                                                 "effect", _(plugin->title), path);
2719                                         MainError::show_error(string);
2720                                 }
2721                         }
2722                 }
2723
2724                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2725                         if( !edit->transition ) continue;
2726 // ok we need to find transition in plugindb
2727                         PluginServer *server =
2728                                 scan_plugindb(edit->transition->title, track->data_type);
2729                         if( !server || !server->transition ) {
2730                                 sprintf(string,
2731         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2732           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2733                                         "transition", _(edit->transition->title), path);
2734                                 MainError::show_error(string);
2735                         }
2736                 }
2737         }
2738 }
2739
2740
2741 void MWindow::init_shm(const char *pfn, int64_t min)
2742 {
2743         int64_t result = 0;
2744 // Fix shared memory
2745         FILE *fd = fopen(pfn, "r");
2746         if( fd ) {
2747                 fscanf(fd, "%jd", &result);
2748                 fclose(fd);
2749                 if( result >= min ) return;
2750         }
2751
2752         fd = fopen(pfn, "w");
2753         if( !fd ) return;
2754         fprintf(fd, "0x%jx", min);
2755         fclose(fd);
2756
2757         fd = fopen(pfn, "r");
2758         if( !fd ) {
2759                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2760                 return;
2761         }
2762
2763         fscanf(fd, "%jd", &result);
2764         fclose(fd);
2765         if( result < min ) {
2766                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2767                         "you probably need to be root, or:\n"
2768                         "as root, run: echo 0x%jx > %s\n"
2769                         "before trying to start cinelerra.\n"
2770                         "It should be at least 0x%jx for Cinelerra.\n"),
2771                         pfn, (void *)result, min, pfn, min);
2772         }
2773 }
2774
2775 void MWindow::create_objects(int want_gui,
2776         int want_new,
2777         char *config_path)
2778 {
2779         const int debug = 0;
2780         if(debug) PRINT_TRACE
2781
2782 // For some reason, init_signals must come after show_splash or the signals won't
2783 // get trapped.
2784         init_signals();
2785         if(debug) PRINT_TRACE
2786         init_3d();
2787
2788         if(debug) PRINT_TRACE
2789
2790         if(debug) PRINT_TRACE
2791         default_standard = default_std();
2792         init_defaults(defaults, config_path);
2793         check_language();
2794         show_splash();
2795         init_preferences();
2796         if(splash_window)
2797                 splash_window->update_status(_("Initializing Plugins"));
2798         init_plugins(this, preferences);
2799         if(debug) PRINT_TRACE
2800         init_ladspa_plugins(this, preferences);
2801         if(debug) PRINT_TRACE
2802         init_plugin_tips(*plugindb, cin_lang);
2803         if(splash_window)
2804                 splash_window->update_status(_("Initializing GUI"));
2805         if(debug) PRINT_TRACE
2806         init_theme();
2807
2808         if(debug) PRINT_TRACE
2809         init_error();
2810
2811         if(splash_window)
2812                 splash_window->update_status(_("Initializing Fonts"));
2813         char string[BCTEXTLEN];
2814         strcpy(string, preferences->plugin_dir);
2815         strcat(string, "/" FONT_SEARCHPATH);
2816         BC_Resources::init_fontconfig(string);
2817         if(debug) PRINT_TRACE
2818 // use if plugged
2819         init_x10tv();
2820         if( !x10tv )
2821                 init_wintv();
2822
2823 // Default project created here
2824         init_edl();
2825         if(debug) PRINT_TRACE
2826
2827         init_cache();
2828         if(debug) PRINT_TRACE
2829
2830         Timer timer;
2831
2832         init_awindow();
2833         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2834
2835         init_compositor();
2836         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2837
2838 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2839         if(session->show_vwindow)
2840                 get_viewer(1, DEFAULT_VWINDOW);
2841         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2842
2843         init_gui();
2844         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2845
2846         init_levelwindow();
2847         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2848
2849         init_indexes();
2850         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2851
2852         init_channeldb();
2853         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2854
2855         init_gwindow();
2856         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2857
2858         init_render();
2859         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2860
2861         init_shuttle();
2862         init_brender();
2863         init_exportedl();
2864         init_commercials();
2865         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2866         mainprogress = new MainProgress(this, gui);
2867         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2868         undo = new MainUndo(this);
2869
2870         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2871
2872         plugin_guis = new PluginGUIs(this);
2873         dead_plugins = new ArrayList<PluginServer*>;
2874         keyframe_threads = new ArrayList<KeyFrameThread*>;
2875
2876         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2877                 __LINE__,
2878                 vwindows.size(),
2879                 session->show_vwindow);
2880
2881 // Show all vwindows
2882 //      if(session->show_vwindow) {
2883 //              for(int j = 0; j < vwindows.size(); j++) {
2884 //                      VWindow *vwindow = vwindows[j];
2885 //                      if( !vwindow->is_running() ) continue;
2886 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2887 //                              __LINE__,
2888 //                              vwindow);
2889 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2890 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2891 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2892 //                      vwindow->gui->show_window();
2893 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2894 //                      vwindow->gui->unlock_window();
2895 //              }
2896 //      }
2897
2898
2899         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2900
2901         if(session->show_cwindow)
2902         {
2903                 cwindow->gui->lock_window("MWindow::create_objects 1");
2904                 cwindow->gui->show_window();
2905                 cwindow->gui->unlock_window();
2906         }
2907
2908         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2909         if(session->show_awindow)
2910         {
2911                 awindow->gui->lock_window("MWindow::create_objects 1");
2912                 awindow->gui->show_window();
2913                 awindow->gui->unlock_window();
2914         }
2915
2916         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2917         if(session->show_lwindow)
2918         {
2919                 lwindow->gui->lock_window("MWindow::create_objects 1");
2920                 lwindow->gui->show_window();
2921                 lwindow->gui->unlock_window();
2922         }
2923
2924         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2925                 __LINE__,
2926                 (int)timer.get_difference(),
2927                 gwindow->gui);
2928         if(session->show_gwindow)
2929         {
2930                 gwindow->gui->lock_window("MWindow::create_objects 1");
2931                 gwindow->gui->show_window();
2932                 gwindow->gui->unlock_window();
2933         }
2934
2935         if(debug) PRINT_TRACE
2936
2937         gui->lock_window("MWindow::create_objects 1");
2938         gui->mainmenu->load_defaults(defaults);
2939         gui->mainmenu->update_toggles(0);
2940         gui->update_patchbay();
2941         gui->draw_canvas(0, 0);
2942         gui->draw_cursor(1);
2943         gui->show_window();
2944         gui->raise_window();
2945         gui->unlock_window();
2946         cwindow->gui->lock_window("MWindow::create_objects 1");
2947         cwindow->gui->tool_panel->raise_tool();
2948         cwindow->gui->unlock_window();
2949         if(debug) PRINT_TRACE
2950
2951         if(preferences->use_tipwindow)
2952                 init_tipwindow();
2953         if(debug) PRINT_TRACE
2954
2955         gui->add_keyboard_listener(
2956                 (int (BC_WindowBase::*)(BC_WindowBase *))
2957                 &MWindowGUI::keyboard_listener);
2958
2959         hide_splash();
2960         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2961         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2962         if(debug) PRINT_TRACE
2963
2964         BC_WindowBase::get_resources()->vframe_shm = 1;
2965 }
2966
2967 int MWindow::uses_opengl()
2968 {
2969         if( !playback_3d || !playback_3d->running() ) return 0;
2970         PlaybackConfig *playback_config = edl->session->playback_config;
2971         return playback_config->vconfig->driver == PLAYBACK_X11_GL ? 1 : 0;
2972 }
2973
2974 void MWindow::show_splash()
2975 {
2976 #include "data/heroine_logo9_png.h"
2977         VFrame *frame = new VFramePng(heroine_logo9_png);
2978         BC_DisplayInfo dpyi;
2979         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2980         int rr = (rw < rh ? rw : rh) / 4;
2981         splash_window = new SplashGUI(frame, rr, rr);
2982         splash_window->create_objects();
2983 }
2984
2985 void MWindow::hide_splash()
2986 {
2987         if(splash_window)
2988                 delete splash_window;
2989         splash_window = 0;
2990 }
2991
2992
2993 void MWindow::start()
2994 {
2995 ENABLE_BUFFER
2996 //PRINT_TRACE
2997 //      vwindows[DEFAULT_VWINDOW]->start();
2998         awindow->start();
2999 //PRINT_TRACE
3000         cwindow->start();
3001 //PRINT_TRACE
3002         lwindow->start();
3003 //PRINT_TRACE
3004         gwindow->start();
3005 //PRINT_TRACE
3006 //      Thread::start();
3007 //PRINT_TRACE
3008         playback_3d->start();
3009 //PRINT_TRACE
3010 }
3011
3012 void MWindow::run()
3013 {
3014         run_lock->lock("MWindow::run");
3015         gui->run_window();
3016         stop_playback(1);
3017
3018         brender_lock->lock("MWindow::run 1");
3019         delete brender;         brender = 0;
3020         brender_lock->unlock();
3021
3022         interrupt_indexes();
3023         clean_indexes();
3024         save_defaults();
3025         run_lock->unlock();
3026 }
3027
3028 void MWindow::show_vwindow(int raise)
3029 {
3030         int total_running = 0;
3031         session->show_vwindow = 1;
3032
3033 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
3034 // Raise all windows which are visible
3035         for(int j = 0; j < vwindows.size(); j++) {
3036                 VWindow *vwindow = vwindows[j];
3037                 if( !vwindow->is_running() ) continue;
3038                 total_running++;
3039                 if( !raise && !vwindow->gui->is_hidden() ) continue;
3040                 vwindow->gui->lock_window("MWindow::show_vwindow");
3041                 vwindow->gui->show_window(0);
3042                 vwindow->gui->raise_window();
3043                 vwindow->gui->flush();
3044                 vwindow->gui->unlock_window();
3045         }
3046 // If no windows visible
3047         if( !total_running )
3048                 get_viewer(1, DEFAULT_VWINDOW);
3049
3050         gui->mainmenu->show_vwindow->set_checked(1);
3051 }
3052
3053
3054 void MWindow::hide_vwindow(int raise)
3055 {
3056         session->show_vwindow = 0;
3057         int total_running = 0;
3058
3059         for(int j = 0; j < vwindows.size(); j++) {
3060                 VWindow *vwindow = vwindows[j];
3061                 if( !vwindow->is_running() ) continue;
3062                 total_running++;
3063                 if( !raise && !vwindow->gui->is_hidden() ) continue;
3064                 vwindow->gui->lock_window("MWindow::show_vwindow");
3065                 vwindow->gui->hide_window(0);
3066                 vwindow->gui->unlock_window();
3067         }
3068         gui->mainmenu->show_vwindow->set_checked(0);
3069 }
3070
3071
3072 void MWindow::show_awindow()
3073 {
3074         session->show_awindow = 1;
3075         awindow->gui->lock_window("MWindow::show_awindow");
3076         awindow->gui->show_window();
3077         awindow->gui->raise_window();
3078         awindow->gui->flush();
3079         awindow->gui->unlock_window();
3080         gui->mainmenu->show_awindow->set_checked(1);
3081 }
3082
3083 void MWindow::hide_awindow()
3084 {
3085         session->show_awindow = 0;
3086
3087         awindow->gui->lock_window("MWindow::show_awindow");
3088         awindow->gui->hide_window();
3089         awindow->gui->unlock_window();
3090         gui->mainmenu->show_awindow->set_checked(0);
3091 }
3092
3093
3094 char *MWindow::get_cwindow_display()
3095 {
3096         char *x11_host = screens < 2 || session->window_config == 0 ?
3097                 session->a_x11_host : session->b_x11_host;
3098         return *x11_host ? x11_host : 0;
3099 }
3100
3101 void MWindow::show_cwindow()
3102 {
3103         session->show_cwindow = 1;
3104         cwindow->show_window();
3105         cwindow->gui->tool_panel->raise_tool();
3106         gui->mainmenu->show_cwindow->set_checked(1);
3107 }
3108
3109
3110 void MWindow::hide_cwindow()
3111 {
3112         session->show_cwindow = 0;
3113
3114         cwindow->gui->lock_window("MWindow::show_cwindow");
3115         cwindow->gui->hide_window();
3116         cwindow->gui->unlock_window();
3117         gui->mainmenu->show_cwindow->set_checked(0);
3118 }
3119
3120
3121 void MWindow::show_gwindow()
3122 {
3123         session->show_gwindow = 1;
3124
3125         gwindow->gui->lock_window("MWindow::show_gwindow");
3126         gwindow->gui->show_window();
3127         gwindow->gui->raise_window();
3128         gwindow->gui->flush();
3129         gwindow->gui->unlock_window();
3130
3131         gui->mainmenu->show_gwindow->set_checked(1);
3132 }
3133
3134 void MWindow::hide_gwindow()
3135 {
3136         session->show_gwindow = 0;
3137
3138         gwindow->gui->lock_window("MWindow::show_gwindow");
3139         gwindow->gui->hide_window();
3140         gwindow->gui->unlock_window();
3141         gui->mainmenu->show_gwindow->set_checked(0);
3142 }
3143
3144 void MWindow::show_lwindow()
3145 {
3146         session->show_lwindow = 1;
3147         lwindow->gui->lock_window("MWindow::show_lwindow");
3148         lwindow->gui->show_window();
3149         lwindow->gui->raise_window();
3150         lwindow->gui->flush();
3151         lwindow->gui->unlock_window();
3152         gui->mainmenu->show_lwindow->set_checked(1);
3153 }
3154
3155 void MWindow::hide_lwindow()
3156 {
3157         session->show_lwindow = 0;
3158
3159         lwindow->gui->lock_window("MWindow::show_lwindow");
3160         lwindow->gui->hide_window();
3161         lwindow->gui->unlock_window();
3162         gui->mainmenu->show_lwindow->set_checked(0);
3163 }
3164
3165
3166 void MWindow::restore_windows()
3167 {
3168         gui->unlock_window();
3169         if( !session->show_vwindow ) {
3170                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
3171                         VWindow *vwindow = vwindows[i];
3172                         if( !vwindow || !vwindow->is_running() ) continue;
3173                         vwindow->gui->lock_window("MWindow::restore_windows");
3174                         vwindow->gui->close(1);
3175                         vwindow->gui->unlock_window();
3176                 }
3177         }
3178         else 
3179                 show_vwindow(0);
3180
3181         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
3182                 awindow->gui->lock_window("MWindow::restore_windows");
3183                 awindow->gui->close_event();
3184                 awindow->gui->unlock_window();
3185         }
3186         else if( session->show_awindow && awindow->gui->is_hidden() )
3187                 show_awindow();
3188
3189         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
3190                 cwindow->gui->lock_window("MWindow::restore_windows");
3191                 cwindow->hide_window();
3192                 cwindow->gui->unlock_window();
3193         }
3194         else if( session->show_cwindow && cwindow->gui->is_hidden() )
3195                 show_cwindow();
3196
3197         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
3198                 gwindow->gui->lock_window("MWindow::restore_windows");
3199                 gwindow->gui->close_event();
3200                 gwindow->gui->unlock_window();
3201         }
3202         else if( session->show_gwindow && gwindow->gui->is_hidden() )
3203                 show_gwindow();
3204
3205         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
3206                 lwindow->gui->lock_window("MWindow::restore_windows");
3207                 lwindow->gui->close_event();
3208                 lwindow->gui->unlock_window();
3209         }
3210         else if( session->show_lwindow && lwindow->gui->is_hidden() )
3211                 show_lwindow();
3212
3213         tile_mixers();
3214         gui->lock_window("MWindow::restore_windows");
3215         gui->focus();
3216 }
3217
3218 void MWindow::load_layout(const char *layout)
3219 {
3220         char path[BCTEXTLEN];
3221         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3222         session->load_file(path);
3223         restore_windows();
3224         gui->default_positions();
3225         save_defaults();
3226 }
3227
3228 void MWindow::save_layout(const char *layout)
3229 {
3230         char path[BCTEXTLEN];
3231         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3232         session->save_file(path);
3233 }
3234
3235 void MWindow::delete_layout(const char *layout)
3236 {
3237         char path[BCTEXTLEN];
3238         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3239         unlink(path);
3240 }
3241
3242 int MWindow::tile_windows(int window_config)
3243 {
3244         int need_reload = 0;
3245         int play_config = window_config==0 ? 0 : 1;
3246         edl->session->playback_config->load_defaults(defaults, play_config);
3247         session->default_window_positions(window_config);
3248         if( screens == 1 ) {
3249                 gui->default_positions();
3250                 sync_parameters(CHANGE_ALL);
3251         }
3252         else
3253                 need_reload = 1;
3254         return need_reload;
3255 }
3256
3257 void MWindow::toggle_loop_playback()
3258 {
3259         edl->local_session->loop_playback = !edl->local_session->loop_playback;
3260         set_loop_boundaries();
3261         save_backup();
3262
3263         gui->draw_overlays(1);
3264         sync_parameters(CHANGE_PARAMS);
3265 }
3266
3267 void MWindow::set_screens(int value)
3268 {
3269         screens = value;
3270 }
3271
3272 void MWindow::set_auto_keyframes(int value)
3273 {
3274         edl->session->auto_keyframes = value;
3275         gui->mbuttons->edit_panel->keyframe->update(value);
3276         gui->flush();
3277         cwindow->gui->lock_window("MWindow::set_auto_keyframes");
3278         cwindow->gui->flush();
3279         cwindow->gui->unlock_window();
3280 }
3281
3282 void MWindow::set_span_keyframes(int value)
3283 {
3284         edl->session->span_keyframes = value;
3285         gui->mbuttons->edit_panel->span_keyframe->update(value);
3286         gui->flush();
3287         cwindow->gui->lock_window("MWindow::set_span_keyframes");
3288         cwindow->gui->flush();
3289         cwindow->gui->unlock_window();
3290 }
3291
3292 void MWindow::set_auto_visibility(Autos *autos, int value)
3293 {
3294         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
3295                 edl->session->auto_conf->plugins = value;
3296         else if( autos->autoidx >= 0 )
3297                 edl->session->auto_conf->autos[autos->autoidx] = value;
3298         else
3299                 return;
3300
3301         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3302         gui->mainmenu->update_toggles(1);
3303         gui->unlock_window();
3304         gwindow->gui->update_toggles(1);
3305         gui->lock_window("MWindow::set_auto_visibility");
3306 }
3307
3308 void MWindow::set_keyframe_type(int mode)
3309 {
3310         gui->lock_window("MWindow::set_keyframe_type");
3311         edl->local_session->floatauto_type = mode;
3312         gui->mainmenu->update_toggles(0);
3313         gui->unlock_window();
3314 }
3315
3316 int MWindow::set_editing_mode(int new_editing_mode)
3317 {
3318         edl->session->editing_mode = new_editing_mode;
3319         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
3320         gui->mbuttons->edit_panel->update();
3321         gui->set_editing_mode(1);
3322
3323         cwindow->gui->lock_window("MWindow::set_editing_mode");
3324         cwindow->gui->edit_panel->update();
3325         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
3326         cwindow->gui->unlock_window();
3327         return 0;
3328 }
3329
3330 void MWindow::toggle_editing_mode()
3331 {
3332         int mode = edl->session->editing_mode;
3333         if( mode == EDITING_ARROW )
3334                 set_editing_mode(EDITING_IBEAM);
3335         else
3336                 set_editing_mode(EDITING_ARROW);
3337 }
3338
3339 void MWindow::toggle_camera_xyz()
3340 {
3341         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3342         gwindow->gui->toggle_camera_xyz();
3343         gwindow->gui->unlock_window();
3344 }
3345
3346 void MWindow::toggle_projector_xyz()
3347 {
3348         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3349         gwindow->gui->toggle_projector_xyz();
3350         gwindow->gui->unlock_window();
3351 }
3352
3353 void MWindow::set_labels_follow_edits(int value)
3354 {
3355         edl->session->labels_follow_edits = value;
3356         gui->mbuttons->edit_panel->locklabels->update(value);
3357         gui->mainmenu->labels_follow_edits->set_checked(value);
3358         gui->flush();
3359 }
3360
3361 void MWindow::sync_parameters(int change_type)
3362 {
3363         if( in_destructor ) return;
3364
3365 // Sync engines which are playing back
3366         if( cwindow->playback_engine->is_playing_back ) {
3367                 if( change_type == CHANGE_PARAMS ) {
3368 // TODO: block keyframes until synchronization is done
3369                         cwindow->playback_engine->sync_parameters(edl);
3370                 }
3371                 else {
3372 // Stop and restart
3373                         int command = cwindow->playback_engine->command->command;
3374 // Waiting for tracking to finish would make the restart position more
3375 // accurate but it can't lock the window to stop tracking for some reason.
3376 // Not waiting for tracking gives a faster response but restart position is
3377 // only as accurate as the last tracking update.
3378                         cwindow->playback_engine->transport_stop(0);
3379                         cwindow->playback_engine->next_command->realtime = 1;
3380                         cwindow->playback_engine->transport_command(command, change_type, edl, 0);
3381                 }
3382         }
3383         else {
3384                 cwindow->refresh_frame(change_type);
3385         }
3386 }
3387
3388 void MWindow::age_caches()
3389 {
3390 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3391 // __LINE__,
3392 // preferences->cache_size,
3393 // audio_cache->get_memory_usage(1),
3394 // video_cache->get_memory_usage(1),
3395 // frame_cache->get_memory_usage(),
3396 // wave_cache->get_memory_usage(),
3397 // memory_usage);
3398         frame_cache->age_cache(512);
3399         wave_cache->age_cache(8192);
3400
3401         int64_t memory_usage;
3402         int64_t prev_memory_usage = 0;
3403         int result = 0;
3404         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3405         while( !result && prev_memory_usage !=
3406                 (memory_usage=video_cache->get_memory_usage(1)) &&
3407                 memory_usage > video_size ) {
3408                 video_cache->delete_oldest();
3409                 prev_memory_usage = memory_usage;
3410         }
3411
3412         prev_memory_usage = 0;
3413         result = 0;
3414         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3415         while( !result && prev_memory_usage !=
3416                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3417                 memory_usage > audio_size ) {
3418                 audio_cache->delete_oldest();
3419                 prev_memory_usage = memory_usage;
3420         }
3421 }
3422
3423 void MWindow::reset_android_remote()
3424 {
3425         gui->use_android_remote(preferences->android_remote);
3426 }
3427
3428
3429 void MWindow::show_keyframe_gui(Plugin *plugin)
3430 {
3431         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3432 // Find existing thread
3433         for( int i=0; i<keyframe_threads->size(); ++i ) {
3434                 int plugin_id = keyframe_threads->get(i)->plugin_id;
3435                 if( plugin_id == plugin->orig_id ) {
3436                         keyframe_threads->get(i)->start_window(plugin, 0);
3437                         keyframe_gui_lock->unlock();
3438                         return;
3439                 }
3440         }
3441
3442 // Find unused thread
3443         for( int i=0; i<keyframe_threads->size(); ++i ) {
3444                 if( keyframe_threads->get(i)->plugin_id < 0 ) {
3445                         keyframe_threads->get(i)->start_window(plugin, 0);
3446                         keyframe_gui_lock->unlock();
3447                         return;
3448                 }
3449         }
3450
3451 // Create new thread
3452         KeyFrameThread *thread = new KeyFrameThread(this);
3453         keyframe_threads->append(thread);
3454         thread->start_window(plugin, 0);
3455         keyframe_gui_lock->unlock();
3456 }
3457
3458
3459 void MWindow::show_plugin(Plugin *plugin)
3460 {
3461         int done = 0;
3462
3463 SET_TRACE
3464 // Remove previously deleted plugin GUIs
3465         dead_plugin_lock->lock("MWindow::show_plugin");
3466         dead_plugins->remove_all_objects();
3467         dead_plugin_lock->unlock();
3468
3469 //printf("MWindow::show_plugin %d\n", __LINE__);
3470 SET_TRACE
3471
3472         plugin_gui_lock->lock("MWindow::show_plugin");
3473         for( int i=0; i<plugin_guis->total; ++i ) {
3474 // Pointer/id comparison
3475                 PluginServer *plugin_gui = plugin_guis->get(i);
3476                 if( plugin_gui->plugin_id == plugin->orig_id ) {
3477                         plugin_gui->raise_window();
3478                         done = 1;
3479                         break;
3480                 }
3481         }
3482 SET_TRACE
3483
3484 //printf("MWindow::show_plugin 1\n");
3485         if( !done && !plugin->track ) {
3486                 printf("MWindow::show_plugin track not defined.\n");
3487                 done = 1;
3488         }
3489         if( !done ) {
3490                 PluginServer *server = scan_plugindb(plugin->title,
3491                         plugin->track->data_type);
3492
3493 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3494                 if(server && server->uses_gui)
3495                 {
3496                         PluginServer *gui = new PluginServer(*server);
3497                         plugin_guis->append(gui);
3498 // Needs mwindow to do GUI
3499                         gui->set_mwindow(this);
3500                         gui->open_plugin(0, preferences, edl, plugin);
3501                         plugin->show = 1;
3502                         gui->show_gui();
3503                 }
3504         }
3505         plugin_gui_lock->unlock();
3506 // update show/gui_id
3507         sync_parameters(CHANGE_PARAMS);
3508 //printf("MWindow::show_plugin %d\n", __LINE__);
3509 SET_TRACE
3510 //sleep(1);
3511 //printf("MWindow::show_plugin 2\n");
3512 }
3513
3514 void MWindow::hide_plugin(Plugin *plugin, int lock)
3515 {
3516         plugin->show = 0;
3517         return hide_plugin(plugin->orig_id, lock);
3518 }
3519
3520 void MWindow::hide_plugin(int plugin_id, int lock)
3521 {
3522 // Update the toggle
3523         gui->lock_window("MWindow::hide_plugin");
3524         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3525         gui->unlock_window();
3526
3527         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3528         for( int i=0; i<plugin_guis->total; ++i ) {
3529                 PluginServer *plugin_gui = plugin_guis->get(i);
3530                 if( plugin_gui->plugin_id == plugin_id ) {
3531                         plugin_guis->remove(plugin_gui);
3532                         if(lock) plugin_gui_lock->unlock();
3533 // Last command executed in client side close
3534 // Schedule for deletion
3535                         plugin_gui->hide_gui();
3536                         delete_plugin(plugin_gui);
3537 //sleep(1);
3538                         return;
3539                 }
3540         }
3541         if(lock) plugin_gui_lock->unlock();
3542 // update show/gui_id
3543         sync_parameters(CHANGE_PARAMS);
3544 }
3545
3546 void MWindow::delete_plugin(PluginServer *plugin)
3547 {
3548         dead_plugin_lock->lock("MWindow::delete_plugin");
3549         dead_plugins->append(plugin);
3550         dead_plugin_lock->unlock();
3551 }
3552
3553 void MWindow::hide_plugins()
3554 {
3555         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3556         while(plugin_guis->size())
3557         {
3558                 PluginServer *ptr = plugin_guis->get(0);
3559                 plugin_guis->remove(ptr);
3560                 plugin_gui_lock->unlock();
3561 // Last command executed in client side close
3562 // Schedule for deletion
3563                 ptr->hide_gui();
3564                 delete_plugin(ptr);
3565                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3566         }
3567         plugin_gui_lock->unlock();
3568
3569         hide_keyframe_guis();
3570 }
3571
3572 void MWindow::hide_keyframe_guis()
3573 {
3574         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3575         for(int i = 0; i < keyframe_threads->size(); i++)
3576         {
3577                 keyframe_threads->get(i)->close_window();
3578         }
3579         keyframe_gui_lock->unlock();
3580 }
3581
3582 void MWindow::hide_keyframe_gui(Plugin *plugin)
3583 {
3584         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3585         for( int i = 0; i < keyframe_threads->size(); i++) {
3586                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3587                 if( keyframe_gui->plugin_id == plugin->orig_id ) {
3588                         keyframe_gui->close_window();
3589                         break;
3590                 }
3591         }
3592         keyframe_gui_lock->unlock();
3593 }
3594
3595 int MWindow::get_hash_color(Edit *edit)
3596 {
3597         Indexable *idxbl = edit->asset ?
3598                 (Indexable*)edit->asset : (Indexable*)edit->nested_edl;
3599         if( !idxbl ) return 0;
3600         char path[BCTEXTLEN];
3601 // map proxy colors to unproxy colors
3602         if( edl->session->proxy_state != PROXY_ACTIVE ||
3603             !edit->asset || edit->track->data_type != TRACK_VIDEO ||
3604             ProxyRender::from_proxy_path(path, (Asset*)idxbl, edl->session->proxy_scale) )
3605                 strcpy(path, idxbl->path);
3606         char *cp = strrchr(path, '/');
3607         cp = !cp ? path : cp+1;
3608         uint8_t *bp = (uint8_t*)cp;
3609         int v = 0;
3610         while( *bp ) v += *bp++;
3611         return get_hash_color(v);
3612 }
3613
3614 int MWindow::get_hash_color(int v)
3615 {
3616         int hash = 0x303030;
3617         if( v & 0x01 ) hash ^= 0x000040;
3618         if( v & 0x02 ) hash ^= 0x004000;
3619         if( v & 0x04 ) hash ^= 0x400000;
3620         if( v & 0x08 ) hash ^= 0x080000;
3621         if( v & 0x10 ) hash ^= 0x000800;
3622         if( v & 0x20 ) hash ^= 0x000008;
3623         if( v & 0x40 ) hash ^= 0x404040;
3624         if( v & 0x80 ) hash ^= 0x080808;
3625         return hash;
3626 }
3627
3628 int MWindow::get_group_color(int v)
3629 {
3630         int color = 0x606060;
3631         if( v & 0x01 ) color ^= 0x000080;
3632         if( v & 0x02 ) color ^= 0x008000;
3633         if( v & 0x04 ) color ^= 0x800000;
3634         if( v & 0x08 ) color ^= 0x100000;
3635         if( v & 0x10 ) color ^= 0x001000;
3636         if( v & 0x20 ) color ^= 0x000010;
3637         if( v & 0x40 ) color ^= 0x080808;
3638         if( v & 0x80 ) color ^= 0x909090;
3639         return color;
3640 }
3641
3642 int MWindow::get_title_color(Edit *edit)
3643 {
3644         unsigned color = edit->color & 0xffffff;
3645         unsigned alpha = (~edit->color>>24) & 0xff;
3646         if( !color ) {
3647                 if( edit->group_id )
3648                         color = get_group_color(edit->group_id);
3649                 else if( preferences->autocolor_assets )
3650                         color = get_hash_color(edit);
3651                 else
3652                         return 0;
3653         }
3654         if( alpha == 0xff )
3655                 alpha = session->title_bar_alpha*255;
3656         return color | (~alpha<<24);
3657 }
3658
3659 void MWindow::update_keyframe_guis()
3660 {
3661 // Send new configuration to keyframe GUI's
3662         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3663         for( int i=0; i<keyframe_threads->size(); ++i ) {
3664                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3665                 Plugin *plugin = edl->tracks->plugin_exists(keyframe_gui->plugin_id);
3666                 if( plugin )
3667                         keyframe_gui->update_gui(1);
3668                 else
3669                         keyframe_gui->close_window();
3670         }
3671         keyframe_gui_lock->unlock();
3672 }
3673
3674 void MWindow::update_plugin_guis(int do_keyframe_guis)
3675 {
3676 // Send new configuration to plugin GUI's
3677         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3678
3679         for( int i=0; i<plugin_guis->size(); ++i ) {
3680                 PluginServer *plugin_gui = plugin_guis->get(i);
3681                 Plugin *plugin = edl->tracks->plugin_exists(plugin_gui->plugin_id);
3682                 if( plugin && plugin->show )
3683                         plugin_gui->update_gui();
3684                 else {
3685 // Schedule for deletion if no plugin or not shown
3686                         plugin_guis->remove_number(i--);
3687                         plugin_gui->hide_gui();
3688                         delete_plugin(plugin_gui);
3689                 }
3690         }
3691
3692
3693 // Change plugin variable if not visible
3694         Track *track = edl->tracks->first;
3695         for( ; track; track=track->next ) {
3696                 for( int i=0; i < track->plugin_set.size(); ++i ) {
3697                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3698                         for( ; plugin; plugin = (Plugin*)plugin->next ) {
3699                                 int got_it = 0;
3700                                 for( int i=0; i<plugin_guis->size(); ++i ) {
3701                                         PluginServer *server = plugin_guis->get(i);
3702                                         if( server->plugin_id == plugin->orig_id ) {
3703                                                 got_it = 1;
3704                                                 break;
3705                                         }
3706                                 }
3707                                 if( !got_it ) plugin->show = 0;
3708                         }
3709                 }
3710         }
3711
3712         plugin_gui_lock->unlock();
3713         if( do_keyframe_guis )
3714                 update_keyframe_guis();
3715 }
3716
3717 void MWindow::stop_plugin_guis()
3718 {
3719 // Send new configuration to plugin GUI's
3720         plugin_gui_lock->lock("MWindow::stop_plugin_guis");
3721
3722         for( int i=0; i<plugin_guis->size(); ++i ) {
3723                 PluginServer *plugin_gui = plugin_guis->get(i);
3724                 plugin_gui->render_stop();
3725         }
3726         plugin_gui_lock->unlock(); 
3727 }
3728
3729 int MWindow::plugin_gui_open(Plugin *plugin)
3730 {
3731         int gui_id = plugin->gui_id;
3732         if( gui_id < 0 ) return 0;
3733         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3734         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3735         int result = plugin_server ? 1 : 0;
3736         plugin_gui_lock->unlock();
3737         return result;
3738 }
3739
3740
3741 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3742 {
3743         int gui_id = plugin->gui_id;
3744         if( gui_id < 0 ) return;
3745         plugin_gui_lock->lock("MWindow::render_plugin_gui 0");
3746         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3747         if( plugin_server )
3748                 plugin_server->render_gui(data);
3749         plugin_gui_lock->unlock();
3750 }
3751
3752 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3753 {
3754         int gui_id = plugin->gui_id;
3755         if( gui_id < 0 ) return;
3756         plugin_gui_lock->lock("MWindow::render_plugin_gui 1");
3757         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3758         if( plugin_server )
3759                 plugin_server->render_gui(data, size);
3760         plugin_gui_lock->unlock();
3761 }
3762
3763 void MWindow::reset_plugin_gui_frames(Plugin *plugin)
3764 {
3765         int gui_id = plugin->gui_id;
3766         if( gui_id < 0 ) return;
3767         plugin_gui_lock->lock("MWindow::reset_plugin_gui_frames");
3768         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3769         if( plugin_server )
3770                 plugin_server->reset_plugin_gui_frames();
3771         plugin_gui_lock->unlock();
3772 }
3773
3774 void MWindow::render_plugin_gui_frames(PluginClientFrames *frames, Plugin *plugin)
3775 {
3776         int gui_id = plugin->gui_id;
3777         if( gui_id < 0 ) return;
3778         plugin_gui_lock->lock("MWindow::render_plugin_gui_frames");
3779         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3780         if( plugin_server )
3781                 plugin_server->render_plugin_gui_frames(frames);
3782         plugin_gui_lock->unlock();
3783 }
3784
3785 double MWindow::get_tracking_position()
3786 {
3787         return edl->local_session->get_selectionstart(1);
3788 }
3789
3790 int MWindow::get_tracking_direction()
3791 {
3792         return cwindow->playback_engine->get_direction();
3793 }
3794
3795 void MWindow::update_plugin_states()
3796 {
3797         plugin_gui_lock->lock("MWindow::update_plugin_states");
3798         for( int i=0; i<plugin_guis->total; ++i ) {
3799 // Get a plugin GUI
3800                 PluginServer *src_plugingui = plugin_guis->get(i);
3801                 int plugin_id = src_plugingui->plugin_id;
3802                 Plugin *src_plugin = edl->tracks->plugin_exists(plugin_id);
3803 // Doesn't exist anymore
3804                 if( !src_plugin ) {
3805                         hide_plugin(plugin_id, 0);
3806                         --i;
3807                 }
3808         }
3809         plugin_gui_lock->unlock();
3810 }
3811
3812
3813 void MWindow::update_plugin_titles()
3814 {
3815         for( int i=0; i<plugin_guis->total; ++i )
3816                 plugin_guis->get(i)->update_title();
3817 }
3818
3819 int MWindow::asset_to_edl(EDL *new_edl,
3820         Asset *new_asset,
3821         RecordLabels *labels)
3822 {
3823 const int debug = 0;
3824 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3825 __LINE__,
3826 new_asset->layers);
3827 // Keep frame rate, sample rate, and output size unchanged.
3828 // These parameters would revert the project if VWindow displayed an asset
3829 // of different size than the project.
3830         if(new_asset->video_data)
3831         {
3832                 new_edl->session->video_tracks = new_asset->layers;
3833         }
3834         else
3835                 new_edl->session->video_tracks = 0;
3836
3837 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3838
3839
3840
3841
3842
3843         if(new_asset->audio_data)
3844         {
3845                 new_edl->session->audio_tracks = new_asset->channels;
3846         }
3847         else
3848                 new_edl->session->audio_tracks = 0;
3849 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3850
3851 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3852         new_edl->create_default_tracks();
3853 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3854 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3855
3856
3857
3858 //printf("MWindow::asset_to_edl 3\n");
3859         new_edl->insert_asset(new_asset,
3860                 0,
3861                 0,
3862                 0,
3863                 labels);
3864 //printf("MWindow::asset_to_edl 3\n");
3865 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3866
3867 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3868         if(edl->session->cursor_on_frames)
3869         {
3870                 double length = new_edl->tracks->total_length();
3871                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3872                 new_edl->tracks->clear(length, edl_length, 1, 1);
3873         }
3874
3875
3876
3877
3878         char string[BCTEXTLEN];
3879         FileSystem fs;
3880         fs.extract_name(string, new_asset->path);
3881 //printf("MWindow::asset_to_edl 3\n");
3882
3883         strcpy(new_edl->local_session->clip_title, string);
3884 //printf("MWindow::asset_to_edl 4 %s\n", string);
3885 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3886
3887         new_edl->local_session->asset2edl = 1;
3888         return 0;
3889 }
3890
3891
3892 // Reset everything after a load.
3893 void MWindow::update_project(int load_mode)
3894 {
3895         const int debug = 0;
3896
3897         if(debug) PRINT_TRACE
3898         edl->tracks->update_y_pixels(theme);
3899         session->update_clip_number();
3900
3901         if(debug) PRINT_TRACE
3902
3903         if( load_mode == LOADMODE_REPLACE ||
3904             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3905                 edl->session->timecode_offset = 0;
3906                 gui->close_keyvalue_popup();
3907                 gui->load_panes();
3908         }
3909
3910         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 1);
3911         if(debug) PRINT_TRACE
3912         gui->unlock_window();
3913         init_brender();
3914
3915         cwindow->update(0, 0, 1, 1, 1);
3916
3917         if(debug) PRINT_TRACE
3918
3919 // Close all the vwindows
3920         if( load_mode == LOADMODE_REPLACE ||
3921             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3922                 if(debug) PRINT_TRACE
3923                 int first_vwindow = 0;
3924                 if(session->show_vwindow) first_vwindow = 1;
3925 // Change visible windows to no source
3926                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3927                         VWindow *vwindow = vwindows[i];
3928                         if( !vwindow->is_running() ) continue;
3929                         vwindow->change_source(-1);
3930                 }
3931
3932 // Close remaining windows
3933                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3934                         VWindow *vwindow = vwindows[i];
3935                         if( !vwindow->is_running() ) continue;
3936                         vwindow->close_window();
3937                 }
3938                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3939                         VWindow *vwindow = get_viewer(1, -1);
3940                         vwindow->change_source(i);
3941                 }
3942                 if(debug) PRINT_TRACE
3943                 select_zwindow(0);
3944                 close_mixers(0);
3945
3946                 for( int i=0; i<edl->mixers.size(); ++i ) {
3947                         Mixer *mixer = edl->mixers[i];
3948                         if( !mixer->show ) continue;
3949                         ZWindow *zwindow = get_mixer(mixer);
3950                         zwindow->set_title(mixer->title);
3951                         zwindow->start();
3952                 }
3953                 cwindow->gui->canvas->set_zoom(edl, 0);
3954         }
3955         update_vwindow();
3956
3957         if(debug) PRINT_TRACE
3958         cwindow->gui->lock_window("MWindow::update_project 2");
3959         cwindow->gui->timebar->update(0);
3960         Track *track = cwindow->calculate_affected_track();
3961         cwindow->mask_track_id = track ? track->get_id() : -1;
3962         cwindow->gui->tool_panel->raise_tool();
3963         cwindow->gui->update_canvas(0);
3964         cwindow->gui->unlock_window();
3965
3966         if(debug) PRINT_TRACE
3967         cwindow->refresh_frame(CHANGE_ALL);
3968
3969         awindow->gui->async_update_assets();
3970         if(debug) PRINT_TRACE
3971
3972         gui->lock_window("MWindow::update_project");
3973         gui->update_mixers(0, 0);
3974         gui->flush();
3975         if(debug) PRINT_TRACE
3976 }
3977
3978 void MWindow::stack_push(EDL *new_edl, Indexable *idxbl)
3979 {
3980         int got_indexes = 0;
3981         for( int i=0; i<new_edl->nested_edls.size(); ++i ) {
3982                 EDL *nested_edl = new_edl->nested_edls[i];
3983                 mainindexes->add_indexable(nested_edl);
3984                 edl->nested_edls.update_index(nested_edl);
3985                 got_indexes = 1;
3986         }
3987         for( Asset *asset=new_edl->assets->first; asset; asset=asset->next ) {
3988                 mainindexes->add_indexable(asset);
3989                 edl->assets->update(asset);
3990                 got_indexes = 1;
3991         }
3992 // Start examining next batch of index files
3993         if( got_indexes )
3994                 mainindexes->start_build();
3995
3996 // needs gui lock
3997         gui->lock_window("MWindow::stack_push");
3998         if( stack.size() < 9 ) {
3999                 save_backup();
4000                 hide_plugins();
4001                 undo_before();
4002                 StackItem &item = stack.append();
4003                 item.edl = edl;
4004                 item.new_edl = new_edl;
4005                 item.duration = new_edl->tracks->total_length();
4006                 item.undo = undo;
4007                 item.idxbl = idxbl;
4008                 item.mtime = 0;
4009                 if( idxbl && idxbl->is_asset ) {
4010                         struct stat st;
4011                         Asset *asset = (Asset *)idxbl;
4012                         if( asset->format == FILE_REF &&
4013                             !stat(asset->path, &st) )
4014                                 item.mtime = st.st_mtime;
4015                 }
4016                 edl = new_edl;
4017                 edl->add_user();
4018                 strcpy(session->filename, edl->path);
4019                 undo = new MainUndo(this);
4020                 gui->stack_button->update();
4021                 update_project(LOADMODE_REPLACE);
4022         }
4023         gui->unlock_window();
4024         show_plugins();
4025 }
4026
4027 void MWindow::stack_pop()
4028 {
4029         if( !stack.size() ) return;
4030 // writes on config_path/backup%d.xml
4031         save_backup();
4032         hide_plugins();
4033 // already have gui lock
4034         StackItem &item = stack.last();
4035 // session edl replaced, overwrite and save clip data
4036         if( item.new_edl != edl )
4037                 item.new_edl->overwrite_clip(edl);
4038         Indexable *idxbl = item.idxbl;
4039         if( idxbl && idxbl->is_asset && item.mtime ) {
4040                 Asset *asset = (Asset *)idxbl;
4041                 if( asset->format == FILE_REF ) {
4042                         char *path = asset->path;
4043                         struct stat st;
4044                         if( stat(path, &st) || item.mtime == st.st_mtime ) {
4045                                 int cw = xS(250), ch = yS(150), px, py;
4046                                 gui->get_pop_cursor(px, py);
4047                                 px -= cw/2;  py -= ch/2;
4048                                 ConfirmRefWindow confirm(this, path, px, py, cw, ch);
4049                                 confirm.create_objects();
4050                                 int result = confirm.run_window();
4051                                 if( !result ) {
4052                                         FileXML file;
4053                                         item.new_edl->save_xml(&file, path);
4054                                         file.terminate_string();
4055                                         if(file.write_to_file(path))
4056                                                 eprintf(_("Cant write FileREF: %s"), path);
4057                                 }
4058                         }
4059                 }
4060         }
4061         edl->remove_user();
4062         edl = item.edl;
4063         delete undo;
4064         undo = item.undo;
4065         stack.remove();
4066         if( idxbl ) {
4067 // resize the indexable edits if the new_edl duration changed
4068                 double duration = item.new_edl->tracks->total_length();
4069                 double dt = duration - item.duration;
4070                 if( fabs(dt) > 1e-4 )
4071                         edl->tracks->update_idxbl_length(idxbl->id, dt);
4072                 gui->unlock_window();
4073                 gui->resource_thread->close_indexable(idxbl);
4074                 remove_from_caches(idxbl);
4075                 IndexFile::delete_index_files(preferences, idxbl);
4076                 mainindexes->add_indexable(idxbl);
4077                 mainindexes->start_build();
4078                 awindow->gui->async_update_assets();
4079                 gui->lock_window("MWindow::stack_pop");
4080         }
4081         strcpy(session->filename, edl->path);
4082         update_project(LOADMODE_REPLACE);
4083         undo_after(_("open edl"), LOAD_ALL);
4084         show_plugins();
4085         gui->stack_button->update();
4086 }
4087
4088 int MWindow::save(EDL *edl, char *filename, int stat)
4089 {
4090         FileXML file;
4091         edl->save_xml(&file, filename);
4092         file.terminate_string();
4093         if( file.write_to_file(filename) ) {
4094                 eprintf(_("Couldn't open %s"), filename);
4095                 return 1;
4096         }
4097         if( stat ) {
4098                 char string[BCTEXTLEN];
4099                 char *filename = stack.size() ?
4100                         stack[0].edl->path : session->filename;
4101                 sprintf(string, _("\"%s\" %jdC written"),
4102                          filename, file.length());
4103                 gui->lock_window("SaveAs::run");
4104                 gui->show_message(string);
4105                 gui->unlock_window();
4106         }
4107         return 0;
4108 }
4109
4110 int MWindow::save(int save_as)
4111 {
4112         char new_path[BCTEXTLEN];  new_path[0] = 0;
4113         char *path = stack.size() ? stack[0].edl->path : session->filename;
4114         if( save_as || !path[0] ) {
4115                 if( ConfirmSave::get_save_path(this, new_path) )
4116                         return 1;
4117                 if( stack.size() ) {
4118                         strcpy(path, new_path);
4119                         set_titlebar(new_path);
4120                 }
4121                 else
4122                         set_filename(new_path);
4123                 gui->mainmenu->add_load(new_path);
4124                 path = new_path;
4125         }
4126         for( int i=stack.size(); --i>=0;  ) {
4127                 StackItem &item = stack[i];
4128                 Indexable *idxbl = item.idxbl;
4129                 if( !idxbl ) continue;
4130                 if( idxbl->is_asset ) {
4131                         Asset *asset = (Asset *)idxbl;
4132                         if( asset->format == FILE_REF ) {
4133                                 if( save(item.new_edl, asset->path, 0) )
4134                                         return 1;
4135                         }
4136                 }
4137                 else if( item.new_edl != idxbl )
4138                         item.new_edl->overwrite_clip((EDL*)idxbl);
4139         }
4140         EDL *new_edl = stack.size() ? stack[0].edl : edl;
4141         save(new_edl, path, 1);
4142         return 0;
4143 }
4144
4145 void MWindow::show_plugins()
4146 {
4147         for( Track *track=edl->tracks->first; track; track=track->next ) {
4148                 for( int i=0; i<track->plugin_set.size(); ++i ) {
4149                         PluginSet *plugins = track->plugin_set[i];
4150                         Plugin *plugin = plugins->get_first_plugin();
4151                         for( ; plugin; plugin=(Plugin*)plugin->next ) {
4152                                 if( plugin->plugin_type == PLUGIN_STANDALONE &&
4153                                     plugin->show )
4154                                         show_plugin(plugin);
4155                         }
4156                 }
4157         }
4158 }
4159
4160 void MWindow::clip_to_media()
4161 {
4162         if( edl->session->proxy_scale != 1 ) {
4163                 eprintf("Nesting not allowed when proxy scale != 1");
4164                 return;
4165         }
4166         undo_before();
4167         awindow->gui->stop_vicon_drawing();
4168         int clips_total = session->drag_clips->total;
4169         for( int i=0; i<clips_total; ++i ) {
4170                 EDL *clip = session->drag_clips->values[i];
4171                 time_t dt;      time(&dt);
4172                 struct tm dtm;  localtime_r(&dt, &dtm);
4173                 char path[BCTEXTLEN], *cp = path, *ep = cp+sizeof(path)-1;
4174 // path_basename = "Nested_<date>-<time>_<basename>"
4175                 cp += snprintf(cp, ep-cp, _("Nested_%02d%02d%02d-%02d%02d%02d_"),
4176                         dtm.tm_year+1900, dtm.tm_mon+1, dtm.tm_mday,
4177                         dtm.tm_hour, dtm.tm_min, dtm.tm_sec);
4178                 char *bp = strrchr(clip->local_session->clip_title, '/');
4179                 bp = bp ? bp+1 : clip->local_session->clip_title;
4180                 cp += snprintf(cp, ep-cp, "%s", bp);
4181                 EDL *nested = edl->new_nested_clip(clip, path);
4182                 edl->clips.remove(clip);
4183                 clip->remove_user();
4184                 mainindexes->add_indexable(nested);
4185         }
4186         undo_after(_("clip2media"), LOAD_ALL);
4187         mainindexes->start_build();
4188         awindow->gui->async_update_assets();
4189 }
4190
4191 void MWindow::media_to_clip()
4192 {
4193         undo_before();
4194         int assets_total = session->drag_assets->total;
4195         for( int i=0; i<assets_total; ++i ) {
4196                 Indexable *idxbl = session->drag_assets->values[i];
4197                 if( idxbl->is_asset ) {
4198                         eprintf(_("media is not EDL:\n%s"), idxbl->path);
4199                         continue;
4200                 }
4201                 char clip_title[BCSTRLEN];
4202                 int name_ok = 0;
4203                 while( !name_ok ) {
4204                         name_ok = 1;
4205                         sprintf(clip_title, _("Clip %d"), session->clip_number++);
4206                         for( int i=0; name_ok && i<edl->clips.size(); ++i ) {
4207                                 char *title = edl->clips[i]->local_session->clip_title;
4208                                 if( !strcasecmp(clip_title, title) ) name_ok = 0;
4209                         }
4210                 }
4211                 EDL *nested = (EDL *)idxbl;
4212                 EDL *clip = edl->add_clip(nested);
4213                 strcpy(clip->local_session->clip_title, clip_title);
4214                 snprintf(clip->local_session->clip_notes,
4215                         sizeof(clip->local_session->clip_notes),
4216                         _("From: %s"), nested->path);
4217         }
4218         undo_after(_("media2clip"), LOAD_ALL);
4219         awindow->gui->async_update_assets();
4220 }
4221
4222 int MWindow::create_ref(Asset *asset, EDL *ref)
4223 {
4224         asset->format = FILE_REF;
4225         double secs = ref->tracks->total_length();
4226         int audio_channels = ref->session->audio_channels;
4227         asset->audio_data = audio_channels > 0 ? 1 : 0;
4228         asset->channels = audio_channels;
4229         asset->sample_rate = ref->session->sample_rate;
4230         asset->audio_length = audio_channels > 0 && secs > 0 ?
4231                  secs * asset->sample_rate : 0;
4232         strcpy(asset->acodec, _("reference"));
4233
4234         int video_layers = ref->session->video_channels;
4235         asset->video_data = video_layers > 0 ? 1 : 0;
4236         asset->layers = video_layers > 0 ? 1 : 0;
4237         asset->actual_width = ref->session->output_w;
4238         asset->actual_height = ref->session->output_h;
4239         asset->width = asset->actual_width;
4240         asset->height = asset->actual_height;
4241         asset->frame_rate = ref->session->frame_rate;
4242         asset->video_length = video_layers > 0 && secs > 0 ?
4243                 secs * asset->frame_rate : 0;
4244         strcpy(asset->vcodec, _("reference"));
4245         return 0;
4246 }
4247
4248 void MWindow::update_preferences(Preferences *prefs)
4249 {
4250         if( prefs != preferences )
4251                 preferences->copy_from(prefs);
4252         if( cwindow->playback_engine )
4253                 cwindow->playback_engine->update_preferences(prefs);
4254         for(int i = 0; i < vwindows.size(); i++) {
4255                 VWindow *vwindow = vwindows[i];
4256                 if( !vwindow->is_running() ) continue;
4257                 if( vwindow->playback_engine )
4258                         vwindow->playback_engine->update_preferences(prefs);
4259         }
4260         for(int i = 0; i < zwindows.size(); i++) {
4261                 ZWindow *zwindow = zwindows[i];
4262                 if( !zwindow->is_running() ) continue;
4263                 if( zwindow->zgui->playback_engine )
4264                         zwindow->zgui->playback_engine->update_preferences(prefs);
4265         }
4266 }
4267
4268 void MWindow::update_vwindow()
4269 {
4270         for( int i=0; i<vwindows.size(); ++i ) {
4271                 VWindow *vwindow = vwindows[i];
4272                 if( vwindow->is_running() ) {
4273                         vwindow->gui->lock_window("MWindow::update_vwindow");
4274                         vwindow->update(1);
4275                         vwindow->gui->unlock_window();
4276                 }
4277         }
4278 }
4279
4280 void MWindow::remove_indexfile(Indexable *indexable)
4281 {
4282         if( !indexable->is_asset ) return;
4283 // Erase file
4284         IndexFile::delete_index_files(preferences, indexable);
4285 }
4286
4287 void MWindow::rebuild_indices()
4288 {
4289         for(int i = 0; i < session->drag_assets->total; i++)
4290         {
4291                 Indexable *indexable = session->drag_assets->get(i);
4292 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4293                 remove_indexfile(indexable);
4294 // Schedule index build
4295                 indexable->index_state->remove_user();
4296                 indexable->index_state = new IndexState;
4297                 IndexFile::delete_index_files(preferences, indexable);
4298                 if( indexable->is_asset ) {
4299                         Asset *asset = (Asset *)indexable;
4300                         if( asset->format != FILE_PCM ) {
4301                                 asset->format = FILE_UNKNOWN;
4302                                 asset->reset_audio();
4303                         }
4304                         asset->reset_video();
4305                         remove_from_caches(asset);
4306 //                      File file; // re-probe the asset
4307 //                      file.open_file(preferences, asset, 1, 0);
4308                 }
4309                 mainindexes->add_indexable(indexable);
4310         }
4311 // still in render engine
4312         sync_parameters(CHANGE_ALL);
4313         awindow->gui->async_update_assets();
4314         mainindexes->start_build();
4315 }
4316
4317
4318 void MWindow::get_backup_path(char *path, int len)
4319 {
4320         char *cp = path, *ep = cp + len-1;
4321         cp += snprintf(cp, ep-cp, "%s/", File::get_config_path());
4322         int idx = stack.size();
4323         cp += snprintf(cp, ep-cp, idx ? BACKUPn_FILE : BACKUP_FILE, idx);
4324 }
4325
4326 void MWindow::create_timestamped_copy_from_previous_backup(char *previouspath)
4327 {
4328   if (previouspath == NULL) return;
4329   char backup_path[BCTEXTLEN];
4330   backup_path[0] = 0;
4331   time_t now = time(NULL);
4332   struct tm* currenttime = localtime(&now);
4333   snprintf(backup_path, sizeof(backup_path), 
4334       "%s/%s_%d%.2d%.2d_%.2d%.2d%.2d",
4335       File::get_config_path(), BACKUP_FILE1, 
4336       currenttime->tm_year + 1900,
4337       currenttime->tm_mon + 1,
4338       currenttime->tm_mday,
4339       currenttime->tm_hour,
4340       currenttime->tm_min,
4341       currenttime->tm_sec);
4342         rename(previouspath, backup_path);
4343 }
4344
4345 void MWindow::save_backup()
4346 {
4347         FileXML file;
4348         edl->optimize();
4349         edl->set_path(session->filename);
4350
4351         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
4352         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
4353                 File::get_config_path(), BACKUP_FILE1);
4354         get_backup_path(backup_path, sizeof(backup_path));
4355         if( preferences->ongoing_backups )
4356                 create_timestamped_copy_from_previous_backup(backup_path1);
4357         rename(backup_path, backup_path1);
4358         edl->save_xml(&file, backup_path);
4359         file.terminate_string();
4360         FileSystem fs;
4361         fs.complete_path(backup_path);
4362
4363         if(file.write_to_file(backup_path)) {
4364                 char string2[256];
4365                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
4366                 gui->show_message(string2);
4367         }
4368         save_undo_data();
4369 }
4370
4371 void MWindow::load_backup()
4372 {
4373         ArrayList<char*> path_list;
4374         path_list.set_array_delete();
4375         char *out_path;
4376         char backup_path[BCTEXTLEN];
4377         get_backup_path(backup_path, sizeof(backup_path));
4378         FileSystem fs;
4379         fs.complete_path(backup_path);
4380
4381         path_list.append(out_path = new char[strlen(backup_path) + 1]);
4382         strcpy(out_path, backup_path);
4383
4384         load_filenames(&path_list, LOADMODE_REPLACE, LOADMODE_EDL_CLIP, 0);
4385         edl->local_session->clip_title[0] = 0;
4386 // This is unique to backups since the path of the backup is different than the
4387 // path of the project.
4388         set_filename(edl->path);
4389         path_list.remove_all_objects();
4390         save_backup();
4391 }
4392
4393
4394 void MWindow::save_undo_data()
4395 {
4396         if( stack.size() > 0 ) return;
4397         if( !preferences->perpetual_session ) return;
4398         char perpetual_path[BCTEXTLEN];
4399         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4400                 File::get_config_path(), PERPETUAL_FILE);
4401         FILE *fp = fopen(perpetual_path,"w");
4402         if( !fp ) return;
4403         undo->save(fp);
4404         fclose(fp);
4405 }
4406
4407 void MWindow::load_undo_data()
4408 {
4409         if( stack.size() > 0 ) return;
4410         if( !preferences->perpetual_session ) return;
4411         char perpetual_path[BCTEXTLEN];
4412         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4413                 File::get_config_path(), PERPETUAL_FILE);
4414         FILE *fp = fopen(perpetual_path,"r");
4415         if( !fp ) return;
4416         undo->load(fp);
4417         undo_before();
4418         undo_after(_("perpetual load"), LOAD_ALL);
4419         fclose(fp);
4420 }
4421
4422 void MWindow::remove_undo_data()
4423 {
4424         if( stack.size() > 0 ) return;
4425         char perpetual_path[BCTEXTLEN];
4426         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4427                 File::get_config_path(), PERPETUAL_FILE);
4428         ::remove(perpetual_path);
4429 }
4430
4431 int MWindow::copy_target(const char *path, const char *target)
4432 {
4433         int ifd = ::open(path, O_RDONLY);
4434         if( ifd < 0 ) {
4435                 eprintf("Cannot open asset: %s", path);
4436                 return 1;
4437         }
4438         int ret = 0;
4439         int ofd = ::open(target, O_CREAT+O_TRUNC+O_WRONLY, 0777);
4440         if( ofd >= 0 ) {
4441                 struct stat st;
4442                 int64_t total_bytes = !fstat(ifd, &st) ? st.st_size : 0;
4443                 char progress_title[BCTEXTLEN];
4444                 sprintf(progress_title, _("Copying: %s\n"), target);
4445                 BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
4446
4447                 int64_t count = 0, len = -1;
4448                 int bfrsz = 0x100000;
4449                 uint8_t *bfr = new uint8_t[bfrsz];
4450                 while( (len=::read(ifd, bfr, bfrsz)) > 0 ) {
4451                         if( len != ::write(ofd, bfr, len) ) {
4452                                 eprintf("Error writing: %s", target);
4453                                 break;
4454                         }
4455                         if( progress.is_cancelled() ) {
4456                                 ret = 1;
4457                                 break;
4458                         }
4459                         progress.update(count += len, 1);
4460                 }
4461                 delete [] bfr;
4462                 ::close(ofd);
4463
4464                 progress.stop_progress();
4465                 if( len < 0 ) {
4466                         eprintf("Error reading: %s", path);
4467                         ret = 1;
4468                 }
4469         }
4470         else
4471                 eprintf("Cannot create asset target: %s", target);
4472         ::close(ifd);
4473         return ret;
4474 }
4475
4476 int MWindow::link_target(const char *real_path, const char *link_path, int relative)
4477 {
4478         char target[BCTEXTLEN];
4479         if( relative ) {
4480                 const char *bp = real_path, *cp = bp;
4481                 const char *lp = link_path, *np = lp;
4482                 char *tp = target, *ep = tp+sizeof(target)-1, lch;
4483                 while( *lp && *bp && (lch=*lp++) == *bp++ ) {
4484                         if( lch == '/' ) { np = lp;  cp = bp; }
4485                 }
4486                 while( tp<ep && *np ) {
4487                         if( *np++ != '/' ) continue;
4488                         *tp++ = '.';  *tp++ = '.';  *tp++ = '/';
4489                 }
4490                 while( tp<ep && *cp ) *tp++ = *cp++;
4491                 *tp = 0;
4492         }
4493         else
4494                 strcpy(target, real_path);
4495         if( symlink(target, link_path) ) {
4496                 eprintf("Cannot create symlink: %s", link_path);
4497                 return 1;
4498         }
4499         return 0;
4500 }
4501
4502 void MWindow::save_project(const char *dir, int save_mode, int overwrite, int reload)
4503 {
4504         char dir_path[BCTEXTLEN];
4505         strcpy(dir_path, dir);
4506         FileSystem fs;
4507         fs.complete_path(dir_path);
4508
4509         struct stat st;
4510         if( !stat(dir_path, &st) ) {
4511                 if( !S_ISDIR(st.st_mode) ) {
4512                         eprintf("Path exists and is not a directory\n%s", dir_path);
4513                         return;
4514                 }
4515         }
4516         else {
4517                 if( mkdir(dir_path, S_IRWXU | S_IRWXG | S_IRWXO) ) {
4518                         eprintf("Cannot create directory\n%s", dir_path);
4519                         return;
4520                 }
4521         }
4522         char *real_dir = realpath(dir_path, 0);
4523         strcpy(dir_path, real_dir);
4524         free(real_dir);
4525
4526         EDL *save_edl = new EDL;
4527         save_edl->create_objects();
4528         save_edl->copy_all(edl);
4529
4530         char progress_title[BCTEXTLEN];
4531         sprintf(progress_title, _("Saving to %s:\n"), dir);
4532         int total_assets = save_edl->assets->total();
4533         gui->lock_window("MWindow::save_project");
4534         MainProgressBar *progress = mainprogress->start_progress(progress_title, total_assets);
4535         gui->unlock_window();
4536
4537         int ret = 0;
4538         Asset *current = save_edl->assets->first;
4539         for( int i=0; !ret && current; ++i, current=NEXT ) {
4540                 char *path = current->path;
4541                 if( ::stat(path, &st) ) {
4542                         eprintf("Asset not found: %s", path);
4543                         continue;
4544                 }
4545                 char *real_path = realpath(path, 0);
4546                 const char *cp = strrchr(path, '/'), *bp = !cp ? path : cp+1;
4547                 char link_path[BCTEXTLEN];
4548                 snprintf(link_path, sizeof(link_path), "%s/%s", dir_path, bp);
4549                 int skip = 0;
4550                 if( strcmp(real_path, link_path) ) {
4551                         if( !::lstat(link_path, &st) ) {
4552                                 if( overwrite )
4553                                         ::remove(link_path);
4554                                 else
4555                                         skip = 1;
4556                         }
4557                 }
4558                 else {
4559                         eprintf("copy/link to self, skippped: %s", path);
4560                         skip = 1;
4561                 }
4562                 if( !skip ) {
4563                         if( save_mode == SAVE_PROJECT_COPY ) {
4564                                 if( copy_target(real_path, link_path) )
4565                                         ret = 1;
4566                         }
4567                         else {
4568                                 link_target(real_path, link_path,
4569                                         save_mode == SAVE_PROJECT_RELLINK ? 1 : 0);
4570                         }
4571                 }
4572                 free(real_path);
4573                 strcpy(path, link_path);
4574
4575                 if( progress->is_cancelled() ) break;
4576                 progress->update(i);
4577         }
4578
4579         progress->stop_progress();
4580         delete progress;
4581
4582         char *cp = strrchr(dir_path,'/');
4583         char *bp = cp ? cp+1 : dir_path;
4584         char filename[BCTEXTLEN];
4585         snprintf(filename, sizeof(filename), "%s/%s.xml", dir_path, bp);
4586         save_edl->set_path(filename);
4587         FileXML file;
4588         save_edl->save_xml(&file, filename);
4589         file.terminate_string();
4590
4591         if( !file.write_to_file(filename) ) {
4592                 char string[BCTEXTLEN];
4593                 sprintf(string, _("\"%s\" %dC written"), filename, (int)strlen(file.string()));
4594                 gui->lock_window("SaveProject::run 2");
4595                 gui->show_message(string);
4596                 gui->unlock_window();
4597                 gui->mainmenu->add_load(filename);
4598         }
4599         else
4600                 eprintf(_("Couldn't open %s."), filename);
4601
4602         save_edl->remove_user();
4603
4604         if( reload ) {
4605                 gui->lock_window("MWindow::save_project");
4606                 ArrayList<char*> filenames;
4607                 filenames.append(filename);
4608                 load_filenames(&filenames);
4609                 gui->unlock_window();
4610         }
4611 }
4612
4613
4614 static inline int gcd(int m, int n)
4615 {
4616         int r;
4617         if( m < n ) { r = m;  m = n;  n = r; }
4618         while( (r = m % n) != 0 ) { m = n;  n = r; }
4619         return n;
4620 }
4621
4622 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
4623 {
4624         w = 1;  h = 1;
4625         double ar;
4626         
4627         if(!width || !height) return 1;
4628         if( width == 720 && (height == 480 || height == 576) ) {
4629                 w = 4;  h = 3;  return 0; // for NTSC and PAL
4630         }
4631         
4632         ar = (double)width / height;
4633 // square-ish pixels
4634         if( EQUIV(ar, 1.0000) ) return 0;
4635         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
4636         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
4637         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
4638         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
4639         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
4640         if( EQUIV(ar, 2.37037) ) { w = 64; h = 27;  return 0; }
4641
4642         int ww = width, hh = height;
4643         // numerator, denominator must be under mx
4644         int mx = 255, n = gcd(ww, hh);
4645         if( n > 1 ) { ww /= n; hh /= n; }
4646         // search near height in case extra/missing lines
4647         if( ww >= mx || hh >= mx ) {
4648                 double err = height;  // +/- 2 percent height
4649                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
4650                         int iw = width, ih = height+i;
4651                         if( (n=gcd(iw, ih)) > 1 ) {
4652                                 int u = iw/n;  if( u >= mx ) continue;
4653                                 int v = ih/n;  if( v >= mx ) continue;
4654                                 double r = (double) u/v, er = fabs(ar-r);
4655                                 if( er >= err ) continue;
4656                                 err = er;  ww = u;  hh = v;
4657                         }
4658                 }
4659         }
4660
4661         w = ww;  h = hh;
4662         return 0;
4663 }
4664
4665 void MWindow::reset_caches(int locked)
4666 {
4667         if( locked ) gui->unlock_window();
4668         awindow->gui->stop_vicon_drawing(1);
4669         if( cwindow->playback_engine )
4670                 cwindow->playback_engine->create_cache();
4671         for(int i = 0; i < vwindows.size(); i++) {
4672                 VWindow *vwindow = vwindows[i];
4673                 if( !vwindow->is_running() ) continue;
4674                 if( !vwindow->playback_engine ) continue;
4675                 vwindow->playback_engine->create_cache();
4676         }
4677         gui->lock_window("MWindow::reset_caches");
4678         frame_cache->remove_all();
4679         wave_cache->remove_all();
4680         audio_cache->remove_all();
4681         video_cache->remove_all();
4682         if( !locked ) gui->unlock_window();
4683 }
4684
4685 void MWindow::remove_from_caches(Indexable *idxbl)
4686 {
4687         awindow->gui->stop_vicon_drawing(1);
4688         frame_cache->remove_item(idxbl);
4689         wave_cache->remove_item(idxbl);
4690         if( gui->render_engine &&
4691             gui->render_engine_id == idxbl->id ) {
4692                 delete gui->render_engine;
4693                 gui->render_engine = 0;
4694         }
4695         gui->resource_thread->close_indexable(idxbl);
4696         if( !idxbl->is_asset ) return;
4697         Asset *asset = (Asset *)idxbl;
4698         audio_cache->delete_entry(asset);
4699         video_cache->delete_entry(asset);
4700         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
4701                 cwindow->playback_engine->audio_cache->delete_entry(asset);
4702         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
4703                 cwindow->playback_engine->video_cache->delete_entry(asset);
4704         for(int i = 0; i < vwindows.size(); i++) {
4705                 VWindow *vwindow = vwindows[i];
4706                 if( !vwindow->is_running() ) continue;
4707                 if( !vwindow->playback_engine ) continue;
4708                 if( vwindow->playback_engine->audio_cache )
4709                         vwindow->playback_engine->audio_cache->delete_entry(asset);
4710                 if( vwindow->playback_engine->video_cache )
4711                         vwindow->playback_engine->video_cache->delete_entry(asset);
4712         }
4713         for(int i = 0; i < zwindows.size(); i++) {
4714                 ZWindow *zwindow = zwindows[i];
4715                 if( !zwindow->is_running() ) continue;
4716                 if( zwindow->zgui->playback_engine->audio_cache )
4717                         zwindow->zgui->playback_engine->audio_cache->delete_entry(asset);
4718                 if( zwindow->zgui->playback_engine->video_cache )
4719                         zwindow->zgui->playback_engine->video_cache->delete_entry(asset);
4720         }
4721         awindow->gui->start_vicon_drawing();
4722 }
4723
4724 void MWindow::remove_assets_from_project(int push_undo, int redraw, int delete_indexes,
4725                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
4726 {
4727         awindow->gui->stop_vicon_drawing(1);
4728
4729 // Remove from VWindow.
4730         if( drag_clips ) {
4731                 for(int i = 0; i < drag_clips->total; i++) {
4732                         for(int j = 0; j < vwindows.size(); j++) {
4733                                 VWindow *vwindow = vwindows[j];
4734                                 if( !vwindow->is_running() ) continue;
4735                                 if(drag_clips->get(i) == vwindow->get_edl()) {
4736                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
4737                                         vwindow->delete_source(1, 1);
4738                                         vwindow->gui->unlock_window();
4739                                 }
4740                         }
4741                 }
4742         }
4743
4744         if( drag_assets ) {
4745                 for(int i = 0; i < drag_assets->size(); i++) {
4746                         for(int j = 0; j < vwindows.size(); j++) {
4747                                 VWindow *vwindow = vwindows[j];
4748                                 if( !vwindow->is_running() ) continue;
4749                                 if(drag_assets->get(i) == vwindow->get_source()) {
4750                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
4751                                         vwindow->delete_source(1, 1);
4752                                         vwindow->gui->unlock_window();
4753                                 }
4754                         }
4755                 }
4756
4757                 for(int i = 0; i < drag_assets->total; i++) {
4758                         Indexable *indexable = drag_assets->get(i);
4759                         if(indexable->is_asset) remove_from_caches(indexable);
4760                 }
4761
4762                 if( delete_indexes ) {
4763                         for(int i = 0; i < drag_assets->size(); i++) {
4764                                 Indexable *indexable = drag_assets->get(i);
4765                                 remove_indexfile(indexable);
4766                         }
4767                 }
4768         }
4769
4770 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4771         if(push_undo) undo_before();
4772         if(drag_assets) edl->remove_from_project(drag_assets);
4773         if(drag_clips) edl->remove_from_project(drag_clips);
4774         if(redraw) save_backup();
4775         if(push_undo) undo_after(_("remove assets"), LOAD_ALL);
4776         if(redraw) {
4777                 restart_brender();
4778
4779                 gui->lock_window("MWindow::remove_assets_from_project 3");
4780                 gui->update(1, NORMAL_DRAW, 1, 1, 0, 1, 0);
4781                 gui->unlock_window();
4782
4783         // Removes from playback here
4784                 sync_parameters(CHANGE_ALL);
4785         }
4786
4787         awindow->gui->async_update_assets();
4788 }
4789
4790 void MWindow::remove_assets_from_disk()
4791 {
4792         remove_assets_from_project(1, 1, 1,
4793                 session->drag_assets, session->drag_clips);
4794
4795 // Remove from disk
4796         for(int i = 0; i < session->drag_assets->total; i++)
4797         {
4798                 remove(session->drag_assets->get(i)->path);
4799         }
4800 }
4801
4802 void MWindow::dump_plugins(FILE *fp)
4803 {
4804         if( !plugindb ) return;
4805         for(int i = 0; i < plugindb->total; i++)
4806         {
4807                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
4808                         " synth=%d transition=%d theme=%d %s\n",
4809                         plugindb->get(i)->plugin_type,
4810                         plugindb->get(i)->audio,
4811                         plugindb->get(i)->video,
4812                         plugindb->get(i)->realtime,
4813                         plugindb->get(i)->multichannel,
4814                         plugindb->get(i)->get_synthesis(),
4815                         plugindb->get(i)->transition,
4816                         plugindb->get(i)->theme,
4817                         plugindb->get(i)->title);
4818         }
4819 }
4820
4821 void MWindow::dump_edl(FILE *fp)
4822 {
4823         if( !edl ) return;
4824         edl->dump(fp);
4825 }
4826
4827 void MWindow::dump_undo(FILE *fp)
4828 {
4829         if( !undo ) return;
4830         undo->dump(fp);
4831 }
4832
4833 void MWindow::dump_exe(FILE *fp)
4834 {
4835         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
4836         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
4837
4838         int ret = -1, n = 100;
4839         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
4840                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
4841                 ret = 0;
4842         }
4843         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
4844
4845         struct stat st;
4846         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
4847         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
4848         struct tm *tm = localtime(&st.st_mtime);
4849         char mtime[256];
4850         strftime(mtime, sizeof(mtime), "%F %T", tm);
4851         fprintf(fp,"mtime: %s\n", mtime);
4852 #if 0
4853 // people hit ctl-c waiting for this
4854         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
4855         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
4856         uint8_t *bfr = 0;
4857         int64_t bfrsz = 0;
4858         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
4859         int64_t maxsz = 1024*pagsz;
4860         int64_t size = st.st_size, pos = 0;
4861         SHA1 sha1;
4862         while( (bfrsz = size-pos) > 0 ) {
4863                 if( bfrsz > maxsz ) bfrsz = maxsz;
4864                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
4865                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
4866                 if( bfr == MAP_FAILED ) break;
4867                 sha1.addBytes(bfr, bfrsz);
4868                 munmap(bfr, bfrsz);
4869                 pos += bfrsz;
4870         }
4871         close(fd);
4872         ret = pos < size ? EIO : 0;
4873         fprintf(fp, "SHA1: ");
4874         uint8_t digest[20];  sha1.computeHash(digest);
4875         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
4876         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
4877         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
4878 #endif
4879         fprintf(fp, "\n");
4880 }
4881
4882 void MWindow::dump_caches(FILE *fp)
4883 {
4884         fprintf(fp, "audio cache: ");
4885         audio_cache->dump(fp);
4886         fprintf(fp, "video cache: ");
4887         video_cache->dump(fp);
4888 }
4889
4890 void MWindow::trap_hook(FILE *fp, void *vp)
4891 {
4892         MWindow *mwindow = (MWindow *)vp;
4893 //      fprintf(fp, "\nPLUGINS:\n");
4894 //      mwindow->dump_plugins(fp);
4895         fprintf(fp, "\nEDL:\n");
4896         mwindow->dump_edl(fp);
4897         fprintf(fp, "\nUNDO:\n");
4898         mwindow->dump_undo(fp);
4899         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
4900         mwindow->dump_exe(fp);
4901         fprintf(fp, "\nCACHES:\n");
4902         mwindow->dump_caches(fp);
4903 }
4904
4905
4906
4907
4908
4909
4910 int MWindow::save_defaults()
4911 {
4912         gui->save_defaults(defaults);
4913         edl->save_defaults(defaults);
4914         session->save_defaults(defaults);
4915         preferences->save_defaults(defaults);
4916
4917         for(int i = 0; i < plugin_guis->total; i++)
4918         {
4919 // Pointer comparison
4920                 plugin_guis->get(i)->save_defaults();
4921         }
4922         awindow->save_defaults(defaults);
4923
4924         defaults->save();
4925         return 0;
4926 }
4927
4928 int MWindow::run_script(FileXML *script)
4929 {
4930         int result = 0, result2 = 0;
4931         while(!result && !result2)
4932         {
4933                 result = script->read_tag();
4934                 if(!result)
4935                 {
4936                         if(script->tag.title_is("new_project"))
4937                         {
4938 // Run new in immediate mode.
4939 //                              gui->mainmenu->new_project->run_script(script);
4940                         }
4941                         else
4942                         if(script->tag.title_is("record"))
4943                         {
4944 // Run record as a thread.  It is a terminal command.
4945                                 ;
4946 // Will read the complete scipt file without letting record read it if not
4947 // terminated.
4948                                 result2 = 1;
4949                         }
4950                         else
4951                         {
4952                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
4953                         }
4954                 }
4955         }
4956         return result2;
4957 }
4958
4959 // ================================= synchronization
4960
4961
4962 int MWindow::interrupt_indexes()
4963 {
4964         mainprogress->cancelled = 1;
4965         mainindexes->interrupt_build();
4966         return 0;
4967 }
4968
4969
4970
4971 void MWindow::next_time_format()
4972 {
4973         switch( edl->session->time_format ) {
4974         case TIME_HMS:          edl->session->time_format = TIME_HMSF;         break;
4975         case TIME_HMSF:         edl->session->time_format = TIME_TIMECODE;     break;
4976         case TIME_TIMECODE:     edl->session->time_format = TIME_FRAMES;       break;
4977         case TIME_FRAMES:       edl->session->time_format = TIME_SAMPLES;      break;
4978         case TIME_SAMPLES:      edl->session->time_format = TIME_SAMPLES_HEX;  break;
4979         case TIME_SAMPLES_HEX:  edl->session->time_format = TIME_SECONDS;      break;
4980         case TIME_SECONDS:      edl->session->time_format = TIME_FEET_FRAMES;  break;
4981         case TIME_FEET_FRAMES:  edl->session->time_format = TIME_HMS;          break;
4982         }
4983         time_format_common();
4984 }
4985
4986 void MWindow::prev_time_format()
4987 {
4988         switch( edl->session->time_format ) {
4989         case TIME_HMS:          edl->session->time_format = TIME_FEET_FRAMES;  break;
4990         case TIME_HMSF:         edl->session->time_format = TIME_HMS;          break;
4991         case TIME_TIMECODE:     edl->session->time_format = TIME_HMSF;         break;
4992         case TIME_FRAMES:       edl->session->time_format = TIME_TIMECODE;     break;
4993         case TIME_SAMPLES:      edl->session->time_format = TIME_FRAMES;       break;
4994         case TIME_SAMPLES_HEX:  edl->session->time_format = TIME_SAMPLES;      break;
4995         case TIME_SECONDS:      edl->session->time_format = TIME_SAMPLES_HEX;  break;
4996         case TIME_FEET_FRAMES:  edl->session->time_format = TIME_SECONDS;      break;
4997         }
4998
4999         time_format_common();
5000 }
5001
5002 void MWindow::time_format_common()
5003 {
5004         gui->lock_window("MWindow::next_time_format");
5005         gui->redraw_time_dependancies();
5006
5007
5008         char string[BCTEXTLEN], string2[BCTEXTLEN];
5009         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
5010         gui->show_message(string);
5011         gui->flush();
5012         gui->unlock_window();
5013 }
5014
5015
5016 int MWindow::set_filename(const char *filename)
5017 {
5018         if( filename != session->filename )
5019                 strcpy(session->filename, filename);
5020         if( filename != edl->path )
5021                 strcpy(edl->path, filename);
5022         return set_titlebar(filename);
5023 }
5024
5025 int MWindow::set_titlebar(const char *filename)
5026 {
5027         if( !gui ) return 0;
5028         if( filename[0] ) {
5029                 FileSystem dir;
5030                 char string[BCTEXTLEN], string2[BCTEXTLEN];
5031                 dir.extract_name(string, filename);
5032                 sprintf(string2, PROGRAM_NAME ": %s", string);
5033                 gui->set_title(string2);
5034         }
5035         else
5036                 gui->set_title(PROGRAM_NAME);
5037         return 0;
5038 }
5039
5040
5041 int MWindow::set_loop_boundaries()
5042 {
5043         double start = edl->local_session->get_selectionstart();
5044         double end = edl->local_session->get_selectionend();
5045
5046         if(start !=
5047                 end)
5048         {
5049                 ;
5050         }
5051         else
5052         if(edl->tracks->total_length())
5053         {
5054                 start = 0;
5055                 end = edl->tracks->total_length();
5056         }
5057         else
5058         {
5059                 start = end = 0;
5060         }
5061
5062         if(edl->local_session->loop_playback && start != end)
5063         {
5064                 edl->local_session->loop_start = start;
5065                 edl->local_session->loop_end = end;
5066         }
5067         return 0;
5068 }
5069
5070
5071
5072
5073
5074
5075
5076 int MWindow::reset_meters()
5077 {
5078         cwindow->gui->lock_window("MWindow::reset_meters 1");
5079         cwindow->gui->meters->reset_meters();
5080         cwindow->gui->unlock_window();
5081
5082         for(int j = 0; j < vwindows.size(); j++) {
5083                 VWindow *vwindow = vwindows[j];
5084                 if( !vwindow->is_running() ) continue;
5085                 vwindow->gui->lock_window("MWindow::reset_meters 2");
5086                 vwindow->gui->meters->reset_meters();
5087                 vwindow->gui->unlock_window();
5088         }
5089
5090         lwindow->gui->lock_window("MWindow::reset_meters 3");
5091         lwindow->gui->panel->reset_meters();
5092         lwindow->gui->unlock_window();
5093
5094         gui->lock_window("MWindow::reset_meters 4");
5095         gui->reset_meters();
5096         gui->unlock_window();
5097         return 0;
5098 }
5099
5100
5101 void MWindow::resync_guis()
5102 {
5103 // Update GUIs
5104         restart_brender();
5105         gui->lock_window("MWindow::resync_guis");
5106         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 0);
5107         gui->unlock_window();
5108
5109         cwindow->gui->lock_window("MWindow::resync_guis");
5110         cwindow->gui->resize_event(cwindow->gui->get_w(),
5111                 cwindow->gui->get_h());
5112         int channels = edl->session->audio_channels;
5113         cwindow->gui->meters->set_meters(channels, 1);
5114         cwindow->gui->flush();
5115         cwindow->gui->unlock_window();
5116
5117         for(int i = 0; i < vwindows.size(); i++) {
5118                 VWindow *vwindow = vwindows[i];
5119                 if( !vwindow->is_running() ) continue;
5120                 vwindow->gui->lock_window("MWindow::resync_guis");
5121                 vwindow->gui->resize_event(vwindow->gui->get_w(),
5122                         vwindow->gui->get_h());
5123                 vwindow->gui->meters->set_meters(channels, 1);
5124                 vwindow->gui->flush();
5125                 vwindow->gui->unlock_window();
5126         }
5127
5128         lwindow->gui->lock_window("MWindow::resync_guis");
5129         lwindow->gui->panel->set_meters(channels, 1);
5130         lwindow->gui->flush();
5131         lwindow->gui->unlock_window();
5132 #ifdef GLx4
5133 // Warn user
5134         if(((edl->session->output_w % 4) ||
5135                 (edl->session->output_h % 4)) &&
5136                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
5137         {
5138                 MainError::show_error(
5139                         _("This project's dimensions are not multiples of 4 so\n"
5140                         "it can't be rendered by OpenGL."));
5141         }
5142 #endif
5143
5144 // Flash frame
5145         sync_parameters(CHANGE_ALL);
5146 }
5147
5148 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
5149 {
5150         File *file = new File;
5151         EDLSession *session = edl->session;
5152         double old_framerate = session->frame_rate;
5153         double old_samplerate = session->sample_rate;
5154         int old_auto_keyframes = session->auto_keyframes;
5155         session->auto_keyframes = 0;
5156         int result = file->open_file(preferences, asset, 1, 0);
5157         if( !result && delete_tracks > 0 )
5158                 undo_before();
5159         int video_layers = asset->get_video_layers();
5160         if( !result && asset->video_data && vstream < video_layers ) {
5161                 // try to get asset up to date, may fail
5162                 file->select_video_stream(asset, vstream);
5163                 // either way use what was/is there.
5164                 double framerate = asset->get_frame_rate();
5165                 int width = asset->get_w();
5166                 int height = asset->get_h();
5167 #ifdef GLx4
5168                 // must be multiple of 4 for opengl
5169                 width = (width+3) & ~3;  height = (height+3) & ~3;
5170 #endif
5171                 int driver = session->playback_config->vconfig->driver;
5172                 int color_model = file->get_best_colormodel(asset, driver);
5173 //              color_model = BC_CModels::is_yuv(color_model) ?
5174 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
5175 //                      BC_CModels::is_float(color_model) ?
5176 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
5177 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
5178 // have alpha for now
5179                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
5180                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
5181                 session->color_model = color_model;
5182                 session->output_w = width;
5183                 session->output_h = height;
5184                 session->frame_rate = framerate;
5185                 session->interlace_mode = asset->interlace_mode;
5186                 // not, asset->actual_width/actual_height
5187                 asset->width = session->output_w;
5188                 asset->height = session->output_h;
5189                 asset->frame_rate = session->frame_rate;
5190                 
5191                 create_aspect_ratio(session->aspect_w, session->aspect_h,
5192                         session->output_w, session->output_h);
5193         float ar = asset->aspect_ratio;
5194         if (ar) {
5195         //printf ("Aspect ratio from asset: %f \n", ar);
5196         if( EQUIV(ar, 1.3333) ) { session->aspect_w = 4;  session->aspect_h = 3;  }
5197         if( EQUIV(ar, 1.7777) ) { session->aspect_w = 16; session->aspect_h = 9;   }
5198         if( EQUIV(ar, 2.1111) ) { session->aspect_w = 19; session->aspect_h = 9;  }
5199         if( EQUIV(ar, 2.2222) ) { session->aspect_w = 20; session->aspect_h = 9;   }
5200         if( EQUIV(ar, 2.3333) ) { session->aspect_w = 21; session->aspect_h = 9;   }
5201         if( EQUIV(ar, 2.370370) ) { session->aspect_w = 64; session->aspect_h = 27; }
5202         }
5203                         
5204                         
5205                 Track *track = edl->tracks->first;
5206                 for( Track *next_track=0; track; track=next_track ) {
5207                         next_track = track->next;
5208                         if( track->data_type != TRACK_VIDEO ) continue;
5209                         if( delete_tracks ) {
5210                                 Edit *edit = track->edits->first;
5211                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
5212                                         next_edit = edit->next;
5213                                         if( edit->channel != vstream ||
5214                                             !edit->asset || !edit->asset->is_asset ||
5215                                             !asset->equivalent(*edit->asset,1,1,edl) )
5216                                                 delete edit;
5217                                 }
5218                         }
5219                         if( track->edits->first ) {
5220                                 track->track_w = edl->session->output_w;
5221                                 track->track_h = edl->session->output_h;
5222                         }
5223                         else if( delete_tracks )
5224                                 edl->tracks->delete_track(track, 0);
5225                 }
5226                 edl->retrack();
5227                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
5228         }
5229         if( !result && asset->audio_data && asset->channels > 0 ) {
5230                 session->sample_rate = asset->get_sample_rate();
5231                 int64_t channel_mask = 0;
5232                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
5233                         file->get_audio_for_video(vstream, astream, channel_mask);
5234                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
5235                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
5236                 int channels = 0;
5237                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
5238                 if( channels < 1 ) channels = 1;
5239                 if( channels > 6 ) channels = 6;
5240                 session->audio_tracks = session->audio_channels = channels;
5241
5242                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
5243                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
5244                 remap_audio(MWindow::AUDIO_1_TO_1);
5245
5246                 if( delete_tracks ) {
5247                         Track *track = edl->tracks->first;
5248                         for( Track *next_track=0; track; track=next_track ) {
5249                                 next_track = track->next;
5250                                 if( track->data_type != TRACK_AUDIO ) continue;
5251                                 Edit *edit = track->edits->first;
5252                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
5253                                         next_edit = edit->next;
5254                                         if( !((1<<edit->channel) & channel_mask) ||
5255                                             !edit->asset || !edit->asset->is_asset ||
5256                                             !asset->equivalent(*edit->asset,1,1,edl) )
5257                                                 delete edit;
5258                                 }
5259                                 if( !track->edits->first )
5260                                         edl->tracks->delete_track(track, 0);
5261                         }
5262                 }
5263                 edl->rechannel();
5264                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
5265         }
5266         delete file;
5267         session->auto_keyframes = old_auto_keyframes;
5268         if( !result && delete_tracks > 0 ) {
5269                 save_backup();
5270                 undo_after(_("select asset"), LOAD_ALL);
5271         }
5272         resync_guis();
5273         return result;
5274 }
5275
5276 int MWindow::select_asset(int vtrack, int delete_tracks)
5277 {
5278         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
5279         if( !track )
5280                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
5281         if( !track ) return 1;
5282         Edit *edit = track->edits->first;
5283         if( !edit ) return 1;
5284         Asset *asset = edit->asset;
5285         if( !asset || !asset->is_asset ) return 1;
5286         return select_asset(asset, edit->channel, 0, delete_tracks);
5287 }
5288
5289 void MWindow::dump_plugindb(FILE *fp)
5290 {
5291         if( !plugindb ) return;
5292         for(int i = 0; i < plugindb->total; i++)
5293                 plugindb->get(i)->dump(fp);
5294 }
5295
5296 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
5297 {
5298         Auto *current = 0;
5299         double unit_position = edl->local_session->get_selectionstart(1);
5300         unit_position = patch->track->to_units(unit_position, 0);
5301
5302         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
5303         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5304 }
5305
5306 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
5307 {
5308         Auto *current = 0;
5309         double unit_position = edl->local_session->get_selectionstart(1);
5310         unit_position = patch->track->to_units(unit_position, 0);
5311
5312         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
5313         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5314 }
5315
5316 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
5317 {
5318         Auto *current = 0;
5319         double unit_position = edl->local_session->get_selectionstart(1);
5320         unit_position = patch->track->to_units(unit_position, 0);
5321
5322         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
5323         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5324 }
5325
5326 PatchGUI *MWindow::get_patchgui(Track *track)
5327 {
5328         PatchGUI *patchgui = 0;
5329         TimelinePane **panes = gui->pane;
5330         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
5331                 if( !panes[i] ) continue;
5332                 PatchBay *patchbay = panes[i]->patchbay;
5333                 if( !patchbay ) continue;
5334                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
5335                         if( patchbay->patches.values[j]->track == track )
5336                                 patchgui = patchbay->patches.values[j];
5337                 }
5338         }
5339         return patchgui;
5340 }
5341
5342 int MWindow::get_cpus(int out_w, int out_h)
5343 {
5344         if( !out_w ) out_w = edl->session->output_w;
5345         if( !out_h ) out_h = edl->session->output_h;
5346         int cpus = out_w*out_h/0x80000 + 1;
5347         if( cpus > preferences->processors )
5348                 cpus = preferences->processors;
5349         return cpus;
5350 }
5351 int MWindow::get_cpus()
5352 {
5353         return get_cpus(edl->session->output_w, edl->session->output_h);
5354 }
5355
5356 void MWindow::draw_trackmovement()
5357 {
5358         if( !redraw_tracks )
5359                 redraw_tracks = new DrawTrackMovement(this);
5360         redraw_tracks->start();
5361 }
5362
5363 DrawTrackMovement::DrawTrackMovement(MWindow *mwindow)
5364  : Thread(1, 0, 0)
5365 {
5366         this->mwindow = mwindow;
5367 }
5368 DrawTrackMovement::~DrawTrackMovement()
5369 {
5370         join();
5371 }
5372
5373 void DrawTrackMovement::run()
5374 {
5375         mwindow->gui->lock_window("DrawTrackMovement::run");
5376         mwindow->edl->tracks->update_y_pixels(mwindow->theme);
5377         mwindow->gui->draw_trackmovement();
5378         mwindow->gui->unlock_window();
5379 }
5380
5381
5382 ConfirmRefWindow::ConfirmRefWindow(MWindow *mwindow, char *path,
5383                 int px, int py, int cw, int ch)
5384  : BC_Window(_(PROGRAM_NAME ": Confirm update"), px, py, cw, ch, cw, ch)
5385 {
5386         this->mwindow = mwindow;
5387         this->path = path;
5388 // *** CONTEXT_HELP ***
5389         context_help_set_keyword("File by Reference");
5390 }
5391
5392 ConfirmRefWindow::~ConfirmRefWindow()
5393 {
5394 }
5395
5396 void ConfirmRefWindow::create_objects()
5397 {
5398         lock_window("ConfirmRefWindow::create_objects()");
5399         int x = xS(10), y = yS(10), pad = yS(5);
5400         BC_Title *title;
5401         add_subwindow(title = new BC_Title(x, y, _("FileREF not updated:")));
5402         y += title->get_h() + pad;
5403         BC_TextBox *text_box;
5404         add_subwindow(text_box = new BC_TextBox(x,y, get_w()-2*x, 1, path));
5405         y += text_box->get_h() + 2*pad;
5406         add_subwindow(title = new BC_Title(x, y, _("Save file ref changes?")));
5407         add_subwindow(new BC_OKButton(this));
5408         add_subwindow(new BC_CancelButton(this));
5409         show_window();
5410         unlock_window();
5411 }
5412