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