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