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