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