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