sams last ladspa icons, libopus/vp9, mixer fixer, plugin resets, fmt frmsz, shm fixes
[goodguy/history.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 "bcdisplayinfo.h"
31 #include "bcsignals.h"
32 #include "bctimer.h"
33 #include "bctrace.h"
34 #include "bdcreate.h"
35 #include "brender.h"
36 #include "cache.h"
37 #include "channel.h"
38 #include "channeldb.h"
39 #include "channelinfo.h"
40 #include "clip.h"
41 #include "bccmodels.h"
42 #include "commercials.h"
43 #include "cplayback.h"
44 #include "ctimebar.h"
45 #include "cwindowgui.h"
46 #include "cwindow.h"
47 #include "cwindowtool.h"
48 #include "bchash.h"
49 #include "devicedvbinput.inc"
50 #include "dvdcreate.h"
51 #include "editpanel.h"
52 #include "edl.h"
53 #include "edlsession.h"
54 #include "errorbox.h"
55 #include "fileformat.h"
56 #include "file.h"
57 #include "filesystem.h"
58 #include "filexml.h"
59 #include "floatautos.h"
60 #include "framecache.h"
61 #include "gwindow.h"
62 #include "gwindowgui.h"
63 #include "keyframegui.h"
64 #include "indexfile.h"
65 #include "intautos.h"
66 #include "interlacemodes.h"
67 #include "language.h"
68 #include "levelwindowgui.h"
69 #include "levelwindow.h"
70 #include "loadfile.inc"
71 #include "localsession.h"
72 #include "maincursor.h"
73 #include "mainerror.h"
74 #include "mainindexes.h"
75 #include "mainmenu.h"
76 #include "mainprogress.h"
77 #include "mainsession.h"
78 #include "mainundo.h"
79 #include "mbuttons.h"
80 #include "mutex.h"
81 #include "mwindowgui.h"
82 #include "mwindow.h"
83 #include "nestededls.h"
84 #include "new.h"
85 #include "panautos.h"
86 #include "patchbay.h"
87 #include "playback3d.h"
88 #include "playbackengine.h"
89 #include "plugin.h"
90 #include "pluginserver.h"
91 #include "pluginset.h"
92 #include "preferences.h"
93 #include "proxy.h"
94 #include "record.h"
95 #include "recordmonitor.h"
96 #include "recordlabel.h"
97 #include "removefile.h"
98 #include "render.h"
99 #include "resourcethread.h"
100 #include "samplescroll.h"
101 #include "sha1.h"
102 #include "sighandler.h"
103 #include "splashgui.h"
104 #include "statusbar.h"
105 #include "theme.h"
106 #include "threadloader.h"
107 #include "timebar.h"
108 #include "timelinepane.h"
109 #include "tipwindow.h"
110 #include "trackcanvas.h"
111 #include "track.h"
112 #include "tracking.h"
113 #include "trackscroll.h"
114 #include "tracks.h"
115 #include "transition.h"
116 #include "transportque.h"
117 #include "vframe.h"
118 #include "vtrack.h"
119 #include "versioninfo.h"
120 #include "videodevice.inc"
121 #include "videowindow.h"
122 #include "vplayback.h"
123 #include "vwindowgui.h"
124 #include "vwindow.h"
125 #include "wavecache.h"
126 #include "wwindow.h"
127 #include "zoombar.h"
128 #include "zwindow.h"
129 #include "zwindowgui.h"
130 #include "exportedl.h"
131
132 #include "defaultformats.h"
133 #include "ntsczones.h"
134
135 #include <stdint.h>
136 #include <stdlib.h>
137 #include <unistd.h>
138 #include <fcntl.h>
139 #include <string.h>
140 #include <sys/types.h>
141 #include <sys/stat.h>
142 #include <sys/time.h>
143 #include <sys/mman.h>
144 #include <limits.h>
145 #include <errno.h>
146
147
148 extern "C"
149 {
150
151
152
153
154 // Hack for libdv to remove glib dependancy
155
156 // void
157 // g_log (const char    *log_domain,
158 //        int  log_level,
159 //        const char    *format,
160 //        ...)
161 // {
162 // }
163 //
164 // void
165 // g_logv (const char    *log_domain,
166 //        int  log_level,
167 //        const char    *format,
168 //        ...)
169 // {
170 // }
171 //
172
173 }
174
175
176
177 ArrayList<PluginServer*>* MWindow::plugindb = 0;
178 Commercials* MWindow::commercials = 0;
179
180
181 MWindow::MWindow()
182  : Thread(1, 0, 0)
183 {
184         run_lock = new Mutex("MWindow::run_lock");
185         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
186         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
187         vwindows_lock = new Mutex("MWindow::vwindows_lock");
188         zwindows_lock = new Mutex("MWindow::zwindows_lock");
189         brender_lock = new Mutex("MWindow::brender_lock");
190         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
191
192         playback_3d = 0;
193         splash_window = 0;
194         undo = 0;
195         defaults = 0;
196         assets = 0;
197         //commercials = 0;
198         commercial_active = 0;
199         audio_cache = 0;
200         video_cache = 0;
201         frame_cache = 0;
202         wave_cache = 0;
203         preferences = 0;
204         session = 0;
205         theme = 0;
206         mainindexes = 0;
207         mainprogress = 0;
208         brender = 0;
209         brender_active = 0;
210         strcpy(cin_lang,"en");
211         channeldb_buz =  new ChannelDB;
212         channeldb_v4l2jpeg =  new ChannelDB;
213         //file_server = 0;
214         plugin_guis = 0;
215         dead_plugins = 0;
216         keyframe_threads = 0;
217         create_bd = 0;
218         create_dvd = 0;
219         batch_render = 0;
220         render = 0;
221         edl = 0;
222         gui = 0;
223         cwindow = 0;
224         awindow = 0;
225         gwindow = 0;
226         twindow = 0;
227         wwindow = 0;
228         lwindow = 0;
229         sighandler = 0;
230         restart_status = 0;
231         screens = 1;
232         in_destructor = 0;
233 }
234
235
236 // Need to delete brender temporary here.
237 MWindow::~MWindow()
238 {
239         run_lock->lock("MWindow::~MWindow");
240         in_destructor = 1;
241 //printf("MWindow::~MWindow %d\n", __LINE__);
242         gui->remote_control->deactivate();
243         gui->record->stop();
244 #ifdef HAVE_DVB
245         gui->channel_info->stop();
246 #endif
247         delete create_bd;       create_bd = 0;
248         delete create_dvd;      create_dvd = 0;
249         delete batch_render;    batch_render = 0;
250         delete render;          render = 0;
251         commit_commercial();
252         if( commercials && !commercials->remove_user() ) commercials = 0;
253         close_mixers();
254
255 // Save defaults for open plugins
256         plugin_gui_lock->lock("MWindow::~MWindow");
257         for(int i = 0; i < plugin_guis->size(); i++) {
258                 plugin_guis->get(i)->hide_gui();
259                 delete_plugin(plugin_guis->get(i));
260         }
261         plugin_gui_lock->unlock();
262         hide_keyframe_guis();
263         clean_indexes();
264         save_defaults();
265 // Give up and go to a movie
266 //  cant run valgrind if this is used
267
268         gui->del_keyboard_listener(
269                 (int (BC_WindowBase::*)(BC_WindowBase *))
270                 &MWindowGUI::keyboard_listener);
271 #if 0
272 // release the hounds
273         if( awindow && awindow->gui ) awindow->gui->close(0);
274         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
275         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
276         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
277         if( twindow && twindow->is_running() ) twindow->close_window();
278         if( wwindow && wwindow->is_running() ) wwindow->close_window();
279         vwindows.remove_all_objects();
280         zwindows.remove_all_objects();
281         gui->close(0);
282         if( awindow ) awindow->join();
283         if( cwindow ) cwindow->join();
284         if( lwindow ) lwindow->join();
285         if( twindow ) twindow->join();
286         if( wwindow ) wwindow->join();
287         if( gwindow ) gwindow->join();
288         join();
289 #else
290 // one at a time, or nouveau chokes
291 #define close_gui(win) if( win ) { \
292   if( win->gui ) win->gui->close(0); \
293   win->join(); }
294         close_gui(awindow);
295         close_gui(cwindow);
296         close_gui(lwindow);
297         close_gui(gwindow);
298         close_gui(twindow);
299         close_gui(wwindow);
300         vwindows.remove_all_objects();
301         zwindows.remove_all_objects();
302         gui->close(0);
303         join();
304 #endif
305         reset_caches();
306         dead_plugins->remove_all_objects();
307 // must delete theme before destroying plugindb
308 //  theme destructor will be deleted by delete_plugins
309         delete theme;           theme = 0;
310         delete_plugins();
311         finit_error();
312         keyframe_threads->remove_all_objects();
313         colormodels.remove_all_objects();
314         delete awindow;         awindow = 0;
315         delete lwindow;         lwindow = 0;
316         delete twindow;         twindow = 0;
317         delete wwindow;         wwindow = 0;
318         delete gwindow;         gwindow = 0;
319         delete cwindow;         cwindow = 0;
320         delete gui;             gui = 0;
321         //delete file_server;  file_server = 0; // reusable
322         delete mainindexes;     mainindexes = 0;
323         delete mainprogress;    mainprogress = 0;
324         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
325         delete video_cache;     video_cache = 0;  // delete the cache after the assets
326         delete frame_cache;     frame_cache = 0;
327         delete wave_cache;      wave_cache = 0;
328         delete plugin_guis;     plugin_guis = 0;
329         delete dead_plugins;    dead_plugins = 0;
330         delete keyframe_threads;  keyframe_threads = 0;
331         delete undo;            undo = 0;
332         delete preferences;     preferences = 0;
333         delete exportedl;       exportedl = 0;
334         delete session;         session = 0;
335         delete defaults;        defaults = 0;
336         delete assets;          assets = 0;
337         delete splash_window;   splash_window = 0;
338         if( !edl->Garbage::remove_user() ) edl = 0;
339         delete channeldb_buz;
340         delete channeldb_v4l2jpeg;
341 // This must be last thread to exit
342         delete playback_3d;     playback_3d = 0;
343         delete dead_plugin_lock;
344         delete plugin_gui_lock;
345         delete vwindows_lock;
346         delete zwindows_lock;
347         delete brender_lock;
348         delete keyframe_gui_lock;
349         colormodels.remove_all_objects();
350         interlace_project_modes.remove_all_objects();
351         interlace_asset_modes.remove_all_objects();
352         interlace_asset_fixmethods.remove_all_objects();
353         sighandler->terminate();
354         delete sighandler;
355         delete run_lock;
356 }
357
358
359 void MWindow::quit()
360 {
361         gui->set_done(0);
362 }
363
364 void MWindow::init_error()
365 {
366         MainError::init_error(this);
367 }
368
369 void MWindow::finit_error()
370 {
371         MainError::finit_error();
372 }
373
374 void MWindow::create_defaults_path(char *string, const char *config_file)
375 {
376 // set the .bcast path
377         FileSystem fs;
378
379         sprintf(string, "%s/", File::get_config_path());
380         fs.complete_path(string);
381         if(!fs.is_dir(string))
382                 fs.create_dir(string);
383
384 // load the defaults
385         strcat(string, config_file);
386 }
387 const char *MWindow::default_std()
388 {
389         char buf[BCTEXTLEN], *p = 0;
390
391         int fd = open(TIMEZONE_NAME, O_RDONLY);
392         if( fd >= 0 ) {
393                 int l = read(fd, buf, sizeof(buf)-1);
394                 close(fd);
395                 if( l > 0 ) {
396                         if( buf[l-1] == '\n' ) --l;
397                         buf[l] = 0;
398                         p = buf;
399                 }
400         }
401         if( !p ) {
402                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
403                 if( l > 0 ) {
404                         buf[l] = 0;
405                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
406                         p += strlen(ZONEINFO_STR);
407                 }
408         }
409
410         if( p ) {
411                 for( int i=0; ntsc_zones[i]; ++i ) {
412                         if( !strcmp(ntsc_zones[i], p) )
413                                 return "NTSC";
414                 }
415         }
416
417         p = getenv("TZ");
418         if( p ) {
419                 for( int i=0; ntsc_zones[i]; ++i ) {
420                         if( !strcmp(ntsc_zones[i], p) )
421                                 return "NTSC";
422                 }
423         }
424
425 //__timezone: Seconds west of UTC.  240sec/deg
426         double tz_deg = -__timezone / 240.;
427 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
428         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
429 }
430
431 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
432 {
433         struct formatpresets *fpr;
434
435         for(fpr = &format_presets[0]; fpr->name; fpr++)
436         {
437                 if(strcmp(_(fpr->name), preset) == 0)
438                 {
439                         session->audio_channels = fpr->audio_channels;
440                         session->audio_tracks = fpr->audio_tracks;
441                         session->sample_rate = fpr->sample_rate;
442                         session->video_channels = fpr->video_channels;
443                         session->video_tracks = fpr->video_tracks;
444                         session->frame_rate = fpr->frame_rate;
445                         session->output_w = fpr->output_w;
446                         session->output_h = fpr->output_h;
447                         session->aspect_w = fpr->aspect_w;
448                         session->aspect_h = fpr->aspect_h;
449                         session->interlace_mode = fpr->interlace_mode;
450                         session->color_model = fpr->color_model;
451                         return;
452                 }
453         }
454 }
455
456 const char *MWindow::get_preset_name(int index)
457 {
458         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
459                 return "Error";
460         return _(format_presets[index].name);
461 }
462
463
464 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
465 {
466         char path[BCTEXTLEN];
467 // Use user supplied path
468         if(config_path[0])
469                 strcpy(path, config_path);
470         else
471                 create_defaults_path(path, CONFIG_FILE);
472
473         defaults = new BC_Hash(path);
474         defaults->load();
475 }
476
477
478 void MWindow::check_language()
479 {
480         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
481         const char *env_lang = getenv("LANGUAGE");
482         if( !env_lang ) env_lang = getenv("LC_ALL");
483         if( !env_lang ) env_lang = getenv("LANG");
484         if( !env_lang ) {
485                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
486                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
487                 env_lang = curr_lang;
488         }
489         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
490         defaults->get("LAST_LANG",last_lang);
491         if( strcmp(env_lang,last_lang)) {
492                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
493                 defaults->update("LAST_LANG",env_lang);
494                 char plugin_path[BCTEXTLEN];
495                 create_defaults_path(plugin_path, PLUGIN_FILE);
496                 ::remove(plugin_path);
497                 char ladspa_path[BCTEXTLEN];
498                 create_defaults_path(ladspa_path, LADSPA_FILE);
499                 ::remove(ladspa_path);
500                 defaults->save();
501         }
502         if( strlen(env_lang) > 1 &&
503             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
504                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
505         }
506         else
507                 strcpy(cin_lang, "en");
508 }
509
510 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
511 {
512         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
513         if( plug_dir ) {
514                 const char *dp = plug_dir;
515                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
516                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
517         }
518         strcpy(path, bp);
519         delete [] base_path;
520 }
521
522 int MWindow::load_plugin_index(MWindow *mwindow, const char *index_path, const char *plugin_dir)
523 {
524 // load index
525         FILE *fp = fopen(index_path, "r");
526         if( !fp ) return -1;
527
528         int ret = 0;
529         char index_line[BCTEXTLEN];
530         int index_version = -1, len = strlen(plugin_dir);
531         if( !fgets(index_line, BCTEXTLEN, fp) ||
532             sscanf(index_line, "%d", &index_version) != 1 ||
533             index_version != PLUGIN_FILE_VERSION ||
534             !fgets(index_line, BCTEXTLEN, fp) ||
535             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
536             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
537
538         ArrayList<PluginServer*> plugins;
539         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
540                 if( index_line[0] == ';' ) continue;
541                 if( index_line[0] == '#' ) continue;
542                 int type = PLUGIN_TYPE_UNKNOWN;
543                 char path[BCTEXTLEN], title[BCTEXTLEN];
544                 int64_t mtime = 0;
545                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
546                         ret = 1; continue;
547                 }
548                 PluginServer *server = 0;
549                 switch( type ) {
550                 case PLUGIN_TYPE_BUILTIN:
551                 case PLUGIN_TYPE_EXECUTABLE:
552                 case PLUGIN_TYPE_LADSPA: {
553                         char plugin_path[BCTEXTLEN];  struct stat st;
554                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
555                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
556                                 ret = 1; continue;
557                         }
558                         server = new PluginServer(mwindow, plugin_path, type);
559                         break; }
560                 case PLUGIN_TYPE_FFMPEG: {
561                         server = new_ffmpeg_server(mwindow, path);
562                         break; }
563                 }
564                 if( !server ) continue;
565                 plugins.append(server);
566 // Create plugin server from index entry
567                 server->set_title(title);
568                 if( server->read_table(index_line) ) {
569                         ret = 1;  continue;
570                 }
571         }
572         fclose(fp);
573
574         if( !ret )
575                 ret = check_plugin_index(plugins, plugin_dir, ".");
576
577         if( !ret )
578                 add_plugins(plugins);
579         else
580                 plugins.remove_all_objects();
581
582         return ret;
583 }
584
585 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
586         const char *plug_dir, const char *plug_path)
587 {
588         char plugin_path[BCTEXTLEN];
589         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
590         FileSystem fs;
591         fs.set_filter( "[*.plugin][*.so]" );
592         if( fs.update(plugin_path) )
593                 return 1;
594
595         for( int i=0; i<fs.dir_list.total; ++i ) {
596                 char fs_path[BCTEXTLEN];
597                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
598                 if( fs.is_dir(fs_path) ) {
599                         get_plugin_path(plugin_path, plug_dir, fs_path);
600                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
601                                 return 1;
602                 }
603                 else if( !plugin_exists(fs_path, plugins) )
604                         return 1;
605         }
606         return 0;
607 }
608
609
610 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
611 {
612         if( !plugindb )
613                 plugindb = new ArrayList<PluginServer*>;
614         init_ffmpeg();
615         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
616         create_defaults_path(index_path, PLUGIN_FILE);
617         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
618         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
619         if( !load_plugin_index(mwindow, index_path, plugin_path) ) return 1;
620         printf("init plugin index: %s\n", plugin_path);
621         FILE *fp = fopen(index_path,"w");
622         if( !fp ) {
623                 fprintf(stderr,_("MWindow::init_plugins: "
624                         "can't create plugin index: %s\n"), index_path);
625                 return 1;
626         }
627         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
628         fprintf(fp, "%s\n", plugin_path);
629         init_plugin_index(mwindow, preferences, fp, plugin_path);
630         init_ffmpeg_index(mwindow, preferences, fp);
631         fclose(fp);
632         return load_plugin_index(mwindow, index_path, plugin_path);
633 }
634
635 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
636 {
637         char *path = getenv("LADSPA_PATH");
638         char ladspa_path[BCTEXTLEN];
639         if( !path ) {
640                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
641                 path = ladspa_path;
642         }
643         for( int len=0; *path; path+=len ) {
644                 char *cp = strchr(path,':');
645                 len = !cp ? strlen(path) : cp-path;
646                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
647                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
648                 if( cp ) ++len;
649                 char *plugin_dir = FileSystem::basepath(plugin_path);
650                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
651                 create_defaults_path(index_path, LADSPA_FILE);
652                 cp = index_path + strlen(index_path);
653                 for( char *bp=plugin_path; *bp!=0; ++bp )
654                         *cp++ = *bp=='/' ? '_' : *bp;
655                 *cp = 0;
656                 if( !load_plugin_index(mwindow, index_path, plugin_path) ) continue;
657                 if( init_ladspa_index(mwindow, preferences, index_path, plugin_path) ) continue;
658                 load_plugin_index(mwindow, index_path, plugin_path);
659         }
660         return 1;
661 }
662
663 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
664         FILE *fp, const char *plugin_dir)
665 {
666         int idx = PLUGIN_IDS;
667         if( plugindb ) {
668                 for( int i=0; i<plugindb->size(); ++i ) {
669                         PluginServer *server = plugindb->get(i);
670                         if( server->dir_idx >= idx )
671                                 idx = server->dir_idx+1;
672                 }
673         }
674         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
675 }
676
677 int MWindow::init_ladspa_index(MWindow *mwindow, Preferences *preferences,
678         const char *index_path, const char *plugin_dir)
679 {
680         char plugin_path[BCTEXTLEN], *path = FileSystem::basepath(plugin_dir);
681         strcpy(plugin_path, path);  delete [] path;
682         printf("init ladspa index: %s\n", plugin_dir);
683         FILE *fp = fopen(index_path,"w");
684         if( !fp ) {
685                 fprintf(stderr,_("MWindow::init_ladspa_index: "
686                         "can't create plugin index: %s\n"), index_path);
687                 return 1;
688         }
689         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
690         fprintf(fp, "%s\n", plugin_dir);
691         init_plugin_index(mwindow, preferences, fp, plugin_path);
692         fclose(fp);
693         return 0;
694 }
695
696 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
697         const char *plug_dir, const char *plug_path, int &idx)
698 {
699         char plugin_path[BCTEXTLEN];
700         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
701         FileSystem fs;
702         fs.set_filter( "[*.plugin][*.so]" );
703         int result = fs.update(plugin_path);
704         if( result || !fs.dir_list.total ) return;
705         int vis_id = idx++;
706
707         for( int i=0; i<fs.dir_list.total; ++i ) {
708                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
709                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
710                 get_plugin_path(path, plug_dir, fs_path);
711                 if( fs.is_dir(fs_path) ) {
712                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
713                         continue;
714                 }
715                 if( plugin_exists(path) ) continue;
716                 struct stat st;
717                 if( stat(fs_path, &st) ) continue;
718                 int64_t mtime = st.st_mtime;
719                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
720                 result = server.open_plugin(1, preferences, 0, 0);
721                 if( !result ) {
722                         server.write_table(fp, path, vis_id, mtime);
723                         server.close_plugin();
724                 }
725                 else if( result == PLUGINSERVER_IS_LAD ) {
726                         int lad_index = 0;
727                         for(;;) {
728                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
729                                 ladspa.set_lad_index(lad_index++);
730                                 result = ladspa.open_plugin(1, preferences, 0, 0);
731                                 if( result ) break;
732                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
733                                 ladspa.close_plugin();
734                         }
735                 }
736         }
737 }
738
739 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
740 {
741         for( int i=0; i<plugins.size(); ++i )
742                 plugindb->append(plugins[i]);
743         plugins.remove_all();
744 }
745
746 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
747 {
748         const char *cfg_path = File::get_cindat_path();
749         char msg_path[BCTEXTLEN];  int txt = 0;
750         FILE *fp = 0;
751         if( BC_Resources::language[0] ) {
752                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
753                         cfg_path, lang);
754                 fp = fopen(msg_path, "r");
755         }
756         if( !fp ) {
757                 txt = 1;
758                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
759                         cfg_path);
760                 fp = fopen(msg_path, "r");
761         }
762         if( !fp ) return;
763         char text[BCTEXTLEN];
764         char *tp = text, *ep = tp + sizeof(text)-1;
765         char title[BCTEXTLEN];
766         title[0] = 0;
767         int no = 0;
768         for(;;) {
769                 ++no;  int done = 1;
770                 char line[BCTEXTLEN], *cp = line;
771                 if( fgets(line,sizeof(line)-1,fp) ) {
772                         if( *cp == '#' ) continue;
773                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
774                 }
775                 if( done ) {
776                         if( tp > text && *--tp == '\n' ) *tp = 0;
777                         if( title[0] ) {
778                                 tp = !txt ? title : _(title);
779                                 int idx = plugins.size();
780                                 while( --idx>=0 && strcmp(plugins[idx]->title, tp) );
781                                 if( idx >= 0 ) {
782                                         delete [] plugins[idx]->tip;
783                                         plugins[idx]->tip = cstrdup(text);
784                                 }
785                                 title[0] = 0;
786                         }
787                         if( done > 0 ) break;
788                         tp = text;  *tp = 0;
789                         char *dp = strchr(cp, ':');
790                         if( !dp ) {
791                                 printf("plugin tips: error on line %d\n", no);
792                                 continue;
793                         }
794                         char *bp = title;
795                         while( cp < dp ) *bp++ = *cp++;
796                         *bp = 0;
797                         ++cp;
798                 }
799
800                 while( *cp == ' ' || *cp == '\t' ) ++cp;
801                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
802         }
803         fclose(fp);
804 }
805
806 void MWindow::delete_plugins()
807 {
808         plugindb->remove_all_objects();
809         delete plugindb;
810         plugindb = 0;
811 }
812
813 void MWindow::search_plugindb(int do_audio,
814                 int do_video,
815                 int is_realtime,
816                 int is_transition,
817                 int is_theme,
818                 ArrayList<PluginServer*> &results)
819 {
820 // Get plugins
821         for(int i = 0; i < MWindow::plugindb->total; i++)
822         {
823                 PluginServer *current = MWindow::plugindb->get(i);
824
825                 if(current->audio == do_audio &&
826                         current->video == do_video &&
827                         (current->realtime == is_realtime || is_realtime < 0) &&
828                         current->transition == is_transition &&
829                         current->theme == is_theme)
830                         results.append(current);
831         }
832
833 // Alphabetize list by title
834         int done = 0;
835         while(!done)
836         {
837                 done = 1;
838
839                 for(int i = 0; i < results.total - 1; i++)
840                 {
841                         PluginServer *value1 = results[i];
842                         PluginServer *value2 = results[i + 1];
843                         if(strcmp(_(value1->title), _(value2->title)) > 0)
844                         {
845                                 done = 0;
846                                 results[i] = value2;
847                                 results[i + 1] = value1;
848                         }
849                 }
850         }
851 }
852
853 PluginServer* MWindow::scan_plugindb(char *title,
854                 int data_type)
855 {
856 //      if(data_type < 0)
857 //      {
858 //              printf("MWindow::scan_plugindb data_type < 0\n");
859 //              return 0;
860 //      }
861
862         for(int i = 0; i < plugindb->total; i++)
863         {
864                 PluginServer *server = plugindb->get(i);
865                 if(server->title &&
866                         !strcasecmp(server->title, title) &&
867                         (data_type < 0 ||
868                                 (data_type == TRACK_AUDIO && server->audio) ||
869                                 (data_type == TRACK_VIDEO && server->video)))
870                         return plugindb->get(i);
871         }
872         return 0;
873 }
874
875 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
876 {
877         for( int i=0; i<plugins.size(); ++i )
878                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
879         return 0;
880 }
881
882 int MWindow::plugin_exists(char *plugin_path)
883 {
884         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
885 }
886
887 void MWindow::init_preferences()
888 {
889         preferences = new Preferences;
890         preferences->load_defaults(defaults);
891         session = new MainSession(this);
892         session->load_defaults(defaults);
893         // set x11_host, screens, window_config
894         screens = session->set_default_x11_host();
895         BC_Signals::set_trap_hook(trap_hook, this);
896         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
897         BC_Signals::set_catch_intr(preferences->trap_sigintr);
898         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
899                 BC_Trace::enable_locks();
900         }
901         else {
902                 BC_Trace::disable_locks();
903         }
904         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
905         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
906         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
907 }
908
909 void MWindow::clean_indexes()
910 {
911         FileSystem fs;
912         int total_excess;
913         long oldest = 0;
914         int oldest_item = -1;
915         int result;
916         char string[BCTEXTLEN];
917         char string2[BCTEXTLEN];
918
919 // Delete extra indexes
920         fs.set_filter("*.idx");
921         fs.complete_path(preferences->index_directory);
922         fs.update(preferences->index_directory);
923 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
924
925 // Eliminate directories
926         result = 1;
927         while(result)
928         {
929                 result = 0;
930                 for(int i = 0; i < fs.dir_list.total && !result; i++)
931                 {
932                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
933                         if(fs.is_dir(string))
934                         {
935                                 delete fs.dir_list[i];
936                                 fs.dir_list.remove_number(i);
937                                 result = 1;
938                         }
939                 }
940         }
941         total_excess = fs.dir_list.total - preferences->index_count;
942
943 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
944         while(total_excess > 0)
945         {
946 // Get oldest
947                 for(int i = 0; i < fs.dir_list.total; i++)
948                 {
949                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
950
951                         if(i == 0 || fs.get_date(string) <= oldest)
952                         {
953                                 oldest = fs.get_date(string);
954                                 oldest_item = i;
955                         }
956                 }
957
958                 if(oldest_item >= 0)
959                 {
960 // Remove index file
961                         fs.join_names(string,
962                                 preferences->index_directory,
963                                 fs.dir_list[oldest_item]->name);
964 //printf("MWindow::clean_indexes 1 %s\n", string);
965                         if(remove(string))
966                                 perror("delete_indexes");
967                         delete fs.dir_list[oldest_item];
968                         fs.dir_list.remove_number(oldest_item);
969
970 // Remove table of contents if it exists
971                         strcpy(string2, string);
972                         char *ptr = strrchr(string2, '.');
973                         if(ptr)
974                         {
975 //printf("MWindow::clean_indexes 2 %s\n", string2);
976                                 sprintf(ptr, ".toc");
977                                 remove(string2);
978                                 sprintf(ptr, ".mkr");
979                                 remove(string2);
980                         }
981                 }
982
983                 total_excess--;
984         }
985 }
986
987 void MWindow::init_awindow()
988 {
989         awindow = new AWindow(this);
990         awindow->create_objects();
991 }
992
993 void MWindow::init_gwindow()
994 {
995         gwindow = new GWindow(this);
996         gwindow->create_objects();
997 }
998
999 void MWindow::init_tipwindow()
1000 {
1001         TipWindow::load_tips(cin_lang);
1002         if( !twindow )
1003                 twindow = new TipWindow(this);
1004         twindow->start();
1005 }
1006
1007 void MWindow::show_warning(int *do_warning, const char *text)
1008 {
1009         if( do_warning && !*do_warning ) return;
1010         if( !wwindow )
1011                 wwindow = new WWindow(this);
1012         wwindow->show_warning(do_warning, text);
1013 }
1014
1015 int MWindow::wait_warning()
1016 {
1017         return wwindow->wait_result();
1018 }
1019
1020 void MWindow::init_theme()
1021 {
1022         Timer timer;
1023         theme = 0;
1024
1025         PluginServer *theme_plugin = 0;
1026         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1027                 if( plugindb->get(i)->theme &&
1028                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1029                         theme_plugin = plugindb->get(i);
1030         }
1031
1032         if( !theme_plugin )
1033                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1034                          preferences->theme);
1035
1036         const char *default_theme = _(DEFAULT_THEME);
1037         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1038                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1039                         default_theme);
1040                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1041                         if( plugindb->get(i)->theme &&
1042                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1043                                 theme_plugin = plugindb->get(i);
1044                 }
1045         }
1046
1047         if(!theme_plugin) {
1048                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1049                 exit(1);
1050         }
1051
1052         PluginServer *plugin = new PluginServer(*theme_plugin);
1053         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1054                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1055                         theme_plugin->title);
1056                 exit(1);
1057         }
1058
1059         theme = plugin->new_theme();
1060         theme->mwindow = this;
1061         strcpy(theme->path, plugin->path);
1062         delete plugin;
1063
1064 // Load default images & settings
1065         theme->Theme::initialize();
1066 // Load user images & settings
1067         theme->initialize();
1068 // Create menus with user colors
1069         theme->build_menus();
1070         init_menus();
1071
1072         theme->sort_image_sets();
1073         theme->check_used();
1074 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1075 }
1076
1077 void MWindow::init_3d()
1078 {
1079         playback_3d = new Playback3D(this);
1080         playback_3d->create_objects();
1081 }
1082
1083 void MWindow::init_edl()
1084 {
1085         edl = new EDL;
1086         edl->create_objects();
1087         fill_preset_defaults(default_standard, edl->session);
1088         edl->load_defaults(defaults);
1089         edl->session->brender_start = edl->session->brender_end = 0;
1090         edl->create_default_tracks();
1091         edl->tracks->update_y_pixels(theme);
1092 }
1093
1094 void MWindow::init_compositor()
1095 {
1096         cwindow = new CWindow(this);
1097         cwindow->create_objects();
1098 }
1099
1100 void MWindow::init_levelwindow()
1101 {
1102         lwindow = new LevelWindow(this);
1103         lwindow->create_objects();
1104 }
1105
1106 VWindow *MWindow::get_viewer(int start_it, int idx)
1107 {
1108         vwindows_lock->lock("MWindow::get_viewer");
1109         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1110         if( !vwindow ) idx = vwindows.size();
1111         while( !vwindow && --idx >= 0 ) {
1112                 VWindow *vwin = vwindows[idx];
1113                 if( !vwin->is_running() || !vwin->get_edl() )
1114                         vwindow = vwin;
1115         }
1116         if( !vwindow ) {
1117                 vwindow = new VWindow(this);
1118                 vwindow->load_defaults();
1119                 vwindow->create_objects();
1120                 vwindows.append(vwindow);
1121         }
1122         vwindows_lock->unlock();
1123         if( start_it ) vwindow->start();
1124         return vwindow;
1125 }
1126
1127 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1128 {
1129         zwindows_lock->lock("MWindow::get_mixer");
1130         if( !mixer ) mixer = edl->mixers.new_mixer();
1131         ZWindow *zwindow = 0;
1132         for( int i=0; !zwindow && i<zwindows.size(); ++i )
1133                 if( zwindows[i]->idx < 0 ) zwindow = zwindows[i];
1134         if( !zwindow )
1135                 zwindows.append(zwindow = new ZWindow(this));
1136         zwindow->idx = mixer->idx;
1137         zwindows_lock->unlock();
1138         return zwindow;
1139 }
1140
1141 void MWindow::del_mixer(ZWindow *zwindow)
1142 {
1143         zwindows_lock->lock("MWindow::del_mixer 0");
1144         edl->mixers.del_mixer(zwindow->idx);
1145         zwindow->idx = -1;
1146         if( session->selected_zwindow >= 0 ) {
1147                 int i = zwindows.number_of(zwindow);
1148                 if( i >= 0 && i < session->selected_zwindow )
1149                         --session->selected_zwindow;
1150                 else if( i == session->selected_zwindow )
1151                         session->selected_zwindow = -1;
1152         }
1153         zwindows_lock->unlock();
1154         gui->lock_window("MWindow::del_mixer 1");
1155         gui->update_mixers(0, -1);
1156         gui->unlock_window();
1157 }
1158
1159 void MWindow::start_mixer()
1160 {
1161         Mixer *mixer = 0;
1162         ZWindow *zwindow = get_mixer(mixer);
1163         const char *title = 0;
1164
1165         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1166                 PatchGUI *patchgui = get_patchgui(track);
1167                 if( !patchgui || !patchgui->mixer ) continue;
1168                 mixer->mixer_ids.append(track->get_mixer_id());
1169                 if( !title ) title = track->title;
1170         }
1171
1172         session->selected_zwindow = -1;
1173         gui->lock_window("MWindow::start_mixer");
1174         gui->update_mixers(0, 0);
1175         gui->unlock_window();
1176
1177         zwindow->set_title(title);
1178         zwindow->start();
1179         refresh_mixers();
1180 }
1181
1182 int MWindow::mixer_track_active(Track *track)
1183 {
1184         int i = session->selected_zwindow;
1185         if( i < 0 || i >= zwindows.size() ) return 0;
1186         ZWindow *zwindow = zwindows[i];
1187         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1188         if( !mixer ) return 0;
1189         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1190         return n >= 0 ? 1 : 0;
1191 }
1192
1193 void MWindow::update_mixer_tracks()
1194 {
1195         zwindows_lock->lock("MixPatch::handle_event");
1196         int i = session->selected_zwindow;
1197         if( i >= 0 && i < zwindows.size() ) {
1198                 ZWindow *zwindow = zwindows[i];
1199                 zwindow->update_mixer_ids();
1200         }
1201         zwindows_lock->unlock();
1202 }
1203
1204 void MWindow::queue_mixers(EDL *edl, int command, int wait_tracking,
1205                 int use_inout, int update_refresh, int toggle_audio)
1206 {
1207         zwindows_lock->lock("MWindow::queue_mixers");
1208         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1209                 ZWindow *zwindow = zwindows[vidx];
1210                 if( zwindow->idx < 0 ) continue;
1211                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1212                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1213                 int k = -1;
1214                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1215                         if( track->data_type != TRACK_VIDEO ) continue;
1216                         int mixer_id = track->get_mixer_id();
1217                         k = mixer->mixer_ids.size();
1218                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1219                 }
1220                 if( k < 0 ) continue;
1221                 EDL *mixer_edl = new EDL(this->edl);
1222                 mixer_edl->create_objects();
1223                 mixer_edl->copy_all(edl);
1224                 mixer_edl->remove_vwindow_edls();
1225                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1226                         k = mixer->mixer_ids.size();
1227                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1228                         if( k >= 0 ) {
1229                                 track->record = 1;
1230                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1231                         }
1232                         else
1233                                 track->record = track->play = 0;
1234                 }
1235                 zwindow->change_source(mixer_edl);
1236                 zwindow->issue_command(command,
1237                         wait_tracking, use_inout, update_refresh, toggle_audio);
1238         }
1239         zwindows_lock->unlock();
1240 }
1241
1242 void MWindow::refresh_mixers()
1243 {
1244         queue_mixers(edl,CURRENT_FRAME,0,0,1,0);
1245 }
1246
1247 void MWindow::stop_mixers()
1248 {
1249         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1250                 ZWindow *zwindow = zwindows[vidx];
1251                 if( zwindow->idx < 0 ) continue;
1252                 zwindow->issue_command(STOP, 0, 0, 0, 0);
1253         }
1254 }
1255
1256 void MWindow::close_mixers()
1257 {
1258         zwindows_lock->lock("MWindow::close_mixers");
1259         for( int i=0; i<zwindows.size(); ++i ) {
1260                 ZWindow *zwindow = zwindows[i];
1261                 if( zwindow->idx < 0 ) continue;
1262                 ZWindowGUI *zgui = zwindow->zgui;
1263                 zgui->lock_window("MWindow::select_zwindow 0");
1264                 zgui->set_done(0);
1265                 zgui->unlock_window();
1266         }
1267         zwindows_lock->unlock();
1268         for( int i=0; i<zwindows.size(); ++i ) {
1269                 ZWindow *zwindow = zwindows[i];
1270                 if( zwindow->idx < 0 ) continue;
1271                 zwindow->close_window();
1272         }
1273 }
1274
1275 int MWindow::select_zwindow(ZWindow *zwindow)
1276 {
1277         int ret = 0, n = zwindows.number_of(zwindow);
1278         if( session->selected_zwindow != n ) {
1279                 session->selected_zwindow = n;
1280                 for( int i=0; i<zwindows.size(); ++i ) {
1281                         ZWindow *zwindow = zwindows[i];
1282                         if( zwindow->idx < 0 ) continue;
1283                         ZWindowGUI *zgui = zwindow->zgui;
1284                         zgui->lock_window("MWindow::select_zwindow 0");
1285                         zwindow->highlighted = i == n ? 1 : 0;
1286                         if( zgui->draw_overlays() )
1287                                 zgui->canvas->get_canvas()->flash(1);
1288                         zgui->unlock_window();
1289                 }
1290                 ret = 1;
1291                 gui->lock_window("MWindow::select_window 1");
1292                 gui->update_mixers(0, -1);
1293                 gui->unlock_window();
1294         }
1295         return ret;
1296 }
1297
1298 void MWindow::tile_mixers()
1299 {
1300         int nz = 0;
1301         for( int i=0; i<zwindows.size(); ++i ) {
1302                 ZWindow *zwindow = zwindows[i];
1303                 if( zwindow->idx < 0 ) continue;
1304                 ++nz;
1305         }
1306         if( !nz ) return;
1307         int zn = ceil(sqrt(nz));
1308         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1309         int y1 = 1, y2 = gui->get_y();
1310         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1311         if( x1 < 0 ) x1 = 0;
1312         if( y1 < 0 ) y1 = 0;
1313         if( x2 > rw ) x2 = rw;
1314         if( y2 > rh ) y2 = rh;
1315         int dx = x2 - x1, dy = y2 - y1;
1316         int zw = dx / zn;
1317         int lt = BC_DisplayInfo::get_left_border();
1318         int top = BC_DisplayInfo::get_top_border();
1319         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1320         int bh = top + BC_DisplayInfo::get_bottom_border();
1321         int zx = 0, zy = 0;  // window origins
1322         int mw = 10+10, mh = 10+10; // canvas margins
1323         int rsz = 0, n = 0, dz = 0;
1324         int ow = edl->session->output_w, oh = edl->session->output_h;
1325         for( int i=0; i<zwindows.size(); ++i ) {
1326                 ZWindow *zwindow = zwindows[i];
1327                 if( zwindow->idx < 0 ) continue;
1328                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1329                 if( rsz < hh ) rsz = hh;
1330                 int xx = zx + x1, yy = zy + y1;
1331                 int mx = x2 - zw, my = y2 - zh;
1332                 if( xx > mx ) xx = mx;
1333                 if( yy > my ) yy = my;
1334                 xx += lt + dz;  yy += top + dz;
1335                 zwindow->reposition(xx,yy, ww,hh);
1336                 if( zwindow->running() ) {
1337                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1338                         gui->lock_window("MWindow::tile_mixers");
1339                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1340                         gui->unlock_window();
1341                 }
1342                 if( ++n >= zn ) {
1343                         n = 0;  rsz += bh;
1344                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1345                         rsz = 0;
1346                         zx = 0;
1347                 }
1348                 else
1349                         zx += zw;
1350         }
1351 }
1352
1353
1354 void MWindow::init_cache()
1355 {
1356         audio_cache = new CICache(preferences);
1357         video_cache = new CICache(preferences);
1358         frame_cache = new FrameCache;
1359         wave_cache = new WaveCache;
1360 }
1361
1362 void MWindow::init_channeldb()
1363 {
1364         channeldb_buz->load("channeldb_buz");
1365         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1366 }
1367
1368 void MWindow::init_menus()
1369 {
1370         char string[BCTEXTLEN];
1371
1372         // Color Models
1373         BC_CModels::to_text(string, BC_RGB888);
1374         colormodels.append(new ColormodelItem(string, BC_RGB888));
1375         BC_CModels::to_text(string, BC_RGBA8888);
1376         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1377 //      BC_CModels::to_text(string, BC_RGB161616);
1378 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1379 //      BC_CModels::to_text(string, BC_RGBA16161616);
1380 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1381         BC_CModels::to_text(string, BC_RGB_FLOAT);
1382         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1383         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1384         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1385         BC_CModels::to_text(string, BC_YUV888);
1386         colormodels.append(new ColormodelItem(string, BC_YUV888));
1387         BC_CModels::to_text(string, BC_YUVA8888);
1388         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1389 //      BC_CModels::to_text(string, BC_YUV161616);
1390 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1391 //      BC_CModels::to_text(string, BC_YUVA16161616);
1392 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1393
1394 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1395                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1396
1397 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1398                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1399
1400 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1401                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1402
1403         // Interlacing Modes
1404         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1405
1406         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1407         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1408
1409         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1410         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1411
1412         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1413         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1414
1415         // Interlacing Fixing Methods
1416         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1417         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1418         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1419 }
1420
1421 void MWindow::init_indexes()
1422 {
1423         mainindexes = new MainIndexes(this);
1424         mainindexes->start_loop();
1425 }
1426
1427 void MWindow::init_gui()
1428 {
1429         gui = new MWindowGUI(this);
1430         gui->lock_window("MWindow::init_gui");
1431         gui->create_objects();
1432         gui->unlock_window();
1433         gui->load_defaults(defaults);
1434 }
1435
1436 void MWindow::init_signals()
1437 {
1438         sighandler = new SigHandler;
1439         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1440 ENABLE_BUFFER
1441 }
1442
1443 void MWindow::init_render()
1444 {
1445         render = new Render(this);
1446         create_bd = new CreateBD_Thread(this);
1447         create_dvd = new CreateDVD_Thread(this);
1448         batch_render = new BatchRenderThread(this);
1449 }
1450
1451 void MWindow::init_exportedl()
1452 {
1453         exportedl = new ExportEDL(this);
1454 }
1455
1456 void MWindow::init_brender()
1457 {
1458         if(preferences->use_brender && !brender)
1459         {
1460                 brender_lock->lock("MWindow::init_brender 1");
1461                 brender = new BRender(this);
1462                 brender->initialize();
1463                 session->brender_end = 0;
1464                 brender_lock->unlock();
1465         }
1466         else
1467         if(!preferences->use_brender && brender)
1468         {
1469                 brender_lock->lock("MWindow::init_brender 2");
1470                 delete brender;
1471                 brender = 0;
1472                 session->brender_end = 0;
1473                 brender_lock->unlock();
1474         }
1475         brender_active = 0;
1476         stop_brender();
1477 }
1478
1479 void MWindow::restart_brender()
1480 {
1481 //printf("MWindow::restart_brender 1\n");
1482         if( !brender_active || !preferences->use_brender ) return;
1483         if( !brender ) return;
1484         int locked  = gui->get_window_lock();
1485         if( locked ) gui->unlock_window();
1486         brender->restart(edl);
1487         if( locked ) gui->lock_window("MWindow::restart_brender");
1488 }
1489
1490 void MWindow::stop_brender()
1491 {
1492         if( !brender ) return;
1493         int locked  = gui->get_window_lock();
1494         if( locked ) gui->unlock_window();
1495         brender->stop();
1496         if( locked ) gui->lock_window("MWindow::stop_brender");
1497 }
1498
1499 int MWindow::brender_available(int position)
1500 {
1501         int result = 0;
1502         brender_lock->lock("MWindow::brender_available 1");
1503         if(brender && brender_active)
1504         {
1505                 if(brender->map_valid)
1506                 {
1507                         brender->map_lock->lock("MWindow::brender_available 2");
1508                         if(position < brender->map_size &&
1509                                 position >= 0)
1510                         {
1511 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1512                                 if(brender->map[position] == BRender::RENDERED)
1513                                         result = 1;
1514                         }
1515                         brender->map_lock->unlock();
1516                 }
1517         }
1518         brender_lock->unlock();
1519         return result;
1520 }
1521
1522 void MWindow::set_brender_active(int v, int update)
1523 {
1524         if( !preferences->use_brender ) v = 0;
1525         brender_active = v;
1526         gui->mainmenu->brender_active->set_checked(v);
1527         if( v != 0 ) {
1528                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1529                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1530
1531                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1532                         edl->session->brender_end = edl->tracks->total_video_length();
1533                 }
1534                 restart_brender();
1535         }
1536         else {
1537                 edl->session->brender_start = edl->session->brender_end = 0;
1538                 stop_brender();
1539         }
1540         if( update ) {
1541                 gui->update_timebar(0);
1542                 gui->draw_overlays(1);
1543         }
1544 }
1545
1546 int MWindow::has_commercials()
1547 {
1548         return theme->use_commercials;
1549 }
1550
1551 void MWindow::init_commercials()
1552 {
1553         if( !commercials ) {
1554                 commercials = new Commercials(this);
1555                 commercial_active = 0;
1556         }
1557         else
1558                 commercials->add_user();
1559 }
1560
1561 void MWindow::commit_commercial()
1562 {
1563         if( !commercial_active ) return;
1564         commercial_active = 0;
1565         if( !commercials ) return;
1566         commercials->commitDb();
1567 }
1568
1569 void MWindow::undo_commercial()
1570 {
1571         if( !commercial_active ) return;
1572         commercial_active = 0;
1573         if( !commercials ) return;
1574         commercials->undoDb();
1575 }
1576
1577 int MWindow::put_commercial()
1578 {
1579         double start = edl->local_session->get_selectionstart();
1580         double end = edl->local_session->get_selectionend();
1581         if( start >= end ) return 0;
1582
1583         const char *errmsg = 0;
1584         int count = 0;
1585         Tracks *tracks = edl->tracks;
1586         int result = 0;
1587         //check it
1588         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1589                 if( track->data_type != TRACK_VIDEO ) continue;
1590                 if( !track->record ) continue;
1591                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1592                 ++count;
1593                 int64_t units_start = track->to_units(start,0);
1594                 int64_t units_end = track->to_units(end,0);
1595                 Edits *edits = track->edits;
1596                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1597                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1598                 if(!edit1 && !edit2) continue;  // nothing selected
1599                 if(!edit2) {                    // edit2 beyond end of track
1600                         edit2 = edits->last;
1601                         units_end = edits->length();
1602                 }
1603                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1604                 Indexable *indexable = edit1->get_source();
1605                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1606         }
1607         //run it
1608         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1609                 if( track->data_type != TRACK_VIDEO ) continue;
1610                 if( !track->record ) continue;
1611                 int64_t units_start = track->to_units(start,0);
1612                 int64_t units_end = track->to_units(end,0);
1613                 Edits *edits = track->edits;
1614                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1615                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1616                 if(!edit1 && !edit2) continue;  // nothing selected
1617                 if(!edit2) {                    // edit2 beyond end of track
1618                         edit2 = edits->last;
1619                         units_end = edits->length();
1620                 }
1621                 Indexable *indexable = edit1->get_source();
1622                 Asset *asset = (Asset *)indexable;
1623                 File *file = video_cache->check_out(asset, edl);
1624                 if( !file ) { errmsg = _("no file"); break; }
1625                 int64_t edit_length = units_end - units_start;
1626                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1627                 result = commercials->put_clip(file, edit1->channel,
1628                         track->from_units(edit_start), track->from_units(edit_length));
1629                 video_cache->check_in(asset);
1630                 if( result ) { errmsg = _("db failed"); break; }
1631         }
1632         if( errmsg ) {
1633                 char string[BCTEXTLEN];
1634                 sprintf(string, _("put_commercial: %s"), errmsg);
1635                 MainError::show_error(string);
1636                 undo_commercial();
1637                 result = 1;
1638         }
1639         return result;
1640 }
1641
1642 void MWindow::stop_playback(int wait)
1643 {
1644         gui->stop_drawing();
1645
1646         cwindow->stop_playback(wait);
1647
1648         for(int i = 0; i < vwindows.size(); i++) {
1649                 VWindow *vwindow = vwindows[i];
1650                 if( !vwindow->is_running() ) continue;
1651                 vwindow->stop_playback(wait);
1652         }
1653         for(int i = 0; i < zwindows.size(); i++) {
1654                 ZWindow *zwindow = zwindows[i];
1655                 if( zwindow->idx < 0 ) continue;
1656                 zwindow->stop_playback(wait);
1657         }
1658 }
1659
1660 int MWindow::load_filenames(ArrayList<char*> *filenames,
1661         int load_mode,
1662         int update_filename)
1663 {
1664         ArrayList<EDL*> new_edls;
1665         ArrayList<Asset*> new_assets;
1666         ArrayList<File*> new_files;
1667         const int debug = 0;
1668 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1669
1670 //      save_defaults();
1671         gui->start_hourglass();
1672
1673 // Need to stop playback since tracking depends on the EDL not getting
1674 // deleted.
1675         gui->unlock_window();
1676         stop_playback(1);
1677         gui->lock_window("MWindow::load_filenames 0");
1678
1679 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1680         undo->update_undo_before();
1681
1682
1683 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1684
1685 // Define new_edls and new_assets to load
1686         int result = 0, ftype = -1;
1687         for(int i = 0; i < filenames->size(); i++)
1688         {
1689 // Get type of file
1690                 File *new_file = new File;
1691                 Asset *new_asset = new Asset(filenames->get(i));
1692                 EDL *new_edl = new EDL;
1693                 char string[BCTEXTLEN];
1694
1695                 new_edl->create_objects();
1696                 new_edl->copy_session(edl);
1697                 new_file->set_program(edl->session->program_no);
1698
1699                 sprintf(string, _("Loading %s"), new_asset->path);
1700                 gui->show_message(string);
1701 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1702
1703                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1704 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1705
1706                 result = 1;
1707                 switch(ftype)
1708                 {
1709 // Convert media file to EDL
1710                         case FILE_OK:
1711 // Warn about odd image dimensions
1712                                 if(new_asset->video_data &&
1713                                         ((new_asset->width % 2) ||
1714                                         (new_asset->height % 2)))
1715                                 {
1716                                         char string[BCTEXTLEN];
1717                                         sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1718                                                 new_asset->path,
1719                                                 new_asset->width,
1720                                                 new_asset->height);
1721                                         MainError::show_error(string);
1722                                 }
1723
1724                                 if(new_asset->program >= 0 &&
1725                                         edl->session->program_no != new_asset->program)
1726                                 {
1727                                         char string[BCTEXTLEN];
1728                                         sprintf(string, _("%s's index was built for program number %d\n"
1729                                                 "Playback preference is %d.\n  Using program %d."),
1730                                                 new_asset->path, new_asset->program,
1731                                                 edl->session->program_no, new_asset->program);
1732                                         MainError::show_error(string);
1733                                 }
1734
1735
1736                                 if(load_mode != LOADMODE_RESOURCESONLY)
1737                                 {
1738                                         RecordLabels *labels = edl->session->label_cells ?
1739                                                 new RecordLabels(new_file) : 0;
1740                                         asset_to_edl(new_edl, new_asset, labels);
1741                                         new_edls.append(new_edl);
1742                                         new_asset->Garbage::remove_user();
1743                                         delete labels;
1744                                         new_asset = 0;
1745                                 }
1746                                 else
1747                                 {
1748                                         new_assets.append(new_asset);
1749                                         new_asset = 0;
1750                                 }
1751
1752 // Set filename to nothing for assets since save EDL would overwrite them.
1753                                 if(load_mode == LOADMODE_REPLACE ||
1754                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1755                                 {
1756                                         set_filename("");
1757 // Reset timeline position
1758                                         for(int i = 0; i < TOTAL_PANES; i++)
1759                                         {
1760                                                 new_edl->local_session->view_start[i] = 0;
1761                                                 new_edl->local_session->track_start[i] = 0;
1762                                         }
1763                                 }
1764
1765                                 result = 0;
1766                                 break;
1767
1768 // File not found
1769                         case FILE_NOT_FOUND:
1770                                 sprintf(string, _("Failed to open %s"), new_asset->path);
1771                                 gui->show_message(string, theme->message_error);
1772                                 gui->update_default_message();
1773                                 break;
1774
1775 // Unknown format
1776                         case FILE_UNRECOGNIZED_CODEC:
1777                         {
1778 // Test index file
1779                                 {       IndexFile indexfile(this, new_asset);
1780                                         if( !(result = indexfile.open_index()) )
1781                                                 indexfile.close_index();
1782                                 }
1783
1784 // Test existing EDLs
1785                                 for(int j = 0; result && j <= new_edls.total; j++) {
1786                                         Asset *old_asset = j < new_edls.total ?
1787                                                 new_edls[j]->assets->get_asset(new_asset->path) :
1788                                                 edl->assets->get_asset(new_asset->path);
1789                                         if( old_asset ) {
1790                                                 new_asset->copy_from(old_asset,1);
1791                                                 result = 0;
1792                                         }
1793                                 }
1794
1795 // Prompt user
1796                                 if(result)
1797                                 {
1798                                         char string[BCTEXTLEN];
1799                                         FileSystem fs;
1800                                         fs.extract_name(string, new_asset->path);
1801
1802                                         strcat(string, _("'s format couldn't be determined."));
1803                                         new_asset->audio_data = 1;
1804                                         new_asset->format = FILE_PCM;
1805                                         new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1806                                         new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1807                                         new_asset->bits = defaults->get("AUDIO_BITS", 16);
1808                                         new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1809                                         new_asset->signed_ = defaults->get("SIGNED_", 1);
1810                                         new_asset->header = defaults->get("HEADER", 0);
1811
1812                                         FileFormat fwindow(this);
1813                                         fwindow.create_objects(new_asset, string);
1814                                         result = fwindow.run_window();
1815
1816
1817                                         defaults->update("AUDIO_CHANNELS", new_asset->channels);
1818                                         defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1819                                         defaults->update("AUDIO_BITS", new_asset->bits);
1820                                         defaults->update("BYTE_ORDER", new_asset->byte_order);
1821                                         defaults->update("SIGNED_", new_asset->signed_);
1822                                         defaults->update("HEADER", new_asset->header);
1823                                         save_defaults();
1824                                 }
1825
1826 // Append to list
1827                                 if(!result)
1828                                 {
1829 // Recalculate length
1830                                         delete new_file;
1831                                         new_file = new File;
1832                                         result = new_file->open_file(preferences, new_asset, 1, 0);
1833
1834                                         if(load_mode != LOADMODE_RESOURCESONLY)
1835                                         {
1836                                                 RecordLabels *labels = edl->session->label_cells ?
1837                                                         new RecordLabels(new_file) : 0;
1838                                                 asset_to_edl(new_edl, new_asset, labels);
1839                                                 new_edls.append(new_edl);
1840                                                 new_asset->Garbage::remove_user();
1841                                                 delete labels;
1842                                                 new_asset = 0;
1843                                         }
1844                                         else
1845                                         {
1846                                                 new_assets.append(new_asset);
1847                                                 new_asset = 0;
1848                                         }
1849                                 }
1850                                 else
1851                                 {
1852                                         result = 1;
1853                                 }
1854                                 break;
1855                         }
1856
1857                         case FILE_IS_XML:
1858                         {
1859                                 FileXML xml_file;
1860 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1861                                 xml_file.read_from_file(filenames->get(i));
1862 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1863                                 const char *cin_version = 0;
1864                                 while( !xml_file.read_tag() ) {
1865                                         if( xml_file.tag.title_is("EDL") ) {
1866                                                 cin_version = xml_file.tag.get_property("VERSION");
1867                                                 break;
1868                                         }
1869                                 }
1870                                 xml_file.rewind();
1871                                 if( !cin_version ) {
1872                                         eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
1873                                         char string[BCTEXTLEN];
1874                                         sprintf(string,_("Unknown %s"), filenames->get(i));
1875                                         gui->show_message(string);
1876                                         result = 1;
1877                                         break;
1878                                 }
1879                                 if( strcmp(cin_version, CINELERRA_VERSION) ) {
1880                                         char string[BCTEXTLEN];
1881                                         snprintf(string, sizeof(string),
1882                                                  _("Warning: XML from cinelerra version %s\n"
1883                                                 "Session data may be incompatible."), cin_version);
1884                                         show_warning(&preferences->warn_version, string);
1885                                 }
1886                                 if(load_mode == LOADMODE_NESTED)
1887                                 {
1888 // Load temporary EDL for nesting.
1889                                         EDL *nested_edl = new EDL;
1890                                         nested_edl->create_objects();
1891                                         nested_edl->set_path(filenames->get(i));
1892                                         nested_edl->load_xml(&xml_file, LOAD_ALL);
1893 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
1894                                         edl_to_nested(new_edl, nested_edl);
1895                                         nested_edl->Garbage::remove_user();
1896                                 }
1897                                 else
1898                                 {
1899 // Load EDL for pasting
1900                                         new_edl->load_xml(&xml_file, LOAD_ALL);
1901 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1902                                         test_plugins(new_edl, filenames->get(i));
1903 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1904
1905                                         if(load_mode == LOADMODE_REPLACE ||
1906                                                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1907                                         {
1908                                                 strcpy(session->filename, filenames->get(i));
1909                                                 strcpy(new_edl->local_session->clip_title,
1910                                                         filenames->get(i));
1911                                                 if(update_filename)
1912                                                         set_filename(new_edl->local_session->clip_title);
1913                                         }
1914                                         else
1915                                         if( load_mode == LOADMODE_RESOURCESONLY ) {
1916                                                 strcpy(new_edl->local_session->clip_title,
1917                                                         filenames->get(i));
1918                                                 struct stat st;
1919                                                 time_t t = !stat(filenames->get(i),&st) ?
1920                                                         st.st_mtime : time(&t);
1921                                                 ctime_r(&t, new_edl->local_session->clip_notes);
1922                                         }
1923                                 }
1924
1925                                 new_edls.append(new_edl);
1926                                 result = 0;
1927                                 break;
1928                         }
1929                 }
1930
1931 // edls are in new_edls
1932                 if( result && new_edl ) new_edl->Garbage::remove_user();
1933 // assets are copied
1934                 if( new_asset ) new_asset->Garbage::remove_user();
1935
1936 // Store for testing index
1937                 new_files.append(new_file);
1938         }
1939
1940 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1941
1942
1943         if(!result) {
1944                 gui->reset_default_message();
1945                 gui->default_message();
1946         }
1947
1948
1949 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1950
1951 // Paste them.
1952 // Don't back up here.
1953         if(new_edls.size())
1954         {
1955 // For pasting, clear the active region
1956                 if(load_mode == LOADMODE_PASTE ||
1957                         load_mode == LOADMODE_NESTED)
1958                 {
1959                         double start = edl->local_session->get_selectionstart();
1960                         double end = edl->local_session->get_selectionend();
1961                         if(!EQUIV(start, end))
1962                                 edl->clear(start,
1963                                         end,
1964                                         edl->session->labels_follow_edits,
1965                                         edl->session->plugins_follow_edits,
1966                                         edl->session->autos_follow_edits);
1967                 }
1968
1969                 paste_edls(&new_edls, load_mode, 0, -1,
1970                         edl->session->labels_follow_edits,
1971                         edl->session->plugins_follow_edits,
1972                         edl->session->autos_follow_edits,
1973                         0); // overwrite
1974         }
1975
1976
1977
1978
1979 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1980
1981 // Add new assets to EDL and schedule assets for index building.
1982         int got_indexes = 0;
1983         for(int i = 0; i < new_edls.size(); i++)
1984         {
1985                 EDL *new_edl = new_edls[i];
1986                 for(int j = 0; j < new_edl->nested_edls->size(); j++)
1987                 {
1988                         mainindexes->add_next_asset(0,
1989                                 new_edl->nested_edls->get(j));
1990                         got_indexes = 1;
1991                         edl->nested_edls->update_index(new_edl->nested_edls->get(j));
1992                 }
1993
1994         }
1995
1996 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1997         for(int i = 0; i < new_assets.size(); i++)
1998         {
1999                 Asset *new_asset = new_assets[i];
2000
2001                 File *new_file = 0;
2002                 int got_it = 0;
2003                 for(int j = 0; j < new_files.size(); j++)
2004                 {
2005                         new_file = new_files[j];
2006                         if(!strcmp(new_file->asset->path,
2007                                 new_asset->path))
2008                         {
2009                                 got_it = 1;
2010                                 break;
2011                         }
2012                 }
2013
2014                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
2015                 got_indexes = 1;
2016                 edl->assets->update(new_asset);
2017         }
2018 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2019
2020 // Start examining next batch of index files
2021         if(got_indexes) mainindexes->start_build();
2022 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2023
2024 // Open plugin GUIs
2025         Track *track = edl->tracks->first;
2026         while(track)
2027         {
2028                 for(int j = 0; j < track->plugin_set.size(); j++)
2029                 {
2030                         PluginSet *plugins = track->plugin_set[j];
2031                         Plugin *plugin = plugins->get_first_plugin();
2032
2033                         while(plugin)
2034                         {
2035                                 if(load_mode == LOADMODE_REPLACE ||
2036                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
2037                                 {
2038                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
2039                                                 plugin->show)
2040                                         {
2041                                                 show_plugin(plugin);
2042                                         }
2043                                 }
2044
2045                                 plugin = (Plugin*)plugin->next;
2046                         }
2047                 }
2048
2049                 track = track->next;
2050         }
2051
2052         // if just opening one new resource in replace mode
2053         if( ftype != FILE_IS_XML &&
2054             ( load_mode == LOADMODE_REPLACE ||
2055               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
2056                 select_asset(0, 0);
2057                 edl->session->proxy_scale = 1;
2058                 edl->session->proxy_use_scaler = 0;
2059                 edl->session->proxy_auto_scale = 0;
2060                 edl->local_session->preview_start = 0;
2061                 edl->local_session->preview_end = edl->tracks->total_length();
2062                 edl->local_session->loop_playback = 0;
2063                 edl->local_session->set_selectionstart(0);
2064                 edl->local_session->set_selectionend(0);
2065                 set_brender_active(0, 0);
2066                 fit_selection();
2067                 goto_start();
2068         }
2069
2070         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2071             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2072                 ArrayList<Indexable *> orig_idxbls;
2073                 for( int i=0; i<new_assets.size(); ++i )
2074                         orig_idxbls.append(new_assets.get(i));
2075                 for( int i=0; i<new_edls.size(); ++i ) {
2076                         EDL *new_edl = new_edls[i];
2077                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2078                                 if( track->data_type != TRACK_VIDEO ) continue;
2079                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2080                                         Indexable *idxbl = (Indexable *)edit->asset;
2081                                         if( !idxbl ) continue;
2082                                         if( !idxbl->have_video() ) continue;
2083                                         if( edit->channel != 0 ) continue; // first layer only
2084                                         orig_idxbls.append(edit->asset);
2085                                 }
2086                         }
2087                 }
2088                 gui->unlock_window(); // to update progress bar
2089                 render_proxy(orig_idxbls);
2090                 gui->lock_window("MWindow::load_filenames");
2091         }
2092
2093 // need to update undo before project, since mwindow is unlocked & a new load
2094 // can begin here.  Should really prevent loading until we're done.
2095 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2096         undo->update_undo_after(_("load"), LOAD_ALL);
2097
2098         for(int i = 0; i < new_edls.size(); i++)
2099         {
2100                 new_edls[i]->remove_user();
2101         }
2102 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2103
2104         new_edls.remove_all();
2105
2106         for(int i = 0; i < new_assets.size(); i++)
2107         {
2108                 new_assets[i]->Garbage::remove_user();
2109         }
2110
2111         new_assets.remove_all();
2112         new_files.remove_all_objects();
2113
2114
2115 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2116         if(load_mode == LOADMODE_REPLACE ||
2117                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2118         {
2119                 session->changes_made = 0;
2120         }
2121         else
2122         {
2123                 session->changes_made = 1;
2124         }
2125
2126         gui->stop_hourglass();
2127
2128
2129 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2130         update_project(load_mode);
2131
2132 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2133
2134         return 0;
2135 }
2136
2137 void MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2138 {
2139         Asset *format_asset = new Asset;
2140         format_asset->format = FILE_FFMPEG;
2141         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2142         ProxyRender proxy_render(this, format_asset);
2143         int new_scale = edl->session->proxy_scale;
2144         int use_scaler = edl->session->proxy_use_scaler;
2145
2146         for( int i=0; i<new_idxbls.size(); ++i ) {
2147                 Indexable *orig = new_idxbls.get(i);
2148                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2149                 if( !proxy ) continue;
2150                 FileSystem fs;
2151                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2152                 int got_it = exists && // if proxy exists, and is newer than orig
2153                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2154                 if( got_it ) continue;
2155                 proxy_render.add_needed(orig, proxy);
2156         }
2157
2158 // render needed proxies
2159         int result = proxy_render.create_needed_proxies(new_scale);
2160         if( !result ) {
2161                 add_proxy(use_scaler,
2162                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2163         }
2164         format_asset->remove_user();
2165 }
2166
2167 void MWindow::test_plugins(EDL *new_edl, char *path)
2168 {
2169         char string[BCTEXTLEN];
2170
2171 // Do a check weather plugins exist
2172         for(Track *track = new_edl->tracks->first; track; track = track->next)
2173         {
2174                 for(int k = 0; k < track->plugin_set.total; k++)
2175                 {
2176                         PluginSet *plugin_set = track->plugin_set[k];
2177                         for(Plugin *plugin = (Plugin*)plugin_set->first;
2178                                 plugin;
2179                                 plugin = (Plugin*)plugin->next)
2180                         {
2181                                 if(plugin->plugin_type == PLUGIN_STANDALONE)
2182                                 {
2183 // ok we need to find it in plugindb
2184                                         int plugin_found = 0;
2185
2186                                         for(int j = 0; j < plugindb->size(); j++)
2187                                         {
2188                                                 PluginServer *server = plugindb->get(j);
2189                                                 if(server->title &&
2190                                                         !strcasecmp(server->title, plugin->title) &&
2191                                                         ((track->data_type == TRACK_AUDIO && server->audio) ||
2192                                                         (track->data_type == TRACK_VIDEO && server->video)) &&
2193                                                         (!server->transition))
2194                                                         plugin_found = 1;
2195                                         }
2196
2197                                         if (!plugin_found)
2198                                         {
2199                                                 sprintf(string,
2200         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2201           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2202                                                         "effect", plugin->title,
2203                                                         path);
2204                                                 MainError::show_error(string);
2205                                         }
2206                                 }
2207                         }
2208                 }
2209
2210                 for(Edit *edit = (Edit*)track->edits->first;
2211                         edit;
2212                         edit = (Edit*)edit->next)
2213                 {
2214                         if (edit->transition)
2215                         {
2216 // ok we need to find transition in plugindb
2217
2218                                 int transition_found = 0;
2219                                 for(int j = 0; j < plugindb->size(); j++)
2220                                 {
2221                                         PluginServer *server = plugindb->get(j);
2222                                         if(server->title &&
2223                                                 !strcasecmp(server->title, edit->transition->title) &&
2224                                                 ((track->data_type == TRACK_AUDIO && server->audio) ||
2225                                                 (track->data_type == TRACK_VIDEO && server->video)) &&
2226                                                 (server->transition))
2227                                                 transition_found = 1;
2228                                 }
2229
2230                                 if (!transition_found)
2231                                 {
2232                                         sprintf(string,
2233         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2234           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2235                                                 "transition", edit->transition->title,
2236                                                 path);
2237                                         MainError::show_error(string);
2238                                 }
2239                         }
2240                 }
2241         }
2242 }
2243
2244
2245 void MWindow::init_shm()
2246 {
2247 // Fix shared memory
2248         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
2249         if(fd) {
2250                 fprintf(fd, "0x7fffffff");
2251                 fclose(fd);
2252         }
2253         fd = 0;
2254
2255         fd = fopen("/proc/sys/kernel/shmmax", "r");
2256         if(!fd) {
2257                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
2258                 return;
2259         }
2260
2261         int64_t result = 0;
2262         fscanf(fd, "%jd", &result);
2263         fclose(fd);
2264         fd = 0;
2265         if(result < 0x7fffffff) {
2266                 eprintf(_("MWindow::init_shm: /proc/sys/kernel/shmmax is %p.\n"
2267                         "you probably need to be root, or:\n"
2268                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
2269                         "before trying to start cinelerra.\n"
2270                         "It should be at least 0x7fffffff for Cinelerra.\n"), (void *)result);
2271         }
2272 }
2273
2274 void MWindow::create_objects(int want_gui,
2275         int want_new,
2276         char *config_path)
2277 {
2278         const int debug = 0;
2279         if(debug) PRINT_TRACE
2280
2281 // For some reason, init_signals must come after show_splash or the signals won't
2282 // get trapped.
2283         init_signals();
2284         if(debug) PRINT_TRACE
2285         init_3d();
2286
2287         if(debug) PRINT_TRACE
2288         show_splash();
2289
2290         if(debug) PRINT_TRACE
2291         default_standard = default_std();
2292         init_defaults(defaults, config_path);
2293         check_language();
2294         init_preferences();
2295         if(splash_window)
2296                 splash_window->operation->update(_("Initializing Plugins"));
2297         init_plugins(this, preferences);
2298         if(debug) PRINT_TRACE
2299         init_ladspa_plugins(this, preferences);
2300         if(debug) PRINT_TRACE
2301         init_plugin_tips(*plugindb, cin_lang);
2302         if(splash_window)
2303                 splash_window->operation->update(_("Initializing GUI"));
2304         if(debug) PRINT_TRACE
2305         init_theme();
2306
2307         if(debug) PRINT_TRACE
2308         init_error();
2309
2310         if(splash_window)
2311                 splash_window->operation->update(_("Initializing Fonts"));
2312         char string[BCTEXTLEN];
2313         strcpy(string, preferences->plugin_dir);
2314         strcat(string, "/" FONT_SEARCHPATH);
2315         BC_Resources::init_fontconfig(string);
2316         if(debug) PRINT_TRACE
2317
2318 // Initialize before too much else is running
2319 // Preferences & theme are required for building MPEG table of contents
2320
2321 // Default project created here
2322         init_edl();
2323         if(debug) PRINT_TRACE
2324
2325         init_cache();
2326         if(debug) PRINT_TRACE
2327
2328         Timer timer;
2329
2330         init_awindow();
2331         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2332
2333         init_compositor();
2334         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2335
2336 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2337         if(session->show_vwindow)
2338                 get_viewer(1, DEFAULT_VWINDOW);
2339         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2340
2341         init_gui();
2342         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2343
2344         init_levelwindow();
2345         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2346
2347         init_indexes();
2348         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2349
2350         init_channeldb();
2351         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2352
2353         init_gwindow();
2354         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2355
2356         init_render();
2357         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2358
2359         init_brender();
2360         init_exportedl();
2361         init_commercials();
2362         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2363         mainprogress = new MainProgress(this, gui);
2364         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2365         undo = new MainUndo(this);
2366
2367         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2368
2369         plugin_guis = new ArrayList<PluginServer*>;
2370         dead_plugins = new ArrayList<PluginServer*>;
2371         keyframe_threads = new ArrayList<KeyFrameThread*>;
2372
2373         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2374                 __LINE__,
2375                 vwindows.size(),
2376                 session->show_vwindow);
2377
2378 // Show all vwindows
2379 //      if(session->show_vwindow) {
2380 //              for(int j = 0; j < vwindows.size(); j++) {
2381 //                      VWindow *vwindow = vwindows[j];
2382 //                      if( !vwindow->is_running() ) continue;
2383 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2384 //                              __LINE__,
2385 //                              vwindow);
2386 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2387 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2388 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2389 //                      vwindow->gui->show_window();
2390 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2391 //                      vwindow->gui->unlock_window();
2392 //              }
2393 //      }
2394
2395
2396         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2397
2398         if(session->show_cwindow)
2399         {
2400                 cwindow->gui->lock_window("MWindow::create_objects 1");
2401                 cwindow->gui->show_window();
2402                 cwindow->gui->unlock_window();
2403         }
2404
2405         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2406         if(session->show_awindow)
2407         {
2408                 awindow->gui->lock_window("MWindow::create_objects 1");
2409                 awindow->gui->show_window();
2410                 awindow->gui->unlock_window();
2411         }
2412
2413         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2414         if(session->show_lwindow)
2415         {
2416                 lwindow->gui->lock_window("MWindow::create_objects 1");
2417                 lwindow->gui->show_window();
2418                 lwindow->gui->unlock_window();
2419         }
2420
2421         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2422                 __LINE__,
2423                 (int)timer.get_difference(),
2424                 gwindow->gui);
2425         if(session->show_gwindow)
2426         {
2427                 gwindow->gui->lock_window("MWindow::create_objects 1");
2428                 gwindow->gui->show_window();
2429                 gwindow->gui->unlock_window();
2430         }
2431
2432         if(debug) PRINT_TRACE
2433
2434         gui->lock_window("MWindow::create_objects 1");
2435         gui->mainmenu->load_defaults(defaults);
2436         gui->mainmenu->update_toggles(0);
2437         gui->update_patchbay();
2438         gui->draw_canvas(0, 0);
2439         gui->draw_cursor(1);
2440         gui->show_window();
2441         gui->raise_window();
2442         gui->unlock_window();
2443
2444         if(debug) PRINT_TRACE
2445
2446         if(preferences->use_tipwindow)
2447                 init_tipwindow();
2448         if(debug) PRINT_TRACE
2449
2450         gui->add_keyboard_listener(
2451                 (int (BC_WindowBase::*)(BC_WindowBase *))
2452                 &MWindowGUI::keyboard_listener);
2453
2454         hide_splash();
2455         init_shm();
2456         if(debug) PRINT_TRACE
2457
2458         BC_WindowBase::get_resources()->vframe_shm = 1;
2459 }
2460
2461
2462 void MWindow::show_splash()
2463 {
2464 #include "data/heroine_logo9_png.h"
2465         VFrame *frame = new VFramePng(heroine_logo9_png);
2466         BC_DisplayInfo dpyi;
2467         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2468         int rr = (rw < rh ? rw : rh) / 4;
2469         splash_window = new SplashGUI(frame, rr, rr);
2470         splash_window->create_objects();
2471 }
2472
2473 void MWindow::hide_splash()
2474 {
2475         if(splash_window)
2476                 delete splash_window;
2477         splash_window = 0;
2478 }
2479
2480
2481 void MWindow::start()
2482 {
2483 ENABLE_BUFFER
2484 //PRINT_TRACE
2485 //      vwindows[DEFAULT_VWINDOW]->start();
2486         awindow->start();
2487 //PRINT_TRACE
2488         cwindow->start();
2489 //PRINT_TRACE
2490         lwindow->start();
2491 //PRINT_TRACE
2492         gwindow->start();
2493 //PRINT_TRACE
2494 //      Thread::start();
2495 //PRINT_TRACE
2496         playback_3d->start();
2497 //PRINT_TRACE
2498 }
2499
2500 void MWindow::run()
2501 {
2502         run_lock->lock("MWindow::run");
2503         gui->run_window();
2504         stop_playback(1);
2505
2506         brender_lock->lock("MWindow::run 1");
2507         delete brender;         brender = 0;
2508         brender_lock->unlock();
2509
2510         interrupt_indexes();
2511         clean_indexes();
2512         save_defaults();
2513         run_lock->unlock();
2514 }
2515
2516 void MWindow::show_vwindow()
2517 {
2518         int total_running = 0;
2519         session->show_vwindow = 1;
2520
2521 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2522 // Raise all windows which are visible
2523         for(int j = 0; j < vwindows.size(); j++) {
2524                 VWindow *vwindow = vwindows[j];
2525                 if( !vwindow->is_running() ) continue;
2526                 vwindow->gui->lock_window("MWindow::show_vwindow");
2527                 vwindow->gui->show_window(0);
2528                 vwindow->gui->raise_window();
2529                 vwindow->gui->flush();
2530                 vwindow->gui->unlock_window();
2531                 total_running++;
2532         }
2533
2534 // If no windows visible
2535         if(!total_running)
2536         {
2537                 get_viewer(1, DEFAULT_VWINDOW);
2538         }
2539
2540         gui->mainmenu->show_vwindow->set_checked(1);
2541 }
2542
2543 void MWindow::show_awindow()
2544 {
2545         session->show_awindow = 1;
2546         awindow->gui->lock_window("MWindow::show_awindow");
2547         awindow->gui->show_window();
2548         awindow->gui->raise_window();
2549         awindow->gui->flush();
2550         awindow->gui->unlock_window();
2551         gui->mainmenu->show_awindow->set_checked(1);
2552 }
2553
2554 char *MWindow::get_cwindow_display()
2555 {
2556         char *x11_host = screens < 2 || session->window_config == 0 ?
2557                 session->a_x11_host : session->b_x11_host;
2558         return *x11_host ? x11_host : 0;
2559 }
2560
2561 void MWindow::show_cwindow()
2562 {
2563         session->show_cwindow = 1;
2564         cwindow->show_window();
2565         gui->mainmenu->show_cwindow->set_checked(1);
2566 }
2567
2568 void MWindow::show_gwindow()
2569 {
2570         session->show_gwindow = 1;
2571
2572         gwindow->gui->lock_window("MWindow::show_gwindow");
2573         gwindow->gui->show_window();
2574         gwindow->gui->raise_window();
2575         gwindow->gui->flush();
2576         gwindow->gui->unlock_window();
2577
2578         gui->mainmenu->show_gwindow->set_checked(1);
2579 }
2580 void MWindow::hide_gwindow()
2581 {
2582         session->show_gwindow = 0;
2583
2584         gwindow->gui->lock_window("MWindow::show_gwindow");
2585         gwindow->gui->hide_window();
2586         gwindow->gui->unlock_window();
2587 }
2588
2589 void MWindow::show_lwindow()
2590 {
2591         session->show_lwindow = 1;
2592         lwindow->gui->lock_window("MWindow::show_lwindow");
2593         lwindow->gui->show_window();
2594         lwindow->gui->raise_window();
2595         lwindow->gui->flush();
2596         lwindow->gui->unlock_window();
2597         gui->mainmenu->show_lwindow->set_checked(1);
2598 }
2599
2600 int MWindow::tile_windows(int window_config)
2601 {
2602         int need_reload = 0;
2603         int play_config = window_config==0 ? 0 : 1;
2604         edl->session->playback_config->load_defaults(defaults, play_config);
2605         session->default_window_positions(window_config);
2606         if( screens == 1 ) {
2607                 gui->default_positions();
2608                 sync_parameters(CHANGE_ALL);
2609         }
2610         else
2611                 need_reload = 1;
2612         return need_reload;
2613 }
2614
2615 void MWindow::toggle_loop_playback()
2616 {
2617         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2618         set_loop_boundaries();
2619         save_backup();
2620
2621         gui->draw_overlays(1);
2622         sync_parameters(CHANGE_PARAMS);
2623 }
2624
2625 //void MWindow::set_titles(int value)
2626 //{
2627 //      edl->session->show_titles = value;
2628 //      trackmovement(edl->local_session->track_start);
2629 //}
2630
2631 void MWindow::set_screens(int value)
2632 {
2633         screens = value;
2634 }
2635
2636 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2637 {
2638         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2639         edl->session->auto_keyframes = value;
2640         gui->mbuttons->edit_panel->keyframe->update(value);
2641         gui->flush();
2642         if(lock_mwindow) gui->unlock_window();
2643
2644         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2645         cwindow->gui->edit_panel->keyframe->update(value);
2646         cwindow->gui->flush();
2647         if(lock_cwindow) cwindow->gui->unlock_window();
2648 }
2649
2650 void MWindow::set_auto_visibility(Autos *autos, int value)
2651 {
2652         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2653                 edl->session->auto_conf->plugins = value;
2654         else if( autos->autoidx >= 0 )
2655                 edl->session->auto_conf->autos[autos->autoidx] = value;
2656         else
2657                 return;
2658
2659         gui->update(0, 1, 0, 0, 0, 0, 0);
2660         gui->mainmenu->update_toggles(1);
2661         gui->unlock_window();
2662         gwindow->gui->update_toggles(1);
2663         gui->lock_window("MWindow::set_auto_visibility");
2664 }
2665
2666 void MWindow::set_keyframe_type(int mode)
2667 {
2668         gui->lock_window("MWindow::set_keyframe_type");
2669         edl->local_session->floatauto_type = mode;
2670         gui->mainmenu->update_toggles(0);
2671         gui->unlock_window();
2672 }
2673
2674 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2675 {
2676         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2677         edl->session->editing_mode = new_editing_mode;
2678         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2679         gui->mbuttons->edit_panel->update();
2680         gui->set_editing_mode(1);
2681         if(lock_mwindow) gui->unlock_window();
2682
2683
2684         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2685         cwindow->gui->edit_panel->update();
2686         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2687         if(lock_cwindow) cwindow->gui->unlock_window();
2688         return 0;
2689 }
2690
2691 void MWindow::toggle_editing_mode()
2692 {
2693         int mode = edl->session->editing_mode;
2694         if( mode == EDITING_ARROW )
2695                 set_editing_mode(EDITING_IBEAM, 0, 1);
2696         else
2697                 set_editing_mode(EDITING_ARROW, 0, 1);
2698 }
2699
2700
2701 void MWindow::set_labels_follow_edits(int value)
2702 {
2703         gui->lock_window("MWindow::set_labels_follow_edits");
2704         edl->session->labels_follow_edits = value;
2705         gui->mbuttons->edit_panel->locklabels->update(value);
2706         gui->mainmenu->labels_follow_edits->set_checked(value);
2707         gui->flush();
2708         gui->unlock_window();
2709 }
2710
2711 void MWindow::sync_parameters(int change_type)
2712 {
2713         if( in_destructor ) return;
2714
2715 // Sync engines which are playing back
2716         if(cwindow->playback_engine->is_playing_back)
2717         {
2718                 if(change_type == CHANGE_PARAMS)
2719                 {
2720 // TODO: block keyframes until synchronization is done
2721                         cwindow->playback_engine->sync_parameters(edl);
2722                 }
2723                 else
2724 // Stop and restart
2725                 {
2726                         int command = cwindow->playback_engine->command->command;
2727                         cwindow->playback_engine->que->send_command(STOP,
2728                                 CHANGE_NONE,
2729                                 0,
2730                                 0);
2731 // Waiting for tracking to finish would make the restart position more
2732 // accurate but it can't lock the window to stop tracking for some reason.
2733 // Not waiting for tracking gives a faster response but restart position is
2734 // only as accurate as the last tracking update.
2735                         cwindow->playback_engine->interrupt_playback(0);
2736                         cwindow->playback_engine->que->send_command(command,
2737                                         change_type,
2738                                         edl,
2739                                         1,
2740                                         0);
2741                 }
2742         }
2743         else
2744         {
2745                 cwindow->refresh_frame(change_type);
2746         }
2747 }
2748
2749 void MWindow::age_caches()
2750 {
2751 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
2752 // __LINE__,
2753 // preferences->cache_size,
2754 // audio_cache->get_memory_usage(1),
2755 // video_cache->get_memory_usage(1),
2756 // frame_cache->get_memory_usage(),
2757 // wave_cache->get_memory_usage(),
2758 // memory_usage);
2759         frame_cache->age_cache(512);
2760         wave_cache->age_cache(8192);
2761
2762         int64_t memory_usage;
2763         int64_t prev_memory_usage = 0;
2764         int result = 0;
2765         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2766         while( !result && prev_memory_usage !=
2767                 (memory_usage=video_cache->get_memory_usage(1)) &&
2768                 memory_usage > video_size ) {
2769                 video_cache->delete_oldest();
2770                 prev_memory_usage = memory_usage;
2771         }
2772
2773         prev_memory_usage = 0;
2774         result = 0;
2775         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2776         while( !result && prev_memory_usage !=
2777                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2778                 memory_usage > audio_size ) {
2779                 audio_cache->delete_oldest();
2780                 prev_memory_usage = memory_usage;
2781         }
2782 }
2783
2784 void MWindow::reset_android_remote()
2785 {
2786         gui->use_android_remote(preferences->android_remote);
2787 }
2788
2789
2790 void MWindow::show_keyframe_gui(Plugin *plugin)
2791 {
2792         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2793 // Find existing thread
2794         for(int i = 0; i < keyframe_threads->size(); i++)
2795         {
2796                 if(keyframe_threads->get(i)->plugin == plugin)
2797                 {
2798                         keyframe_threads->get(i)->start_window(plugin, 0);
2799                         keyframe_gui_lock->unlock();
2800                         return;
2801                 }
2802         }
2803
2804 // Find unused thread
2805         for(int i = 0; i < keyframe_threads->size(); i++)
2806         {
2807                 if(!keyframe_threads->get(i)->plugin)
2808                 {
2809                         keyframe_threads->get(i)->start_window(plugin, 0);
2810                         keyframe_gui_lock->unlock();
2811                         return;
2812                 }
2813         }
2814
2815 // Create new thread
2816         KeyFrameThread *thread = new KeyFrameThread(this);
2817         keyframe_threads->append(thread);
2818         thread->start_window(plugin, 0);
2819
2820         keyframe_gui_lock->unlock();
2821 }
2822
2823
2824
2825
2826
2827 void MWindow::show_plugin(Plugin *plugin)
2828 {
2829         int done = 0;
2830
2831 SET_TRACE
2832 // Remove previously deleted plugin GUIs
2833         dead_plugin_lock->lock("MWindow::show_plugin");
2834         dead_plugins->remove_all_objects();
2835         dead_plugin_lock->unlock();
2836
2837 //printf("MWindow::show_plugin %d\n", __LINE__);
2838 SET_TRACE
2839
2840
2841         plugin_gui_lock->lock("MWindow::show_plugin");
2842         for(int i = 0; i < plugin_guis->total; i++)
2843         {
2844 // Pointer comparison
2845                 if(plugin_guis->get(i)->plugin == plugin)
2846                 {
2847                         plugin_guis->get(i)->raise_window();
2848                         done = 1;
2849                         break;
2850                 }
2851         }
2852 SET_TRACE
2853
2854 //printf("MWindow::show_plugin 1\n");
2855         if( !done && !plugin->track ) {
2856                 printf("MWindow::show_plugin track not defined.\n");
2857                 done = 1;
2858         }
2859         if( !done ) {
2860                 PluginServer *server = scan_plugindb(plugin->title,
2861                         plugin->track->data_type);
2862
2863 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2864                 if(server && server->uses_gui)
2865                 {
2866                         PluginServer *gui = new PluginServer(*server);
2867                         plugin_guis->append(gui);
2868 // Needs mwindow to do GUI
2869                         gui->set_mwindow(this);
2870                         gui->open_plugin(0, preferences, edl, plugin);
2871                         plugin->show = 1;
2872                         gui->show_gui();
2873                 }
2874         }
2875         plugin_gui_lock->unlock();
2876 //printf("MWindow::show_plugin %d\n", __LINE__);
2877 SET_TRACE
2878 //sleep(1);
2879 //printf("MWindow::show_plugin 2\n");
2880 }
2881
2882 void MWindow::hide_plugin(Plugin *plugin, int lock)
2883 {
2884         plugin->show = 0;
2885 // Update the toggle
2886         gui->lock_window("MWindow::hide_plugin");
2887         gui->update(0, 1, 0, 0, 0, 0, 0);
2888         gui->unlock_window();
2889
2890         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2891         for(int i = 0; i < plugin_guis->total; i++)
2892         {
2893                 if(plugin_guis->get(i)->plugin == plugin)
2894                 {
2895                         PluginServer *ptr = plugin_guis->get(i);
2896                         plugin_guis->remove(ptr);
2897                         if(lock) plugin_gui_lock->unlock();
2898 // Last command executed in client side close
2899 // Schedule for deletion
2900                         ptr->hide_gui();
2901                         delete_plugin(ptr);
2902 //sleep(1);
2903                         return;
2904                 }
2905         }
2906         if(lock) plugin_gui_lock->unlock();
2907 }
2908
2909 void MWindow::delete_plugin(PluginServer *plugin)
2910 {
2911         dead_plugin_lock->lock("MWindow::delete_plugin");
2912         dead_plugins->append(plugin);
2913         dead_plugin_lock->unlock();
2914 }
2915
2916 void MWindow::hide_plugins()
2917 {
2918         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2919         while(plugin_guis->size())
2920         {
2921                 PluginServer *ptr = plugin_guis->get(0);
2922                 plugin_guis->remove(ptr);
2923                 plugin_gui_lock->unlock();
2924 // Last command executed in client side close
2925 // Schedule for deletion
2926                 ptr->hide_gui();
2927                 delete_plugin(ptr);
2928                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2929         }
2930         plugin_gui_lock->unlock();
2931
2932         hide_keyframe_guis();
2933 }
2934
2935 void MWindow::hide_keyframe_guis()
2936 {
2937         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2938         for(int i = 0; i < keyframe_threads->size(); i++)
2939         {
2940                 keyframe_threads->get(i)->close_window();
2941         }
2942         keyframe_gui_lock->unlock();
2943 }
2944
2945 void MWindow::hide_keyframe_gui(Plugin *plugin)
2946 {
2947         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2948         for(int i = 0; i < keyframe_threads->size(); i++)
2949         {
2950                 if(keyframe_threads->get(i)->plugin == plugin)
2951                 {
2952                         keyframe_threads->get(i)->close_window();
2953                         break;
2954                 }
2955         }
2956         keyframe_gui_lock->unlock();
2957 }
2958
2959 void MWindow::update_keyframe_guis()
2960 {
2961 // Send new configuration to keyframe GUI's
2962         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2963         for(int i = 0; i < keyframe_threads->size(); i++)
2964         {
2965                 KeyFrameThread *ptr = keyframe_threads->get(i);
2966                 if(edl->tracks->plugin_exists(ptr->plugin))
2967                         ptr->update_gui(1);
2968                 else
2969                 {
2970                         ptr->close_window();
2971                 }
2972         }
2973         keyframe_gui_lock->unlock();
2974 }
2975
2976 void MWindow::update_plugin_guis(int do_keyframe_guis)
2977 {
2978 // Send new configuration to plugin GUI's
2979         plugin_gui_lock->lock("MWindow::update_plugin_guis");
2980
2981         for(int i = 0; i < plugin_guis->size(); i++)
2982         {
2983                 PluginServer *ptr = plugin_guis->get(i);
2984                 if(edl->tracks->plugin_exists(ptr->plugin))
2985                         ptr->update_gui();
2986                 else
2987                 {
2988 // Schedule for deletion if no plugin
2989                         plugin_guis->remove_number(i);
2990                         i--;
2991
2992                         ptr->hide_gui();
2993                         delete_plugin(ptr);
2994                 }
2995         }
2996
2997
2998 // Change plugin variable if not visible
2999         Track *track = edl->tracks->first;
3000         while(track)
3001         {
3002                 for(int i = 0; i < track->plugin_set.size(); i++)
3003                 {
3004                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3005                         while(plugin)
3006                         {
3007                                 int got_it = 0;
3008                                 for(int i = 0; i < plugin_guis->size(); i++)
3009                                 {
3010                                         PluginServer *server = plugin_guis->get(i);
3011                                         if(server->plugin == plugin)
3012                                         {
3013                                                 got_it = 1;
3014                                                 break;
3015                                         }
3016                                 }
3017
3018                                 if(!got_it) plugin->show = 0;
3019
3020                                 plugin = (Plugin*)plugin->next;
3021                         }
3022                 }
3023
3024                 track = track->next;
3025         }
3026
3027         plugin_gui_lock->unlock();
3028
3029
3030         if(do_keyframe_guis) update_keyframe_guis();
3031 }
3032
3033 int MWindow::plugin_gui_open(Plugin *plugin)
3034 {
3035         int result = 0;
3036         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3037         for(int i = 0; i < plugin_guis->total; i++)
3038         {
3039                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3040                 {
3041                         result = 1;
3042                         break;
3043                 }
3044         }
3045         plugin_gui_lock->unlock();
3046         return result;
3047 }
3048
3049 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3050 {
3051         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3052         for(int i = 0; i < plugin_guis->total; i++)
3053         {
3054                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3055                 {
3056                         plugin_guis->get(i)->render_gui(data);
3057                         break;
3058                 }
3059         }
3060         plugin_gui_lock->unlock();
3061 }
3062
3063 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3064 {
3065         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3066         for(int i = 0; i < plugin_guis->total; i++)
3067         {
3068                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3069                 {
3070                         plugin_guis->get(i)->render_gui(data, size);
3071                         break;
3072                 }
3073         }
3074         plugin_gui_lock->unlock();
3075 }
3076
3077
3078 void MWindow::update_plugin_states()
3079 {
3080         plugin_gui_lock->lock("MWindow::update_plugin_states");
3081         for(int i = 0; i < plugin_guis->total; i++)
3082         {
3083                 int result = 0;
3084 // Get a plugin GUI
3085                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
3086                 PluginServer *src_plugingui = plugin_guis->get(i);
3087
3088 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
3089                 for(Track *track = edl->tracks->first;
3090                         track && !result;
3091                         track = track->next)
3092                 {
3093                         for(int j = 0;
3094                                 j < track->plugin_set.total && !result;
3095                                 j++)
3096                         {
3097                                 PluginSet *plugin_set = track->plugin_set[j];
3098                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
3099                                         plugin && !result;
3100                                         plugin = (Plugin*)plugin->next)
3101                                 {
3102                                         if(plugin == src_plugin &&
3103                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
3104                                 }
3105                         }
3106                 }
3107
3108
3109 // Doesn't exist anymore
3110                 if(!result)
3111                 {
3112                         hide_plugin(src_plugin, 0);
3113                         i--;
3114                 }
3115         }
3116         plugin_gui_lock->unlock();
3117 }
3118
3119
3120 void MWindow::update_plugin_titles()
3121 {
3122         for(int i = 0; i < plugin_guis->total; i++)
3123         {
3124                 plugin_guis->get(i)->update_title();
3125         }
3126 }
3127
3128 int MWindow::asset_to_edl(EDL *new_edl,
3129         Asset *new_asset,
3130         RecordLabels *labels)
3131 {
3132 const int debug = 0;
3133 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3134 __LINE__,
3135 new_asset->layers);
3136 // Keep frame rate, sample rate, and output size unchanged.
3137 // These parameters would revert the project if VWindow displayed an asset
3138 // of different size than the project.
3139         if(new_asset->video_data)
3140         {
3141                 new_edl->session->video_tracks = new_asset->layers;
3142         }
3143         else
3144                 new_edl->session->video_tracks = 0;
3145
3146 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3147
3148
3149
3150
3151
3152         if(new_asset->audio_data)
3153         {
3154                 new_edl->session->audio_tracks = new_asset->channels;
3155         }
3156         else
3157                 new_edl->session->audio_tracks = 0;
3158 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3159
3160 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3161         new_edl->create_default_tracks();
3162 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3163 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3164
3165
3166
3167 //printf("MWindow::asset_to_edl 3\n");
3168         new_edl->insert_asset(new_asset,
3169                 0,
3170                 0,
3171                 0,
3172                 labels);
3173 //printf("MWindow::asset_to_edl 3\n");
3174 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3175
3176 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3177         if(edl->session->cursor_on_frames)
3178         {
3179                 double length = new_edl->tracks->total_length();
3180                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3181                 new_edl->tracks->clear(length, edl_length, 1, 1);
3182         }
3183
3184
3185
3186
3187         char string[BCTEXTLEN];
3188         FileSystem fs;
3189         fs.extract_name(string, new_asset->path);
3190 //printf("MWindow::asset_to_edl 3\n");
3191
3192         strcpy(new_edl->local_session->clip_title, string);
3193 //printf("MWindow::asset_to_edl 4 %s\n", string);
3194 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3195
3196         return 0;
3197 }
3198
3199 int MWindow::edl_to_nested(EDL *new_edl,
3200         EDL *nested_edl)
3201 {
3202
3203 // Keep frame rate, sample rate, and output size unchanged.
3204 // These parameters would revert the project if VWindow displayed an asset
3205 // of different size than the project.
3206
3207
3208
3209 // Nest all video & audio outputs
3210         new_edl->session->video_tracks = 1;
3211         new_edl->session->audio_tracks = nested_edl->session->audio_channels;
3212         new_edl->create_default_tracks();
3213
3214
3215
3216         new_edl->insert_asset(0,
3217                 nested_edl,
3218                 0,
3219                 0,
3220                 0);
3221
3222         char string[BCTEXTLEN];
3223         FileSystem fs;
3224         fs.extract_name(string, nested_edl->path);
3225 //printf("MWindow::edl_to_nested %p %s\n", nested_edl, nested_edl->path);
3226
3227         strcpy(new_edl->local_session->clip_title, string);
3228
3229         return 0;
3230 }
3231
3232 // Reset everything after a load.
3233 void MWindow::update_project(int load_mode)
3234 {
3235         const int debug = 0;
3236
3237         if(debug) PRINT_TRACE
3238         init_brender();
3239         edl->tracks->update_y_pixels(theme);
3240
3241         if(debug) PRINT_TRACE
3242
3243         if(load_mode == LOADMODE_REPLACE ||
3244                 load_mode == LOADMODE_REPLACE_CONCATENATE)
3245         {
3246                 gui->load_panes();
3247         }
3248
3249         gui->update(1, 1, 1, 1, 1, 1, 1);
3250         if(debug) PRINT_TRACE
3251         gui->unlock_window();
3252
3253         cwindow->gui->lock_window("MWindow::update_project 1");
3254         cwindow->update(0, 0, 1, 1, 1);
3255         cwindow->gui->unlock_window();
3256
3257         if(debug) PRINT_TRACE
3258
3259 // Close all the vwindows
3260         if( load_mode == LOADMODE_REPLACE ||
3261             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3262                 if(debug) PRINT_TRACE
3263                 int first_vwindow = 0;
3264                 if(session->show_vwindow) first_vwindow = 1;
3265 // Change visible windows to no source
3266                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3267                         VWindow *vwindow = vwindows[i];
3268                         if( !vwindow->is_running() ) continue;
3269                         vwindow->change_source(-1);
3270                 }
3271
3272 // Close remaining windows
3273                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3274                         VWindow *vwindow = vwindows[i];
3275                         if( !vwindow->is_running() ) continue;
3276                         vwindow->close_window();
3277                 }
3278                 if(debug) PRINT_TRACE
3279                 select_zwindow(0);
3280                 close_mixers();
3281
3282                 for( int i=0; i<edl->mixers.size(); ++i ) {
3283                         Mixer *mixer = edl->mixers[i];
3284                         ZWindow *zwindow = get_mixer(mixer);
3285                         zwindow->set_title(mixer->title);
3286                         zwindow->start();
3287                 }
3288         }
3289         else {
3290                 if(vwindows.size()) {
3291                         VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
3292                         if( vwindow->is_running() ) {
3293                                 vwindow->gui->lock_window("MWindow::update_project");
3294                                 vwindow->update(1);
3295                                 vwindow->gui->unlock_window();
3296                         }
3297                 }
3298         }
3299
3300         if(debug) PRINT_TRACE
3301         cwindow->gui->lock_window("MWindow::update_project 2");
3302         cwindow->gui->timebar->update(0);
3303         cwindow->gui->unlock_window();
3304
3305         if(debug) PRINT_TRACE
3306         cwindow->refresh_frame(CHANGE_ALL);
3307
3308         awindow->gui->async_update_assets();
3309         if(debug) PRINT_TRACE
3310
3311         gui->lock_window("MWindow::update_project");
3312         gui->update_mixers(0, 0);
3313         gui->flush();
3314         if(debug) PRINT_TRACE
3315 }
3316
3317 void MWindow::remove_indexfile(Indexable *indexable)
3318 {
3319         if( !indexable->is_asset ) return;
3320         Asset *asset = (Asset *)indexable;
3321 // Erase file
3322         IndexFile::delete_index(preferences, asset, ".toc");
3323         IndexFile::delete_index(preferences, asset, ".idx");
3324         IndexFile::delete_index(preferences, asset, ".mkr");
3325 }
3326
3327 void MWindow::rebuild_indices()
3328 {
3329         for(int i = 0; i < session->drag_assets->total; i++)
3330         {
3331                 Indexable *indexable = session->drag_assets->get(i);
3332 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3333                 remove_indexfile(indexable);
3334 // Schedule index build
3335                 IndexState *index_state = indexable->index_state;
3336                 index_state->index_status = INDEX_NOTTESTED;
3337                 if( indexable->is_asset ) {
3338                         Asset *asset = (Asset *)indexable;
3339                         if( asset->format != FILE_PCM ) {
3340                                 asset->format = FILE_UNKNOWN;
3341                                 asset->reset_audio();
3342                         }
3343                         asset->reset_video();
3344 //                      File file; // re-probe the asset
3345 //                      file.open_file(preferences, asset, 1, 0);
3346                 }
3347                 mainindexes->add_next_asset(0, indexable);
3348         }
3349         mainindexes->start_build();
3350 }
3351
3352
3353 void MWindow::save_backup()
3354 {
3355         FileXML file;
3356         edl->optimize();
3357         edl->set_path(session->filename);
3358         char backup_path[BCTEXTLEN];
3359         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3360                 File::get_config_path(), BACKUP_FILE);
3361         edl->save_xml(&file, backup_path, 0, 0);
3362         file.terminate_string();
3363         FileSystem fs;
3364         fs.complete_path(backup_path);
3365
3366         if(file.write_to_file(backup_path))
3367         {
3368                 char string2[256];
3369                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3370                 gui->show_message(string2);
3371         }
3372 }
3373
3374 void MWindow::load_backup()
3375 {
3376         ArrayList<char*> path_list;
3377         path_list.set_array_delete();
3378         char *out_path;
3379         char backup_path[BCTEXTLEN];
3380         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3381                 File::get_config_path(), BACKUP_FILE);
3382         FileSystem fs;
3383         fs.complete_path(backup_path);
3384
3385         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3386         strcpy(out_path, backup_path);
3387
3388         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3389         edl->local_session->clip_title[0] = 0;
3390 // This is unique to backups since the path of the backup is different than the
3391 // path of the project.
3392         set_filename(edl->path);
3393         path_list.remove_all_objects();
3394         save_backup();
3395 }
3396
3397 static inline int gcd(int m, int n)
3398 {
3399         int r;
3400         if( m < n ) { r = m;  m = n;  n = r; }
3401         while( (r = m % n) != 0 ) { m = n;  n = r; }
3402         return n;
3403 }
3404
3405 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3406 {
3407         w = 1;  h = 1;
3408         if(!width || !height) return 1;
3409         if( width == 720 && (height == 480 || height == 576) ) {
3410                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3411         }
3412         double ar = (double)width / height;
3413 // square-ish pixels
3414         if( EQUIV(ar, 1.0000) ) return 0;
3415         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3416         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3417         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3418         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3419         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3420         int ww = width, hh = height;
3421         // numerator, denominator must be under mx
3422         int mx = 255, n = gcd(ww, hh);
3423         if( n > 1 ) { ww /= n; hh /= n; }
3424         // search near height in case extra/missing lines
3425         if( ww >= mx || hh >= mx ) {
3426                 double err = height;  // +/- 2 percent height
3427                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3428                         int iw = width, ih = height+i;
3429                         if( (n=gcd(iw, ih)) > 1 ) {
3430                                 int u = iw/n;  if( u >= mx ) continue;
3431                                 int v = ih/n;  if( v >= mx ) continue;
3432                                 double r = (double) u/v, er = fabs(ar-r);
3433                                 if( er >= err ) continue;
3434                                 err = er;  ww = u;  hh = v;
3435                         }
3436                 }
3437         }
3438
3439         w = ww;  h = hh;
3440         return 0;
3441 }
3442
3443 void MWindow::reset_caches()
3444 {
3445         frame_cache->remove_all();
3446         wave_cache->remove_all();
3447         audio_cache->remove_all();
3448         video_cache->remove_all();
3449         if( cwindow->playback_engine ) {
3450                 if( cwindow->playback_engine->audio_cache )
3451                         cwindow->playback_engine->audio_cache->remove_all();
3452                 if( cwindow->playback_engine->video_cache )
3453                         cwindow->playback_engine->video_cache->remove_all();
3454         }
3455         for(int i = 0; i < vwindows.size(); i++) {
3456                 VWindow *vwindow = vwindows[i];
3457                 if( !vwindow->is_running() ) continue;
3458                 if( !vwindow->playback_engine ) continue;
3459                 if( vwindow->playback_engine->audio_cache )
3460                         vwindow->playback_engine->audio_cache->remove_all();
3461                 if( vwindow->playback_engine->video_cache )
3462                         vwindow->playback_engine->video_cache->remove_all();
3463         }
3464 }
3465
3466 void MWindow::remove_asset_from_caches(Asset *asset)
3467 {
3468         frame_cache->remove_asset(asset);
3469         wave_cache->remove_asset(asset);
3470         audio_cache->delete_entry(asset);
3471         video_cache->delete_entry(asset);
3472         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3473                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3474         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3475                 cwindow->playback_engine->video_cache->delete_entry(asset);
3476         for(int i = 0; i < vwindows.size(); i++) {
3477                 VWindow *vwindow = vwindows[i];
3478                 if( !vwindow->is_running() ) continue;
3479                 if( !vwindow->playback_engine ) continue;
3480                 if( vwindow->playback_engine->audio_cache )
3481                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3482                 if( vwindow->playback_engine->video_cache )
3483                         vwindow->playback_engine->video_cache->delete_entry(asset);
3484         }
3485 }
3486
3487
3488 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3489                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3490 {
3491         for(int i = 0; i < drag_assets->total; i++) {
3492                 Indexable *indexable = drag_assets->get(i);
3493                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3494         }
3495
3496 // Remove from VWindow.
3497         for(int i = 0; i < session->drag_clips->total; i++) {
3498                 for(int j = 0; j < vwindows.size(); j++) {
3499                         VWindow *vwindow = vwindows[j];
3500                         if( !vwindow->is_running() ) continue;
3501                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3502                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3503                                 vwindow->delete_source(1, 1);
3504                                 vwindow->gui->unlock_window();
3505                         }
3506                 }
3507         }
3508
3509         for(int i = 0; i < drag_assets->size(); i++) {
3510                 for(int j = 0; j < vwindows.size(); j++) {
3511                         VWindow *vwindow = vwindows[j];
3512                         if( !vwindow->is_running() ) continue;
3513                         if(drag_assets->get(i) == vwindow->get_source()) {
3514                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3515                                 vwindow->delete_source(1, 1);
3516                                 vwindow->gui->unlock_window();
3517                         }
3518                 }
3519         }
3520
3521         for(int i = 0; i < drag_assets->size(); i++) {
3522                 Indexable *indexable = drag_assets->get(i);
3523                 remove_indexfile(indexable);
3524         }
3525
3526 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3527         if(push_undo) undo->update_undo_before();
3528         if(drag_assets) edl->remove_from_project(drag_assets);
3529         if(drag_clips) edl->remove_from_project(drag_clips);
3530         if(redraw) save_backup();
3531         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3532         if(redraw) {
3533                 restart_brender();
3534
3535                 gui->lock_window("MWindow::remove_assets_from_project 3");
3536                 gui->update(1, 1, 1, 1, 0, 1, 0);
3537                 gui->unlock_window();
3538
3539         // Removes from playback here
3540                 sync_parameters(CHANGE_ALL);
3541         }
3542
3543         awindow->gui->async_update_assets();
3544 }
3545
3546 void MWindow::remove_assets_from_disk()
3547 {
3548 // Remove from disk
3549         for(int i = 0; i < session->drag_assets->total; i++)
3550         {
3551                 remove(session->drag_assets->get(i)->path);
3552         }
3553
3554         remove_assets_from_project(1,
3555                 1,
3556                 session->drag_assets,
3557                 session->drag_clips);
3558 }
3559
3560 void MWindow::dump_plugins(FILE *fp)
3561 {
3562         if( !plugindb ) return;
3563         for(int i = 0; i < plugindb->total; i++)
3564         {
3565                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3566                         " synth=%d transition=%d theme=%d %s\n",
3567                         plugindb->get(i)->plugin_type,
3568                         plugindb->get(i)->audio,
3569                         plugindb->get(i)->video,
3570                         plugindb->get(i)->realtime,
3571                         plugindb->get(i)->multichannel,
3572                         plugindb->get(i)->get_synthesis(),
3573                         plugindb->get(i)->transition,
3574                         plugindb->get(i)->theme,
3575                         plugindb->get(i)->title);
3576         }
3577 }
3578
3579 void MWindow::dump_edl(FILE *fp)
3580 {
3581         if( !edl ) return;
3582         edl->dump(fp);
3583 }
3584
3585 void MWindow::dump_undo(FILE *fp)
3586 {
3587         if( !undo ) return;
3588         undo->dump(fp);
3589 }
3590
3591 void MWindow::dump_exe(FILE *fp)
3592 {
3593         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3594         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3595
3596         int ret = -1, n = 100;
3597         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3598                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3599                 ret = 0;
3600         }
3601         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3602
3603         struct stat st;
3604         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3605         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3606         struct tm *tm = localtime(&st.st_mtime);
3607         char mtime[256];
3608         strftime(mtime, sizeof(mtime), "%F %T", tm);
3609         fprintf(fp,"mtime: %s\n", mtime);
3610 #if 0
3611 // people hit ctl-c waiting for this
3612         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3613         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3614         uint8_t *bfr = 0;
3615         int64_t bfrsz = 0;
3616         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3617         int64_t maxsz = 1024*pagsz;
3618         int64_t size = st.st_size, pos = 0;
3619         SHA1 sha1;
3620         while( (bfrsz = size-pos) > 0 ) {
3621                 if( bfrsz > maxsz ) bfrsz = maxsz;
3622                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3623                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3624                 if( bfr == MAP_FAILED ) break;
3625                 sha1.addBytes(bfr, bfrsz);
3626                 munmap(bfr, bfrsz);
3627                 pos += bfrsz;
3628         }
3629         close(fd);
3630         ret = pos < size ? EIO : 0;
3631         fprintf(fp, "SHA1: ");
3632         uint8_t digest[20];  sha1.computeHash(digest);
3633         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3634         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3635         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3636 #endif
3637         fprintf(fp, "\n");
3638 }
3639
3640 void MWindow::trap_hook(FILE *fp, void *vp)
3641 {
3642         MWindow *mwindow = (MWindow *)vp;
3643 //      fprintf(fp, "\nPLUGINS:\n");
3644 //      mwindow->dump_plugins(fp);
3645         fprintf(fp, "\nEDL:\n");
3646         mwindow->dump_edl(fp);
3647         fprintf(fp, "\nUNDO:\n");
3648         mwindow->dump_undo(fp);
3649         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
3650         mwindow->dump_exe(fp);
3651 }
3652
3653
3654
3655
3656
3657
3658 int MWindow::save_defaults()
3659 {
3660         gui->save_defaults(defaults);
3661         edl->save_defaults(defaults);
3662         session->save_defaults(defaults);
3663         preferences->save_defaults(defaults);
3664
3665         for(int i = 0; i < plugin_guis->total; i++)
3666         {
3667 // Pointer comparison
3668                 plugin_guis->get(i)->save_defaults();
3669         }
3670         awindow->save_defaults(defaults);
3671
3672         defaults->save();
3673         return 0;
3674 }
3675
3676 int MWindow::run_script(FileXML *script)
3677 {
3678         int result = 0, result2 = 0;
3679         while(!result && !result2)
3680         {
3681                 result = script->read_tag();
3682                 if(!result)
3683                 {
3684                         if(script->tag.title_is("new_project"))
3685                         {
3686 // Run new in immediate mode.
3687 //                              gui->mainmenu->new_project->run_script(script);
3688                         }
3689                         else
3690                         if(script->tag.title_is("record"))
3691                         {
3692 // Run record as a thread.  It is a terminal command.
3693                                 ;
3694 // Will read the complete scipt file without letting record read it if not
3695 // terminated.
3696                                 result2 = 1;
3697                         }
3698                         else
3699                         {
3700                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3701                         }
3702                 }
3703         }
3704         return result2;
3705 }
3706
3707 // ================================= synchronization
3708
3709
3710 int MWindow::interrupt_indexes()
3711 {
3712         mainprogress->cancelled = 1;
3713         mainindexes->interrupt_build();
3714         return 0;
3715 }
3716
3717
3718
3719 void MWindow::next_time_format()
3720 {
3721         switch(edl->session->time_format)
3722         {
3723                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3724                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3725                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3726                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3727                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3728                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3729                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3730         }
3731
3732         time_format_common();
3733 }
3734
3735 void MWindow::prev_time_format()
3736 {
3737         switch(edl->session->time_format)
3738         {
3739                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3740                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3741                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3742                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3743                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3744                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3745                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3746         }
3747
3748         time_format_common();
3749 }
3750
3751 void MWindow::time_format_common()
3752 {
3753         gui->lock_window("MWindow::next_time_format");
3754         gui->redraw_time_dependancies();
3755
3756
3757         char string[BCTEXTLEN], string2[BCTEXTLEN];
3758         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3759         gui->show_message(string);
3760         gui->flush();
3761         gui->unlock_window();
3762 }
3763
3764
3765 int MWindow::set_filename(const char *filename)
3766 {
3767         if( filename != session->filename )
3768                 strcpy(session->filename, filename);
3769         if( filename != edl->path )
3770                 strcpy(edl->path, filename);
3771
3772         if(gui)
3773         {
3774                 if(filename[0] == 0)
3775                 {
3776                         gui->set_title(PROGRAM_NAME);
3777                 }
3778                 else
3779                 {
3780                         FileSystem dir;
3781                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3782                         dir.extract_name(string, filename);
3783                         sprintf(string2, PROGRAM_NAME ": %s", string);
3784                         gui->set_title(string2);
3785                 }
3786         }
3787         return 0;
3788 }
3789
3790
3791
3792
3793
3794
3795
3796
3797 int MWindow::set_loop_boundaries()
3798 {
3799         double start = edl->local_session->get_selectionstart();
3800         double end = edl->local_session->get_selectionend();
3801
3802         if(start !=
3803                 end)
3804         {
3805                 ;
3806         }
3807         else
3808         if(edl->tracks->total_length())
3809         {
3810                 start = 0;
3811                 end = edl->tracks->total_length();
3812         }
3813         else
3814         {
3815                 start = end = 0;
3816         }
3817
3818         if(edl->local_session->loop_playback && start != end)
3819         {
3820                 edl->local_session->loop_start = start;
3821                 edl->local_session->loop_end = end;
3822         }
3823         return 0;
3824 }
3825
3826
3827
3828
3829
3830
3831
3832 int MWindow::reset_meters()
3833 {
3834         cwindow->gui->lock_window("MWindow::reset_meters 1");
3835         cwindow->gui->meters->reset_meters();
3836         cwindow->gui->unlock_window();
3837
3838         for(int j = 0; j < vwindows.size(); j++) {
3839                 VWindow *vwindow = vwindows[j];
3840                 if( !vwindow->is_running() ) continue;
3841                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3842                 vwindow->gui->meters->reset_meters();
3843                 vwindow->gui->unlock_window();
3844         }
3845
3846         lwindow->gui->lock_window("MWindow::reset_meters 3");
3847         lwindow->gui->panel->reset_meters();
3848         lwindow->gui->unlock_window();
3849
3850         gui->lock_window("MWindow::reset_meters 4");
3851         gui->reset_meters();
3852         gui->unlock_window();
3853         return 0;
3854 }
3855
3856
3857 void MWindow::resync_guis()
3858 {
3859 // Update GUIs
3860         restart_brender();
3861         gui->lock_window("MWindow::resync_guis");
3862         gui->update(1, 1, 1, 1, 1, 1, 0);
3863         gui->unlock_window();
3864
3865         cwindow->gui->lock_window("MWindow::resync_guis");
3866         cwindow->gui->resize_event(cwindow->gui->get_w(),
3867                 cwindow->gui->get_h());
3868         int channels = edl->session->audio_channels;
3869         cwindow->gui->meters->set_meters(channels, 1);
3870         cwindow->gui->flush();
3871         cwindow->gui->unlock_window();
3872
3873         for(int i = 0; i < vwindows.size(); i++) {
3874                 VWindow *vwindow = vwindows[i];
3875                 if( !vwindow->is_running() ) continue;
3876                 vwindow->gui->lock_window("MWindow::resync_guis");
3877                 vwindow->gui->resize_event(vwindow->gui->get_w(),
3878                         vwindow->gui->get_h());
3879                 vwindow->gui->meters->set_meters(channels, 1);
3880                 vwindow->gui->flush();
3881                 vwindow->gui->unlock_window();
3882         }
3883
3884         lwindow->gui->lock_window("MWindow::resync_guis");
3885         lwindow->gui->panel->set_meters(channels, 1);
3886         lwindow->gui->flush();
3887         lwindow->gui->unlock_window();
3888
3889 // Warn user
3890         if(((edl->session->output_w % 4) ||
3891                 (edl->session->output_h % 4)) &&
3892                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3893         {
3894                 MainError::show_error(
3895                         _("This project's dimensions are not multiples of 4 so\n"
3896                         "it can't be rendered by OpenGL."));
3897         }
3898
3899
3900 // Flash frame
3901         sync_parameters(CHANGE_ALL);
3902 }
3903
3904 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3905 {
3906         File *file = new File;
3907         EDLSession *session = edl->session;
3908         double old_framerate = session->frame_rate;
3909         double old_samplerate = session->sample_rate;
3910         int old_auto_keyframes = session->auto_keyframes;
3911         session->auto_keyframes = 0;
3912         int result = file->open_file(preferences, asset, 1, 0);
3913         if( !result && delete_tracks > 0 )
3914                 undo->update_undo_before();
3915         int video_layers = asset->get_video_layers();
3916         if( !result && asset->video_data && vstream < video_layers ) {
3917                 // try to get asset up to date, may fail
3918                 file->select_video_stream(asset, vstream);
3919                 // either way use what was/is there.
3920                 double framerate = asset->get_frame_rate();
3921                 int width = asset->get_w();
3922                 int height = asset->get_h();
3923                 // must be multiple of 4 for opengl
3924                 width = (width+3) & ~3;  height = (height+3) & ~3;
3925                 int driver = session->playback_config->vconfig->driver;
3926                 int color_model = file->get_best_colormodel(asset, driver);
3927 //              color_model = BC_CModels::is_yuv(color_model) ?
3928 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3929 //                      BC_CModels::is_float(color_model) ?
3930 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3931 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3932 // have alpha for now
3933                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
3934                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
3935                 session->color_model = color_model;
3936                 session->output_w = width;
3937                 session->output_h = height;
3938                 session->frame_rate = framerate;
3939                 // not, asset->actual_width/actual_height
3940                 asset->width = session->output_w;
3941                 asset->height = session->output_h;
3942                 asset->frame_rate = session->frame_rate;
3943                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3944                         session->output_w, session->output_h);
3945                 Track *track = edl->tracks->first;
3946                 for( Track *next_track=0; track; track=next_track ) {
3947                         next_track = track->next;
3948                         if( track->data_type != TRACK_VIDEO ) continue;
3949                         if( delete_tracks ) {
3950                                 Edit *edit = track->edits->first;
3951                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3952                                         next_edit = edit->next;
3953                                         if( edit->channel != vstream ||
3954                                             !edit->asset || !edit->asset->is_asset ||
3955                                             !asset->equivalent(*edit->asset,1,1,edl) )
3956                                                 delete edit;
3957                                 }
3958                         }
3959                         if( track->edits->first ) {
3960                                 track->track_w = edl->session->output_w;
3961                                 track->track_h = edl->session->output_h;
3962                         }
3963                         else if( delete_tracks )
3964                                 edl->tracks->delete_track(track);
3965                 }
3966                 edl->retrack();
3967                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3968         }
3969         if( !result && asset->audio_data && asset->channels > 0 ) {
3970                 session->sample_rate = asset->get_sample_rate();
3971                 int64_t channel_mask = 0;
3972                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
3973                         file->get_audio_for_video(vstream, astream, channel_mask);
3974                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3975                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3976                 int channels = 0;
3977                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3978                 if( channels < 1 ) channels = 1;
3979                 if( channels > 6 ) channels = 6;
3980                 session->audio_tracks = session->audio_channels = channels;
3981                 switch( channels ) {
3982                 case 6:
3983                         session->achannel_positions[0] = 90;
3984                         session->achannel_positions[1] = 150;
3985                         session->achannel_positions[2] = 30;
3986                         session->achannel_positions[3] = 210;
3987                         session->achannel_positions[4] = 330;
3988                         session->achannel_positions[5] = 270;
3989                         break;
3990                 case 2:
3991                         session->achannel_positions[0] = 180;
3992                         session->achannel_positions[1] = 0;
3993                         break;
3994                 case 1:
3995                         session->achannel_positions[1] = 90;
3996                         break;
3997                 default: {
3998                         if( !channels ) break;
3999                         double t = 0, dt = 360./channels;
4000                         for( int i=channels; --i>=0; t+=dt )
4001                                 session->achannel_positions[i] = int(t+0.5);
4002                         break; }
4003                 }
4004                 remap_audio(MWindow::AUDIO_1_TO_1);
4005
4006                 if( delete_tracks ) {
4007                         Track *track = edl->tracks->first;
4008                         for( Track *next_track=0; track; track=next_track ) {
4009                                 next_track = track->next;
4010                                 if( track->data_type != TRACK_AUDIO ) continue;
4011                                 Edit *edit = track->edits->first;
4012                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
4013                                         next_edit = edit->next;
4014                                         if( !((1<<edit->channel) & channel_mask) ||
4015                                             !edit->asset || !edit->asset->is_asset ||
4016                                             !asset->equivalent(*edit->asset,1,1,edl) )
4017                                                 delete edit;
4018                                 }
4019                                 if( !track->edits->first )
4020                                         edl->tracks->delete_track(track);
4021                         }
4022                 }
4023                 edl->rechannel();
4024                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
4025         }
4026         delete file;
4027         session->auto_keyframes = old_auto_keyframes;
4028         if( !result && delete_tracks > 0 ) {
4029                 save_backup();
4030                 undo->update_undo_after(_("select asset"), LOAD_ALL);
4031         }
4032         resync_guis();
4033         return result;
4034 }
4035
4036 int MWindow::select_asset(int vtrack, int delete_tracks)
4037 {
4038         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
4039         if( !track )
4040                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
4041         if( !track ) return 1;
4042         Edit *edit = track->edits->first;
4043         if( !edit ) return 1;
4044         Asset *asset = edit->asset;
4045         if( !asset || !asset->is_asset ) return 1;
4046         return select_asset(asset, edit->channel, 0, delete_tracks);
4047 }
4048
4049 void MWindow::dump_plugindb(FILE *fp)
4050 {
4051         if( !plugindb ) return;
4052         for(int i = 0; i < plugindb->total; i++)
4053                 plugindb->get(i)->dump(fp);
4054 }
4055
4056 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
4057 {
4058         Auto *current = 0;
4059         double unit_position = edl->local_session->get_selectionstart(1);
4060         unit_position = patch->track->to_units(unit_position, 0);
4061
4062         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
4063         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4064 }
4065
4066 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
4067 {
4068         Auto *current = 0;
4069         double unit_position = edl->local_session->get_selectionstart(1);
4070         unit_position = patch->track->to_units(unit_position, 0);
4071
4072         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
4073         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4074 }
4075
4076 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
4077 {
4078         Auto *current = 0;
4079         double unit_position = edl->local_session->get_selectionstart(1);
4080         unit_position = patch->track->to_units(unit_position, 0);
4081
4082         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
4083         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4084 }
4085
4086 PatchGUI *MWindow::get_patchgui(Track *track)
4087 {
4088         PatchGUI *patchgui = 0;
4089         TimelinePane **panes = gui->pane;
4090         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
4091                 if( !panes[i] ) continue;
4092                 PatchBay *patchbay = panes[i]->patchbay;
4093                 if( !patchbay ) continue;
4094                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
4095                         if( patchbay->patches.values[j]->track == track )
4096                                 patchgui = patchbay->patches.values[j];
4097                 }
4098         }
4099         return patchgui;
4100 }
4101