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