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