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