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