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