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