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