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