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