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