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