0fe6752f3598394b1fe16e6d1900e18a6c0631ba
[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 void MWindow::close_mixer(ZWindow *zwindow)
1214 {
1215         zwindows_lock->lock("MWindow::close_mixer 0");
1216         if( session->selected_zwindow >= 0 ) {
1217                 int i = zwindows.number_of(zwindow);
1218                 if( i >= 0 && i < session->selected_zwindow )
1219                         --session->selected_zwindow;
1220                 else if( i == session->selected_zwindow )
1221                         session->selected_zwindow = -1;
1222         }
1223         zwindows_lock->unlock();
1224         gui->lock_window("MWindow::close_mixer 1");
1225         gui->update_mixers(0, -1);
1226         gui->unlock_window();
1227 }
1228
1229 void MWindow::start_mixer()
1230 {
1231         Mixer *mixer = 0;
1232         ZWindow *zwindow = get_mixer(mixer);
1233         const char *title = 0;
1234
1235         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1236                 PatchGUI *patchgui = get_patchgui(track);
1237                 if( !patchgui || !patchgui->mixer ) continue;
1238                 mixer->mixer_ids.append(track->get_mixer_id());
1239                 if( !title ) title = track->title;
1240         }
1241
1242         session->selected_zwindow = -1;
1243         gui->lock_window("MWindow::start_mixer");
1244         gui->update_mixers(0, 0);
1245         gui->unlock_window();
1246
1247         zwindow->set_title(title);
1248         zwindow->start();
1249         refresh_mixers();
1250 }
1251
1252 int MWindow::mixer_track_active(Track *track)
1253 {
1254         int i = session->selected_zwindow;
1255         if( i < 0 || i >= zwindows.size() ) return 0;
1256         ZWindow *zwindow = zwindows[i];
1257         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1258         if( !mixer ) return 0;
1259         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1260         return n >= 0 ? 1 : 0;
1261 }
1262
1263 void MWindow::update_mixer_tracks()
1264 {
1265         zwindows_lock->lock("MixPatch::handle_event");
1266         int i = session->selected_zwindow;
1267         if( i >= 0 && i < zwindows.size() ) {
1268                 ZWindow *zwindow = zwindows[i];
1269                 zwindow->update_mixer_ids();
1270         }
1271         zwindows_lock->unlock();
1272 }
1273
1274 void MWindow::handle_mixers(EDL *edl, int command, int wait_tracking,
1275                 int use_inout, int toggle_audio, int loop_play, float speed)
1276 {
1277         zwindows_lock->lock("MWindow::handle_mixers");
1278         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1279                 ZWindow *zwindow = zwindows[vidx];
1280                 if( zwindow->idx < 0 ) continue;
1281                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1282                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1283                 int k = -1;
1284                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1285                         if( track->data_type != TRACK_VIDEO ) continue;
1286                         int mixer_id = track->get_mixer_id();
1287                         k = mixer->mixer_ids.size();
1288                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1289                 }
1290                 if( k < 0 ) continue;
1291                 EDL *mixer_edl = new EDL(this->edl);
1292                 mixer_edl->create_objects();
1293                 mixer_edl->copy_all(edl);
1294                 mixer_edl->remove_vwindow_edls();
1295                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1296                         k = mixer->mixer_ids.size();
1297                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1298                         if( k >= 0 ) {
1299                                 track->record = 1;
1300                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1301                         }
1302                         else
1303                                 track->record = track->play = 0;
1304                 }
1305                 zwindow->change_source(mixer_edl);
1306                 zwindow->handle_mixer(command, 0,
1307                                 use_inout, toggle_audio, loop_play, speed);
1308         }
1309         zwindows_lock->unlock();
1310 }
1311
1312 void MWindow::refresh_mixers(int dir)
1313 {
1314         int command = dir >= 0 ? CURRENT_FRAME : LAST_FRAME;
1315         handle_mixers(edl, command, 0, 0, 0, 0, 0);
1316 }
1317
1318 void MWindow::stop_mixers()
1319 {
1320         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1321                 ZWindow *zwindow = zwindows[vidx];
1322                 if( zwindow->idx < 0 ) continue;
1323                 zwindow->handle_mixer(STOP, 0, 0, 0, 0, 0);
1324         }
1325 }
1326
1327 void MWindow::close_mixers(int result)
1328 {
1329         ArrayList<ZWindow*> closed;
1330         zwindows_lock->lock("MWindow::close_mixers");
1331         for( int i=zwindows.size(); --i>=0; ) {
1332                 ZWindow *zwindow = zwindows[i];
1333                 if( zwindow->idx < 0 ) continue;
1334                 zwindow->idx = -1;
1335                 ZWindowGUI *zgui = zwindow->zgui;
1336                 zgui->lock_window("MWindow::select_zwindow 0");
1337                 zgui->set_done(result);
1338                 zgui->unlock_window();
1339                 closed.append(zwindow);
1340         }
1341         zwindows_lock->unlock();
1342         for( int i=0; i<closed.size(); ++i ) {
1343                 ZWindow *zwindow = closed[i];
1344                 zwindow->join();
1345         }
1346 }
1347
1348 ZWindow *MWindow::create_mixer(Indexable *indexable, double position)
1349 {
1350         ArrayList<Indexable*> new_assets;
1351         new_assets.append(indexable);
1352         Track *track = edl->tracks->last;
1353         load_assets(&new_assets, position, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 1);
1354         track = !track ? edl->tracks->first : track->next;
1355         Mixer *mixer = 0;
1356         ZWindow *zwindow = get_mixer(mixer);
1357         while( track ) {
1358                 track->play = track->record = 0;
1359                 if( track->data_type == TRACK_VIDEO ) {
1360                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1361                 }
1362                 mixer->mixer_ids.append(track->get_mixer_id());
1363                 track = track->next;
1364         }
1365         if(  indexable->is_asset ) {
1366                 char *path = indexable->path;
1367                 char *tp = strrchr(path, '/');
1368                 if( !tp ) tp = path; else ++tp;
1369                 zwindow->set_title(tp);
1370         }
1371         else {
1372                 char *title = ((EDL*)indexable)->local_session->clip_title;
1373                 zwindow->set_title(title);
1374         }
1375         return zwindow;
1376 }
1377
1378 void MWindow::create_mixers(double position)
1379 {
1380         if( !session->drag_assets->size() &&
1381             !session->drag_clips->size() ) return;
1382         undo_before();
1383
1384         select_zwindow(0);
1385         ArrayList<ZWindow *>new_mixers;
1386
1387         for( int i=0; i<session->drag_assets->size(); ++i ) {
1388                 Indexable *indexable = session->drag_assets->get(i);
1389                 if( !indexable->have_video() ) continue;
1390                 ZWindow *zwindow = create_mixer(indexable, position);
1391                 new_mixers.append(zwindow);
1392         }
1393         for( int i=0; i<session->drag_clips->size(); ++i ) {
1394                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1395                 if( !indexable->have_video() ) continue;
1396                 ZWindow *zwindow = create_mixer(indexable, position);
1397                 new_mixers.append(zwindow);
1398         }
1399
1400         tile_mixers();
1401         for( int i=0; i<new_mixers.size(); ++i )
1402                 new_mixers[i]->start();
1403
1404         refresh_mixers();
1405         save_backup();
1406         undo_after(_("create mixers"), LOAD_ALL);
1407         restart_brender();
1408         gui->update(1, FORCE_REDRAW, 1, 1, 1, 1, 0);
1409         sync_parameters(CHANGE_ALL);
1410 }
1411
1412 void MWindow::open_mixers()
1413 {
1414         for( int i=0; i<edl->mixers.size(); ++i ) {
1415                 Mixer *mixer = edl->mixers[i];
1416                 ZWindow *zwindow = get_mixer(mixer);
1417                 zwindow->set_title(mixer->title);
1418                 zwindow->start();
1419         }
1420         refresh_mixers();
1421 }
1422
1423 int MWindow::select_zwindow(ZWindow *zwindow)
1424 {
1425         int ret = 0, n = zwindows.number_of(zwindow);
1426         if( session->selected_zwindow != n ) {
1427                 session->selected_zwindow = n;
1428                 for( int i=0; i<zwindows.size(); ++i ) {
1429                         ZWindow *zwindow = zwindows[i];
1430                         if( zwindow->idx < 0 ) continue;
1431                         ZWindowGUI *zgui = zwindow->zgui;
1432                         zgui->lock_window("MWindow::select_zwindow 0");
1433                         zwindow->highlighted = i == n ? 1 : 0;
1434                         if( zgui->draw_overlays() )
1435                                 zgui->canvas->get_canvas()->flash(1);
1436                         zgui->unlock_window();
1437                 }
1438                 ret = 1;
1439                 gui->lock_window("MWindow::select_window 1");
1440                 gui->update_mixers(0, -1);
1441                 gui->unlock_window();
1442         }
1443         return ret;
1444 }
1445
1446 void MWindow::tile_mixers()
1447 {
1448         int nz = 0;
1449         for( int i=0; i<zwindows.size(); ++i ) {
1450                 ZWindow *zwindow = zwindows[i];
1451                 if( zwindow->idx < 0 ) continue;
1452                 ++nz;
1453         }
1454         if( !nz ) return;
1455         int zn = ceil(sqrt(nz));
1456         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1457         int y1 = 1, y2 = gui->get_y();
1458         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1459         if( x1 < 0 ) x1 = 0;
1460         if( y1 < 0 ) y1 = 0;
1461         if( x2 > rw ) x2 = rw;
1462         if( y2 > rh ) y2 = rh;
1463         int dx = x2 - x1, dy = y2 - y1;
1464         int zw = dx / zn;
1465         int lt = BC_DisplayInfo::get_left_border();
1466         int top = BC_DisplayInfo::get_top_border();
1467         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1468         int bh = top + BC_DisplayInfo::get_bottom_border();
1469         int zx = 0, zy = 0;  // window origins
1470         int mw = xS(10+10), mh = yS(10+10); // canvas margins
1471         int rsz = 0, n = 0, dz = 0;
1472         int ow = edl->session->output_w, oh = edl->session->output_h;
1473         for( int i=0; i<zwindows.size(); ++i ) {
1474                 ZWindow *zwindow = zwindows[i];
1475                 if( zwindow->idx < 0 ) continue;
1476                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1477                 if( rsz < hh ) rsz = hh;
1478                 int xx = zx + x1, yy = zy + y1;
1479                 int mx = x2 - zw, my = y2 - zh;
1480                 if( xx > mx ) xx = mx;
1481                 if( yy > my ) yy = my;
1482                 xx += lt + xS(dz);  yy += top + yS(dz);
1483                 zwindow->reposition(xx,yy, ww,hh);
1484                 if( zwindow->running() ) {
1485                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1486                         gui->lock_window("MWindow::tile_mixers");
1487                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1488                         gui->unlock_window();
1489                 }
1490                 if( ++n >= zn ) {
1491                         n = 0;  rsz += bh;
1492                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1493                         rsz = 0;
1494                         zx = 0;
1495                 }
1496                 else
1497                         zx += zw;
1498         }
1499 }
1500
1501 void MWindow::init_cache()
1502 {
1503         audio_cache = new CICache(preferences);
1504         video_cache = new CICache(preferences);
1505         frame_cache = new FrameCache;
1506         wave_cache = new WaveCache;
1507 }
1508
1509 void MWindow::init_channeldb()
1510 {
1511         channeldb_buz->load("channeldb_buz");
1512         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1513 }
1514
1515 void MWindow::init_menus()
1516 {
1517         char string[BCTEXTLEN];
1518
1519         // Color Models
1520         BC_CModels::to_text(string, BC_RGB888);
1521         colormodels.append(new ColormodelItem(string, BC_RGB888));
1522         BC_CModels::to_text(string, BC_RGBA8888);
1523         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1524 //      BC_CModels::to_text(string, BC_RGB161616);
1525 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1526 //      BC_CModels::to_text(string, BC_RGBA16161616);
1527 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1528         BC_CModels::to_text(string, BC_RGB_FLOAT);
1529         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1530         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1531         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1532         BC_CModels::to_text(string, BC_YUV888);
1533         colormodels.append(new ColormodelItem(string, BC_YUV888));
1534         BC_CModels::to_text(string, BC_YUVA8888);
1535         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1536 //      BC_CModels::to_text(string, BC_YUV161616);
1537 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1538 //      BC_CModels::to_text(string, BC_YUVA16161616);
1539 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1540
1541 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1542                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1543
1544 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1545                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1546
1547         // Interlacing Modes
1548         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1549
1550         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1551         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1552
1553         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1554         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1555
1556         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1557         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1558
1559         mixers_align = new MixersAlign(this);
1560 }
1561
1562 void MWindow::init_indexes()
1563 {
1564         mainindexes = new MainIndexes(this);
1565         mainindexes->start_loop();
1566 }
1567
1568 void MWindow::init_gui()
1569 {
1570         gui = new MWindowGUI(this);
1571         gui->create_objects();
1572         gui->load_defaults(defaults);
1573 }
1574
1575 void MWindow::init_signals()
1576 {
1577         sighandler = new SigHandler;
1578         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1579 ENABLE_BUFFER
1580 }
1581
1582 void MWindow::init_render()
1583 {
1584         render = new Render(this);
1585         create_bd = new CreateBD_Thread(this);
1586         create_dvd = new CreateDVD_Thread(this);
1587         batch_render = new BatchRenderThread(this);
1588 }
1589
1590 void MWindow::init_exportedl()
1591 {
1592         exportedl = new ExportEDL(this);
1593 }
1594
1595
1596 void MWindow::init_shuttle()
1597 {
1598 #ifdef HAVE_SHUTTLE
1599         int ret = Shuttle::probe();
1600         if( ret >= 0 ) {
1601                 shuttle = new Shuttle(this);
1602                 if( shuttle->read_config_file() > 0 ) {
1603                         printf("shuttle: bad config file\n");
1604                         delete shuttle;  shuttle = 0;
1605                         return;
1606                 }
1607                 shuttle->start(ret);
1608         }
1609 #endif
1610 }
1611 void MWindow::init_wintv()
1612 {
1613 #ifdef HAVE_WINTV
1614         wintv = WinTV::probe(this);
1615         if( wintv )
1616                 wintv->start();
1617 #endif
1618 }
1619 void MWindow::init_x10tv()
1620 {
1621 #ifdef HAVE_X10TV
1622         x10tv = X10TV::probe(this);
1623         if( x10tv )
1624                 x10tv->start();
1625 #endif
1626 }
1627
1628
1629 void MWindow::init_brender()
1630 {
1631         if(preferences->use_brender && !brender)
1632         {
1633                 brender_lock->lock("MWindow::init_brender 1");
1634                 brender = new BRender(this);
1635                 brender->initialize();
1636                 session->brender_end = 0;
1637                 brender_lock->unlock();
1638         }
1639         else
1640         if(!preferences->use_brender && brender)
1641         {
1642                 brender_lock->lock("MWindow::init_brender 2");
1643                 delete brender;
1644                 brender = 0;
1645                 session->brender_end = 0;
1646                 brender_lock->unlock();
1647         }
1648         brender_active = 0;
1649         stop_brender();
1650 }
1651
1652 void MWindow::restart_brender()
1653 {
1654 //printf("MWindow::restart_brender 1\n");
1655         if( !brender_active || !preferences->use_brender ) return;
1656         if( !brender ) return;
1657         brender->restart(edl);
1658 }
1659
1660 void MWindow::stop_brender()
1661 {
1662         if( !brender ) return;
1663 // cannot be holding mwindow->gui display lock
1664         brender->stop();
1665 }
1666
1667 int MWindow::brender_available(int position)
1668 {
1669         int result = 0;
1670         brender_lock->lock("MWindow::brender_available 1");
1671         if(brender && brender_active)
1672         {
1673                 if(brender->map_valid)
1674                 {
1675                         brender->map_lock->lock("MWindow::brender_available 2");
1676                         if(position < brender->map_size &&
1677                                 position >= 0)
1678                         {
1679 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1680                                 if(brender->map[position] == BRender::RENDERED)
1681                                         result = 1;
1682                         }
1683                         brender->map_lock->unlock();
1684                 }
1685         }
1686         brender_lock->unlock();
1687         return result;
1688 }
1689
1690 void MWindow::set_brender_active(int v, int update)
1691 {
1692         if( !preferences->use_brender ) v = 0;
1693         brender_active = v;
1694         gui->mainmenu->brender_active->set_checked(v);
1695         if( v != 0 ) {
1696                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1697                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1698
1699                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1700                         edl->session->brender_end = edl->tracks->total_video_length();
1701                 }
1702                 restart_brender();
1703         }
1704         else {
1705                 edl->session->brender_start = edl->session->brender_end = 0;
1706                 gui->unlock_window();
1707                 stop_brender();
1708                 gui->lock_window("MWindow::set_brender_active");
1709         }
1710         if( update ) {
1711                 gui->update_timebar(0);
1712                 gui->draw_overlays(1);
1713         }
1714 }
1715
1716 int MWindow::has_commercials()
1717 {
1718 #ifdef HAVE_COMMERCIAL
1719         return theme->use_commercials;
1720 #else
1721         return 0;
1722 #endif
1723 }
1724
1725 void MWindow::init_commercials()
1726 {
1727 #ifdef HAVE_COMMERCIAL
1728         if( !commercials ) {
1729                 commercials = new Commercials(this);
1730                 commercial_active = 0;
1731         }
1732         else
1733                 commercials->add_user();
1734 #endif
1735 }
1736
1737 void MWindow::commit_commercial()
1738 {
1739 #ifdef HAVE_COMMERCIAL
1740         if( !commercial_active ) return;
1741         commercial_active = 0;
1742         if( !commercials ) return;
1743         commercials->commitDb();
1744 #endif
1745 }
1746
1747 void MWindow::undo_commercial()
1748 {
1749 #ifdef HAVE_COMMERCIAL
1750         if( !commercial_active ) return;
1751         commercial_active = 0;
1752         if( !commercials ) return;
1753         commercials->undoDb();
1754 #endif
1755 }
1756
1757 int MWindow::put_commercial()
1758 {
1759         int result = 0;
1760 #ifdef HAVE_COMMERCIAL
1761         double start = edl->local_session->get_selectionstart();
1762         double end = edl->local_session->get_selectionend();
1763         if( start >= end ) return 0;
1764
1765         const char *errmsg = 0;
1766         int count = 0;
1767         Tracks *tracks = edl->tracks;
1768         //check it
1769         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1770                 if( track->data_type != TRACK_VIDEO ) continue;
1771                 if( !track->record ) continue;
1772                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1773                 ++count;
1774                 int64_t units_start = track->to_units(start,0);
1775                 int64_t units_end = track->to_units(end,0);
1776                 Edits *edits = track->edits;
1777                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1778                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1779                 if(!edit1 && !edit2) continue;  // nothing selected
1780                 if(!edit2) {                    // edit2 beyond end of track
1781                         edit2 = edits->last;
1782                         units_end = edits->length();
1783                 }
1784                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1785                 Indexable *indexable = edit1->get_source();
1786                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1787         }
1788         //run it
1789         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1790                 if( track->data_type != TRACK_VIDEO ) continue;
1791                 if( !track->record ) continue;
1792                 int64_t units_start = track->to_units(start,0);
1793                 int64_t units_end = track->to_units(end,0);
1794                 Edits *edits = track->edits;
1795                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1796                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1797                 if(!edit1 && !edit2) continue;  // nothing selected
1798                 if(!edit2) {                    // edit2 beyond end of track
1799                         edit2 = edits->last;
1800                         units_end = edits->length();
1801                 }
1802                 Indexable *indexable = edit1->get_source();
1803                 Asset *asset = (Asset *)indexable;
1804                 File *file = video_cache->check_out(asset, edl);
1805                 if( !file ) { errmsg = _("no file"); break; }
1806                 int64_t edit_length = units_end - units_start;
1807                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1808                 result = commercials->put_clip(file, edit1->channel,
1809                         track->from_units(edit_start), track->from_units(edit_length));
1810                 video_cache->check_in(asset);
1811                 if( result ) { errmsg = _("db failed"); break; }
1812         }
1813         if( errmsg ) {
1814                 char string[BCTEXTLEN];
1815                 sprintf(string, _("put_commercial: %s"), errmsg);
1816                 MainError::show_error(string);
1817                 undo_commercial();
1818                 result = 1;
1819         }
1820 #endif
1821         return result;
1822 }
1823
1824 void MWindow::stop_playback(int wait)
1825 {
1826         gui->stop_drawing();
1827
1828         cwindow->stop_playback(wait);
1829
1830         for(int i = 0; i < vwindows.size(); i++) {
1831                 VWindow *vwindow = vwindows[i];
1832                 if( !vwindow->is_running() ) continue;
1833                 vwindow->stop_playback(wait);
1834         }
1835         for(int i = 0; i < zwindows.size(); i++) {
1836                 ZWindow *zwindow = zwindows[i];
1837                 if( zwindow->idx < 0 ) continue;
1838                 zwindow->stop_playback(wait);
1839         }
1840 }
1841
1842 void MWindow::stop_transport()
1843 {
1844         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1845 }
1846
1847 void MWindow::undo_before(const char *description, void *creator)
1848 {
1849         undo->update_undo_before(description, creator);
1850 }
1851
1852 void MWindow::undo_after(const char *description, uint32_t load_flags, int changes_made)
1853 {
1854         undo->update_undo_after(description, load_flags, changes_made);
1855 }
1856
1857 void MWindow::beep(double freq, double secs, double gain)
1858 {
1859         if( !beeper ) beeper = new Beeper(this);
1860         beeper->tone(freq, secs, gain);
1861 }
1862
1863 Beeper::Beeper(MWindow *mwindow)
1864  : Thread(1, 0, 0)
1865 {
1866         this->mwindow = mwindow;
1867         audio = new AudioDevice(mwindow);
1868         playing_audio = 0;
1869         interrupted = -1;
1870 }
1871
1872 Beeper::~Beeper()
1873 {
1874         stop(0);
1875         delete audio;
1876 }
1877
1878 void Beeper::run()
1879 {
1880         int channels = 2;
1881         int64_t bfrsz = BEEP_SAMPLE_RATE;
1882         EDL *edl = mwindow->edl;
1883         EDLSession *session = edl->session;
1884         AudioOutConfig *aconfig = session->playback_config->aconfig;
1885         audio->open_output(aconfig, BEEP_SAMPLE_RATE, bfrsz, channels, 0);
1886         audio->start_playback();
1887
1888         double out0[bfrsz], out1[bfrsz], *out[2] = { out0, out1 };
1889         const double two_pi = 2*M_PI;
1890         int64_t audio_len = BEEP_SAMPLE_RATE * secs;
1891         const double dt = two_pi * freq/BEEP_SAMPLE_RATE;
1892         double th = 0;
1893
1894         audio_pos = 0;
1895         playing_audio = 1;
1896         while( !interrupted ) {
1897                 int len = audio_len - audio_pos;
1898                 if( len <= 0 ) break;
1899                 if( len > bfrsz ) len = bfrsz;
1900                 int k = audio_pos;
1901                 for( int i=0; i<len; ++i,++k,th+=dt ) {
1902                         double t = th - two_pi;
1903                         if( t >= 0 ) th = t;
1904                         out0[i] = out1[i] = sin(th) * gain;
1905                 }
1906                 audio->write_buffer(out, channels, len);
1907                 audio_pos = k;
1908         }
1909
1910         if( !interrupted )
1911                 audio->set_last_buffer();
1912         audio->stop_audio(interrupted ? 0 : 1);
1913         playing_audio = 0;
1914
1915         audio->close_all();
1916 }
1917
1918 void Beeper::start()
1919 {
1920         if( running() ) return;
1921         audio_pos = -1;
1922         interrupted = 0;
1923         Thread::start();
1924 }
1925
1926 void Beeper::stop(int wait)
1927 {
1928         if( running() && !interrupted ) {
1929                 interrupted = 1;
1930                 audio->stop_audio(wait);
1931         }
1932         Thread::join();
1933 }
1934
1935 void Beeper::tone(double freq, double secs, double gain)
1936 {
1937         stop(0);
1938         this->freq = freq;
1939         this->secs = secs;
1940         this->gain = gain;
1941         start();
1942 }
1943
1944
1945 int MWindow::load_filenames(ArrayList<char*> *filenames,
1946                 int load_mode, int edl_mode, int update_filename)
1947 {
1948         ArrayList<EDL*> new_edls;
1949         ArrayList<Asset*> new_assets;
1950         ArrayList<File*> new_files;
1951
1952 //      save_defaults();
1953         gui->start_hourglass();
1954
1955 // Need to stop playback since tracking depends on the EDL not getting
1956 // deleted.
1957         gui->unlock_window();
1958         stop_playback(1);
1959         gui->lock_window("MWindow::load_filenames 0");
1960         undo_before();
1961
1962 const int debug = 0;
1963 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1964
1965 // Define new_edls and new_assets to load
1966         int result = 0, ftype = -1;
1967
1968         for( int i=0; i<filenames->size(); ++i ) {
1969 // Get type of file
1970                 File *new_file = new File;
1971                 Asset *new_asset = new Asset(filenames->get(i));
1972                 EDL *new_edl = new EDL;
1973                 new_edl->create_objects();
1974                 new_edl->copy_session(edl, -1);
1975                 new_file->set_program(edl->session->program_no);
1976
1977                 char string[BCTEXTLEN];
1978                 sprintf(string, _("Loading %s"), new_asset->path);
1979                 gui->show_message(string);
1980
1981                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1982
1983                 result = 1;
1984                 switch( ftype ) {
1985 // Convert media file to EDL
1986                 case FILE_OK: {
1987 // Warn about odd image dimensions
1988                         if( new_asset->video_data &&
1989                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
1990                                 eprintf(_("%s's resolution is %dx%d.\n"
1991                                         "Images with odd dimensions may not decode properly."),
1992                                         new_asset->path, new_asset->width, new_asset->height);
1993                         }
1994
1995                         if( new_asset->program >= 0 &&
1996                             edl->session->program_no != new_asset->program ) {
1997                                 eprintf(_("%s's index was built for program number %d\n"
1998                                         "Playback preference is %d.\n  Using program %d."),
1999                                         new_asset->path, new_asset->program,
2000                                         edl->session->program_no, new_asset->program);
2001                         }
2002
2003                         if( load_mode == LOADMODE_RESOURCESONLY ) {
2004                                 new_assets.append(new_asset);
2005                                 new_asset->add_user();
2006                                 result = 0;
2007                                 break;
2008                         }
2009
2010                         RecordLabels *labels = edl->session->label_cells ?
2011                                 new RecordLabels(new_file) : 0;
2012                         asset_to_edl(new_edl, new_asset, labels);
2013                         new_edls.append(new_edl);
2014                         new_edl->add_user();
2015                         delete labels;
2016
2017                         if( load_mode == LOADMODE_REPLACE ||
2018                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2019 // Set filename to nothing for assets since save EDL would overwrite them.
2020                                 set_filename("");
2021 // Reset timeline position
2022                                 for( int i=0; i<TOTAL_PANES; ++i ) {
2023                                         new_edl->local_session->view_start[i] = 0;
2024                                         new_edl->local_session->track_start[i] = 0;
2025                                 }
2026                         }
2027                         result = 0;
2028                         break; }
2029
2030                 case FILE_NOT_FOUND: {
2031                         eprintf(_("Failed to open %s"), new_asset->path);
2032                         sprintf(string, _("Failed to open %s"), new_asset->path);
2033                         gui->show_message(string, theme->message_error);
2034                         gui->update_default_message();
2035                         break; }
2036
2037 // Unknown format
2038                 case FILE_UNRECOGNIZED_CODEC: {
2039 // Test index file
2040                         { IndexFile indexfile(this, new_asset);
2041                         if( !(result = indexfile.open_index()) )
2042                                 indexfile.close_index(); }
2043
2044 // Test existing EDLs
2045                         for( int j=0; result && j<new_edls.total; ++j ) {
2046                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
2047                                 if( old_asset ) {
2048                                         new_asset->copy_from(old_asset,1);
2049                                         result = 0;
2050                                 }
2051                         }
2052                         if( result ) {
2053                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
2054                                 if( old_asset ) {
2055                                         new_asset->copy_from(old_asset,1);
2056                                         result = 0;
2057                                 }
2058                         }
2059
2060 // Prompt user
2061                         if( result ) {
2062                                 new_asset->audio_data = 1;
2063                                 new_asset->format = FILE_PCM;
2064                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
2065                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
2066                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
2067                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
2068                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
2069                                 new_asset->header = defaults->get("HEADER", 0);
2070
2071                                 FileSystem fs;
2072                                 fs.extract_name(string, new_asset->path);
2073                                 strcat(string, _("'s format couldn't be determined."));
2074                                 FileFormat fwindow(this);
2075                                 fwindow.create_objects(new_asset, string);
2076                                 result = fwindow.run_window();
2077
2078                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
2079                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
2080                                 defaults->update("AUDIO_BITS", new_asset->bits);
2081                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
2082                                 defaults->update("SIGNED_", new_asset->signed_);
2083                                 defaults->update("HEADER", new_asset->header);
2084                                 save_defaults();
2085                         }
2086 // Append to list
2087                         if( !result ) {
2088 // Recalculate length
2089                                 delete new_file;
2090                                 new_file = new File;
2091                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2092
2093                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
2094                                         RecordLabels *labels = edl->session->label_cells ?
2095                                                 new RecordLabels(new_file) : 0;
2096                                         asset_to_edl(new_edl, new_asset, labels);
2097                                         new_edls.append(new_edl);
2098                                         new_edl->add_user();
2099                                         delete labels;
2100                                 }
2101                                 else {
2102                                         new_assets.append(new_asset);
2103                                         new_asset->add_user();
2104                                 }
2105                         }
2106                         break; }
2107
2108                 case FILE_IS_XML: {
2109                         FileXML xml_file;
2110                         const char *filename = filenames->get(i);
2111                         if( xml_file.read_from_file(filename, 1) ) {
2112                                 eprintf(_("Error: unable to open:\n  %s"), filename);
2113                                 break;
2114                         }
2115                         const char *cin_version = 0;
2116                         while( !xml_file.read_tag() ) {
2117                                 if( xml_file.tag.title_is("EDL") ) {
2118                                         cin_version = xml_file.tag.get_property("VERSION");
2119                                         break;
2120                                 }
2121                         }
2122                         xml_file.rewind();
2123                         if( !cin_version ) {
2124                                 eprintf(_("XML file %s\n not from cinelerra."),filename);
2125                                 char string[BCTEXTLEN];
2126                                 sprintf(string,_("Unknown %s"), filename);
2127                                 gui->show_message(string);
2128                                 break;
2129                         }
2130                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2131                             strcmp(cin_version, "Unify") &&
2132                             strcmp(cin_version, "5.1") ) {
2133                                 eprintf(_("Warning: XML from cinelerra version %s\n"
2134                                         "Session data may be incompatible."), cin_version);
2135                         }
2136                         if( new_edl->load_xml(&xml_file, LOAD_ALL) ) {
2137                                 eprintf(_("Error: unable to load:\n  %s"), filename);
2138                                 break;
2139                         }
2140                         test_plugins(new_edl, filename);
2141                         int groups = new_edl->regroup(session->group_number);
2142                         session->group_number += groups;
2143                         switch( edl_mode ) {
2144                         case LOADMODE_EDL_CLIP: {
2145                                 strcpy(new_edl->local_session->clip_title,
2146                                         filenames->get(i));
2147                                 struct stat st;
2148                                 time_t t = !stat(filenames->get(i),&st) ?
2149                                         st.st_mtime : time(&t);
2150                                 ctime_r(&t, new_edl->local_session->clip_notes);
2151                                 switch( load_mode ) {
2152                                 case LOADMODE_REPLACE:
2153                                 case LOADMODE_REPLACE_CONCATENATE:
2154                                         strcpy(session->filename, filename);
2155                                         if( update_filename ) set_filename(filename);
2156                                         break;
2157                                 }
2158                                 result = 0;
2159                                 break; }
2160                         case LOADMODE_EDL_NESTED: {
2161                                 EDL *nested_edl = new EDL;
2162                                 nested_edl->create_objects();
2163                                 nested_edl->copy_session(edl, -1);
2164                                 nested_edl->create_nested(new_edl);
2165                                 nested_edl->set_path(filename);
2166                                 new_edl->remove_user();
2167                                 new_edl = nested_edl;
2168                                 result = 0;
2169                                 break; }
2170                         case LOADMODE_EDL_FILEREF: {
2171                                 result = create_ref(new_asset, new_edl);
2172                                 if( result ) break;
2173                                 new_assets.append(new_asset);
2174                                 new_asset->add_user();
2175                                 new_edl->remove_user();
2176                                 new_edl = new EDL;
2177                                 new_edl->create_objects();
2178                                 new_edl->copy_session(edl, -1);
2179                                 asset_to_edl(new_edl, new_asset);
2180                                 delete new_file;
2181                                 new_file = new File;
2182                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2183                                 break; }
2184                         }
2185                         if( !result ) {
2186                                 new_edls.append(new_edl);
2187                                 new_edl->add_user();
2188                         }
2189                         else
2190                                 eprintf(_("Error: Unable to load xml:\n  %s"), new_asset->path);
2191                         break; }
2192                 }
2193
2194                 new_edl->Garbage::remove_user();
2195                 new_asset->Garbage::remove_user();
2196
2197 // Store for testing index
2198                 new_files.append(new_file);
2199         }
2200
2201 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2202
2203         if(!result) {
2204                 gui->reset_default_message();
2205                 gui->default_message();
2206         }
2207
2208 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2209
2210 // Paste them.
2211 // Don't back up here.
2212         if( new_edls.size() ) {
2213 // For pasting, clear the active region
2214                 if( load_mode == LOADMODE_PASTE ) {
2215                         double start = edl->local_session->get_selectionstart();
2216                         double end = edl->local_session->get_selectionend();
2217                         if(!EQUIV(start, end))
2218                                 edl->clear(start, end,
2219                                         edl->session->labels_follow_edits,
2220                                         edl->session->plugins_follow_edits,
2221                                         edl->session->autos_follow_edits);
2222
2223                         paste_edls(&new_edls, load_mode, 0, -1,
2224                                 edl->session->labels_follow_edits,
2225                                 edl->session->plugins_follow_edits,
2226                                 edl->session->autos_follow_edits,
2227                                 0); // overwrite
2228                 }
2229                 else if( load_mode == LOADMODE_NEW_TRACKS &&
2230                          edl_mode != LOADMODE_EDL_CLIP )
2231                         paste_edls(&new_edls, load_mode, 0, -1, 0, 0, 0, 0);
2232                 else if( load_mode != LOADMODE_RESOURCESONLY ||
2233                          edl_mode == LOADMODE_EDL_CLIP )
2234                         paste_edls(&new_edls, load_mode, 0, -1, 1, 1, 1, 0);
2235                 else
2236                         paste_edls(&new_edls, LOADMODE_NOTHING, 0, -1, 0, 0, 0, 0);
2237
2238         }
2239
2240 // Add new assets to EDL and schedule assets for index building.
2241         int got_indexes = 0;
2242         for( int i=0; i<new_edls.size(); ++i ) {
2243                 EDL *new_edl = new_edls[i];
2244                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2245                         mainindexes->add_indexable(new_edl->nested_edls[j]);
2246                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2247                         got_indexes = 1;
2248                 }
2249
2250         }
2251
2252         for( int i=0; i<new_assets.size(); ++i ) {
2253                 Asset *new_asset = new_assets[i];
2254                 mainindexes->add_indexable(new_asset);
2255                 edl->assets->update(new_asset);
2256                 got_indexes = 1;
2257         }
2258
2259 // Start examining next batch of index files
2260         if(got_indexes) mainindexes->start_build();
2261
2262 // Open plugin GUIs
2263         show_plugins();
2264
2265         // opening new session
2266         if( ( load_mode == LOADMODE_REPLACE ||
2267               load_mode == LOADMODE_REPLACE_CONCATENATE ) &&
2268             (ftype != FILE_IS_XML || edl_mode != LOADMODE_EDL_CLIP) ) {
2269                 select_asset(0, 0);
2270                 edl->session->proxy_scale = 1;
2271                 edl->session->proxy_disabled_scale = 1;
2272                 edl->session->proxy_use_scaler = 0;
2273                 edl->session->proxy_auto_scale = 0;
2274                 edl->session->proxy_beep = 0;
2275                 edl->local_session->preview_start = 0;
2276                 edl->local_session->preview_end = -1;
2277                 edl->local_session->loop_playback = 0;
2278                 edl->local_session->set_selectionstart(0);
2279                 edl->local_session->set_selectionend(0);
2280                 edl->local_session->unset_inpoint();
2281                 edl->local_session-> unset_outpoint();
2282                 set_brender_active(0, 0);
2283                 fit_selection();
2284                 goto_start();
2285         }
2286
2287         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2288             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2289                 ArrayList<Indexable *> orig_idxbls;
2290                 for( int i=0; i<new_assets.size(); ++i )
2291                         orig_idxbls.append(new_assets.get(i));
2292                 for( int i=0; i<new_edls.size(); ++i ) {
2293                         EDL *new_edl = new_edls[i];
2294                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2295                                 if( track->data_type != TRACK_VIDEO ) continue;
2296                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2297                                         Indexable *idxbl = (Indexable *)edit->asset;
2298                                         if( !idxbl ) continue;
2299                                         if( !idxbl->have_video() ) continue;
2300                                         if( edit->channel != 0 ) continue; // first layer only
2301                                         orig_idxbls.append(edit->asset);
2302                                 }
2303                         }
2304                 }
2305                 gui->unlock_window(); // to update progress bar
2306                 int ret = render_proxy(orig_idxbls);
2307                 gui->lock_window("MWindow::load_filenames");
2308                 float gain = edl->session->proxy_beep;
2309                 if( ret >= 0 && gain > 0 ) {
2310                         if( ret > 0 )
2311                                 beep(2000., 1.5, gain);
2312                         else
2313                                 beep(4000., 0.25, gain);
2314                 }
2315         }
2316
2317 // need to update undo before project, since mwindow is unlocked & a new load
2318 // can begin here.  Should really prevent loading until we're done.
2319 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2320         undo_after(_("load"), LOAD_ALL);
2321
2322         for(int i = 0; i < new_edls.size(); i++)
2323         {
2324                 new_edls[i]->remove_user();
2325         }
2326 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2327
2328         new_edls.remove_all();
2329
2330         for(int i = 0; i < new_assets.size(); i++)
2331         {
2332                 new_assets[i]->Garbage::remove_user();
2333         }
2334
2335         new_assets.remove_all();
2336         new_files.remove_all_objects();
2337
2338
2339 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2340         if(load_mode == LOADMODE_REPLACE ||
2341                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2342         {
2343                 session->changes_made = 0;
2344         }
2345         else
2346         {
2347                 session->changes_made = 1;
2348         }
2349
2350         gui->stop_hourglass();
2351
2352
2353 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2354         update_project(load_mode);
2355
2356 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2357
2358         return 0;
2359 }
2360
2361 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2362 {
2363         Asset *format_asset = new Asset;
2364         format_asset->format = FILE_FFMPEG;
2365         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2366         int new_scale = edl->session->proxy_scale;
2367         ProxyRender proxy_render(this, format_asset, new_scale);
2368
2369         for( int i=0; i<new_idxbls.size(); ++i ) {
2370                 Indexable *orig = new_idxbls.get(i);
2371                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2372                 if( !proxy ) continue;
2373                 FileSystem fs;
2374                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2375                 int got_it = exists && // if proxy exists, and is newer than orig
2376                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2377                 if( got_it ) continue;
2378                 proxy_render.add_needed(orig, proxy);
2379         }
2380
2381 // render needed proxies
2382         int result = proxy_render.create_needed_proxies(new_scale);
2383         if( !result ) {
2384                 add_proxy(&proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2385         }
2386         format_asset->remove_user();
2387         return !result ? proxy_render.needed_proxies.size() : -1;
2388 }
2389
2390 int MWindow::enable_proxy()
2391 {
2392         int ret = 0;
2393         if( edl->session->proxy_scale == 1 &&
2394             edl->session->proxy_disabled_scale != 1 ) {
2395                 int new_scale = edl->session->proxy_disabled_scale;
2396                 int new_use_scaler = edl->session->proxy_use_scaler;
2397                 Asset *asset = new Asset;
2398                 asset->format = FILE_FFMPEG;
2399                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2400                 ret = to_proxy(asset, new_scale, new_use_scaler);
2401                 asset->remove_user();
2402                 if( ret > 0 ) {
2403                         float gain = edl->session->proxy_beep;
2404                         beep(2000., 1.5, gain);
2405                 }
2406                 edl->session->proxy_disabled_scale = 1;
2407                 gui->lock_window("MWindow::to_proxy");
2408                 update_project(LOADMODE_REPLACE);
2409                 gui->unlock_window();
2410         }
2411         return 1;
2412 }
2413
2414 int MWindow::disable_proxy()
2415 {
2416         if( edl->session->proxy_scale != 1 &&
2417             edl->session->proxy_disabled_scale == 1 ) {
2418                 int old_scale = edl->session->proxy_scale, new_scale = 1;
2419                 int new_use_scaler = edl->session->proxy_use_scaler;
2420                 Asset *asset = new Asset;
2421                 asset->format = FILE_FFMPEG;
2422                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2423                 to_proxy(asset, new_scale, new_use_scaler);
2424                 asset->remove_user();
2425                 edl->session->proxy_disabled_scale = old_scale;
2426                 gui->lock_window("MWindow::to_proxy");
2427                 update_project(LOADMODE_REPLACE);
2428                 gui->unlock_window();
2429         }
2430         return 1;
2431 }
2432
2433 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2434 {
2435         ArrayList<Indexable*> orig_idxbls;
2436         ArrayList<Indexable*> proxy_assets;
2437
2438         edl->Garbage::add_user();
2439         save_backup();
2440         undo_before(_("proxy"), this);
2441         int asset_scale = new_scale == 1 ? 0 :
2442                         !new_use_scaler ? 1 : new_scale;
2443         ProxyRender proxy_render(this, asset, asset_scale);
2444
2445 // revert project to original size from current size
2446 // remove all session proxy assets at the at the current proxy_scale
2447         int proxy_scale = edl->session->proxy_scale;
2448
2449         if( proxy_scale > 1 ) {
2450                 Asset *orig_asset = edl->assets->first;
2451                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2452                         char new_path[BCTEXTLEN];
2453                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2454 // test if proxy asset was already added to proxy_assets
2455                         int got_it = 0;
2456                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2457                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2458                         if( got_it ) continue;
2459                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2460                         if( !proxy_asset ) continue;
2461 // add pointer to existing EDL asset if it exists
2462 // EDL won't delete it unless it's the same pointer.
2463                         proxy_assets.append(proxy_asset);
2464                         proxy_asset->add_user();
2465                         orig_idxbls.append(orig_asset);
2466                         orig_asset->add_user();
2467                 }
2468                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2469                         EDL *orig_nested = edl->nested_edls[i];
2470                         char new_path[BCTEXTLEN];
2471                         if( !ProxyRender::from_proxy_path(new_path, orig_nested, proxy_scale) )
2472                                 continue;
2473                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2474 // test if proxy asset was already added to proxy_assets
2475                         int got_it = 0;
2476                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2477                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2478                         if( got_it ) continue;
2479                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2480                         if( !proxy_nested ) continue;
2481 // add pointer to existing EDL asset if it exists
2482 // EDL won't delete it unless it's the same pointer.
2483                         proxy_assets.append(proxy_nested);
2484                         proxy_nested->add_user();
2485                         orig_idxbls.append(orig_nested);
2486                         orig_nested->add_user();
2487                 }
2488
2489 // convert from the proxy assets to the original assets
2490                 edl->set_proxy(1, 0, &proxy_assets, &orig_idxbls);
2491
2492 // remove the references
2493                 for( int i=0; i<proxy_assets.size(); ++i ) {
2494                         Asset *proxy = (Asset *) proxy_assets[i];
2495                         proxy->width = proxy->actual_width;
2496                         proxy->height = proxy->actual_height;
2497                         proxy->remove_user();
2498                         edl->assets->remove_pointer(proxy);
2499                         proxy->remove_user();
2500                 }
2501                 proxy_assets.remove_all();
2502                 for( int i = 0; i < orig_idxbls.size(); i++ )
2503                         orig_idxbls[i]->remove_user();
2504                 orig_idxbls.remove_all();
2505         }
2506
2507         ArrayList<char *> confirm_paths;    // test for new files
2508         confirm_paths.set_array_delete();
2509
2510 // convert to new size if not original size
2511         if( new_scale != 1 ) {
2512                 FileSystem fs;
2513                 Asset *orig = edl->assets->first;
2514                 for( ; orig; orig=orig->next ) {
2515                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2516                         if( !proxy ) continue;
2517                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2518                         int got_it = exists && // if proxy exists, and is newer than orig
2519                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2520                         if( !got_it ) {
2521                                 if( exists ) // prompt user to overwrite
2522                                         confirm_paths.append(cstrdup(proxy->path));
2523                                 proxy_render.add_needed(orig, proxy);
2524                         }
2525                 }
2526                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2527                         EDL *orig_nested = edl->nested_edls[i];
2528                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2529                         if( !proxy ) continue;
2530                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2531                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2532                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2533                         if( !got_it ) {
2534                                 if( exists ) // prompt user to overwrite
2535                                         confirm_paths.append(cstrdup(proxy->path));
2536                                 proxy_render.add_needed(orig_nested, proxy);
2537                         }
2538                 }
2539         }
2540
2541         int result = 0;
2542 // test for existing files
2543         if( confirm_paths.size() ) {
2544                 result = ConfirmSave::test_files(this, &confirm_paths);
2545                 confirm_paths.remove_all_objects();
2546         }
2547
2548         if( !result )
2549                 result = proxy_render.create_needed_proxies(new_scale);
2550
2551         if( !result ) // resize project
2552                 edl->set_proxy(new_scale, new_use_scaler,
2553                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2554
2555         undo_after(_("proxy"), LOAD_ALL);
2556         edl->Garbage::remove_user();
2557         restart_brender();
2558
2559         return !result ? proxy_render.needed_proxies.size() : -1;
2560 }
2561
2562 void MWindow::test_plugins(EDL *new_edl, const char *path)
2563 {
2564         char string[BCTEXTLEN];
2565
2566 // Do a check whether plugins exist
2567         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2568                 for( int k=0; k<track->plugin_set.total; ++k ) {
2569                         PluginSet *plugin_set = track->plugin_set[k];
2570                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2571                                         plugin; plugin = (Plugin*)plugin->next ) {
2572                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2573 // ok we need to find it in plugindb
2574                                 PluginServer *server =
2575                                         scan_plugindb(plugin->title, track->data_type);
2576                                 if( !server || server->transition ) {
2577                                         sprintf(string,
2578         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2579           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2580                                                 "effect", _(plugin->title), path);
2581                                         MainError::show_error(string);
2582                                 }
2583                         }
2584                 }
2585
2586                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2587                         if( !edit->transition ) continue;
2588 // ok we need to find transition in plugindb
2589                         PluginServer *server =
2590                                 scan_plugindb(edit->transition->title, track->data_type);
2591                         if( !server || !server->transition ) {
2592                                 sprintf(string,
2593         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2594           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2595                                         "transition", _(edit->transition->title), path);
2596                                 MainError::show_error(string);
2597                         }
2598                 }
2599         }
2600 }
2601
2602
2603 void MWindow::init_shm(const char *pfn, int64_t min)
2604 {
2605         int64_t result = 0;
2606 // Fix shared memory
2607         FILE *fd = fopen(pfn, "r");
2608         if( fd ) {
2609                 fscanf(fd, "%jd", &result);
2610                 fclose(fd);
2611                 if( result >= min ) return;
2612         }
2613
2614         fd = fopen(pfn, "w");
2615         if( !fd ) return;
2616         fprintf(fd, "0x%jx", min);
2617         fclose(fd);
2618
2619         fd = fopen(pfn, "r");
2620         if( !fd ) {
2621                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2622                 return;
2623         }
2624
2625         fscanf(fd, "%jd", &result);
2626         fclose(fd);
2627         if( result < min ) {
2628                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2629                         "you probably need to be root, or:\n"
2630                         "as root, run: echo 0x%jx > %s\n"
2631                         "before trying to start cinelerra.\n"
2632                         "It should be at least 0x%jx for Cinelerra.\n"),
2633                         pfn, (void *)result, min, pfn, min);
2634         }
2635 }
2636
2637 void MWindow::create_objects(int want_gui,
2638         int want_new,
2639         char *config_path)
2640 {
2641         const int debug = 0;
2642         if(debug) PRINT_TRACE
2643
2644 // For some reason, init_signals must come after show_splash or the signals won't
2645 // get trapped.
2646         init_signals();
2647         if(debug) PRINT_TRACE
2648         init_3d();
2649
2650         if(debug) PRINT_TRACE
2651         show_splash();
2652
2653         if(debug) PRINT_TRACE
2654         default_standard = default_std();
2655         init_defaults(defaults, config_path);
2656         check_language();
2657         init_preferences();
2658         if(splash_window)
2659                 splash_window->update_status(_("Initializing Plugins"));
2660         init_plugins(this, preferences);
2661         if(debug) PRINT_TRACE
2662         init_ladspa_plugins(this, preferences);
2663         if(debug) PRINT_TRACE
2664         init_plugin_tips(*plugindb, cin_lang);
2665         if(splash_window)
2666                 splash_window->update_status(_("Initializing GUI"));
2667         if(debug) PRINT_TRACE
2668         init_theme();
2669
2670         if(debug) PRINT_TRACE
2671         init_error();
2672
2673         if(splash_window)
2674                 splash_window->update_status(_("Initializing Fonts"));
2675         char string[BCTEXTLEN];
2676         strcpy(string, preferences->plugin_dir);
2677         strcat(string, "/" FONT_SEARCHPATH);
2678         BC_Resources::init_fontconfig(string);
2679         if(debug) PRINT_TRACE
2680 // use if plugged
2681         init_x10tv();
2682         if( !x10tv )
2683                 init_wintv();
2684
2685 // Default project created here
2686         init_edl();
2687         if(debug) PRINT_TRACE
2688
2689         init_cache();
2690         if(debug) PRINT_TRACE
2691
2692         Timer timer;
2693
2694         init_awindow();
2695         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2696
2697         init_compositor();
2698         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2699
2700 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2701         if(session->show_vwindow)
2702                 get_viewer(1, DEFAULT_VWINDOW);
2703         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2704
2705         init_gui();
2706         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2707
2708         init_levelwindow();
2709         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2710
2711         init_indexes();
2712         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2713
2714         init_channeldb();
2715         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2716
2717         init_gwindow();
2718         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2719
2720         init_render();
2721         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2722
2723         init_shuttle();
2724         init_brender();
2725         init_exportedl();
2726         init_commercials();
2727         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2728         mainprogress = new MainProgress(this, gui);
2729         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2730         undo = new MainUndo(this);
2731
2732         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2733
2734         plugin_guis = new PluginGUIs(this);
2735         dead_plugins = new ArrayList<PluginServer*>;
2736         keyframe_threads = new ArrayList<KeyFrameThread*>;
2737
2738         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2739                 __LINE__,
2740                 vwindows.size(),
2741                 session->show_vwindow);
2742
2743 // Show all vwindows
2744 //      if(session->show_vwindow) {
2745 //              for(int j = 0; j < vwindows.size(); j++) {
2746 //                      VWindow *vwindow = vwindows[j];
2747 //                      if( !vwindow->is_running() ) continue;
2748 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2749 //                              __LINE__,
2750 //                              vwindow);
2751 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2752 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2753 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2754 //                      vwindow->gui->show_window();
2755 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2756 //                      vwindow->gui->unlock_window();
2757 //              }
2758 //      }
2759
2760
2761         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2762
2763         if(session->show_cwindow)
2764         {
2765                 cwindow->gui->lock_window("MWindow::create_objects 1");
2766                 cwindow->gui->show_window();
2767                 cwindow->gui->unlock_window();
2768         }
2769
2770         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2771         if(session->show_awindow)
2772         {
2773                 awindow->gui->lock_window("MWindow::create_objects 1");
2774                 awindow->gui->show_window();
2775                 awindow->gui->unlock_window();
2776         }
2777
2778         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2779         if(session->show_lwindow)
2780         {
2781                 lwindow->gui->lock_window("MWindow::create_objects 1");
2782                 lwindow->gui->show_window();
2783                 lwindow->gui->unlock_window();
2784         }
2785
2786         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2787                 __LINE__,
2788                 (int)timer.get_difference(),
2789                 gwindow->gui);
2790         if(session->show_gwindow)
2791         {
2792                 gwindow->gui->lock_window("MWindow::create_objects 1");
2793                 gwindow->gui->show_window();
2794                 gwindow->gui->unlock_window();
2795         }
2796
2797         if(debug) PRINT_TRACE
2798
2799         gui->lock_window("MWindow::create_objects 1");
2800         gui->mainmenu->load_defaults(defaults);
2801         gui->mainmenu->update_toggles(0);
2802         gui->update_patchbay();
2803         gui->draw_canvas(0, 0);
2804         gui->draw_cursor(1);
2805         gui->show_window();
2806         gui->raise_window();
2807         gui->unlock_window();
2808         cwindow->gui->lock_window("MWindow::create_objects 1");
2809         cwindow->gui->tool_panel->raise_tool();
2810         cwindow->gui->unlock_window();
2811         if(debug) PRINT_TRACE
2812
2813         if(preferences->use_tipwindow)
2814                 init_tipwindow();
2815         if(debug) PRINT_TRACE
2816
2817         gui->add_keyboard_listener(
2818                 (int (BC_WindowBase::*)(BC_WindowBase *))
2819                 &MWindowGUI::keyboard_listener);
2820
2821         hide_splash();
2822         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2823         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2824         if(debug) PRINT_TRACE
2825
2826         BC_WindowBase::get_resources()->vframe_shm = 1;
2827 }
2828
2829 int MWindow::uses_opengl()
2830 {
2831         if( !playback_3d || !playback_3d->running() ) return 0;
2832         PlaybackConfig *playback_config = edl->session->playback_config;
2833         return playback_config->vconfig->driver == PLAYBACK_X11_GL ? 1 : 0;
2834 }
2835
2836 void MWindow::show_splash()
2837 {
2838 #include "data/heroine_logo9_png.h"
2839         VFrame *frame = new VFramePng(heroine_logo9_png);
2840         BC_DisplayInfo dpyi;
2841         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2842         int rr = (rw < rh ? rw : rh) / 4;
2843         splash_window = new SplashGUI(frame, rr, rr);
2844         splash_window->create_objects();
2845 }
2846
2847 void MWindow::hide_splash()
2848 {
2849         if(splash_window)
2850                 delete splash_window;
2851         splash_window = 0;
2852 }
2853
2854
2855 void MWindow::start()
2856 {
2857 ENABLE_BUFFER
2858 //PRINT_TRACE
2859 //      vwindows[DEFAULT_VWINDOW]->start();
2860         awindow->start();
2861 //PRINT_TRACE
2862         cwindow->start();
2863 //PRINT_TRACE
2864         lwindow->start();
2865 //PRINT_TRACE
2866         gwindow->start();
2867 //PRINT_TRACE
2868 //      Thread::start();
2869 //PRINT_TRACE
2870         playback_3d->start();
2871 //PRINT_TRACE
2872 }
2873
2874 void MWindow::run()
2875 {
2876         run_lock->lock("MWindow::run");
2877         gui->run_window();
2878         stop_playback(1);
2879
2880         brender_lock->lock("MWindow::run 1");
2881         delete brender;         brender = 0;
2882         brender_lock->unlock();
2883
2884         interrupt_indexes();
2885         clean_indexes();
2886         save_defaults();
2887         run_lock->unlock();
2888 }
2889
2890 void MWindow::show_vwindow()
2891 {
2892         int total_running = 0;
2893         session->show_vwindow = 1;
2894
2895 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2896 // Raise all windows which are visible
2897         for(int j = 0; j < vwindows.size(); j++) {
2898                 VWindow *vwindow = vwindows[j];
2899                 if( !vwindow->is_running() ) continue;
2900                 vwindow->gui->lock_window("MWindow::show_vwindow");
2901                 vwindow->gui->show_window(0);
2902                 vwindow->gui->raise_window();
2903                 vwindow->gui->flush();
2904                 vwindow->gui->unlock_window();
2905                 total_running++;
2906         }
2907
2908 // If no windows visible
2909         if(!total_running)
2910         {
2911                 get_viewer(1, DEFAULT_VWINDOW);
2912         }
2913
2914         gui->mainmenu->show_vwindow->set_checked(1);
2915 }
2916
2917 void MWindow::show_awindow()
2918 {
2919         session->show_awindow = 1;
2920         awindow->gui->lock_window("MWindow::show_awindow");
2921         awindow->gui->show_window();
2922         awindow->gui->raise_window();
2923         awindow->gui->flush();
2924         awindow->gui->unlock_window();
2925         gui->mainmenu->show_awindow->set_checked(1);
2926 }
2927
2928 char *MWindow::get_cwindow_display()
2929 {
2930         char *x11_host = screens < 2 || session->window_config == 0 ?
2931                 session->a_x11_host : session->b_x11_host;
2932         return *x11_host ? x11_host : 0;
2933 }
2934
2935 void MWindow::show_cwindow()
2936 {
2937         session->show_cwindow = 1;
2938         cwindow->show_window();
2939         gui->mainmenu->show_cwindow->set_checked(1);
2940 }
2941
2942 void MWindow::show_gwindow()
2943 {
2944         session->show_gwindow = 1;
2945
2946         gwindow->gui->lock_window("MWindow::show_gwindow");
2947         gwindow->gui->show_window();
2948         gwindow->gui->raise_window();
2949         gwindow->gui->flush();
2950         gwindow->gui->unlock_window();
2951
2952         gui->mainmenu->show_gwindow->set_checked(1);
2953 }
2954 void MWindow::hide_gwindow()
2955 {
2956         session->show_gwindow = 0;
2957
2958         gwindow->gui->lock_window("MWindow::show_gwindow");
2959         gwindow->gui->hide_window();
2960         gwindow->gui->unlock_window();
2961 }
2962
2963 void MWindow::show_lwindow()
2964 {
2965         session->show_lwindow = 1;
2966         lwindow->gui->lock_window("MWindow::show_lwindow");
2967         lwindow->gui->show_window();
2968         lwindow->gui->raise_window();
2969         lwindow->gui->flush();
2970         lwindow->gui->unlock_window();
2971         gui->mainmenu->show_lwindow->set_checked(1);
2972 }
2973
2974 void MWindow::restore_windows()
2975 {
2976         if( !session->show_vwindow ) {
2977                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
2978                         VWindow *vwindow = vwindows[i];
2979                         if( !vwindow || !vwindow->is_running() ) continue;
2980                         vwindow->gui->lock_window("MWindow::restore_windows");
2981                         vwindow->gui->close(1);
2982                         vwindow->gui->unlock_window();
2983                 }
2984         }
2985         else
2986                 show_vwindow();
2987
2988         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
2989                 awindow->gui->lock_window("MWindow::restore_windows");
2990                 awindow->gui->close_event();
2991                 awindow->gui->unlock_window();
2992         }
2993         else if( session->show_awindow && awindow->gui->is_hidden() )
2994                 show_awindow();
2995
2996         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
2997                 cwindow->gui->lock_window("MWindow::restore_windows");
2998                 cwindow->hide_window();
2999                 cwindow->gui->unlock_window();
3000         }
3001         else if( session->show_cwindow && cwindow->gui->is_hidden() )
3002                 cwindow->show_window();
3003
3004         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
3005                 gwindow->gui->lock_window("MWindow::restore_windows");
3006                 gwindow->gui->close_event();
3007                 gwindow->gui->unlock_window();
3008         }
3009         else if( session->show_gwindow && gwindow->gui->is_hidden() )
3010                 show_gwindow();
3011
3012         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
3013                 lwindow->gui->lock_window("MWindow::restore_windows");
3014                 lwindow->gui->close_event();
3015                 lwindow->gui->unlock_window();
3016         }
3017         else if( session->show_lwindow && lwindow->gui->is_hidden() )
3018                 show_lwindow();
3019
3020         gui->focus();
3021 }
3022
3023 void MWindow::load_layout(const char *layout)
3024 {
3025         char path[BCTEXTLEN];
3026         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3027         session->load_file(path);
3028         restore_windows();
3029         gui->default_positions();
3030         save_defaults();
3031 }
3032
3033 void MWindow::save_layout(const char *layout)
3034 {
3035         char path[BCTEXTLEN];
3036         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3037         session->save_file(path);
3038 }
3039
3040 void MWindow::delete_layout(const char *layout)
3041 {
3042         char path[BCTEXTLEN];
3043         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3044         unlink(path);
3045 }
3046
3047 int MWindow::tile_windows(int window_config)
3048 {
3049         int need_reload = 0;
3050         int play_config = window_config==0 ? 0 : 1;
3051         edl->session->playback_config->load_defaults(defaults, play_config);
3052         session->default_window_positions(window_config);
3053         if( screens == 1 ) {
3054                 gui->default_positions();
3055                 sync_parameters(CHANGE_ALL);
3056         }
3057         else
3058                 need_reload = 1;
3059         return need_reload;
3060 }
3061
3062 void MWindow::toggle_loop_playback()
3063 {
3064         edl->local_session->loop_playback = !edl->local_session->loop_playback;
3065         set_loop_boundaries();
3066         save_backup();
3067
3068         gui->draw_overlays(1);
3069         sync_parameters(CHANGE_PARAMS);
3070 }
3071
3072 void MWindow::set_screens(int value)
3073 {
3074         screens = value;
3075 }
3076
3077 void MWindow::set_auto_keyframes(int value)
3078 {
3079         edl->session->auto_keyframes = value;
3080         gui->mbuttons->edit_panel->keyframe->update(value);
3081         gui->flush();
3082         cwindow->gui->lock_window("MWindow::set_auto_keyframes");
3083         cwindow->gui->flush();
3084         cwindow->gui->unlock_window();
3085 }
3086
3087 void MWindow::set_span_keyframes(int value)
3088 {
3089         edl->session->span_keyframes = value;
3090         gui->mbuttons->edit_panel->span_keyframe->update(value);
3091         gui->flush();
3092         cwindow->gui->lock_window("MWindow::set_span_keyframes");
3093         cwindow->gui->flush();
3094         cwindow->gui->unlock_window();
3095 }
3096
3097 void MWindow::set_auto_visibility(Autos *autos, int value)
3098 {
3099         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
3100                 edl->session->auto_conf->plugins = value;
3101         else if( autos->autoidx >= 0 )
3102                 edl->session->auto_conf->autos[autos->autoidx] = value;
3103         else
3104                 return;
3105
3106         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3107         gui->mainmenu->update_toggles(1);
3108         gui->unlock_window();
3109         gwindow->gui->update_toggles(1);
3110         gui->lock_window("MWindow::set_auto_visibility");
3111 }
3112
3113 void MWindow::set_keyframe_type(int mode)
3114 {
3115         gui->lock_window("MWindow::set_keyframe_type");
3116         edl->local_session->floatauto_type = mode;
3117         gui->mainmenu->update_toggles(0);
3118         gui->unlock_window();
3119 }
3120
3121 int MWindow::set_editing_mode(int new_editing_mode)
3122 {
3123         edl->session->editing_mode = new_editing_mode;
3124         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
3125         gui->mbuttons->edit_panel->update();
3126         gui->set_editing_mode(1);
3127
3128         cwindow->gui->lock_window("MWindow::set_editing_mode");
3129         cwindow->gui->edit_panel->update();
3130         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
3131         cwindow->gui->unlock_window();
3132         return 0;
3133 }
3134
3135 void MWindow::toggle_editing_mode()
3136 {
3137         int mode = edl->session->editing_mode;
3138         if( mode == EDITING_ARROW )
3139                 set_editing_mode(EDITING_IBEAM);
3140         else
3141                 set_editing_mode(EDITING_ARROW);
3142 }
3143
3144 void MWindow::toggle_camera_xyz()
3145 {
3146         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3147         gwindow->gui->toggle_camera_xyz();
3148         gwindow->gui->unlock_window();
3149 }
3150
3151 void MWindow::toggle_projector_xyz()
3152 {
3153         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3154         gwindow->gui->toggle_projector_xyz();
3155         gwindow->gui->unlock_window();
3156 }
3157
3158 void MWindow::set_labels_follow_edits(int value)
3159 {
3160         edl->session->labels_follow_edits = value;
3161         gui->mbuttons->edit_panel->locklabels->update(value);
3162         gui->mainmenu->labels_follow_edits->set_checked(value);
3163         gui->flush();
3164 }
3165
3166 void MWindow::sync_parameters(int change_type)
3167 {
3168         if( in_destructor ) return;
3169
3170 // Sync engines which are playing back
3171         if( cwindow->playback_engine->is_playing_back ) {
3172                 if( change_type == CHANGE_PARAMS ) {
3173 // TODO: block keyframes until synchronization is done
3174                         cwindow->playback_engine->sync_parameters(edl);
3175                 }
3176                 else {
3177 // Stop and restart
3178                         int command = cwindow->playback_engine->command->command;
3179 // Waiting for tracking to finish would make the restart position more
3180 // accurate but it can't lock the window to stop tracking for some reason.
3181 // Not waiting for tracking gives a faster response but restart position is
3182 // only as accurate as the last tracking update.
3183                         cwindow->playback_engine->transport_stop(0);
3184                         cwindow->playback_engine->next_command->realtime = 1;
3185                         cwindow->playback_engine->transport_command(command, change_type, edl, 0);
3186                 }
3187         }
3188         else {
3189                 cwindow->refresh_frame(change_type);
3190         }
3191 }
3192
3193 void MWindow::age_caches()
3194 {
3195 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3196 // __LINE__,
3197 // preferences->cache_size,
3198 // audio_cache->get_memory_usage(1),
3199 // video_cache->get_memory_usage(1),
3200 // frame_cache->get_memory_usage(),
3201 // wave_cache->get_memory_usage(),
3202 // memory_usage);
3203         frame_cache->age_cache(512);
3204         wave_cache->age_cache(8192);
3205
3206         int64_t memory_usage;
3207         int64_t prev_memory_usage = 0;
3208         int result = 0;
3209         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3210         while( !result && prev_memory_usage !=
3211                 (memory_usage=video_cache->get_memory_usage(1)) &&
3212                 memory_usage > video_size ) {
3213                 video_cache->delete_oldest();
3214                 prev_memory_usage = memory_usage;
3215         }
3216
3217         prev_memory_usage = 0;
3218         result = 0;
3219         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3220         while( !result && prev_memory_usage !=
3221                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3222                 memory_usage > audio_size ) {
3223                 audio_cache->delete_oldest();
3224                 prev_memory_usage = memory_usage;
3225         }
3226 }
3227
3228 void MWindow::reset_android_remote()
3229 {
3230         gui->use_android_remote(preferences->android_remote);
3231 }
3232
3233
3234 void MWindow::show_keyframe_gui(Plugin *plugin)
3235 {
3236         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3237 // Find existing thread
3238         for( int i=0; i<keyframe_threads->size(); ++i ) {
3239                 int plugin_id = keyframe_threads->get(i)->plugin_id;
3240                 if( plugin_id == plugin->orig_id ) {
3241                         keyframe_threads->get(i)->start_window(plugin, 0);
3242                         keyframe_gui_lock->unlock();
3243                         return;
3244                 }
3245         }
3246
3247 // Find unused thread
3248         for( int i=0; i<keyframe_threads->size(); ++i ) {
3249                 if( keyframe_threads->get(i)->plugin_id < 0 ) {
3250                         keyframe_threads->get(i)->start_window(plugin, 0);
3251                         keyframe_gui_lock->unlock();
3252                         return;
3253                 }
3254         }
3255
3256 // Create new thread
3257         KeyFrameThread *thread = new KeyFrameThread(this);
3258         keyframe_threads->append(thread);
3259         thread->start_window(plugin, 0);
3260         keyframe_gui_lock->unlock();
3261 }
3262
3263
3264 void MWindow::show_plugin(Plugin *plugin)
3265 {
3266         int done = 0;
3267
3268 SET_TRACE
3269 // Remove previously deleted plugin GUIs
3270         dead_plugin_lock->lock("MWindow::show_plugin");
3271         dead_plugins->remove_all_objects();
3272         dead_plugin_lock->unlock();
3273
3274 //printf("MWindow::show_plugin %d\n", __LINE__);
3275 SET_TRACE
3276
3277         plugin_gui_lock->lock("MWindow::show_plugin");
3278         for( int i=0; i<plugin_guis->total; ++i ) {
3279 // Pointer/id comparison
3280                 PluginServer *plugin_gui = plugin_guis->get(i);
3281                 if( plugin_gui->plugin_id == plugin->orig_id ) {
3282                         plugin_gui->raise_window();
3283                         done = 1;
3284                         break;
3285                 }
3286         }
3287 SET_TRACE
3288
3289 //printf("MWindow::show_plugin 1\n");
3290         if( !done && !plugin->track ) {
3291                 printf("MWindow::show_plugin track not defined.\n");
3292                 done = 1;
3293         }
3294         if( !done ) {
3295                 PluginServer *server = scan_plugindb(plugin->title,
3296                         plugin->track->data_type);
3297
3298 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3299                 if(server && server->uses_gui)
3300                 {
3301                         PluginServer *gui = new PluginServer(*server);
3302                         plugin_guis->append(gui);
3303 // Needs mwindow to do GUI
3304                         gui->set_mwindow(this);
3305                         gui->open_plugin(0, preferences, edl, plugin);
3306                         plugin->show = 1;
3307                         gui->show_gui();
3308                 }
3309         }
3310         plugin_gui_lock->unlock();
3311 // update show/gui_id
3312         sync_parameters(CHANGE_PARAMS);
3313 //printf("MWindow::show_plugin %d\n", __LINE__);
3314 SET_TRACE
3315 //sleep(1);
3316 //printf("MWindow::show_plugin 2\n");
3317 }
3318
3319 void MWindow::hide_plugin(Plugin *plugin, int lock)
3320 {
3321         plugin->show = 0;
3322         return hide_plugin(plugin->orig_id, lock);
3323 }
3324
3325 void MWindow::hide_plugin(int plugin_id, int lock)
3326 {
3327 // Update the toggle
3328         gui->lock_window("MWindow::hide_plugin");
3329         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3330         gui->unlock_window();
3331
3332         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3333         for( int i=0; i<plugin_guis->total; ++i ) {
3334                 PluginServer *plugin_gui = plugin_guis->get(i);
3335                 if( plugin_gui->plugin_id == plugin_id ) {
3336                         plugin_guis->remove(plugin_gui);
3337                         if(lock) plugin_gui_lock->unlock();
3338 // Last command executed in client side close
3339 // Schedule for deletion
3340                         plugin_gui->hide_gui();
3341                         delete_plugin(plugin_gui);
3342 //sleep(1);
3343                         return;
3344                 }
3345         }
3346         if(lock) plugin_gui_lock->unlock();
3347 // update show/gui_id
3348         sync_parameters(CHANGE_PARAMS);
3349 }
3350
3351 void MWindow::delete_plugin(PluginServer *plugin)
3352 {
3353         dead_plugin_lock->lock("MWindow::delete_plugin");
3354         dead_plugins->append(plugin);
3355         dead_plugin_lock->unlock();
3356 }
3357
3358 void MWindow::hide_plugins()
3359 {
3360         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3361         while(plugin_guis->size())
3362         {
3363                 PluginServer *ptr = plugin_guis->get(0);
3364                 plugin_guis->remove(ptr);
3365                 plugin_gui_lock->unlock();
3366 // Last command executed in client side close
3367 // Schedule for deletion
3368                 ptr->hide_gui();
3369                 delete_plugin(ptr);
3370                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3371         }
3372         plugin_gui_lock->unlock();
3373
3374         hide_keyframe_guis();
3375 }
3376
3377 void MWindow::hide_keyframe_guis()
3378 {
3379         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3380         for(int i = 0; i < keyframe_threads->size(); i++)
3381         {
3382                 keyframe_threads->get(i)->close_window();
3383         }
3384         keyframe_gui_lock->unlock();
3385 }
3386
3387 void MWindow::hide_keyframe_gui(Plugin *plugin)
3388 {
3389         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3390         for( int i = 0; i < keyframe_threads->size(); i++) {
3391                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3392                 if( keyframe_gui->plugin_id == plugin->orig_id ) {
3393                         keyframe_gui->close_window();
3394                         break;
3395                 }
3396         }
3397         keyframe_gui_lock->unlock();
3398 }
3399
3400 int MWindow::get_hash_color(Edit *edit)
3401 {
3402         Indexable *idxbl = edit->asset ?
3403                 (Indexable*)edit->asset : (Indexable*)edit->nested_edl;
3404         if( !idxbl ) return 0;
3405         char path[BCTEXTLEN];
3406         if( !edit->asset || edit->track->data_type != TRACK_VIDEO ||
3407             edl->session->proxy_scale == 1 ||
3408             ProxyRender::from_proxy_path(path, idxbl, edl->session->proxy_scale) )
3409                 strcpy(path, idxbl->path);
3410         char *cp = strrchr(path, '/');
3411         cp = !cp ? path : cp+1;
3412         uint8_t *bp = (uint8_t*)cp;
3413         int v = 0;
3414         while( *bp ) v += *bp++;
3415         return get_hash_color(v);
3416 }
3417
3418 int MWindow::get_hash_color(int v)
3419 {
3420         int hash = 0x303030;
3421         if( v & 0x01 ) hash ^= 0x000040;
3422         if( v & 0x02 ) hash ^= 0x004000;
3423         if( v & 0x04 ) hash ^= 0x400000;
3424         if( v & 0x08 ) hash ^= 0x080000;
3425         if( v & 0x10 ) hash ^= 0x000800;
3426         if( v & 0x20 ) hash ^= 0x000008;
3427         if( v & 0x40 ) hash ^= 0x404040;
3428         if( v & 0x80 ) hash ^= 0x080808;
3429         return hash;
3430 }
3431
3432 int MWindow::get_group_color(int v)
3433 {
3434         int color = 0x606060;
3435         if( v & 0x01 ) color ^= 0x000080;
3436         if( v & 0x02 ) color ^= 0x008000;
3437         if( v & 0x04 ) color ^= 0x800000;
3438         if( v & 0x08 ) color ^= 0x100000;
3439         if( v & 0x10 ) color ^= 0x001000;
3440         if( v & 0x20 ) color ^= 0x000010;
3441         if( v & 0x40 ) color ^= 0x080808;
3442         if( v & 0x80 ) color ^= 0x909090;
3443         return color;
3444 }
3445
3446 int MWindow::get_title_color(Edit *edit)
3447 {
3448         unsigned color = edit->color & 0xffffff;
3449         unsigned alpha = (~edit->color>>24) & 0xff;
3450         if( !color ) {
3451                 if( edit->group_id )
3452                         color = get_group_color(edit->group_id);
3453                 else if( preferences->autocolor_assets )
3454                         color = get_hash_color(edit);
3455                 else
3456                         return 0;
3457         }
3458         if( alpha == 0xff )
3459                 alpha = session->title_bar_alpha*255;
3460         return color | (~alpha<<24);
3461 }
3462
3463 void MWindow::update_keyframe_guis()
3464 {
3465 // Send new configuration to keyframe GUI's
3466         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3467         for( int i=0; i<keyframe_threads->size(); ++i ) {
3468                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3469                 Plugin *plugin = edl->tracks->plugin_exists(keyframe_gui->plugin_id);
3470                 if( plugin )
3471                         keyframe_gui->update_gui(1);
3472                 else
3473                         keyframe_gui->close_window();
3474         }
3475         keyframe_gui_lock->unlock();
3476 }
3477
3478 void MWindow::update_plugin_guis(int do_keyframe_guis)
3479 {
3480 // Send new configuration to plugin GUI's
3481         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3482
3483         for( int i=0; i<plugin_guis->size(); ++i ) {
3484                 PluginServer *plugin_gui = plugin_guis->get(i);
3485                 Plugin *plugin = edl->tracks->plugin_exists(plugin_gui->plugin_id);
3486                 if( plugin && plugin->show )
3487                         plugin_gui->update_gui();
3488                 else {
3489 // Schedule for deletion if no plugin or not shown
3490                         plugin_guis->remove_number(i--);
3491                         plugin_gui->hide_gui();
3492                         delete_plugin(plugin_gui);
3493                 }
3494         }
3495
3496
3497 // Change plugin variable if not visible
3498         Track *track = edl->tracks->first;
3499         for( ; track; track=track->next ) {
3500                 for( int i=0; i < track->plugin_set.size(); ++i ) {
3501                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3502                         for( ; plugin; plugin = (Plugin*)plugin->next ) {
3503                                 int got_it = 0;
3504                                 for( int i=0; i<plugin_guis->size(); ++i ) {
3505                                         PluginServer *server = plugin_guis->get(i);
3506                                         if( server->plugin_id == plugin->orig_id ) {
3507                                                 got_it = 1;
3508                                                 break;
3509                                         }
3510                                 }
3511                                 if( !got_it ) plugin->show = 0;
3512                         }
3513                 }
3514         }
3515
3516         plugin_gui_lock->unlock();
3517         if( do_keyframe_guis )
3518                 update_keyframe_guis();
3519 }
3520
3521 void MWindow::stop_plugin_guis()
3522 {
3523 // Send new configuration to plugin GUI's
3524         plugin_gui_lock->lock("MWindow::stop_plugin_guis");
3525
3526         for( int i=0; i<plugin_guis->size(); ++i ) {
3527                 PluginServer *plugin_gui = plugin_guis->get(i);
3528                 plugin_gui->render_stop();
3529         }
3530         plugin_gui_lock->unlock(); 
3531 }
3532
3533 int MWindow::plugin_gui_open(Plugin *plugin)
3534 {
3535         int gui_id = plugin->gui_id;
3536         if( gui_id < 0 ) return 0;
3537         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3538         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3539         int result = plugin_server ? 1 : 0;
3540         plugin_gui_lock->unlock();
3541         return result;
3542 }
3543
3544
3545 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3546 {
3547         int gui_id = plugin->gui_id;
3548         if( gui_id < 0 ) return;
3549         plugin_gui_lock->lock("MWindow::render_plugin_gui 0");
3550         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3551         if( plugin_server )
3552                 plugin_server->render_gui(data);
3553         plugin_gui_lock->unlock();
3554 }
3555
3556 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3557 {
3558         int gui_id = plugin->gui_id;
3559         if( gui_id < 0 ) return;
3560         plugin_gui_lock->lock("MWindow::render_plugin_gui 1");
3561         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3562         if( plugin_server )
3563                 plugin_server->render_gui(data, size);
3564         plugin_gui_lock->unlock();
3565 }
3566
3567 void MWindow::reset_plugin_gui_frames(Plugin *plugin)
3568 {
3569         int gui_id = plugin->gui_id;
3570         if( gui_id < 0 ) return;
3571         plugin_gui_lock->lock("MWindow::reset_plugin_gui_frames");
3572         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3573         if( plugin_server )
3574                 plugin_server->reset_plugin_gui_frames();
3575         plugin_gui_lock->unlock();
3576 }
3577
3578 void MWindow::render_plugin_gui_frames(PluginClientFrames *frames, Plugin *plugin)
3579 {
3580         int gui_id = plugin->gui_id;
3581         if( gui_id < 0 ) return;
3582         plugin_gui_lock->lock("MWindow::render_plugin_gui_frames");
3583         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3584         if( plugin_server )
3585                 plugin_server->render_plugin_gui_frames(frames);
3586         plugin_gui_lock->unlock();
3587 }
3588
3589 double MWindow::get_tracking_position()
3590 {
3591         return edl->local_session->get_selectionstart(1);
3592 }
3593
3594 int MWindow::get_tracking_direction()
3595 {
3596         return cwindow->playback_engine->get_direction();
3597 }
3598
3599 void MWindow::update_plugin_states()
3600 {
3601         plugin_gui_lock->lock("MWindow::update_plugin_states");
3602         for( int i=0; i<plugin_guis->total; ++i ) {
3603 // Get a plugin GUI
3604                 PluginServer *src_plugingui = plugin_guis->get(i);
3605                 int plugin_id = src_plugingui->plugin_id;
3606                 Plugin *src_plugin = edl->tracks->plugin_exists(plugin_id);
3607 // Doesn't exist anymore
3608                 if( !src_plugin ) {
3609                         hide_plugin(plugin_id, 0);
3610                         --i;
3611                 }
3612         }
3613         plugin_gui_lock->unlock();
3614 }
3615
3616
3617 void MWindow::update_plugin_titles()
3618 {
3619         for( int i=0; i<plugin_guis->total; ++i )
3620                 plugin_guis->get(i)->update_title();
3621 }
3622
3623 int MWindow::asset_to_edl(EDL *new_edl,
3624         Asset *new_asset,
3625         RecordLabels *labels)
3626 {
3627 const int debug = 0;
3628 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3629 __LINE__,
3630 new_asset->layers);
3631 // Keep frame rate, sample rate, and output size unchanged.
3632 // These parameters would revert the project if VWindow displayed an asset
3633 // of different size than the project.
3634         if(new_asset->video_data)
3635         {
3636                 new_edl->session->video_tracks = new_asset->layers;
3637         }
3638         else
3639                 new_edl->session->video_tracks = 0;
3640
3641 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3642
3643
3644
3645
3646
3647         if(new_asset->audio_data)
3648         {
3649                 new_edl->session->audio_tracks = new_asset->channels;
3650         }
3651         else
3652                 new_edl->session->audio_tracks = 0;
3653 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3654
3655 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3656         new_edl->create_default_tracks();
3657 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3658 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3659
3660
3661
3662 //printf("MWindow::asset_to_edl 3\n");
3663         new_edl->insert_asset(new_asset,
3664                 0,
3665                 0,
3666                 0,
3667                 labels);
3668 //printf("MWindow::asset_to_edl 3\n");
3669 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3670
3671 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3672         if(edl->session->cursor_on_frames)
3673         {
3674                 double length = new_edl->tracks->total_length();
3675                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3676                 new_edl->tracks->clear(length, edl_length, 1, 1);
3677         }
3678
3679
3680
3681
3682         char string[BCTEXTLEN];
3683         FileSystem fs;
3684         fs.extract_name(string, new_asset->path);
3685 //printf("MWindow::asset_to_edl 3\n");
3686
3687         strcpy(new_edl->local_session->clip_title, string);
3688 //printf("MWindow::asset_to_edl 4 %s\n", string);
3689 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3690
3691         new_edl->local_session->asset2edl = 1;
3692         return 0;
3693 }
3694
3695
3696 // Reset everything after a load.
3697 void MWindow::update_project(int load_mode)
3698 {
3699         const int debug = 0;
3700
3701         if(debug) PRINT_TRACE
3702         edl->tracks->update_y_pixels(theme);
3703         session->update_clip_number();
3704
3705         if(debug) PRINT_TRACE
3706
3707         if( load_mode == LOADMODE_REPLACE ||
3708             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3709                 delete gui->keyvalue_popup;
3710                 gui->keyvalue_popup = 0;
3711                 gui->load_panes();
3712         }
3713
3714         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 1);
3715         if(debug) PRINT_TRACE
3716         gui->unlock_window();
3717         init_brender();
3718
3719         cwindow->update(0, 0, 1, 1, 1);
3720
3721         if(debug) PRINT_TRACE
3722
3723 // Close all the vwindows
3724         if( load_mode == LOADMODE_REPLACE ||
3725             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3726                 if(debug) PRINT_TRACE
3727                 int first_vwindow = 0;
3728                 if(session->show_vwindow) first_vwindow = 1;
3729 // Change visible windows to no source
3730                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3731                         VWindow *vwindow = vwindows[i];
3732                         if( !vwindow->is_running() ) continue;
3733                         vwindow->change_source(-1);
3734                 }
3735
3736 // Close remaining windows
3737                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3738                         VWindow *vwindow = vwindows[i];
3739                         if( !vwindow->is_running() ) continue;
3740                         vwindow->close_window();
3741                 }
3742                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3743                         VWindow *vwindow = get_viewer(1, -1);
3744                         vwindow->change_source(i);
3745                 }
3746                 if(debug) PRINT_TRACE
3747                 select_zwindow(0);
3748                 close_mixers(0);
3749
3750                 for( int i=0; i<edl->mixers.size(); ++i ) {
3751                         Mixer *mixer = edl->mixers[i];
3752                         if( !mixer->show ) continue;
3753                         ZWindow *zwindow = get_mixer(mixer);
3754                         zwindow->set_title(mixer->title);
3755                         zwindow->start();
3756                 }
3757                 cwindow->gui->canvas->set_zoom(edl, 0);
3758         }
3759         update_vwindow();
3760
3761         if(debug) PRINT_TRACE
3762         cwindow->gui->lock_window("MWindow::update_project 2");
3763         cwindow->gui->timebar->update(0);
3764         Track *track = cwindow->calculate_affected_track();
3765         cwindow->mask_track_id = track ? track->get_id() : -1;
3766         cwindow->gui->tool_panel->raise_tool();
3767         cwindow->gui->update_canvas(0);
3768         cwindow->gui->unlock_window();
3769
3770         if(debug) PRINT_TRACE
3771         cwindow->refresh_frame(CHANGE_ALL);
3772
3773         awindow->gui->async_update_assets();
3774         if(debug) PRINT_TRACE
3775
3776         gui->lock_window("MWindow::update_project");
3777         gui->update_mixers(0, 0);
3778         gui->flush();
3779         if(debug) PRINT_TRACE
3780 }
3781
3782 void MWindow::stack_push(EDL *new_edl, Indexable *idxbl, Edit *edit)
3783 {
3784         int got_indexes = 0;
3785         for( int i=0; i<new_edl->nested_edls.size(); ++i ) {
3786                 EDL *nested_edl = new_edl->nested_edls[i];
3787                 mainindexes->add_indexable(nested_edl);
3788                 edl->nested_edls.update_index(nested_edl);
3789                 got_indexes = 1;
3790         }
3791         for( Asset *asset=new_edl->assets->first; asset; asset=asset->next ) {
3792                 mainindexes->add_indexable(asset);
3793                 edl->assets->update(asset);
3794                 got_indexes = 1;
3795         }
3796 // Start examining next batch of index files
3797         if( got_indexes )
3798                 mainindexes->start_build();
3799
3800 // needs gui lock
3801         gui->lock_window("MWindow::stack_push");
3802         if( stack.size() < 9 ) {
3803                 save_backup();
3804                 hide_plugins();
3805                 undo_before();
3806                 StackItem &item = stack.append();
3807                 item.edl = edl;
3808                 item.edit = edit;
3809                 item.new_edl = new_edl;
3810                 item.duration = new_edl->tracks->total_length();
3811                 item.undo = undo;
3812                 item.idxbl = idxbl;
3813                 item.mtime = 0;
3814                 if( idxbl && idxbl->is_asset ) {
3815                         struct stat st;
3816                         Asset *asset = (Asset *)idxbl;
3817                         if( asset->format == FILE_REF &&
3818                             !stat(asset->path, &st) )
3819                                 item.mtime = st.st_mtime;
3820                 }
3821                 edl = new_edl;
3822                 edl->add_user();
3823                 strcpy(session->filename, edl->path);
3824                 undo = new MainUndo(this);
3825                 gui->stack_button->update();
3826                 update_project(LOADMODE_REPLACE);
3827         }
3828         gui->unlock_window();
3829         show_plugins();
3830 }
3831
3832 void MWindow::stack_pop()
3833 {
3834         if( !stack.size() ) return;
3835 // writes on config_path/backup%d.xml
3836         save_backup();
3837         hide_plugins();
3838 // already have gui lock
3839         StackItem &item = stack.last();
3840 // session edl replaced, overwrite and save clip data
3841         if( item.new_edl != edl )
3842                 item.new_edl->overwrite_clip(edl);
3843         Edit *edit = item.edit;
3844 // resize the referring edit if the edl duration changed
3845         if( edit ) {
3846                 double duration = item.new_edl->tracks->total_length();
3847                 double dt = duration - item.duration;
3848                 if( fabs(dt) > 1e-4 ) {
3849                         int64_t du = edit->track->to_units(dt,0);
3850                         if( (edit->length+=du) < 0 )
3851                                 edit->length = 0;
3852                 }
3853         }
3854         edl->remove_user();
3855         edl = item.edl;
3856         delete undo;
3857         undo = item.undo;
3858         Indexable *idxbl = item.idxbl;
3859         int64_t mtime = item.mtime;
3860         stack.remove();
3861         if( idxbl ) {
3862                 gui->unlock_window();
3863                 gui->resource_thread->close_indexable(idxbl);
3864                 remove_from_caches(idxbl);
3865                 remove_indexfile(idxbl);
3866                 mainindexes->add_indexable(idxbl);
3867                 mainindexes->start_build();
3868                 awindow->gui->async_update_assets();
3869                 gui->lock_window("MWindow::stack_pop");
3870         }
3871         strcpy(session->filename, edl->path);
3872         update_project(LOADMODE_REPLACE);
3873         undo_after(_("open edl"), LOAD_ALL);
3874         show_plugins();
3875         gui->stack_button->update();
3876         if( mtime && idxbl && idxbl->is_asset ) {
3877                 struct stat st;
3878                 Asset *asset = (Asset *)idxbl;
3879                 if( asset->format == FILE_REF && !stat(asset->path, &st) &&
3880                     item.mtime == st.st_mtime ) {
3881                         char text[BCTEXTLEN];
3882                         snprintf(text, sizeof(text),
3883                                  _("Warning: Asset not updated: %s"), asset->path);
3884                         show_warning(&preferences->warn_stack, text);
3885                 }
3886         }
3887 }
3888
3889 int MWindow::save(EDL *edl, char *filename, int stat)
3890 {
3891         FileXML file;
3892         edl->save_xml(&file, filename);
3893         file.terminate_string();
3894         if( file.write_to_file(filename) ) {
3895                 eprintf(_("Couldn't open %s"), filename);
3896                 return 1;
3897         }
3898         if( stat ) {
3899                 char string[BCTEXTLEN];
3900                 char *filename = stack.size() ?
3901                         stack[0].edl->path : session->filename;
3902                 sprintf(string, _("\"%s\" %jdC written"),
3903                          filename, file.length());
3904                 gui->lock_window("SaveAs::run");
3905                 gui->show_message(string);
3906                 gui->unlock_window();
3907         }
3908         return 0;
3909 }
3910
3911 int MWindow::save(int save_as)
3912 {
3913         char new_path[BCTEXTLEN];  new_path[0] = 0;
3914         char *path = stack.size() ? stack[0].edl->path : session->filename;
3915         if( save_as || !path[0] ) {
3916                 if( ConfirmSave::get_save_path(this, new_path) )
3917                         return 1;
3918                 if( stack.size() ) {
3919                         strcpy(path, new_path);
3920                         set_titlebar(new_path);
3921                 }
3922                 else
3923                         set_filename(new_path);
3924                 gui->mainmenu->add_load(new_path);
3925                 path = new_path;
3926         }
3927         for( int i=stack.size(); --i>=0;  ) {
3928                 StackItem &item = stack[i];
3929                 Indexable *idxbl = item.idxbl;
3930                 if( idxbl->is_asset ) {
3931                         Asset *asset = (Asset *)idxbl;
3932                         if( asset->format == FILE_REF ) {
3933                                 if( save(item.new_edl, asset->path, 0) )
3934                                         return 1;
3935                         }
3936                 }
3937                 else if( item.new_edl != item.idxbl )
3938                         item.new_edl->overwrite_clip((EDL*)item.idxbl);
3939         }
3940         EDL *new_edl = stack.size() ? stack[0].edl : edl;
3941         save(new_edl, path, 1);
3942         return 0;
3943 }
3944
3945 void MWindow::show_plugins()
3946 {
3947         for( Track *track=edl->tracks->first; track; track=track->next ) {
3948                 for( int i=0; i<track->plugin_set.size(); ++i ) {
3949                         PluginSet *plugins = track->plugin_set[i];
3950                         Plugin *plugin = plugins->get_first_plugin();
3951                         for( ; plugin; plugin=(Plugin*)plugin->next ) {
3952                                 if( plugin->plugin_type == PLUGIN_STANDALONE &&
3953                                     plugin->show )
3954                                         show_plugin(plugin);
3955                         }
3956                 }
3957         }
3958 }
3959
3960 void MWindow::clip_to_media()
3961 {
3962         if( edl->session->proxy_scale != 1 ) {
3963                 eprintf("Nesting not allowed when proxy scale != 1");
3964                 return;
3965         }
3966         undo_before();
3967         awindow->gui->stop_vicon_drawing();
3968         int clips_total = session->drag_clips->total;
3969         for( int i=0; i<clips_total; ++i ) {
3970                 EDL *clip = session->drag_clips->values[i];
3971                 time_t dt;      time(&dt);
3972                 struct tm dtm;  localtime_r(&dt, &dtm);
3973                 char path[BCTEXTLEN], *cp = path, *ep = cp+sizeof(path)-1;
3974 // path_basename = "Nested_<date>-<time>_<basename>"
3975                 cp += snprintf(cp, ep-cp, _("Nested_%02d%02d%02d-%02d%02d%02d_"),
3976                         dtm.tm_year+1900, dtm.tm_mon+1, dtm.tm_mday,
3977                         dtm.tm_hour, dtm.tm_min, dtm.tm_sec);
3978                 char *bp = strrchr(clip->local_session->clip_title, '/');
3979                 bp = bp ? bp+1 : clip->local_session->clip_title;
3980                 cp += snprintf(cp, ep-cp, "%s", bp);
3981                 EDL *nested = edl->new_nested_edl(clip, path);
3982                 edl->clips.remove(clip);
3983                 clip->remove_user();
3984                 mainindexes->add_indexable(nested);
3985         }
3986         undo_after(_("clip2media"), LOAD_ALL);
3987         mainindexes->start_build();
3988         awindow->gui->async_update_assets();
3989 }
3990
3991 void MWindow::media_to_clip()
3992 {
3993         undo_before();
3994         int assets_total = session->drag_assets->total;
3995         for( int i=0; i<assets_total; ++i ) {
3996                 Indexable *idxbl = session->drag_assets->values[i];
3997                 if( idxbl->is_asset ) {
3998                         eprintf(_("media is not EDL:\n%s"), idxbl->path);
3999                         continue;
4000                 }
4001                 char clip_title[BCSTRLEN];
4002                 int name_ok = 0;
4003                 while( !name_ok ) {
4004                         name_ok = 1;
4005                         sprintf(clip_title, _("Clip %d"), session->clip_number++);
4006                         for( int i=0; name_ok && i<edl->clips.size(); ++i ) {
4007                                 char *title = edl->clips[i]->local_session->clip_title;
4008                                 if( !strcasecmp(clip_title, title) ) name_ok = 0;
4009                         }
4010                 }
4011                 EDL *nested = (EDL *)idxbl;
4012                 EDL *clip = edl->add_clip(nested);
4013                 strcpy(clip->local_session->clip_title, clip_title);
4014                 snprintf(clip->local_session->clip_notes,
4015                         sizeof(clip->local_session->clip_notes),
4016                         _("From: %s"), nested->path);
4017         }
4018         undo_after(_("media2clip"), LOAD_ALL);
4019         awindow->gui->async_update_assets();
4020 }
4021
4022 int MWindow::create_ref(Asset *asset, EDL *ref)
4023 {
4024         asset->format = FILE_REF;
4025         double secs = ref->tracks->total_length();
4026         int audio_channels = ref->session->audio_channels;
4027         asset->audio_data = audio_channels > 0 ? 1 : 0;
4028         asset->channels = audio_channels;
4029         asset->sample_rate = ref->session->sample_rate;
4030         asset->audio_length = audio_channels > 0 && secs > 0 ?
4031                  secs * asset->sample_rate : 0;
4032         strcpy(asset->acodec, _("reference"));
4033
4034         int video_layers = ref->session->video_channels;
4035         asset->video_data = video_layers > 0 ? 1 : 0;
4036         asset->layers = video_layers > 0 ? 1 : 0;
4037         asset->actual_width = ref->session->output_w;
4038         asset->actual_height = ref->session->output_h;
4039         asset->width = asset->actual_width;
4040         asset->height = asset->actual_height;
4041         asset->frame_rate = ref->session->frame_rate;
4042         asset->video_length = video_layers > 0 && secs > 0 ?
4043                 secs * asset->frame_rate : 0;
4044         strcpy(asset->vcodec, _("reference"));
4045         return 0;
4046 }
4047
4048 void MWindow::update_preferences(Preferences *prefs)
4049 {
4050         if( prefs != preferences )
4051                 preferences->copy_from(prefs);
4052         if( cwindow->playback_engine )
4053                 cwindow->playback_engine->preferences->copy_from(prefs);
4054         for(int i = 0; i < vwindows.size(); i++) {
4055                 VWindow *vwindow = vwindows[i];
4056                 if( !vwindow->is_running() ) continue;
4057                 if( vwindow->playback_engine )
4058                         vwindow->playback_engine->preferences->copy_from(prefs);
4059         }
4060         for(int i = 0; i < zwindows.size(); i++) {
4061                 ZWindow *zwindow = zwindows[i];
4062                 if( !zwindow->is_running() ) continue;
4063                 if( zwindow->zgui->playback_engine )
4064                         zwindow->zgui->playback_engine->preferences->copy_from(prefs);
4065         }
4066 }
4067
4068 void MWindow::update_vwindow()
4069 {
4070         for( int i=0; i<vwindows.size(); ++i ) {
4071                 VWindow *vwindow = vwindows[i];
4072                 if( vwindow->is_running() ) {
4073                         vwindow->gui->lock_window("MWindow::update_vwindow");
4074                         vwindow->update(1);
4075                         vwindow->gui->unlock_window();
4076                 }
4077         }
4078 }
4079
4080 void MWindow::remove_indexfile(Indexable *indexable)
4081 {
4082         if( !indexable->is_asset ) return;
4083         Asset *asset = (Asset *)indexable;
4084 // Erase file
4085         IndexFile::delete_index(preferences, asset, ".toc");
4086         IndexFile::delete_index(preferences, asset, ".idx");
4087         IndexFile::delete_index(preferences, asset, ".mkr");
4088 }
4089
4090 void MWindow::rebuild_indices()
4091 {
4092         for(int i = 0; i < session->drag_assets->total; i++)
4093         {
4094                 Indexable *indexable = session->drag_assets->get(i);
4095 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4096                 remove_indexfile(indexable);
4097 // Schedule index build
4098                 indexable->index_state->remove_user();
4099                 indexable->index_state = new IndexState;
4100                 IndexFile::delete_index_files(preferences, indexable);
4101                 if( indexable->is_asset ) {
4102                         Asset *asset = (Asset *)indexable;
4103                         if( asset->format != FILE_PCM ) {
4104                                 asset->format = FILE_UNKNOWN;
4105                                 asset->reset_audio();
4106                         }
4107                         asset->reset_video();
4108                         remove_from_caches(asset);
4109 //                      File file; // re-probe the asset
4110 //                      file.open_file(preferences, asset, 1, 0);
4111                 }
4112                 mainindexes->add_indexable(indexable);
4113         }
4114 // still in render engine
4115         sync_parameters(CHANGE_ALL);
4116         awindow->gui->async_update_assets();
4117         mainindexes->start_build();
4118 }
4119
4120
4121 void MWindow::get_backup_path(char *path, int len)
4122 {
4123         char *cp = path, *ep = cp + len-1;
4124         cp += snprintf(cp, ep-cp, "%s/", File::get_config_path());
4125         int idx = stack.size();
4126         cp += snprintf(cp, ep-cp, idx ? BACKUPn_FILE : BACKUP_FILE, idx);
4127 }
4128
4129 void MWindow::save_backup()
4130 {
4131         FileXML file;
4132         edl->optimize();
4133         edl->set_path(session->filename);
4134
4135         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
4136         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
4137                 File::get_config_path(), BACKUP_FILE1);
4138         get_backup_path(backup_path, sizeof(backup_path));
4139         rename(backup_path, backup_path1);
4140         edl->save_xml(&file, backup_path);
4141         file.terminate_string();
4142         FileSystem fs;
4143         fs.complete_path(backup_path);
4144
4145         if(file.write_to_file(backup_path)) {
4146                 char string2[256];
4147                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
4148                 gui->show_message(string2);
4149         }
4150         save_undo_data();
4151 }
4152
4153 void MWindow::load_backup()
4154 {
4155         ArrayList<char*> path_list;
4156         path_list.set_array_delete();
4157         char *out_path;
4158         char backup_path[BCTEXTLEN];
4159         get_backup_path(backup_path, sizeof(backup_path));
4160         FileSystem fs;
4161         fs.complete_path(backup_path);
4162
4163         path_list.append(out_path = new char[strlen(backup_path) + 1]);
4164         strcpy(out_path, backup_path);
4165
4166         load_filenames(&path_list, LOADMODE_REPLACE, LOADMODE_EDL_CLIP, 0);
4167         edl->local_session->clip_title[0] = 0;
4168 // This is unique to backups since the path of the backup is different than the
4169 // path of the project.
4170         set_filename(edl->path);
4171         path_list.remove_all_objects();
4172         save_backup();
4173 }
4174
4175
4176 void MWindow::save_undo_data()
4177 {
4178         if( stack.size() > 0 ) return;
4179         if( !preferences->perpetual_session ) return;
4180         char perpetual_path[BCTEXTLEN];
4181         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4182                 File::get_config_path(), PERPETUAL_FILE);
4183         FILE *fp = fopen(perpetual_path,"w");
4184         if( !fp ) return;
4185         undo->save(fp);
4186         fclose(fp);
4187 }
4188
4189 void MWindow::load_undo_data()
4190 {
4191         if( stack.size() > 0 ) return;
4192         if( !preferences->perpetual_session ) return;
4193         char perpetual_path[BCTEXTLEN];
4194         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4195                 File::get_config_path(), PERPETUAL_FILE);
4196         FILE *fp = fopen(perpetual_path,"r");
4197         if( !fp ) return;
4198         undo->load(fp);
4199         undo_before();
4200         undo_after(_("perpetual load"), LOAD_ALL);
4201         fclose(fp);
4202 }
4203
4204 void MWindow::remove_undo_data()
4205 {
4206         if( stack.size() > 0 ) return;
4207         char perpetual_path[BCTEXTLEN];
4208         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4209                 File::get_config_path(), PERPETUAL_FILE);
4210         ::remove(perpetual_path);
4211 }
4212
4213 int MWindow::copy_target(const char *path, const char *target)
4214 {
4215         int ifd = ::open(path, O_RDONLY);
4216         if( ifd < 0 ) {
4217                 eprintf("Cannot open asset: %s", path);
4218                 return 1;
4219         }
4220         int ret = 0;
4221         int ofd = ::open(target, O_CREAT+O_TRUNC+O_WRONLY, 0777);
4222         if( ofd >= 0 ) {
4223                 struct stat st;
4224                 int64_t total_bytes = !fstat(ifd, &st) ? st.st_size : 0;
4225                 char progress_title[BCTEXTLEN];
4226                 sprintf(progress_title, _("Copying: %s\n"), target);
4227                 BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
4228
4229                 int64_t count = 0, len = -1;
4230                 int bfrsz = 0x100000;
4231                 uint8_t *bfr = new uint8_t[bfrsz];
4232                 while( (len=::read(ifd, bfr, bfrsz)) > 0 ) {
4233                         if( len != ::write(ofd, bfr, len) ) {
4234                                 eprintf("Error writing: %s", target);
4235                                 break;
4236                         }
4237                         if( progress.is_cancelled() ) {
4238                                 ret = 1;
4239                                 break;
4240                         }
4241                         progress.update(count += len, 1);
4242                 }
4243                 delete [] bfr;
4244                 ::close(ofd);
4245
4246                 progress.stop_progress();
4247                 if( len < 0 ) {
4248                         eprintf("Error reading: %s", path);
4249                         ret = 1;
4250                 }
4251         }
4252         else
4253                 eprintf("Cannot create asset target: %s", target);
4254         ::close(ifd);
4255         return ret;
4256 }
4257
4258 int MWindow::link_target(const char *real_path, const char *link_path, int relative)
4259 {
4260         char target[BCTEXTLEN];
4261         if( relative ) {
4262                 const char *bp = real_path, *cp = bp;
4263                 const char *lp = link_path, *np = lp;
4264                 char *tp = target, *ep = tp+sizeof(target)-1, lch;
4265                 while( *lp && *bp && (lch=*lp++) == *bp++ ) {
4266                         if( lch == '/' ) { np = lp;  cp = bp; }
4267                 }
4268                 while( tp<ep && *np ) {
4269                         if( *np++ != '/' ) continue;
4270                         *tp++ = '.';  *tp++ = '.';  *tp++ = '/';
4271                 }
4272                 while( tp<ep && *cp ) *tp++ = *cp++;
4273                 *tp = 0;
4274         }
4275         else
4276                 strcpy(target, real_path);
4277         if( symlink(target, link_path) ) {
4278                 eprintf("Cannot create symlink: %s", link_path);
4279                 return 1;
4280         }
4281         return 0;
4282 }
4283
4284 void MWindow::save_project(const char *dir, int save_mode, int overwrite, int reload)
4285 {
4286         char dir_path[BCTEXTLEN];
4287         strcpy(dir_path, dir);
4288         FileSystem fs;
4289         fs.complete_path(dir_path);
4290
4291         struct stat st;
4292         if( !stat(dir_path, &st) ) {
4293                 if( !S_ISDIR(st.st_mode) ) {
4294                         eprintf("Path exists and is not a directory\n%s", dir_path);
4295                         return;
4296                 }
4297         }
4298         else {
4299                 if( mkdir(dir_path, S_IRWXU | S_IRWXG | S_IRWXO) ) {
4300                         eprintf("Cannot create directory\n%s", dir_path);
4301                         return;
4302                 }
4303         }
4304         char *real_dir = realpath(dir_path, 0);
4305         strcpy(dir_path, real_dir);
4306         free(real_dir);
4307
4308         EDL *save_edl = new EDL;
4309         save_edl->create_objects();
4310         save_edl->copy_all(edl);
4311
4312         char progress_title[BCTEXTLEN];
4313         sprintf(progress_title, _("Saving to %s:\n"), dir);
4314         int total_assets = save_edl->assets->total();
4315         gui->lock_window("MWindow::save_project");
4316         MainProgressBar *progress = mainprogress->start_progress(progress_title, total_assets);
4317         gui->unlock_window();
4318
4319         int ret = 0;
4320         Asset *current = save_edl->assets->first;
4321         for( int i=0; !ret && current; ++i, current=NEXT ) {
4322                 char *path = current->path;
4323                 if( ::stat(path, &st) ) {
4324                         eprintf("Asset not found: %s", path);
4325                         continue;
4326                 }
4327                 char *real_path = realpath(path, 0);
4328                 const char *cp = strrchr(path, '/'), *bp = !cp ? path : cp+1;
4329                 char link_path[BCTEXTLEN];
4330                 snprintf(link_path, sizeof(link_path), "%s/%s", dir_path, bp);
4331                 int skip = 0;
4332                 if( strcmp(real_path, link_path) ) {
4333                         if( !::lstat(link_path, &st) ) {
4334                                 if( overwrite )
4335                                         ::remove(link_path);
4336                                 else
4337                                         skip = 1;
4338                         }
4339                 }
4340                 else {
4341                         eprintf("copy/link to self, skippped: %s", path);
4342                         skip = 1;
4343                 }
4344                 if( !skip ) {
4345                         if( save_mode == SAVE_PROJECT_COPY ) {
4346                                 if( copy_target(real_path, link_path) )
4347                                         ret = 1;
4348                         }
4349                         else {
4350                                 link_target(real_path, link_path,
4351                                         save_mode == SAVE_PROJECT_RELLINK ? 1 : 0);
4352                         }
4353                 }
4354                 free(real_path);
4355                 strcpy(path, link_path);
4356
4357                 if( progress->is_cancelled() ) break;
4358                 progress->update(i);
4359         }
4360
4361         progress->stop_progress();
4362         delete progress;
4363
4364         char *cp = strrchr(dir_path,'/');
4365         char *bp = cp ? cp+1 : dir_path;
4366         char filename[BCTEXTLEN];
4367         snprintf(filename, sizeof(filename), "%s/%s.xml", dir_path, bp);
4368         save_edl->set_path(filename);
4369         FileXML file;
4370         save_edl->save_xml(&file, filename);
4371         file.terminate_string();
4372
4373         if( !file.write_to_file(filename) ) {
4374                 char string[BCTEXTLEN];
4375                 sprintf(string, _("\"%s\" %dC written"), filename, (int)strlen(file.string()));
4376                 gui->lock_window("SaveProject::run 2");
4377                 gui->show_message(string);
4378                 gui->unlock_window();
4379                 gui->mainmenu->add_load(filename);
4380         }
4381         else
4382                 eprintf(_("Couldn't open %s."), filename);
4383
4384         save_edl->remove_user();
4385
4386         if( reload ) {
4387                 gui->lock_window("MWindow::save_project");
4388                 ArrayList<char*> filenames;
4389                 filenames.append(filename);
4390                 load_filenames(&filenames);
4391                 gui->unlock_window();
4392         }
4393 }
4394
4395
4396 static inline int gcd(int m, int n)
4397 {
4398         int r;
4399         if( m < n ) { r = m;  m = n;  n = r; }
4400         while( (r = m % n) != 0 ) { m = n;  n = r; }
4401         return n;
4402 }
4403
4404 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
4405 {
4406         w = 1;  h = 1;
4407         if(!width || !height) return 1;
4408         if( width == 720 && (height == 480 || height == 576) ) {
4409                 w = 4;  h = 3;  return 0; // for NTSC and PAL
4410         }
4411         double ar = (double)width / height;
4412 // square-ish pixels
4413         if( EQUIV(ar, 1.0000) ) return 0;
4414         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
4415         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
4416         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
4417         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
4418         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
4419         int ww = width, hh = height;
4420         // numerator, denominator must be under mx
4421         int mx = 255, n = gcd(ww, hh);
4422         if( n > 1 ) { ww /= n; hh /= n; }
4423         // search near height in case extra/missing lines
4424         if( ww >= mx || hh >= mx ) {
4425                 double err = height;  // +/- 2 percent height
4426                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
4427                         int iw = width, ih = height+i;
4428                         if( (n=gcd(iw, ih)) > 1 ) {
4429                                 int u = iw/n;  if( u >= mx ) continue;
4430                                 int v = ih/n;  if( v >= mx ) continue;
4431                                 double r = (double) u/v, er = fabs(ar-r);
4432                                 if( er >= err ) continue;
4433                                 err = er;  ww = u;  hh = v;
4434                         }
4435                 }
4436         }
4437
4438         w = ww;  h = hh;
4439         return 0;
4440 }
4441
4442 void MWindow::reset_caches()
4443 {
4444         awindow->gui->stop_vicon_drawing();
4445         frame_cache->remove_all();
4446         wave_cache->remove_all();
4447         audio_cache->remove_all();
4448         video_cache->remove_all();
4449         if( cwindow->playback_engine ) {
4450                 if( cwindow->playback_engine->audio_cache )
4451                         cwindow->playback_engine->audio_cache->remove_all();
4452                 if( cwindow->playback_engine->video_cache )
4453                         cwindow->playback_engine->video_cache->remove_all();
4454         }
4455         for(int i = 0; i < vwindows.size(); i++) {
4456                 VWindow *vwindow = vwindows[i];
4457                 if( !vwindow->is_running() ) continue;
4458                 if( !vwindow->playback_engine ) continue;
4459                 if( vwindow->playback_engine->audio_cache )
4460                         vwindow->playback_engine->audio_cache->remove_all();
4461                 if( vwindow->playback_engine->video_cache )
4462                         vwindow->playback_engine->video_cache->remove_all();
4463         }
4464 }
4465
4466 void MWindow::remove_from_caches(Indexable *idxbl)
4467 {
4468         awindow->gui->stop_vicon_drawing();
4469         frame_cache->remove_item(idxbl);
4470         wave_cache->remove_item(idxbl);
4471         if( gui->render_engine &&
4472             gui->render_engine_id == idxbl->id ) {
4473                 delete gui->render_engine;
4474                 gui->render_engine = 0;
4475         }
4476         gui->resource_thread->close_indexable(idxbl);
4477         if( !idxbl->is_asset ) return;
4478         Asset *asset = (Asset *)idxbl;
4479         audio_cache->delete_entry(asset);
4480         video_cache->delete_entry(asset);
4481         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
4482                 cwindow->playback_engine->audio_cache->delete_entry(asset);
4483         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
4484                 cwindow->playback_engine->video_cache->delete_entry(asset);
4485         for(int i = 0; i < vwindows.size(); i++) {
4486                 VWindow *vwindow = vwindows[i];
4487                 if( !vwindow->is_running() ) continue;
4488                 if( !vwindow->playback_engine ) continue;
4489                 if( vwindow->playback_engine->audio_cache )
4490                         vwindow->playback_engine->audio_cache->delete_entry(asset);
4491                 if( vwindow->playback_engine->video_cache )
4492                         vwindow->playback_engine->video_cache->delete_entry(asset);
4493         }
4494         for(int i = 0; i < zwindows.size(); i++) {
4495                 ZWindow *zwindow = zwindows[i];
4496                 if( !zwindow->is_running() ) continue;
4497                 if( zwindow->zgui->playback_engine->audio_cache )
4498                         zwindow->zgui->playback_engine->audio_cache->delete_entry(asset);
4499                 if( zwindow->zgui->playback_engine->video_cache )
4500                         zwindow->zgui->playback_engine->video_cache->delete_entry(asset);
4501         }
4502         awindow->gui->start_vicon_drawing();
4503 }
4504
4505 void MWindow::remove_assets_from_project(int push_undo, int redraw, int delete_indexes,
4506                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
4507 {
4508         awindow->gui->stop_vicon_drawing();
4509
4510 // Remove from VWindow.
4511         if( drag_clips ) {
4512                 for(int i = 0; i < drag_clips->total; i++) {
4513                         for(int j = 0; j < vwindows.size(); j++) {
4514                                 VWindow *vwindow = vwindows[j];
4515                                 if( !vwindow->is_running() ) continue;
4516                                 if(drag_clips->get(i) == vwindow->get_edl()) {
4517                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
4518                                         vwindow->delete_source(1, 1);
4519                                         vwindow->gui->unlock_window();
4520                                 }
4521                         }
4522                 }
4523         }
4524
4525         if( drag_assets ) {
4526                 for(int i = 0; i < drag_assets->size(); i++) {
4527                         for(int j = 0; j < vwindows.size(); j++) {
4528                                 VWindow *vwindow = vwindows[j];
4529                                 if( !vwindow->is_running() ) continue;
4530                                 if(drag_assets->get(i) == vwindow->get_source()) {
4531                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
4532                                         vwindow->delete_source(1, 1);
4533                                         vwindow->gui->unlock_window();
4534                                 }
4535                         }
4536                 }
4537
4538                 for(int i = 0; i < drag_assets->total; i++) {
4539                         Indexable *indexable = drag_assets->get(i);
4540                         if(indexable->is_asset) remove_from_caches(indexable);
4541                 }
4542
4543                 if( delete_indexes ) {
4544                         for(int i = 0; i < drag_assets->size(); i++) {
4545                                 Indexable *indexable = drag_assets->get(i);
4546                                 remove_indexfile(indexable);
4547                         }
4548                 }
4549         }
4550
4551 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4552         if(push_undo) undo_before();
4553         if(drag_assets) edl->remove_from_project(drag_assets);
4554         if(drag_clips) edl->remove_from_project(drag_clips);
4555         if(redraw) save_backup();
4556         if(push_undo) undo_after(_("remove assets"), LOAD_ALL);
4557         if(redraw) {
4558                 restart_brender();
4559
4560                 gui->lock_window("MWindow::remove_assets_from_project 3");
4561                 gui->update(1, NORMAL_DRAW, 1, 1, 0, 1, 0);
4562                 gui->unlock_window();
4563
4564         // Removes from playback here
4565                 sync_parameters(CHANGE_ALL);
4566         }
4567
4568         awindow->gui->async_update_assets();
4569 }
4570
4571 void MWindow::remove_assets_from_disk()
4572 {
4573         remove_assets_from_project(1, 1, 1,
4574                 session->drag_assets, session->drag_clips);
4575
4576 // Remove from disk
4577         for(int i = 0; i < session->drag_assets->total; i++)
4578         {
4579                 remove(session->drag_assets->get(i)->path);
4580         }
4581 }
4582
4583 void MWindow::dump_plugins(FILE *fp)
4584 {
4585         if( !plugindb ) return;
4586         for(int i = 0; i < plugindb->total; i++)
4587         {
4588                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
4589                         " synth=%d transition=%d theme=%d %s\n",
4590                         plugindb->get(i)->plugin_type,
4591                         plugindb->get(i)->audio,
4592                         plugindb->get(i)->video,
4593                         plugindb->get(i)->realtime,
4594                         plugindb->get(i)->multichannel,
4595                         plugindb->get(i)->get_synthesis(),
4596                         plugindb->get(i)->transition,
4597                         plugindb->get(i)->theme,
4598                         plugindb->get(i)->title);
4599         }
4600 }
4601
4602 void MWindow::dump_edl(FILE *fp)
4603 {
4604         if( !edl ) return;
4605         edl->dump(fp);
4606 }
4607
4608 void MWindow::dump_undo(FILE *fp)
4609 {
4610         if( !undo ) return;
4611         undo->dump(fp);
4612 }
4613
4614 void MWindow::dump_exe(FILE *fp)
4615 {
4616         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
4617         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
4618
4619         int ret = -1, n = 100;
4620         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
4621                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
4622                 ret = 0;
4623         }
4624         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
4625
4626         struct stat st;
4627         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
4628         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
4629         struct tm *tm = localtime(&st.st_mtime);
4630         char mtime[256];
4631         strftime(mtime, sizeof(mtime), "%F %T", tm);
4632         fprintf(fp,"mtime: %s\n", mtime);
4633 #if 0
4634 // people hit ctl-c waiting for this
4635         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
4636         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
4637         uint8_t *bfr = 0;
4638         int64_t bfrsz = 0;
4639         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
4640         int64_t maxsz = 1024*pagsz;
4641         int64_t size = st.st_size, pos = 0;
4642         SHA1 sha1;
4643         while( (bfrsz = size-pos) > 0 ) {
4644                 if( bfrsz > maxsz ) bfrsz = maxsz;
4645                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
4646                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
4647                 if( bfr == MAP_FAILED ) break;
4648                 sha1.addBytes(bfr, bfrsz);
4649                 munmap(bfr, bfrsz);
4650                 pos += bfrsz;
4651         }
4652         close(fd);
4653         ret = pos < size ? EIO : 0;
4654         fprintf(fp, "SHA1: ");
4655         uint8_t digest[20];  sha1.computeHash(digest);
4656         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
4657         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
4658         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
4659 #endif
4660         fprintf(fp, "\n");
4661 }
4662
4663 void MWindow::dump_caches(FILE *fp)
4664 {
4665         fprintf(fp, "audio cache: ");
4666         audio_cache->dump(fp);
4667         fprintf(fp, "video cache: ");
4668         video_cache->dump(fp);
4669 }
4670
4671 void MWindow::trap_hook(FILE *fp, void *vp)
4672 {
4673         MWindow *mwindow = (MWindow *)vp;
4674 //      fprintf(fp, "\nPLUGINS:\n");
4675 //      mwindow->dump_plugins(fp);
4676         fprintf(fp, "\nEDL:\n");
4677         mwindow->dump_edl(fp);
4678         fprintf(fp, "\nUNDO:\n");
4679         mwindow->dump_undo(fp);
4680         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
4681         mwindow->dump_exe(fp);
4682         fprintf(fp, "\nCACHES:\n");
4683         mwindow->dump_caches(fp);
4684 }
4685
4686
4687
4688
4689
4690
4691 int MWindow::save_defaults()
4692 {
4693         gui->save_defaults(defaults);
4694         edl->save_defaults(defaults);
4695         session->save_defaults(defaults);
4696         preferences->save_defaults(defaults);
4697
4698         for(int i = 0; i < plugin_guis->total; i++)
4699         {
4700 // Pointer comparison
4701                 plugin_guis->get(i)->save_defaults();
4702         }
4703         awindow->save_defaults(defaults);
4704
4705         defaults->save();
4706         return 0;
4707 }
4708
4709 int MWindow::run_script(FileXML *script)
4710 {
4711         int result = 0, result2 = 0;
4712         while(!result && !result2)
4713         {
4714                 result = script->read_tag();
4715                 if(!result)
4716                 {
4717                         if(script->tag.title_is("new_project"))
4718                         {
4719 // Run new in immediate mode.
4720 //                              gui->mainmenu->new_project->run_script(script);
4721                         }
4722                         else
4723                         if(script->tag.title_is("record"))
4724                         {
4725 // Run record as a thread.  It is a terminal command.
4726                                 ;
4727 // Will read the complete scipt file without letting record read it if not
4728 // terminated.
4729                                 result2 = 1;
4730                         }
4731                         else
4732                         {
4733                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
4734                         }
4735                 }
4736         }
4737         return result2;
4738 }
4739
4740 // ================================= synchronization
4741
4742
4743 int MWindow::interrupt_indexes()
4744 {
4745         mainprogress->cancelled = 1;
4746         mainindexes->interrupt_build();
4747         return 0;
4748 }
4749
4750
4751
4752 void MWindow::next_time_format()
4753 {
4754         switch(edl->session->time_format)
4755         {
4756                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
4757                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
4758                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
4759                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
4760                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
4761                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
4762                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
4763         }
4764
4765         time_format_common();
4766 }
4767
4768 void MWindow::prev_time_format()
4769 {
4770         switch(edl->session->time_format)
4771         {
4772                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
4773                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
4774                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
4775                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
4776                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
4777                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
4778                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
4779         }
4780
4781         time_format_common();
4782 }
4783
4784 void MWindow::time_format_common()
4785 {
4786         gui->lock_window("MWindow::next_time_format");
4787         gui->redraw_time_dependancies();
4788
4789
4790         char string[BCTEXTLEN], string2[BCTEXTLEN];
4791         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
4792         gui->show_message(string);
4793         gui->flush();
4794         gui->unlock_window();
4795 }
4796
4797
4798 int MWindow::set_filename(const char *filename)
4799 {
4800         if( filename != session->filename )
4801                 strcpy(session->filename, filename);
4802         if( filename != edl->path )
4803                 strcpy(edl->path, filename);
4804         return set_titlebar(filename);
4805 }
4806
4807 int MWindow::set_titlebar(const char *filename)
4808 {
4809         if( !gui ) return 0;
4810         if( filename[0] ) {
4811                 FileSystem dir;
4812                 char string[BCTEXTLEN], string2[BCTEXTLEN];
4813                 dir.extract_name(string, filename);
4814                 sprintf(string2, PROGRAM_NAME ": %s", string);
4815                 gui->set_title(string2);
4816         }
4817         else
4818                 gui->set_title(PROGRAM_NAME);
4819         return 0;
4820 }
4821
4822
4823 int MWindow::set_loop_boundaries()
4824 {
4825         double start = edl->local_session->get_selectionstart();
4826         double end = edl->local_session->get_selectionend();
4827
4828         if(start !=
4829                 end)
4830         {
4831                 ;
4832         }
4833         else
4834         if(edl->tracks->total_length())
4835         {
4836                 start = 0;
4837                 end = edl->tracks->total_length();
4838         }
4839         else
4840         {
4841                 start = end = 0;
4842         }
4843
4844         if(edl->local_session->loop_playback && start != end)
4845         {
4846                 edl->local_session->loop_start = start;
4847                 edl->local_session->loop_end = end;
4848         }
4849         return 0;
4850 }
4851
4852
4853
4854
4855
4856
4857
4858 int MWindow::reset_meters()
4859 {
4860         cwindow->gui->lock_window("MWindow::reset_meters 1");
4861         cwindow->gui->meters->reset_meters();
4862         cwindow->gui->unlock_window();
4863
4864         for(int j = 0; j < vwindows.size(); j++) {
4865                 VWindow *vwindow = vwindows[j];
4866                 if( !vwindow->is_running() ) continue;
4867                 vwindow->gui->lock_window("MWindow::reset_meters 2");
4868                 vwindow->gui->meters->reset_meters();
4869                 vwindow->gui->unlock_window();
4870         }
4871
4872         lwindow->gui->lock_window("MWindow::reset_meters 3");
4873         lwindow->gui->panel->reset_meters();
4874         lwindow->gui->unlock_window();
4875
4876         gui->lock_window("MWindow::reset_meters 4");
4877         gui->reset_meters();
4878         gui->unlock_window();
4879         return 0;
4880 }
4881
4882
4883 void MWindow::resync_guis()
4884 {
4885 // Update GUIs
4886         restart_brender();
4887         gui->lock_window("MWindow::resync_guis");
4888         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 0);
4889         gui->unlock_window();
4890
4891         cwindow->gui->lock_window("MWindow::resync_guis");
4892         cwindow->gui->resize_event(cwindow->gui->get_w(),
4893                 cwindow->gui->get_h());
4894         int channels = edl->session->audio_channels;
4895         cwindow->gui->meters->set_meters(channels, 1);
4896         cwindow->gui->flush();
4897         cwindow->gui->unlock_window();
4898
4899         for(int i = 0; i < vwindows.size(); i++) {
4900                 VWindow *vwindow = vwindows[i];
4901                 if( !vwindow->is_running() ) continue;
4902                 vwindow->gui->lock_window("MWindow::resync_guis");
4903                 vwindow->gui->resize_event(vwindow->gui->get_w(),
4904                         vwindow->gui->get_h());
4905                 vwindow->gui->meters->set_meters(channels, 1);
4906                 vwindow->gui->flush();
4907                 vwindow->gui->unlock_window();
4908         }
4909
4910         lwindow->gui->lock_window("MWindow::resync_guis");
4911         lwindow->gui->panel->set_meters(channels, 1);
4912         lwindow->gui->flush();
4913         lwindow->gui->unlock_window();
4914 #ifdef GLx4
4915 // Warn user
4916         if(((edl->session->output_w % 4) ||
4917                 (edl->session->output_h % 4)) &&
4918                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
4919         {
4920                 MainError::show_error(
4921                         _("This project's dimensions are not multiples of 4 so\n"
4922                         "it can't be rendered by OpenGL."));
4923         }
4924 #endif
4925
4926 // Flash frame
4927         sync_parameters(CHANGE_ALL);
4928 }
4929
4930 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
4931 {
4932         File *file = new File;
4933         EDLSession *session = edl->session;
4934         double old_framerate = session->frame_rate;
4935         double old_samplerate = session->sample_rate;
4936         int old_auto_keyframes = session->auto_keyframes;
4937         session->auto_keyframes = 0;
4938         int result = file->open_file(preferences, asset, 1, 0);
4939         if( !result && delete_tracks > 0 )
4940                 undo_before();
4941         int video_layers = asset->get_video_layers();
4942         if( !result && asset->video_data && vstream < video_layers ) {
4943                 // try to get asset up to date, may fail
4944                 file->select_video_stream(asset, vstream);
4945                 // either way use what was/is there.
4946                 double framerate = asset->get_frame_rate();
4947                 int width = asset->get_w();
4948                 int height = asset->get_h();
4949 #ifdef GLx4
4950                 // must be multiple of 4 for opengl
4951                 width = (width+3) & ~3;  height = (height+3) & ~3;
4952 #endif
4953                 int driver = session->playback_config->vconfig->driver;
4954                 int color_model = file->get_best_colormodel(asset, driver);
4955 //              color_model = BC_CModels::is_yuv(color_model) ?
4956 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
4957 //                      BC_CModels::is_float(color_model) ?
4958 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
4959 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
4960 // have alpha for now
4961                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
4962                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
4963                 session->color_model = color_model;
4964                 session->output_w = width;
4965                 session->output_h = height;
4966                 session->frame_rate = framerate;
4967                 // not, asset->actual_width/actual_height
4968                 asset->width = session->output_w;
4969                 asset->height = session->output_h;
4970                 asset->frame_rate = session->frame_rate;
4971                 create_aspect_ratio(session->aspect_w, session->aspect_h,
4972                         session->output_w, session->output_h);
4973                 Track *track = edl->tracks->first;
4974                 for( Track *next_track=0; track; track=next_track ) {
4975                         next_track = track->next;
4976                         if( track->data_type != TRACK_VIDEO ) continue;
4977                         if( delete_tracks ) {
4978                                 Edit *edit = track->edits->first;
4979                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
4980                                         next_edit = edit->next;
4981                                         if( edit->channel != vstream ||
4982                                             !edit->asset || !edit->asset->is_asset ||
4983                                             !asset->equivalent(*edit->asset,1,1,edl) )
4984                                                 delete edit;
4985                                 }
4986                         }
4987                         if( track->edits->first ) {
4988                                 track->track_w = edl->session->output_w;
4989                                 track->track_h = edl->session->output_h;
4990                         }
4991                         else if( delete_tracks )
4992                                 edl->tracks->delete_track(track);
4993                 }
4994                 edl->retrack();
4995                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
4996         }
4997         if( !result && asset->audio_data && asset->channels > 0 ) {
4998                 session->sample_rate = asset->get_sample_rate();
4999                 int64_t channel_mask = 0;
5000                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
5001                         file->get_audio_for_video(vstream, astream, channel_mask);
5002                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
5003                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
5004                 int channels = 0;
5005                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
5006                 if( channels < 1 ) channels = 1;
5007                 if( channels > 6 ) channels = 6;
5008                 session->audio_tracks = session->audio_channels = channels;
5009
5010                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
5011                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
5012                 remap_audio(MWindow::AUDIO_1_TO_1);
5013
5014                 if( delete_tracks ) {
5015                         Track *track = edl->tracks->first;
5016                         for( Track *next_track=0; track; track=next_track ) {
5017                                 next_track = track->next;
5018                                 if( track->data_type != TRACK_AUDIO ) continue;
5019                                 Edit *edit = track->edits->first;
5020                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
5021                                         next_edit = edit->next;
5022                                         if( !((1<<edit->channel) & channel_mask) ||
5023                                             !edit->asset || !edit->asset->is_asset ||
5024                                             !asset->equivalent(*edit->asset,1,1,edl) )
5025                                                 delete edit;
5026                                 }
5027                                 if( !track->edits->first )
5028                                         edl->tracks->delete_track(track);
5029                         }
5030                 }
5031                 edl->rechannel();
5032                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
5033         }
5034         delete file;
5035         session->auto_keyframes = old_auto_keyframes;
5036         if( !result && delete_tracks > 0 ) {
5037                 save_backup();
5038                 undo_after(_("select asset"), LOAD_ALL);
5039         }
5040         resync_guis();
5041         return result;
5042 }
5043
5044 int MWindow::select_asset(int vtrack, int delete_tracks)
5045 {
5046         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
5047         if( !track )
5048                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
5049         if( !track ) return 1;
5050         Edit *edit = track->edits->first;
5051         if( !edit ) return 1;
5052         Asset *asset = edit->asset;
5053         if( !asset || !asset->is_asset ) return 1;
5054         return select_asset(asset, edit->channel, 0, delete_tracks);
5055 }
5056
5057 void MWindow::dump_plugindb(FILE *fp)
5058 {
5059         if( !plugindb ) return;
5060         for(int i = 0; i < plugindb->total; i++)
5061                 plugindb->get(i)->dump(fp);
5062 }
5063
5064 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
5065 {
5066         Auto *current = 0;
5067         double unit_position = edl->local_session->get_selectionstart(1);
5068         unit_position = patch->track->to_units(unit_position, 0);
5069
5070         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
5071         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5072 }
5073
5074 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
5075 {
5076         Auto *current = 0;
5077         double unit_position = edl->local_session->get_selectionstart(1);
5078         unit_position = patch->track->to_units(unit_position, 0);
5079
5080         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
5081         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5082 }
5083
5084 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
5085 {
5086         Auto *current = 0;
5087         double unit_position = edl->local_session->get_selectionstart(1);
5088         unit_position = patch->track->to_units(unit_position, 0);
5089
5090         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
5091         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5092 }
5093
5094 PatchGUI *MWindow::get_patchgui(Track *track)
5095 {
5096         PatchGUI *patchgui = 0;
5097         TimelinePane **panes = gui->pane;
5098         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
5099                 if( !panes[i] ) continue;
5100                 PatchBay *patchbay = panes[i]->patchbay;
5101                 if( !patchbay ) continue;
5102                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
5103                         if( patchbay->patches.values[j]->track == track )
5104                                 patchgui = patchbay->patches.values[j];
5105                 }
5106         }
5107         return patchgui;
5108 }
5109
5110 int MWindow::get_cpus(int out_w, int out_h)
5111 {
5112         if( !out_w ) out_w = edl->session->output_w;
5113         if( !out_h ) out_h = edl->session->output_h;
5114         int cpus = out_w*out_h/0x80000 + 1;
5115         if( cpus > preferences->processors )
5116                 cpus = preferences->processors;
5117         return cpus;
5118 }
5119 int MWindow::get_cpus()
5120 {
5121         return get_cpus(edl->session->output_w, edl->session->output_h);
5122 }
5123