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