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