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