RafaMar + programmer friend Help button in Batch Render addition
[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         save_defaults();
300 // Give up and go to a movie
301 //  cant run valgrind if this is used
302
303         gui->del_keyboard_listener(
304                 (int (BC_WindowBase::*)(BC_WindowBase *))
305                 &MWindowGUI::keyboard_listener);
306         reset_caches(0);
307 #if 0
308 // release the hounds
309         if( awindow && awindow->gui ) awindow->gui->close(0);
310         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
311         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
312         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
313         vwindows.remove_all_objects();
314         zwindows.remove_all_objects();
315         gui->close(0);
316         if( awindow ) awindow->join();
317         if( cwindow ) cwindow->join();
318         if( lwindow ) lwindow->join();
319         if( gwindow ) gwindow->join();
320         join();
321 #else
322 // one at a time, or nouveau chokes
323 #define close_gui(win) if( win ) { \
324   if( win->gui ) win->gui->close(0); \
325   win->join(); }
326         close_gui(awindow);
327         close_gui(cwindow);
328         close_gui(lwindow);
329         close_gui(gwindow);
330         vwindows.remove_all_objects();
331         zwindows.remove_all_objects();
332         gui->close(0);
333         join();
334 #endif
335         dead_plugins->remove_all_objects();
336 // must delete theme before destroying plugindb
337 //  theme destructor will be deleted by delete_plugins
338         delete theme;           theme = 0;
339         delete_plugins();
340         finit_error();
341         keyframe_threads->remove_all_objects();
342         colormodels.remove_all_objects();
343         delete awindow;         awindow = 0;
344         delete lwindow;         lwindow = 0;
345         delete twindow;         twindow = 0;
346         delete wwindow;         wwindow = 0;
347         delete gwindow;         gwindow = 0;
348         delete cwindow;         cwindow = 0;
349         delete gui;             gui = 0;
350         delete mainindexes;     mainindexes = 0;
351         delete mainprogress;    mainprogress = 0;
352  // delete the caches after the assets
353         if( audio_cache ) { audio_cache->remove_user();  audio_cache = 0; }
354         if( video_cache ) { video_cache->remove_user();  video_cache = 0; }
355         delete frame_cache;     frame_cache = 0;
356         delete wave_cache;      wave_cache = 0;
357         delete plugin_guis;     plugin_guis = 0;
358         delete dead_plugins;    dead_plugins = 0;
359         delete keyframe_threads;  keyframe_threads = 0;
360         delete undo;            undo = 0;
361         delete preferences;     preferences = 0;
362         delete exportedl;       exportedl = 0;
363         delete session;         session = 0;
364         delete defaults;        defaults = 0;
365         delete assets;          assets = 0;
366         delete splash_window;   splash_window = 0;
367         if( !edl->Garbage::remove_user() ) edl = 0;
368         delete channeldb_buz;
369         delete channeldb_v4l2jpeg;
370 // This must be last thread to exit
371         delete playback_3d;     playback_3d = 0;
372         delete dead_plugin_lock;
373         delete plugin_gui_lock;
374         delete vwindows_lock;
375         delete zwindows_lock;
376         delete brender_lock;
377         delete keyframe_gui_lock;
378         colormodels.remove_all_objects();
379         interlace_project_modes.remove_all_objects();
380         interlace_asset_modes.remove_all_objects();
381         sighandler->terminate();
382         delete sighandler;
383         delete run_lock;
384 }
385
386
387 void MWindow::quit()
388 {
389         gui->set_done(0);
390 }
391
392 void MWindow::init_error()
393 {
394         MainError::init_error(this);
395 }
396
397 void MWindow::finit_error()
398 {
399         MainError::finit_error();
400 }
401
402 void MWindow::create_defaults_path(char *string, const char *config_file)
403 {
404 // set the .bcast path
405         FileSystem fs;
406
407         sprintf(string, "%s/", File::get_config_path());
408         fs.complete_path(string);
409         if(!fs.is_dir(string))
410                 fs.create_dir(string);
411
412 // load the defaults
413         strcat(string, config_file);
414 }
415 const char *MWindow::default_std()
416 {
417         char buf[BCTEXTLEN], *p = 0;
418
419         int fd = open(TIMEZONE_NAME, O_RDONLY);
420         if( fd >= 0 ) {
421                 int l = read(fd, buf, sizeof(buf)-1);
422                 close(fd);
423                 if( l > 0 ) {
424                         if( buf[l-1] == '\n' ) --l;
425                         buf[l] = 0;
426                         p = buf;
427                 }
428         }
429         if( !p ) {
430                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
431                 if( l > 0 ) {
432                         buf[l] = 0;
433                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
434                         p += strlen(ZONEINFO_STR);
435                 }
436         }
437
438         if( p ) {
439                 for( int i=0; ntsc_zones[i]; ++i ) {
440                         if( !strcmp(ntsc_zones[i], p) )
441                                 return "NTSC";
442                 }
443         }
444
445         p = getenv("TZ");
446         if( p ) {
447                 for( int i=0; ntsc_zones[i]; ++i ) {
448                         if( !strcmp(ntsc_zones[i], p) )
449                                 return "NTSC";
450                 }
451         }
452
453 // cin_timezone: Seconds west of UTC.  240sec/deg
454         double tz_deg =  -cin_timezone / 240.;
455 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
456         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
457 }
458
459 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
460 {
461         struct formatpresets *fpr;
462
463         for(fpr = &format_presets[0]; fpr->name; fpr++)
464         {
465                 if(strcmp(_(fpr->name), preset) == 0)
466                 {
467                         session->audio_channels = fpr->audio_channels;
468                         session->audio_tracks = fpr->audio_tracks;
469                         session->sample_rate = fpr->sample_rate;
470                         session->video_channels = fpr->video_channels;
471                         session->video_tracks = fpr->video_tracks;
472                         session->frame_rate = fpr->frame_rate;
473                         session->output_w = fpr->output_w;
474                         session->output_h = fpr->output_h;
475                         session->aspect_w = fpr->aspect_w;
476                         session->aspect_h = fpr->aspect_h;
477                         session->interlace_mode = fpr->interlace_mode;
478                         session->color_model = fpr->color_model;
479                         return;
480                 }
481         }
482 }
483
484 const char *MWindow::get_preset_name(int index)
485 {
486         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
487                 return "Error";
488         return _(format_presets[index].name);
489 }
490
491
492 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
493 {
494         char path[BCTEXTLEN];
495 // Use user supplied path
496         if(config_path[0])
497                 strcpy(path, config_path);
498         else
499                 create_defaults_path(path, CONFIG_FILE);
500
501         delete defaults;
502         defaults = new BC_Hash(path);
503         defaults->load();
504 }
505
506
507 void MWindow::check_language()
508 {
509         char pref_locale[BCSTRLEN];
510         strcpy(pref_locale, DEFAULT_LOCALE);
511         defaults->get("LOCALE",pref_locale);
512 // set LANGUAGE if pref locale != sys
513         if( strcmp(pref_locale, DEFAULT_LOCALE) )
514                 setenv("LANGUAGE", pref_locale, 1);
515
516         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
517         const char *env_lang = getenv("LANGUAGE");
518         if( !env_lang ) env_lang = getenv("LC_ALL");
519         if( !env_lang ) env_lang = getenv("LANG");
520         if( !env_lang ) {
521                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
522                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
523                 env_lang = curr_lang;
524         }
525         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
526         defaults->get("LAST_LANG",last_lang);
527         if( strcmp(env_lang,last_lang)) {
528                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
529                 defaults->update("LAST_LANG",env_lang);
530                 char plugin_path[BCTEXTLEN];
531                 create_defaults_path(plugin_path, PLUGIN_FILE);
532                 ::remove(plugin_path);
533                 char ladspa_path[BCTEXTLEN];
534                 create_defaults_path(ladspa_path, LADSPA_FILE);
535                 ::remove(ladspa_path);
536                 defaults->save();
537         }
538         if( strlen(env_lang) > 1 &&
539             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
540                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
541         }
542         else
543                 strcpy(cin_lang, "en");
544 }
545
546 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
547 {
548         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
549         if( plug_dir ) {
550                 const char *dp = plug_dir;
551                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
552                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
553         }
554         strcpy(path, bp);
555         delete [] base_path;
556 }
557
558 int MWindow::load_plugin_index(MWindow *mwindow, FILE *fp, const char *plugin_dir)
559 {
560         if( !fp ) return -1;
561 // load index
562         fseek(fp, 0, SEEK_SET);
563         int ret = 0;
564         char index_line[BCTEXTLEN];
565         int index_version = -1, len = strlen(plugin_dir);
566         if( !fgets(index_line, BCTEXTLEN, fp) ||
567             sscanf(index_line, "%d", &index_version) != 1 ||
568             index_version != PLUGIN_FILE_VERSION ||
569             !fgets(index_line, BCTEXTLEN, fp) ||
570             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
571             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
572
573         ArrayList<PluginServer*> plugins;
574         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
575                 if( index_line[0] == ';' ) continue;
576                 if( index_line[0] == '#' ) continue;
577                 int type = PLUGIN_TYPE_UNKNOWN;
578                 char path[BCTEXTLEN], title[BCTEXTLEN];
579                 int64_t mtime = 0;
580                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
581                         ret = 1; continue;
582                 }
583                 PluginServer *server = 0;
584                 switch( type ) {
585                 case PLUGIN_TYPE_BUILTIN:
586                 case PLUGIN_TYPE_EXECUTABLE:
587                 case PLUGIN_TYPE_LADSPA: {
588                         char plugin_path[BCTEXTLEN];  struct stat st;
589                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
590                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
591                                 ret = 1; continue;
592                         }
593                         server = new PluginServer(mwindow, plugin_path, type);
594                         break; }
595                 case PLUGIN_TYPE_FFMPEG: {
596                         server = new_ffmpeg_server(mwindow, path);
597                         break; }
598                 case PLUGIN_TYPE_LV2: {
599                         server = new_lv2_server(mwindow, path);
600                         break; }
601                 }
602                 if( !server ) continue;
603                 plugins.append(server);
604 // Create plugin server from index entry
605                 server->set_title(title);
606                 if( server->read_table(index_line) ) {
607                         ret = 1;  continue;
608                 }
609         }
610
611         if( !ret )
612                 ret = check_plugin_index(plugins, plugin_dir, ".");
613
614         if( !ret )
615                 add_plugins(plugins);
616         else
617                 plugins.remove_all_objects();
618
619         return ret;
620 }
621
622 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
623         const char *plug_dir, const char *plug_path)
624 {
625         char plugin_path[BCTEXTLEN];
626         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
627         FileSystem fs;
628         fs.set_filter( "[*.plugin][*.so]" );
629         if( fs.update(plugin_path) )
630                 return 1;
631
632         for( int i=0; i<fs.dir_list.total; ++i ) {
633                 char fs_path[BCTEXTLEN];
634                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
635                 if( fs.is_dir(fs_path) ) {
636                         get_plugin_path(plugin_path, plug_dir, fs_path);
637                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
638                                 return 1;
639                 }
640                 else if( !plugin_exists(fs_path, plugins) )
641                         return 1;
642         }
643         return 0;
644 }
645
646
647 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
648 {
649         if( !plugindb )
650                 plugindb = new ArrayList<PluginServer*>;
651         init_ffmpeg();
652         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
653         create_defaults_path(index_path, PLUGIN_FILE);
654         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
655         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
656         FILE *fp = fopen(index_path,"a+");
657         if( !fp ) {
658                 fprintf(stderr,_("MWindow::init_plugins: "
659                         "can't open plugin index: %s\n"), index_path);
660                 return -1;
661         }
662         int fd = fileno(fp), ret = -1;
663         if( !flock(fd, LOCK_EX) ) {
664                 fseek(fp, 0, SEEK_SET);
665                 ret = load_plugin_index(mwindow, fp, plugin_path);
666         }
667         if( ret > 0 ) {
668                 ftruncate(fd, 0);
669                 fseek(fp, 0, SEEK_SET);
670                 printf("init plugin index: %s\n", plugin_path);
671                 fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
672                 fprintf(fp, "%s\n", plugin_path);
673                 init_plugin_index(mwindow, preferences, fp, plugin_path);
674                 init_ffmpeg_index(mwindow, preferences, fp);
675                 init_lv2_index(mwindow, preferences, fp);
676                 fseek(fp, 0, SEEK_SET);
677                 ret = load_plugin_index(mwindow, fp, plugin_path);
678         }
679         if( ret ) {
680                 fprintf(stderr,_("MWindow::init_plugins: "
681                         "can't %s plugin index: %s\n"),
682                         ret>0 ? _("create") : _("lock"), index_path);
683         }
684         fclose(fp);
685         return ret;
686 }
687
688 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
689 {
690 #ifdef HAVE_LADSPA
691         char *path = getenv("LADSPA_PATH");
692         char ladspa_path[BCTEXTLEN];
693         if( !path ) {
694                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
695                 path = ladspa_path;
696         }
697         for( int len=0; *path; path+=len ) {
698                 char *cp = strchr(path,':');
699                 len = !cp ? strlen(path) : cp-path;
700                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
701                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
702                 if( cp ) ++len;
703                 char *plugin_dir = FileSystem::basepath(plugin_path);
704                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
705                 create_defaults_path(index_path, LADSPA_FILE);
706                 cp = index_path + strlen(index_path);
707                 for( char *bp=plugin_path; *bp!=0; ++bp )
708                         *cp++ = *bp=='/' ? '_' : *bp;
709                 *cp = 0;
710                 FILE *fp = fopen(index_path,"a+");
711                 if( !fp ) {
712                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
713                                 "can't open ladspa plugin index: %s\n"), index_path);
714                         continue;
715                 }
716                 int fd = fileno(fp), ret = -1;
717                 if( !flock(fd, LOCK_EX) ) {
718                         fseek(fp, 0, SEEK_SET);
719                         ret = load_plugin_index(mwindow, fp, plugin_path);
720                 }
721                 if( ret > 0 ) {
722                         ftruncate(fd, 0);
723                         fseek(fp, 0, SEEK_SET);
724                         init_ladspa_index(mwindow, preferences, fp, plugin_path);
725                         fseek(fp, 0, SEEK_SET);
726                         ret = load_plugin_index(mwindow, fp, plugin_path);
727                 }
728                 if( ret ) {
729                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
730                                 "can't %s ladspa plugin index: %s\n"),
731                                 ret>0 ? _("create") : _("lock"), index_path);
732                 }
733                 fclose(fp);
734         }
735 #endif
736         return 1;
737 }
738
739 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
740         FILE *fp, const char *plugin_dir)
741 {
742         int idx = PLUGIN_IDS;
743         if( plugindb ) {
744                 for( int i=0; i<plugindb->size(); ++i ) {
745                         PluginServer *server = plugindb->get(i);
746                         if( server->dir_idx >= idx )
747                                 idx = server->dir_idx+1;
748                 }
749         }
750         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
751 }
752
753 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
754         const char *plug_dir, const char *plug_path, int &idx)
755 {
756         char plugin_path[BCTEXTLEN];
757         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
758         FileSystem fs;
759         fs.set_filter( "[*.plugin][*.so][*.dll]" );
760         int result = fs.update(plugin_path);
761         if( result || !fs.dir_list.total ) return;
762         int vis_id = idx++;
763
764         for( int i=0; i<fs.dir_list.total; ++i ) {
765                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
766                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
767                 get_plugin_path(path, plug_dir, fs_path);
768                 if( fs.is_dir(fs_path) ) {
769                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
770                         continue;
771                 }
772                 if( plugin_exists(path) ) continue;
773                 struct stat st;
774                 if( stat(fs_path, &st) ) continue;
775                 int64_t mtime = st.st_mtime;
776                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
777                 result = server.open_plugin(1, preferences, 0, 0);
778                 if( !result ) {
779                         server.write_table(fp, path, vis_id, mtime);
780                         server.close_plugin();
781                 }
782                 else if( result == PLUGINSERVER_IS_LAD ) {
783                         int lad_index = 0;
784                         for(;;) {
785                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
786                                 ladspa.set_lad_index(lad_index++);
787                                 result = ladspa.open_plugin(1, preferences, 0, 0);
788                                 if( result ) break;
789                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
790                                 ladspa.close_plugin();
791                         }
792                 }
793         }
794 }
795
796 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
797 {
798         for( int i=0; i<plugins.size(); ++i )
799                 plugindb->append(plugins[i]);
800         plugins.remove_all();
801 }
802
803 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
804 {
805         const char *dat_path = File::get_cindat_path();
806         char msg_path[BCTEXTLEN];
807         FILE *fp = 0;
808         if( BC_Resources::language[0] ) {
809                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
810                         dat_path, lang);
811                 fp = fopen(msg_path, "r");
812         }
813         if( !fp ) {
814                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
815                         dat_path);
816                 fp = fopen(msg_path, "r");
817         }
818         if( !fp ) return;
819         char text[BCTEXTLEN];
820         char *tp = text, *ep = tp + sizeof(text)-1;
821         char title[BCTEXTLEN];
822         title[0] = 0;
823         int no = 0;
824         for(;;) {
825                 ++no;  int done = 1;
826                 char line[BCTEXTLEN], *cp = line;
827                 if( fgets(line,sizeof(line)-1,fp) ) {
828                         if( *cp == '#' ) continue;
829                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
830                 }
831                 if( done ) {
832                         if( tp > text && *--tp == '\n' ) *tp = 0;
833                         if( title[0] ) {
834                                 int idx = plugins.size();
835                                 while( --idx>=0 && strcmp(plugins[idx]->title, title) );
836                                 if( idx >= 0 ) {
837                                         delete [] plugins[idx]->tip;
838                                         plugins[idx]->tip = cstrdup(text);
839                                 }
840                                 title[0] = 0;
841                         }
842                         if( done > 0 ) break;
843                         tp = text;  *tp = 0;
844                         char *dp = strchr(cp, ':');
845                         if( !dp ) {
846                                 printf("plugin tips: error on line %d\n", no);
847                                 continue;
848                         }
849                         char *bp = title;
850                         while( cp < dp ) *bp++ = *cp++;
851                         *bp = 0;
852                         ++cp;
853                 }
854
855                 while( *cp == ' ' || *cp == '\t' ) ++cp;
856                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
857         }
858         fclose(fp);
859 }
860
861 void MWindow::delete_plugins()
862 {
863         plugindb->remove_all_objects();
864         delete plugindb;
865         plugindb = 0;
866 }
867
868 void MWindow::search_plugindb(int do_audio,
869                 int do_video,
870                 int is_realtime,
871                 int is_transition,
872                 int is_theme,
873                 ArrayList<PluginServer*> &results)
874 {
875 // Get plugins
876         for(int i = 0; i < MWindow::plugindb->total; i++)
877         {
878                 PluginServer *current = MWindow::plugindb->get(i);
879
880                 if(current->audio == do_audio &&
881                         current->video == do_video &&
882                         (current->realtime == is_realtime || is_realtime < 0) &&
883                         current->transition == is_transition &&
884                         current->theme == is_theme)
885                         results.append(current);
886         }
887
888 // Alphabetize list by title
889         int done = 0;
890         while(!done)
891         {
892                 done = 1;
893
894                 for(int i = 0; i < results.total - 1; i++)
895                 {
896                         PluginServer *value1 = results[i];
897                         PluginServer *value2 = results[i + 1];
898                         if(strcmp(_(value1->title), _(value2->title)) > 0)
899                         {
900                                 done = 0;
901                                 results[i] = value2;
902                                 results[i + 1] = value1;
903                         }
904                 }
905         }
906 }
907
908 PluginServer* MWindow::scan_plugindb(char *title,
909                 int data_type)
910 {
911 //      if(data_type < 0)
912 //      {
913 //              printf("MWindow::scan_plugindb data_type < 0\n");
914 //              return 0;
915 //      }
916
917         for(int i = 0; i < plugindb->total; i++)
918         {
919                 PluginServer *server = plugindb->get(i);
920                 if(server->title &&
921                         !strcasecmp(server->title, title) &&
922                         (data_type < 0 ||
923                                 (data_type == TRACK_AUDIO && server->audio) ||
924                                 (data_type == TRACK_VIDEO && server->video)))
925                         return plugindb->get(i);
926         }
927         return 0;
928 }
929
930 // repair session files with xlated plugin titles
931 void MWindow::fix_plugin_title(char *title)
932 {
933         for(int i = 0; i < plugindb->total; i++) {
934                 PluginServer *server = plugindb->get(i);
935                 if( !server->title ) continue;
936                 const char *server_title = server->title;
937                 if( !bstrcasecmp(title, _(server_title)) ) {
938                         strcpy(title, server_title);
939                         return;
940                 }
941         }
942 }
943
944 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
945 {
946         for( int i=0; i<plugins.size(); ++i )
947                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
948         return 0;
949 }
950
951 int MWindow::plugin_exists(char *plugin_path)
952 {
953         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
954 }
955
956 void MWindow::remove_plugin_index()
957 {
958         char index_path[BCTEXTLEN];
959         MWindow::create_defaults_path(index_path, PLUGIN_FILE);
960         ::remove(index_path);
961 }
962
963 void MWindow::init_preferences()
964 {
965         preferences = new Preferences;
966         preferences->load_defaults(defaults);
967         File::setenv_path("LV2_PATH",preferences->lv2_path, 1);
968         session = new MainSession(this);
969         session->load_defaults(defaults);
970         // set x11_host, screens, window_config
971         screens = session->set_default_x11_host();
972         BC_Signals::set_trap_hook(trap_hook, this);
973         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
974         BC_Signals::set_catch_intr(preferences->trap_sigintr);
975         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
976                 BC_Trace::enable_locks();
977         }
978         else {
979                 BC_Trace::disable_locks();
980         }
981         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
982         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
983         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
984         YUV::yuv.yuv_set_colors(preferences->yuv_color_space, preferences->yuv_color_range);
985 }
986
987 void MWindow::clean_indexes()
988 {
989         FileSystem fs;
990         int total_excess;
991         long oldest = 0;
992         int oldest_item = -1;
993         int result;
994         char string[BCTEXTLEN];
995         char string2[BCTEXTLEN];
996
997 // Delete extra indexes
998         fs.set_filter("*.idx");
999         fs.complete_path(preferences->index_directory);
1000         fs.update(preferences->index_directory);
1001 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
1002
1003 // Eliminate directories
1004         result = 1;
1005         while(result)
1006         {
1007                 result = 0;
1008                 for(int i = 0; i < fs.dir_list.total && !result; i++)
1009                 {
1010                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1011                         if(fs.is_dir(string))
1012                         {
1013                                 delete fs.dir_list[i];
1014                                 fs.dir_list.remove_number(i);
1015                                 result = 1;
1016                         }
1017                 }
1018         }
1019         total_excess = fs.dir_list.total - preferences->index_count;
1020
1021 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
1022         while(total_excess > 0)
1023         {
1024 // Get oldest
1025                 for(int i = 0; i < fs.dir_list.total; i++)
1026                 {
1027                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1028
1029                         if(i == 0 || fs.get_date(string) <= oldest)
1030                         {
1031                                 oldest = fs.get_date(string);
1032                                 oldest_item = i;
1033                         }
1034                 }
1035
1036                 if(oldest_item >= 0)
1037                 {
1038 // Remove index file
1039                         fs.join_names(string,
1040                                 preferences->index_directory,
1041                                 fs.dir_list[oldest_item]->name);
1042 //printf("MWindow::clean_indexes 1 %s\n", string);
1043                         if(remove(string))
1044                                 perror("delete_indexes");
1045                         delete fs.dir_list[oldest_item];
1046                         fs.dir_list.remove_number(oldest_item);
1047
1048 // Remove table of contents if it exists
1049                         strcpy(string2, string);
1050                         char *ptr = strrchr(string2, '.');
1051                         if(ptr)
1052                         {
1053 //printf("MWindow::clean_indexes 2 %s\n", string2);
1054                                 sprintf(ptr, ".toc");
1055                                 remove(string2);
1056                                 sprintf(ptr, ".mkr");
1057                                 remove(string2);
1058                         }
1059                 }
1060
1061                 total_excess--;
1062         }
1063 }
1064
1065 void MWindow::init_awindow()
1066 {
1067         awindow = new AWindow(this);
1068         awindow->create_objects();
1069 }
1070
1071 void MWindow::init_gwindow()
1072 {
1073         gwindow = new GWindow(this);
1074         gwindow->create_objects();
1075 }
1076
1077 void MWindow::init_tipwindow()
1078 {
1079         TipWindow::load_tips(cin_lang);
1080         if( !twindow )
1081                 twindow = new TipWindow(this);
1082         twindow->start();
1083 }
1084
1085 void MWindow::show_warning(int *do_warning, const char *text)
1086 {
1087         if( do_warning && !*do_warning ) return;
1088         if( !wwindow )
1089                 wwindow = new WWindow(this);
1090         wwindow->show_warning(do_warning, text);
1091 }
1092
1093 int MWindow::wait_warning()
1094 {
1095         return wwindow->wait_result();
1096 }
1097
1098 void MWindow::init_theme()
1099 {
1100         Timer timer;
1101         theme = 0;
1102
1103         PluginServer *theme_plugin = 0;
1104         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1105                 if( plugindb->get(i)->theme &&
1106                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1107                         theme_plugin = plugindb->get(i);
1108         }
1109
1110         if( !theme_plugin )
1111                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1112                          preferences->theme);
1113
1114         const char *default_theme = DEFAULT_THEME;
1115         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1116                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1117                         default_theme);
1118                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1119                         if( plugindb->get(i)->theme &&
1120                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1121                                 theme_plugin = plugindb->get(i);
1122                 }
1123         }
1124
1125         if(!theme_plugin) {
1126                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1127                 exit(1);
1128         }
1129
1130         PluginServer *plugin = new PluginServer(*theme_plugin);
1131         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1132                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1133                         theme_plugin->title);
1134                 exit(1);
1135         }
1136
1137         theme = plugin->new_theme();
1138         theme->mwindow = this;
1139         strcpy(theme->path, plugin->path);
1140         delete plugin;
1141
1142 // Load default images & settings
1143         theme->Theme::initialize();
1144 // Load user images & settings
1145         theme->initialize();
1146 // Create menus with user colors
1147         theme->build_menus();
1148         init_menus();
1149
1150         theme->sort_image_sets();
1151         theme->check_used();
1152 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1153 }
1154
1155 void MWindow::init_3d()
1156 {
1157         playback_3d = new Playback3D(this);
1158         playback_3d->create_objects();
1159 }
1160
1161 void MWindow::init_edl()
1162 {
1163         edl = new EDL;
1164         edl->create_objects();
1165         fill_preset_defaults(default_standard, edl->session);
1166         edl->load_defaults(defaults);
1167         edl->session->brender_start = edl->session->brender_end = 0;
1168         edl->create_default_tracks();
1169         edl->tracks->update_y_pixels(theme);
1170 }
1171
1172 void MWindow::init_compositor()
1173 {
1174         cwindow = new CWindow(this);
1175         cwindow->create_objects();
1176 }
1177
1178 void MWindow::init_levelwindow()
1179 {
1180         lwindow = new LevelWindow(this);
1181         lwindow->create_objects();
1182 }
1183
1184 VWindow *MWindow::get_viewer(int start_it, int idx)
1185 {
1186         vwindows_lock->lock("MWindow::get_viewer");
1187         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1188         if( !vwindow ) idx = vwindows.size();
1189         while( !vwindow && --idx >= 0 ) {
1190                 VWindow *vwin = vwindows[idx];
1191                 if( !vwin->is_running() || !vwin->get_edl() )
1192                         vwindow = vwin;
1193         }
1194         if( !vwindow ) {
1195                 vwindow = new VWindow(this);
1196                 vwindow->load_defaults();
1197                 vwindow->create_objects();
1198                 vwindows.append(vwindow);
1199         }
1200         vwindows_lock->unlock();
1201         if( start_it ) vwindow->start();
1202         return vwindow;
1203 }
1204
1205 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1206 {
1207         zwindows_lock->lock("MWindow::get_mixer");
1208         if( !mixer ) mixer = edl->mixers.new_mixer();
1209         ZWindow *zwindow = 0;
1210         for( int i=0; !zwindow && i<zwindows.size(); ++i ) {
1211                 ZWindow *zwdw = zwindows[i];
1212                 if( zwdw->running() ) continue;
1213                 if( zwdw->idx >= 0 ) continue;
1214                 zwindow = zwindows[i];
1215         }
1216         if( !zwindow )
1217                 zwindows.append(zwindow = new ZWindow(this));
1218         zwindow->idx = mixer->idx;
1219         zwindows_lock->unlock();
1220         return zwindow;
1221 }
1222
1223 ZWindow *MWindow::get_mixer(int idx)
1224 {
1225         ZWindow *zwindow = 0;
1226         zwindows_lock->lock("MWindow::get_mixer");
1227         for( int i=0; !zwindow && i<zwindows.size(); ++i ) {
1228                 ZWindow *zwdw = zwindows[i];
1229                 if( !zwdw->running() ) continue;
1230                 if( zwdw->idx != idx ) continue;
1231                 zwindow = zwindows[i];
1232         }
1233         zwindows_lock->unlock();
1234         return zwindow;
1235 }
1236
1237 void MWindow::close_mixer(ZWindow *zwindow)
1238 {
1239         zwindows_lock->lock("MWindow::close_mixer 0");
1240         if( session->selected_zwindow >= 0 ) {
1241                 int i = zwindows.number_of(zwindow);
1242                 if( i >= 0 && i < session->selected_zwindow )
1243                         --session->selected_zwindow;
1244                 else if( i == session->selected_zwindow )
1245                         session->selected_zwindow = -1;
1246         }
1247         zwindows_lock->unlock();
1248         gui->lock_window("MWindow::close_mixer 1");
1249         gui->update_mixers(0, -1);
1250         gui->unlock_window();
1251 }
1252
1253 void MWindow::start_mixer()
1254 {
1255         Mixer *mixer = 0;
1256         ZWindow *zwindow = get_mixer(mixer);
1257         const char *title = 0;
1258
1259         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1260                 PatchGUI *patchgui = get_patchgui(track);
1261                 if( !patchgui || !patchgui->mixer ) continue;
1262                 mixer->mixer_ids.append(track->get_mixer_id());
1263                 if( !title ) title = track->title;
1264         }
1265
1266         session->selected_zwindow = -1;
1267         gui->lock_window("MWindow::start_mixer");
1268         gui->update_mixers(0, 0);
1269         gui->unlock_window();
1270
1271         zwindow->set_title(title);
1272         zwindow->start();
1273         refresh_mixers();
1274 }
1275
1276 int MWindow::mixer_track_active(Track *track)
1277 {
1278         int i = session->selected_zwindow;
1279         if( i < 0 || i >= zwindows.size() ) return 0;
1280         ZWindow *zwindow = zwindows[i];
1281         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1282         if( !mixer ) return 0;
1283         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1284         return n >= 0 ? 1 : 0;
1285 }
1286
1287 void MWindow::update_mixer_tracks()
1288 {
1289         zwindows_lock->lock("MixPatch::handle_event");
1290         int i = session->selected_zwindow;
1291         if( i >= 0 && i < zwindows.size() ) {
1292                 ZWindow *zwindow = zwindows[i];
1293                 zwindow->update_mixer_ids();
1294         }
1295         zwindows_lock->unlock();
1296 }
1297
1298 void MWindow::handle_mixers(EDL *edl, int command, int wait_tracking,
1299                 int use_inout, int toggle_audio, int loop_play, float speed)
1300 {
1301         zwindows_lock->lock("MWindow::handle_mixers");
1302         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1303                 ZWindow *zwindow = zwindows[vidx];
1304                 if( zwindow->idx < 0 ) continue;
1305                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1306                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1307                 int k = -1;
1308                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1309                         if( track->data_type != TRACK_VIDEO ) continue;
1310                         int mixer_id = track->get_mixer_id();
1311                         k = mixer->mixer_ids.size();
1312                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1313                 }
1314                 if( k < 0 ) continue;
1315                 EDL *mixer_edl = new EDL(this->edl);
1316                 mixer_edl->create_objects();
1317                 mixer_edl->copy_all(edl);
1318                 mixer_edl->remove_vwindow_edls();
1319                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1320                         k = mixer->mixer_ids.size();
1321                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1322                         if( k >= 0 ) {
1323                                 track->armed = 1;
1324                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1325                         }
1326                         else
1327                                 track->armed = track->play = 0;
1328                 }
1329                 zwindow->change_source(mixer_edl);
1330                 zwindow->handle_mixer(command, 0,
1331                                 use_inout, toggle_audio, loop_play, speed);
1332         }
1333         zwindows_lock->unlock();
1334 }
1335
1336 void MWindow::refresh_mixers(int dir)
1337 {
1338         int command = dir >= 0 ? CURRENT_FRAME : LAST_FRAME;
1339         handle_mixers(edl, command, 0, 0, 0, 0, 0);
1340 }
1341
1342 void MWindow::stop_mixers()
1343 {
1344         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1345                 ZWindow *zwindow = zwindows[vidx];
1346                 if( zwindow->idx < 0 ) continue;
1347                 zwindow->handle_mixer(STOP, 0, 0, 0, 0, 0);
1348         }
1349 }
1350
1351 void MWindow::close_mixers(int result)
1352 {
1353         ArrayList<ZWindow*> closed;
1354         zwindows_lock->lock("MWindow::close_mixers");
1355         for( int i=zwindows.size(); --i>=0; ) {
1356                 ZWindow *zwindow = zwindows[i];
1357                 if( zwindow->idx < 0 ) continue;
1358                 zwindow->idx = -1;
1359                 ZWindowGUI *zgui = zwindow->zgui;
1360                 zgui->lock_window("MWindow::select_zwindow 0");
1361                 zgui->set_done(result);
1362                 zgui->unlock_window();
1363                 closed.append(zwindow);
1364         }
1365         zwindows_lock->unlock();
1366         for( int i=0; i<closed.size(); ++i ) {
1367                 ZWindow *zwindow = closed[i];
1368                 zwindow->join();
1369         }
1370 }
1371
1372 ZWindow *MWindow::create_mixer(Indexable *indexable, double position)
1373 {
1374         ArrayList<Indexable*> new_assets;
1375         new_assets.append(indexable);
1376         Track *track = edl->tracks->last;
1377         load_assets(&new_assets, position, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 1);
1378         track = !track ? edl->tracks->first : track->next;
1379         Mixer *mixer = 0;
1380         ZWindow *zwindow = get_mixer(mixer);
1381         while( track ) {
1382                 track->play = track->armed = 0;
1383                 if( track->data_type == TRACK_VIDEO ) {
1384                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1385                 }
1386                 mixer->mixer_ids.append(track->get_mixer_id());
1387                 track = track->next;
1388         }
1389         if(  indexable->is_asset ) {
1390                 char *path = indexable->path;
1391                 char *tp = strrchr(path, '/');
1392                 if( !tp ) tp = path; else ++tp;
1393                 zwindow->set_title(tp);
1394         }
1395         else {
1396                 char *title = ((EDL*)indexable)->local_session->clip_title;
1397                 zwindow->set_title(title);
1398         }
1399         return zwindow;
1400 }
1401
1402 void MWindow::create_mixers(double position)
1403 {
1404         if( !session->drag_assets->size() &&
1405             !session->drag_clips->size() ) return;
1406         undo_before();
1407
1408         select_zwindow(0);
1409         ArrayList<ZWindow *>new_mixers;
1410
1411         for( int i=0; i<session->drag_assets->size(); ++i ) {
1412                 Indexable *indexable = session->drag_assets->get(i);
1413                 if( !indexable->have_video() ) continue;
1414                 ZWindow *zwindow = create_mixer(indexable, position);
1415                 new_mixers.append(zwindow);
1416         }
1417         for( int i=0; i<session->drag_clips->size(); ++i ) {
1418                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1419                 if( !indexable->have_video() ) continue;
1420                 ZWindow *zwindow = create_mixer(indexable, position);
1421                 new_mixers.append(zwindow);
1422         }
1423
1424         tile_mixers();
1425         for( int i=0; i<new_mixers.size(); ++i )
1426                 new_mixers[i]->start();
1427
1428         refresh_mixers();
1429         save_backup();
1430         undo_after(_("create mixers"), LOAD_ALL);
1431         restart_brender();
1432         gui->update(1, FORCE_REDRAW, 1, 1, 1, 1, 0);
1433         sync_parameters(CHANGE_ALL);
1434 }
1435
1436 void MWindow::open_mixers()
1437 {
1438         for( int i=0; i<edl->mixers.size(); ++i ) {
1439                 Mixer *mixer = edl->mixers[i];
1440                 ZWindow *zwindow = get_mixer(mixer);
1441                 zwindow->set_title(mixer->title);
1442                 zwindow->start();
1443         }
1444         refresh_mixers();
1445 }
1446
1447 int MWindow::select_zwindow(ZWindow *zwindow)
1448 {
1449         int ret = 0, n = zwindows.number_of(zwindow);
1450         if( session->selected_zwindow != n ) {
1451                 session->selected_zwindow = n;
1452                 for( int i=0; i<zwindows.size(); ++i ) {
1453                         ZWindow *zwindow = zwindows[i];
1454                         if( zwindow->idx < 0 ) continue;
1455                         ZWindowGUI *zgui = zwindow->zgui;
1456                         zgui->lock_window("MWindow::select_zwindow 0");
1457                         zwindow->highlighted = i == n ? 1 : 0;
1458                         if( zgui->draw_overlays() )
1459                                 zgui->canvas->get_canvas()->flash(1);
1460                         zgui->unlock_window();
1461                 }
1462                 ret = 1;
1463                 gui->lock_window("MWindow::select_window 1");
1464                 gui->update_mixers(0, -1);
1465                 gui->unlock_window();
1466         }
1467         return ret;
1468 }
1469
1470 void MWindow::tile_mixers()
1471 {
1472         int x1 = session->tile_mixers_x;
1473         int y1 = session->tile_mixers_y;
1474         int x2 = x1 + session->tile_mixers_w;
1475         int y2 = y1 + session->tile_mixers_h;
1476         tile_mixers(x1, y1, x2, y2);
1477 }
1478
1479 void MWindow::tile_mixers(int x1, int y1, int x2, int y2)
1480 {
1481         if( x1 == x2 || y1 == y2 ) {
1482 // use top left quadrent
1483                 int sw = gui->get_screen_w(1, -1);
1484                 int sh = gui->get_screen_w(1, -1);
1485                 x1 = 1;     y1 = 1;
1486                 x2 = sw/2;  y2 = sh/2;
1487         }
1488         else {
1489                 if( x1 > x2 ) { int t = x1;  x1 = x2;  x2 = t; }
1490                 if( y1 > y2 ) { int t = y1;  y1 = y2;  y2 = t; }
1491         }
1492         int ow = edl->session->output_w, oh = edl->session->output_h;
1493         int nz = 0;
1494         for( int i=0; i<zwindows.size(); ++i ) {
1495                 ZWindow *zwindow = zwindows[i];
1496                 if( zwindow->idx < 0 ) continue;
1497                 ++nz;
1498         }
1499         if( !nz ) return;
1500         int lt = BC_DisplayInfo::get_left_border();
1501         int top = BC_DisplayInfo::get_top_border();
1502         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1503         int bh = top + BC_DisplayInfo::get_bottom_border();
1504         int mw = xS(10+10), mh = yS(10+10); // canvas margins
1505         int dx = x2 - x1, dy = y2 - y1;
1506         int64_t sz = dx * dy, best_r = sz;
1507         int bx = 1, by = nz;
1508         for( int nx=1; nx<=nz; ++nx ) {
1509                 int ny = ceil((double)nz / nx);
1510                 int zw = dx / nx;
1511                 int ww = zw - bw;
1512                 int hh = (ww - mw) * oh / ow + mh;
1513                 int zh = hh + bh;
1514                 int64_t za = zw*nx * zh*ny;
1515                 int64_t r = sz - za;
1516                 if( r < 0 ) continue;
1517                 if( r >= best_r ) continue;
1518                 best_r = r;
1519                 bx = nx;  by = ny;
1520         }
1521         for( int ny=1; ny<=nz; ++ny ) {
1522                 int nx = ceil((double)nz / ny);
1523                 int zh = dy / ny;
1524                 int hh = zh - bh;
1525                 int ww = (hh - mh) * ow / oh + mw;
1526                 int zw = ww + bw;
1527                 int64_t za = zw*nx * zh*ny;
1528                 int64_t r = sz - za;
1529                 if( r < 0 ) continue;
1530                 if( r >= best_r ) continue;
1531                 best_r = r;
1532                 bx = nx;  by = ny;
1533         }
1534         int zw, zh, ww, hh;
1535         if( bx < by ) {
1536                 zh = dy / by;
1537                 hh = zh - bh;
1538                 ww = (hh - mh) * ow / oh + mw;
1539                 zw = ww + bw;
1540         }
1541         else {
1542                 zw = dx / bx;
1543                 ww = zw - bw;
1544                 hh = (ww - mw) * oh / ow + mh;
1545                 zh = hh + bh;
1546         }
1547
1548         int zx = 0, zy = 0;  // window origins
1549         int n = 0;
1550         for( int i=0; i<zwindows.size(); ++i ) {
1551                 ZWindow *zwindow = zwindows[i];
1552                 if( zwindow->idx < 0 ) continue;
1553                 int xx = zx + x1, yy = zy + y1;
1554                 int mx = x2 - zw, my = y2 - zh;
1555                 if( xx > mx ) xx = mx;
1556                 if( yy > my ) yy = my;
1557                 zwindow->reposition(xx,yy, ww,hh);
1558                 if( zwindow->running() ) {
1559                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1560                         gui->lock_window("MWindow::tile_mixers");
1561                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1562                         gui->unlock_window();
1563                 }
1564                 if( ++n >= bx ) {
1565                         zx = 0;  zy += zh;
1566                         n = 0;
1567                 }
1568                 else
1569                         zx += zw;
1570         }
1571 }
1572
1573 void MWindow::set_gang_tracks(int v)
1574 {
1575         edl->local_session->gang_tracks = v;
1576         sync_parameters(CHANGE_PARAMS);
1577         gui->update(1, 1, 0, 0, 1, 0, 0);
1578         gui->flush();
1579 }
1580
1581
1582 void MWindow::init_cache()
1583 {
1584         audio_cache = new CICache(preferences);
1585         video_cache = new CICache(preferences);
1586         frame_cache = new FrameCache;
1587         wave_cache = new WaveCache;
1588 }
1589
1590 void MWindow::init_channeldb()
1591 {
1592         channeldb_buz->load("channeldb_buz");
1593         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1594 }
1595
1596 void MWindow::init_menus()
1597 {
1598         char string[BCTEXTLEN];
1599
1600         // Color Models
1601         BC_CModels::to_text(string, BC_RGB888);
1602         colormodels.append(new ColormodelItem(string, BC_RGB888));
1603         BC_CModels::to_text(string, BC_RGBA8888);
1604         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1605 //      BC_CModels::to_text(string, BC_RGB161616);
1606 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1607 //      BC_CModels::to_text(string, BC_RGBA16161616);
1608 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1609         BC_CModels::to_text(string, BC_RGB_FLOAT);
1610         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1611         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1612         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1613         BC_CModels::to_text(string, BC_YUV888);
1614         colormodels.append(new ColormodelItem(string, BC_YUV888));
1615         BC_CModels::to_text(string, BC_YUVA8888);
1616         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1617 //      BC_CModels::to_text(string, BC_YUV161616);
1618 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1619 //      BC_CModels::to_text(string, BC_YUVA16161616);
1620 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1621
1622 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1623                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1624
1625 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1626                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1627
1628         // Interlacing Modes
1629         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1630
1631         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1632         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1633
1634         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1635         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1636
1637         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1638         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1639
1640         mixers_align = new MixersAlign(this);
1641 }
1642
1643 void MWindow::init_indexes()
1644 {
1645         mainindexes = new MainIndexes(this);
1646         mainindexes->start_loop();
1647 }
1648
1649 void MWindow::init_gui()
1650 {
1651         gui = new MWindowGUI(this);
1652         gui->create_objects();
1653         gui->load_defaults(defaults);
1654 }
1655
1656 void MWindow::init_signals()
1657 {
1658         sighandler = new SigHandler;
1659         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1660 ENABLE_BUFFER
1661 }
1662
1663 void MWindow::init_render()
1664 {
1665         render = new Render(this);
1666         create_bd = new CreateBD_Thread(this);
1667         create_dvd = new CreateDVD_Thread(this);
1668         batch_render = new BatchRenderThread(this);
1669 }
1670
1671 void MWindow::init_exportedl()
1672 {
1673         exportedl = new ExportEDL(this);
1674 }
1675
1676
1677 void MWindow::init_shuttle()
1678 {
1679 #ifdef HAVE_SHUTTLE
1680         int ret = Shuttle::probe();
1681         if( ret >= 0 ) {
1682                 shuttle = new Shuttle(this);
1683                 if( shuttle->read_config_file() > 0 ) {
1684                         printf("shuttle: bad config file\n");
1685                         delete shuttle;  shuttle = 0;
1686                         return;
1687                 }
1688                 shuttle->start(ret);
1689         }
1690 #endif
1691 }
1692 void MWindow::init_wintv()
1693 {
1694 #ifdef HAVE_WINTV
1695         wintv = WinTV::probe(this);
1696         if( wintv )
1697                 wintv->start();
1698 #endif
1699 }
1700 void MWindow::init_x10tv()
1701 {
1702 #ifdef HAVE_X10TV
1703         x10tv = X10TV::probe(this);
1704         if( x10tv )
1705                 x10tv->start();
1706 #endif
1707 }
1708
1709
1710 void MWindow::init_brender()
1711 {
1712         if(preferences->use_brender && !brender)
1713         {
1714                 brender_lock->lock("MWindow::init_brender 1");
1715                 brender = new BRender(this);
1716                 brender->initialize();
1717                 session->brender_end = 0;
1718                 brender_lock->unlock();
1719         }
1720         else
1721         if(!preferences->use_brender && brender)
1722         {
1723                 brender_lock->lock("MWindow::init_brender 2");
1724                 delete brender;
1725                 brender = 0;
1726                 session->brender_end = 0;
1727                 brender_lock->unlock();
1728         }
1729         brender_active = 0;
1730         stop_brender();
1731 }
1732
1733 void MWindow::restart_brender()
1734 {
1735 //printf("MWindow::restart_brender 1\n");
1736         if( !brender_active || !preferences->use_brender ) return;
1737         if( !brender ) return;
1738         brender->restart(edl);
1739 }
1740
1741 void MWindow::stop_brender()
1742 {
1743         if( !brender ) return;
1744 // cannot be holding mwindow->gui display lock
1745         brender->stop();
1746 }
1747
1748 int MWindow::brender_available(int position)
1749 {
1750         int result = 0;
1751         brender_lock->lock("MWindow::brender_available 1");
1752         if(brender && brender_active)
1753         {
1754                 if(brender->map_valid)
1755                 {
1756                         brender->map_lock->lock("MWindow::brender_available 2");
1757                         if(position < brender->map_size &&
1758                                 position >= 0)
1759                         {
1760 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1761                                 if(brender->map[position] == BRender::RENDERED)
1762                                         result = 1;
1763                         }
1764                         brender->map_lock->unlock();
1765                 }
1766         }
1767         brender_lock->unlock();
1768         return result;
1769 }
1770
1771 void MWindow::set_brender_active(int v, int update)
1772 {
1773         if( !preferences->use_brender ) v = 0;
1774         brender_active = v;
1775         gui->mainmenu->brender_active->set_checked(v);
1776         if( v != 0 ) {
1777                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1778                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1779
1780                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1781                         edl->session->brender_end = edl->tracks->total_video_length();
1782                 }
1783                 restart_brender();
1784         }
1785         else {
1786                 edl->session->brender_start = edl->session->brender_end = 0;
1787                 gui->unlock_window();
1788                 stop_brender();
1789                 gui->lock_window("MWindow::set_brender_active");
1790         }
1791         if( update ) {
1792                 gui->update_timebar(0);
1793                 gui->draw_overlays(1);
1794         }
1795 }
1796
1797 int MWindow::has_commercials()
1798 {
1799 #ifdef HAVE_COMMERCIAL
1800         return theme->use_commercials;
1801 #else
1802         return 0;
1803 #endif
1804 }
1805
1806 void MWindow::init_commercials()
1807 {
1808 #ifdef HAVE_COMMERCIAL
1809         if( !commercials ) {
1810                 commercials = new Commercials(this);
1811                 commercial_active = 0;
1812         }
1813         else
1814                 commercials->add_user();
1815 #endif
1816 }
1817
1818 void MWindow::commit_commercial()
1819 {
1820 #ifdef HAVE_COMMERCIAL
1821         if( !commercial_active ) return;
1822         commercial_active = 0;
1823         if( !commercials ) return;
1824         commercials->commitDb();
1825 #endif
1826 }
1827
1828 void MWindow::undo_commercial()
1829 {
1830 #ifdef HAVE_COMMERCIAL
1831         if( !commercial_active ) return;
1832         commercial_active = 0;
1833         if( !commercials ) return;
1834         commercials->undoDb();
1835 #endif
1836 }
1837
1838 int MWindow::put_commercial()
1839 {
1840         int result = 0;
1841 #ifdef HAVE_COMMERCIAL
1842         double start = edl->local_session->get_selectionstart();
1843         double end = edl->local_session->get_selectionend();
1844         if( start >= end ) return 0;
1845
1846         const char *errmsg = 0;
1847         int count = 0;
1848         Tracks *tracks = edl->tracks;
1849         //check it
1850         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1851                 if( track->data_type != TRACK_VIDEO ) continue;
1852                 if( !track->armed ) continue;
1853                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1854                 ++count;
1855                 int64_t units_start = track->to_units(start,0);
1856                 int64_t units_end = track->to_units(end,0);
1857                 Edits *edits = track->edits;
1858                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1859                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1860                 if(!edit1 && !edit2) continue;  // nothing selected
1861                 if(!edit2) {                    // edit2 beyond end of track
1862                         edit2 = edits->last;
1863                         units_end = edits->length();
1864                 }
1865                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1866                 Indexable *indexable = edit1->get_source();
1867                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1868         }
1869         //run it
1870         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1871                 if( track->data_type != TRACK_VIDEO ) continue;
1872                 if( !track->armed ) continue;
1873                 int64_t units_start = track->to_units(start,0);
1874                 int64_t units_end = track->to_units(end,0);
1875                 Edits *edits = track->edits;
1876                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1877                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1878                 if(!edit1 && !edit2) continue;  // nothing selected
1879                 if(!edit2) {                    // edit2 beyond end of track
1880                         edit2 = edits->last;
1881                         units_end = edits->length();
1882                 }
1883                 Indexable *indexable = edit1->get_source();
1884                 Asset *asset = (Asset *)indexable;
1885                 File *file = video_cache->check_out(asset, edl);
1886                 if( !file ) { errmsg = _("no file"); break; }
1887                 int64_t edit_length = units_end - units_start;
1888                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1889                 result = commercials->put_clip(file, edit1->channel,
1890                         track->from_units(edit_start), track->from_units(edit_length));
1891                 video_cache->check_in(asset);
1892                 if( result ) { errmsg = _("db failed"); break; }
1893         }
1894         if( errmsg ) {
1895                 char string[BCTEXTLEN];
1896                 sprintf(string, _("put_commercial: %s"), errmsg);
1897                 MainError::show_error(string);
1898                 undo_commercial();
1899                 result = 1;
1900         }
1901 #endif
1902         return result;
1903 }
1904
1905 void MWindow::stop_playback(int wait)
1906 {
1907         gui->stop_drawing();
1908
1909         cwindow->stop_playback(wait);
1910
1911         for(int i = 0; i < vwindows.size(); i++) {
1912                 VWindow *vwindow = vwindows[i];
1913                 if( !vwindow->is_running() ) continue;
1914                 vwindow->stop_playback(wait);
1915         }
1916         for(int i = 0; i < zwindows.size(); i++) {
1917                 ZWindow *zwindow = zwindows[i];
1918                 if( zwindow->idx < 0 ) continue;
1919                 zwindow->stop_playback(wait);
1920         }
1921 }
1922
1923 void MWindow::stop_transport()
1924 {
1925         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1926 }
1927
1928 void MWindow::undo_before(const char *description, void *creator)
1929 {
1930         undo->update_undo_before(description, creator);
1931 }
1932
1933 void MWindow::undo_after(const char *description, uint32_t load_flags, int changes_made)
1934 {
1935         undo->update_undo_after(description, load_flags, changes_made);
1936 }
1937
1938 void MWindow::beep(double freq, double secs, double gain)
1939 {
1940         if( !beeper ) beeper = new Beeper(this);
1941         beeper->tone(freq, secs, gain);
1942 }
1943
1944 Beeper::Beeper(MWindow *mwindow)
1945  : Thread(1, 0, 0)
1946 {
1947         this->mwindow = mwindow;
1948         audio = new AudioDevice(mwindow);
1949         playing_audio = 0;
1950         interrupted = -1;
1951 }
1952
1953 Beeper::~Beeper()
1954 {
1955         stop(0);
1956         delete audio;
1957 }
1958
1959 void Beeper::run()
1960 {
1961         int channels = 2;
1962         int64_t bfrsz = BEEP_SAMPLE_RATE;
1963         EDL *edl = mwindow->edl;
1964         EDLSession *session = edl->session;
1965         AudioOutConfig *aconfig = session->playback_config->aconfig;
1966         audio->open_output(aconfig, BEEP_SAMPLE_RATE, bfrsz, channels, 0);
1967         audio->start_playback();
1968
1969         double out0[bfrsz], out1[bfrsz], *out[2] = { out0, out1 };
1970         const double two_pi = 2*M_PI;
1971         int64_t audio_len = BEEP_SAMPLE_RATE * secs;
1972         const double dt = two_pi * freq/BEEP_SAMPLE_RATE;
1973         double th = 0;
1974
1975         audio_pos = 0;
1976         playing_audio = 1;
1977         while( !interrupted ) {
1978                 int len = audio_len - audio_pos;
1979                 if( len <= 0 ) break;
1980                 if( len > bfrsz ) len = bfrsz;
1981                 int k = audio_pos;
1982                 for( int i=0; i<len; ++i,++k,th+=dt ) {
1983                         double t = th - two_pi;
1984                         if( t >= 0 ) th = t;
1985                         out0[i] = out1[i] = sin(th) * gain;
1986                 }
1987                 audio->write_buffer(out, channels, len);
1988                 audio_pos = k;
1989         }
1990
1991         if( !interrupted )
1992                 audio->set_last_buffer();
1993         audio->stop_audio(interrupted ? 0 : 1);
1994         playing_audio = 0;
1995
1996         audio->close_all();
1997 }
1998
1999 void Beeper::start()
2000 {
2001         if( running() ) return;
2002         audio_pos = -1;
2003         interrupted = 0;
2004         Thread::start();
2005 }
2006
2007 void Beeper::stop(int wait)
2008 {
2009         if( running() && !interrupted ) {
2010                 interrupted = 1;
2011                 audio->stop_audio(wait);
2012         }
2013         Thread::join();
2014 }
2015
2016 void Beeper::tone(double freq, double secs, double gain)
2017 {
2018         stop(0);
2019         this->freq = freq;
2020         this->secs = secs;
2021         this->gain = gain;
2022         start();
2023 }
2024
2025
2026 int MWindow::load_filenames(ArrayList<char*> *filenames,
2027                 int load_mode, int edl_mode, int update_filename)
2028 {
2029         ArrayList<EDL*> new_edls;
2030         ArrayList<Asset*> new_assets;
2031         ArrayList<File*> new_files;
2032
2033 //      save_defaults();
2034         gui->start_hourglass();
2035
2036 // Need to stop playback since tracking depends on the EDL not getting
2037 // deleted.
2038         gui->unlock_window();
2039         stop_playback(1);
2040         gui->lock_window("MWindow::load_filenames 0");
2041         undo_before();
2042
2043 const int debug = 0;
2044 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2045
2046 // Define new_edls and new_assets to load
2047         int result = 0, ftype = -1;
2048
2049         for( int i=0; i<filenames->size(); ++i ) {
2050 // Get type of file
2051                 File *new_file = new File;
2052                 Asset *new_asset = new Asset(filenames->get(i));
2053                 EDL *new_edl = new EDL;
2054                 new_edl->create_objects();
2055                 new_edl->copy_session(edl, -1);
2056                 new_file->set_program(edl->session->program_no);
2057
2058                 char string[BCTEXTLEN];
2059                 sprintf(string, _("Loading %s"), new_asset->path);
2060                 gui->show_message(string);
2061
2062                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
2063
2064                 result = 1;
2065                 switch( ftype ) {
2066 // Convert media file to EDL
2067                 case FILE_OK: {
2068 // Warn about odd image dimensions
2069                         if( new_asset->video_data &&
2070                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
2071                                 eprintf(_("%s's resolution is %dx%d.\n"
2072                                         "Images with odd dimensions may not decode properly."),
2073                                         new_asset->path, new_asset->width, new_asset->height);
2074                         }
2075
2076                         if( new_asset->program >= 0 &&
2077                             edl->session->program_no != new_asset->program ) {
2078                                 eprintf(_("%s's index was built for program number %d\n"
2079                                         "Playback preference is %d.\n  Using program %d."),
2080                                         new_asset->path, new_asset->program,
2081                                         edl->session->program_no, new_asset->program);
2082                         }
2083
2084                         if( load_mode == LOADMODE_RESOURCESONLY ) {
2085                                 new_assets.append(new_asset);
2086                                 new_asset->add_user();
2087                                 result = 0;
2088                                 break;
2089                         }
2090
2091                         RecordLabels *labels = edl->session->label_cells ?
2092                                 new RecordLabels(new_file) : 0;
2093                         asset_to_edl(new_edl, new_asset, labels);
2094                         new_edls.append(new_edl);
2095                         new_edl->add_user();
2096                         delete labels;
2097
2098                         if( load_mode == LOADMODE_REPLACE ||
2099                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2100 // Set filename to nothing for assets since save EDL would overwrite them.
2101                                 set_filename("");
2102 // Reset timeline position
2103                                 for( int i=0; i<TOTAL_PANES; ++i ) {
2104                                         new_edl->local_session->view_start[i] = 0;
2105                                         new_edl->local_session->track_start[i] = 0;
2106                                 }
2107                         }
2108                         result = 0;
2109                         break; }
2110
2111                 case FILE_NOT_FOUND: {
2112                         eprintf(_("Failed to open %s"), new_asset->path);
2113                         sprintf(string, _("Failed to open %s"), new_asset->path);
2114                         gui->show_message(string, theme->message_error);
2115                         gui->update_default_message();
2116                         break; }
2117
2118 // Unknown format
2119                 case FILE_UNRECOGNIZED_CODEC: {
2120 // Test index file
2121                         { IndexFile indexfile(this, new_asset);
2122                         if( !(result = indexfile.open_index()) )
2123                                 indexfile.close_index(); }
2124
2125 // Test existing EDLs
2126                         for( int j=0; result && j<new_edls.total; ++j ) {
2127                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
2128                                 if( old_asset ) {
2129                                         new_asset->copy_from(old_asset,1);
2130                                         result = 0;
2131                                 }
2132                         }
2133                         if( result ) {
2134                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
2135                                 if( old_asset ) {
2136                                         new_asset->copy_from(old_asset,1);
2137                                         result = 0;
2138                                 }
2139                         }
2140
2141 // Prompt user
2142                         if( result ) {
2143                                 new_asset->audio_data = 1;
2144                                 new_asset->format = FILE_PCM;
2145                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
2146                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
2147                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
2148                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
2149                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
2150                                 new_asset->header = defaults->get("HEADER", 0);
2151
2152                                 FileSystem fs;
2153                                 fs.extract_name(string, new_asset->path);
2154                                 strcat(string, _("'s format couldn't be determined."));
2155                                 FileFormat fwindow(this);
2156                                 fwindow.create_objects(new_asset, string);
2157                                 result = fwindow.run_window();
2158
2159                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
2160                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
2161                                 defaults->update("AUDIO_BITS", new_asset->bits);
2162                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
2163                                 defaults->update("SIGNED_", new_asset->signed_);
2164                                 defaults->update("HEADER", new_asset->header);
2165                                 save_defaults();
2166                         }
2167 // Append to list
2168                         if( !result ) {
2169 // Recalculate length
2170                                 delete new_file;
2171                                 new_file = new File;
2172                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2173
2174                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
2175                                         RecordLabels *labels = edl->session->label_cells ?
2176                                                 new RecordLabels(new_file) : 0;
2177                                         asset_to_edl(new_edl, new_asset, labels);
2178                                         new_edls.append(new_edl);
2179                                         new_edl->add_user();
2180                                         delete labels;
2181                                 }
2182                                 else {
2183                                         new_assets.append(new_asset);
2184                                         new_asset->add_user();
2185                                 }
2186                         }
2187                         break; }
2188
2189                 case FILE_IS_XML: {
2190                         FileXML xml_file;
2191                         const char *filename = filenames->get(i);
2192                         if( xml_file.read_from_file(filename, 1) ) {
2193                                 eprintf(_("Error: unable to open:\n  %s"), filename);
2194                                 break;
2195                         }
2196                         const char *cin_version = 0;
2197                         while( !xml_file.read_tag() ) {
2198                                 if( xml_file.tag.title_is("EDL") ) {
2199                                         cin_version = xml_file.tag.get_property("VERSION");
2200                                         break;
2201                                 }
2202                         }
2203                         xml_file.rewind();
2204                         if( !cin_version ) {
2205                                 eprintf(_("XML file %s\n not from cinelerra."),filename);
2206                                 char string[BCTEXTLEN];
2207                                 sprintf(string,_("Unknown %s"), filename);
2208                                 gui->show_message(string);
2209                                 break;
2210                         }
2211                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2212                             strcmp(cin_version, "Unify") &&
2213                             strcmp(cin_version, "5.1") ) {
2214                                 eprintf(_("Warning: XML from cinelerra version %s\n"
2215                                         "Session data may be incompatible."), cin_version);
2216                         }
2217                         if( new_edl->load_xml(&xml_file, LOAD_ALL) ) {
2218                                 eprintf(_("Error: unable to load:\n  %s"), filename);
2219                                 break;
2220                         }
2221                         test_plugins(new_edl, filename);
2222                         int groups = new_edl->regroup(session->group_number);
2223                         session->group_number += groups;
2224                         switch( edl_mode ) {
2225                         case LOADMODE_EDL_CLIP: {
2226                                 strcpy(new_edl->local_session->clip_title,
2227                                         filenames->get(i));
2228                                 struct stat st;
2229                                 time_t t = !stat(filenames->get(i),&st) ?
2230                                         st.st_mtime : time(&t);
2231                                 ctime_r(&t, new_edl->local_session->clip_notes);
2232                                 switch( load_mode ) {
2233                                 case LOADMODE_REPLACE:
2234                                 case LOADMODE_REPLACE_CONCATENATE:
2235                                         strcpy(session->filename, filename);
2236                                         if( update_filename ) set_filename(filename);
2237                                         break;
2238                                 }
2239                                 result = 0;
2240                                 break; }
2241                         case LOADMODE_EDL_NESTED: {
2242                                 EDL *nested_edl = new EDL;
2243                                 nested_edl->create_objects();
2244                                 nested_edl->copy_session(edl, -1);
2245                                 nested_edl->create_nested(new_edl);
2246                                 nested_edl->set_path(filename);
2247                                 new_edl->remove_user();
2248                                 new_edl = nested_edl;
2249                                 result = 0;
2250                                 break; }
2251                         case LOADMODE_EDL_FILEREF: {
2252                                 result = create_ref(new_asset, new_edl);
2253                                 if( result ) break;
2254                                 new_assets.append(new_asset);
2255                                 new_asset->add_user();
2256                                 new_edl->remove_user();
2257                                 new_edl = new EDL;
2258                                 new_edl->create_objects();
2259                                 new_edl->copy_session(edl, -1);
2260                                 asset_to_edl(new_edl, new_asset);
2261                                 delete new_file;
2262                                 new_file = new File;
2263                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2264                                 break; }
2265                         }
2266                         if( !result ) {
2267                                 new_edls.append(new_edl);
2268                                 new_edl->add_user();
2269                         }
2270                         else
2271                                 eprintf(_("Error: Unable to load xml:\n  %s"), new_asset->path);
2272                         break; }
2273                 }
2274
2275                 new_edl->Garbage::remove_user();
2276                 new_asset->Garbage::remove_user();
2277
2278 // Store for testing index
2279                 new_files.append(new_file);
2280         }
2281
2282 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2283
2284         if(!result) {
2285                 gui->reset_default_message();
2286                 gui->default_message();
2287         }
2288
2289 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2290
2291 // Paste them.
2292 // Don't back up here.
2293         if( new_edls.size() ) {
2294 // For pasting, clear the active region
2295                 if( load_mode == LOADMODE_PASTE ) {
2296                         double start = edl->local_session->get_selectionstart();
2297                         double end = edl->local_session->get_selectionend();
2298                         if(!EQUIV(start, end))
2299                                 edl->clear(start, end,
2300                                         edl->session->labels_follow_edits,
2301                                         edl->session->plugins_follow_edits,
2302                                         edl->session->autos_follow_edits);
2303
2304                         paste_edls(&new_edls, load_mode, 0, -1,
2305                                 edl->session->labels_follow_edits,
2306                                 edl->session->plugins_follow_edits,
2307                                 edl->session->autos_follow_edits,
2308                                 0); // overwrite
2309                 }
2310                 else if( load_mode == LOADMODE_NEW_TRACKS &&
2311                          edl_mode != LOADMODE_EDL_CLIP )
2312                         paste_edls(&new_edls, load_mode, 0, -1, 0, 0, 0, 0);
2313                 else if( load_mode != LOADMODE_RESOURCESONLY ||
2314                          edl_mode == LOADMODE_EDL_CLIP )
2315                         paste_edls(&new_edls, load_mode, 0, -1, 1, 1, 1, 0);
2316                 else
2317                         paste_edls(&new_edls, LOADMODE_NOTHING, 0, -1, 0, 0, 0, 0);
2318
2319         }
2320
2321 // Add new assets to EDL and schedule assets for index building.
2322         int got_indexes = 0;
2323         for( int i=0; i<new_edls.size(); ++i ) {
2324                 EDL *new_edl = new_edls[i];
2325                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2326                         mainindexes->add_indexable(new_edl->nested_edls[j]);
2327                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2328                         got_indexes = 1;
2329                 }
2330
2331         }
2332
2333         for( int i=0; i<new_assets.size(); ++i ) {
2334                 Asset *new_asset = new_assets[i];
2335                 mainindexes->add_indexable(new_asset);
2336                 edl->assets->update(new_asset);
2337                 got_indexes = 1;
2338         }
2339
2340 // Start examining next batch of index files
2341         if(got_indexes) mainindexes->start_build();
2342
2343 // reload renderengine edl or the plugin guis will flip out
2344         sync_parameters(CHANGE_ALL);
2345 // Open plugin GUIs
2346         show_plugins();
2347
2348         // opening new session
2349         if( ( load_mode == LOADMODE_REPLACE ||
2350               load_mode == LOADMODE_REPLACE_CONCATENATE ) &&
2351             (ftype != FILE_IS_XML || edl_mode != LOADMODE_EDL_CLIP) ) {
2352                 select_asset(0, 0);
2353                 edl->session->proxy_state = PROXY_INACTIVE;
2354                 edl->session->proxy_scale = 1;
2355                 edl->session->proxy_disabled_scale = 1;
2356                 edl->session->proxy_use_scaler = 0;
2357                 edl->session->proxy_auto_scale = 0;
2358                 edl->session->proxy_beep = 0;
2359                 edl->local_session->preview_start = 0;
2360                 edl->local_session->preview_end = -1;
2361                 edl->local_session->loop_playback = 0;
2362                 edl->local_session->set_selectionstart(0);
2363                 edl->local_session->set_selectionend(0);
2364                 edl->local_session->unset_inpoint();
2365                 edl->local_session-> unset_outpoint();
2366                 set_brender_active(0, 0);
2367                 fit_selection();
2368                 goto_start();
2369         }
2370
2371         if( edl->session->proxy_state != PROXY_INACTIVE && edl->session->proxy_auto_scale &&
2372             load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) {
2373                 ArrayList<Indexable *> orig_idxbls;
2374                 for( int i=0; i<new_assets.size(); ++i )
2375                         orig_idxbls.append(new_assets.get(i));
2376                 for( int i=0; i<new_edls.size(); ++i ) {
2377                         EDL *new_edl = new_edls[i];
2378                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2379                                 if( track->data_type != TRACK_VIDEO ) continue;
2380                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2381                                         Indexable *idxbl = (Indexable *)edit->asset;
2382                                         if( !idxbl ) continue;
2383                                         if( !idxbl->have_video() ) continue;
2384                                         if( edit->channel != 0 ) continue; // first layer only
2385                                         orig_idxbls.append(edit->asset);
2386                                 }
2387                         }
2388                 }
2389                 gui->unlock_window(); // to update progress bar
2390                 int ret = render_proxy(orig_idxbls);
2391                 gui->lock_window("MWindow::load_filenames");
2392                 float gain = edl->session->proxy_beep;
2393                 if( ret >= 0 && gain > 0 ) {
2394                         if( ret > 0 )
2395                                 beep(2000., 1.5, gain);
2396                         else
2397                                 beep(4000., 0.25, gain);
2398                 }
2399         }
2400
2401 // need to update undo before project, since mwindow is unlocked & a new load
2402 // can begin here.  Should really prevent loading until we're done.
2403 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2404         undo_after(_("load"), LOAD_ALL);
2405
2406         for(int i = 0; i < new_edls.size(); i++)
2407         {
2408                 new_edls[i]->remove_user();
2409         }
2410 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2411
2412         new_edls.remove_all();
2413
2414         for(int i = 0; i < new_assets.size(); i++)
2415         {
2416                 new_assets[i]->Garbage::remove_user();
2417         }
2418
2419         new_assets.remove_all();
2420         new_files.remove_all_objects();
2421
2422
2423 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2424         if(load_mode == LOADMODE_REPLACE ||
2425                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2426         {
2427                 session->changes_made = 0;
2428         }
2429         else
2430         {
2431                 session->changes_made = 1;
2432         }
2433
2434         gui->stop_hourglass();
2435
2436
2437 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2438         update_project(load_mode);
2439
2440 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2441
2442         return 0;
2443 }
2444
2445 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2446 {
2447         Asset *format_asset = new Asset;
2448         format_asset->format = FILE_FFMPEG;
2449         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2450         int new_scale = edl->session->proxy_scale;
2451         ProxyRender proxy_render(this, format_asset, new_scale);
2452
2453         for( int i=0; i<new_idxbls.size(); ++i ) {
2454                 Indexable *orig = new_idxbls.get(i);
2455                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2456                 if( !proxy ) continue;
2457                 FileSystem fs;
2458                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2459                 int got_it = exists && // if proxy exists, and is newer than orig
2460                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2461                 if( got_it ) continue;
2462                 proxy_render.add_needed(orig, proxy);
2463         }
2464
2465 // render needed proxies
2466         int result = proxy_render.create_needed_proxies(new_scale);
2467         if( !result ) {
2468                 add_proxy(&proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2469         }
2470         format_asset->remove_user();
2471         return !result ? proxy_render.needed_proxies.size() : -1;
2472 }
2473
2474 int MWindow::enable_proxy()
2475 {
2476         int ret = 0;
2477         if( edl->session->proxy_state == PROXY_DISABLED ) {
2478                 int new_scale = edl->session->proxy_disabled_scale;
2479                 int new_use_scaler = edl->session->proxy_use_scaler;
2480                 Asset *asset = new Asset;
2481                 asset->format = FILE_FFMPEG;
2482                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2483                 ret = to_proxy(asset, new_scale, new_use_scaler);
2484                 asset->remove_user();
2485                 if( ret > 0 ) {
2486                         float gain = edl->session->proxy_beep;
2487                         beep(2000., 1.5, gain);
2488                 }
2489                 edl->session->proxy_disabled_scale = 1;
2490                 edl->session->proxy_state = PROXY_ACTIVE;
2491                 gui->lock_window("MWindow::to_proxy");
2492                 update_project(LOADMODE_REPLACE);
2493                 gui->unlock_window();
2494         }
2495         return 1;
2496 }
2497
2498 int MWindow::disable_proxy()
2499 {
2500         if( edl->session->proxy_state == PROXY_ACTIVE ) {
2501                 int old_scale = edl->session->proxy_scale, new_scale = 0;
2502                 int new_use_scaler = edl->session->proxy_use_scaler;
2503                 Asset *asset = new Asset;
2504                 asset->format = FILE_FFMPEG;
2505                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2506                 to_proxy(asset, new_scale, new_use_scaler);
2507                 asset->remove_user();
2508                 edl->session->proxy_state = PROXY_DISABLED;
2509                 edl->session->proxy_disabled_scale = old_scale;
2510                 gui->lock_window("MWindow::to_proxy");
2511                 update_project(LOADMODE_REPLACE);
2512                 gui->unlock_window();
2513         }
2514         return 1;
2515 }
2516
2517 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2518 {
2519         ArrayList<Indexable*> orig_idxbls;
2520         ArrayList<Indexable*> proxy_assets;
2521
2522         edl->Garbage::add_user();
2523         save_backup();
2524         undo_before(_("proxy"), this);
2525         int asset_scale = !new_scale ? 0 :
2526                         !new_use_scaler ? 1 : new_scale;
2527         ProxyRender proxy_render(this, asset, asset_scale);
2528
2529 // revert project to original size from current size
2530 // remove all session proxy assets at the at the current proxy_scale
2531         int proxy_scale = edl->session->proxy_scale;
2532
2533         if( edl->session->proxy_state == PROXY_ACTIVE ) {
2534                 Asset *orig_asset = edl->assets->first;
2535                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2536                         char new_path[BCTEXTLEN];
2537                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2538 // test if proxy asset was already added to proxy_assets
2539                         int got_it = 0;
2540                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2541                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2542                         if( got_it ) continue;
2543                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2544                         if( !proxy_asset ) continue;
2545 // add pointer to existing EDL asset if it exists
2546 // EDL won't delete it unless it's the same pointer.
2547                         proxy_assets.append(proxy_asset);
2548                         proxy_asset->add_user();
2549                         orig_idxbls.append(orig_asset);
2550                         orig_asset->add_user();
2551                 }
2552                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2553                         EDL *orig_nested = edl->nested_edls[i];
2554                         char new_path[BCTEXTLEN];
2555                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2556 // test if proxy asset was already added to proxy_assets
2557                         int got_it = 0;
2558                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2559                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2560                         if( got_it ) continue;
2561                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2562                         if( !proxy_nested ) continue;
2563 // add pointer to existing EDL asset if it exists
2564 // EDL won't delete it unless it's the same pointer.
2565                         proxy_assets.append(proxy_nested);
2566                         proxy_nested->add_user();
2567                         orig_idxbls.append(orig_nested);
2568                         orig_nested->add_user();
2569                 }
2570
2571 // convert from the proxy assets to the original assets
2572                 edl->set_proxy(0, 0, &proxy_assets, &orig_idxbls);
2573
2574 // remove the references
2575                 for( int i=0; i<proxy_assets.size(); ++i ) {
2576                         Asset *proxy = (Asset *) proxy_assets[i];
2577                         proxy->width = proxy->actual_width;
2578                         proxy->height = proxy->actual_height;
2579                         proxy->remove_user();
2580                         edl->assets->remove_pointer(proxy);
2581                         proxy->remove_user();
2582                 }
2583                 proxy_assets.remove_all();
2584                 for( int i = 0; i < orig_idxbls.size(); i++ )
2585                         orig_idxbls[i]->remove_user();
2586                 orig_idxbls.remove_all();
2587         }
2588
2589         ArrayList<char *> confirm_paths;    // test for new files
2590         confirm_paths.set_array_delete();
2591
2592 // convert to new size if not original size
2593         if( new_scale ) {
2594                 FileSystem fs;
2595                 Asset *orig = edl->assets->first;
2596                 for( ; orig; orig=orig->next ) {
2597                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2598                         if( !proxy ) continue;
2599                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2600                         int got_it = exists && // if proxy exists, and is newer than orig
2601                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2602                         if( !got_it ) {
2603                                 if( exists ) // prompt user to overwrite
2604                                         confirm_paths.append(cstrdup(proxy->path));
2605                                 proxy_render.add_needed(orig, proxy);
2606                         }
2607                 }
2608                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2609                         EDL *orig_nested = edl->nested_edls[i];
2610                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2611                         if( !proxy ) continue;
2612                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2613                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2614                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2615                         if( !got_it ) {
2616                                 if( exists ) // prompt user to overwrite
2617                                         confirm_paths.append(cstrdup(proxy->path));
2618                                 proxy_render.add_needed(orig_nested, proxy);
2619                         }
2620                 }
2621                 edl->session->proxy_state = PROXY_ACTIVE;
2622         }
2623         else
2624                 edl->session->proxy_state = PROXY_INACTIVE;
2625
2626         int result = 0;
2627 // test for existing files
2628         if( confirm_paths.size() ) {
2629                 result = ConfirmSave::test_files(this, &confirm_paths);
2630                 confirm_paths.remove_all_objects();
2631         }
2632
2633         if( !result && new_scale )
2634                 result = proxy_render.create_needed_proxies(new_scale);
2635
2636         if( !result ) { // resize project
2637                 edl->set_proxy(new_scale, new_use_scaler,
2638                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2639         }
2640         undo_after(_("proxy"), LOAD_ALL);
2641         edl->Garbage::remove_user();
2642         restart_brender();
2643
2644         return !result ? proxy_render.needed_proxies.size() : -1;
2645 }
2646
2647 void MWindow::test_plugins(EDL *new_edl, const char *path)
2648 {
2649         char string[BCTEXTLEN];
2650
2651 // Do a check whether plugins exist
2652         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2653                 for( int k=0; k<track->plugin_set.total; ++k ) {
2654                         PluginSet *plugin_set = track->plugin_set[k];
2655                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2656                                         plugin; plugin = (Plugin*)plugin->next ) {
2657                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2658 // ok we need to find it in plugindb
2659                                 PluginServer *server =
2660                                         scan_plugindb(plugin->title, track->data_type);
2661                                 if( !server || server->transition ) {
2662                                         sprintf(string,
2663         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2664           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2665                                                 "effect", _(plugin->title), path);
2666                                         MainError::show_error(string);
2667                                 }
2668                         }
2669                 }
2670
2671                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2672                         if( !edit->transition ) continue;
2673 // ok we need to find transition in plugindb
2674                         PluginServer *server =
2675                                 scan_plugindb(edit->transition->title, track->data_type);
2676                         if( !server || !server->transition ) {
2677                                 sprintf(string,
2678         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2679           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2680                                         "transition", _(edit->transition->title), path);
2681                                 MainError::show_error(string);
2682                         }
2683                 }
2684         }
2685 }
2686
2687
2688 void MWindow::init_shm(const char *pfn, int64_t min)
2689 {
2690         int64_t result = 0;
2691 // Fix shared memory
2692         FILE *fd = fopen(pfn, "r");
2693         if( fd ) {
2694                 fscanf(fd, "%jd", &result);
2695                 fclose(fd);
2696                 if( result >= min ) return;
2697         }
2698
2699         fd = fopen(pfn, "w");
2700         if( !fd ) return;
2701         fprintf(fd, "0x%jx", min);
2702         fclose(fd);
2703
2704         fd = fopen(pfn, "r");
2705         if( !fd ) {
2706                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2707                 return;
2708         }
2709
2710         fscanf(fd, "%jd", &result);
2711         fclose(fd);
2712         if( result < min ) {
2713                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2714                         "you probably need to be root, or:\n"
2715                         "as root, run: echo 0x%jx > %s\n"
2716                         "before trying to start cinelerra.\n"
2717                         "It should be at least 0x%jx for Cinelerra.\n"),
2718                         pfn, (void *)result, min, pfn, min);
2719         }
2720 }
2721
2722 void MWindow::create_objects(int want_gui,
2723         int want_new,
2724         char *config_path)
2725 {
2726         const int debug = 0;
2727         if(debug) PRINT_TRACE
2728
2729 // For some reason, init_signals must come after show_splash or the signals won't
2730 // get trapped.
2731         init_signals();
2732         if(debug) PRINT_TRACE
2733         init_3d();
2734
2735         if(debug) PRINT_TRACE
2736
2737         if(debug) PRINT_TRACE
2738         default_standard = default_std();
2739         init_defaults(defaults, config_path);
2740         check_language();
2741         show_splash();
2742         init_preferences();
2743         if(splash_window)
2744                 splash_window->update_status(_("Initializing Plugins"));
2745         init_plugins(this, preferences);
2746         if(debug) PRINT_TRACE
2747         init_ladspa_plugins(this, preferences);
2748         if(debug) PRINT_TRACE
2749         init_plugin_tips(*plugindb, cin_lang);
2750         if(splash_window)
2751                 splash_window->update_status(_("Initializing GUI"));
2752         if(debug) PRINT_TRACE
2753         init_theme();
2754
2755         if(debug) PRINT_TRACE
2756         init_error();
2757
2758         if(splash_window)
2759                 splash_window->update_status(_("Initializing Fonts"));
2760         char string[BCTEXTLEN];
2761         strcpy(string, preferences->plugin_dir);
2762         strcat(string, "/" FONT_SEARCHPATH);
2763         BC_Resources::init_fontconfig(string);
2764         if(debug) PRINT_TRACE
2765 // use if plugged
2766         init_x10tv();
2767         if( !x10tv )
2768                 init_wintv();
2769
2770 // Default project created here
2771         init_edl();
2772         if(debug) PRINT_TRACE
2773
2774         init_cache();
2775         if(debug) PRINT_TRACE
2776
2777         Timer timer;
2778
2779         init_awindow();
2780         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2781
2782         init_compositor();
2783         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2784
2785 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2786         if(session->show_vwindow)
2787                 get_viewer(1, DEFAULT_VWINDOW);
2788         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2789
2790         init_gui();
2791         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2792
2793         init_levelwindow();
2794         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2795
2796         init_indexes();
2797         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2798
2799         init_channeldb();
2800         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2801
2802         init_gwindow();
2803         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2804
2805         init_render();
2806         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2807
2808         init_shuttle();
2809         init_brender();
2810         init_exportedl();
2811         init_commercials();
2812         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2813         mainprogress = new MainProgress(this, gui);
2814         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2815         undo = new MainUndo(this);
2816
2817         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2818
2819         plugin_guis = new PluginGUIs(this);
2820         dead_plugins = new ArrayList<PluginServer*>;
2821         keyframe_threads = new ArrayList<KeyFrameThread*>;
2822
2823         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2824                 __LINE__,
2825                 vwindows.size(),
2826                 session->show_vwindow);
2827
2828 // Show all vwindows
2829 //      if(session->show_vwindow) {
2830 //              for(int j = 0; j < vwindows.size(); j++) {
2831 //                      VWindow *vwindow = vwindows[j];
2832 //                      if( !vwindow->is_running() ) continue;
2833 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2834 //                              __LINE__,
2835 //                              vwindow);
2836 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2837 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2838 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2839 //                      vwindow->gui->show_window();
2840 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2841 //                      vwindow->gui->unlock_window();
2842 //              }
2843 //      }
2844
2845
2846         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2847
2848         if(session->show_cwindow)
2849         {
2850                 cwindow->gui->lock_window("MWindow::create_objects 1");
2851                 cwindow->gui->show_window();
2852                 cwindow->gui->unlock_window();
2853         }
2854
2855         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2856         if(session->show_awindow)
2857         {
2858                 awindow->gui->lock_window("MWindow::create_objects 1");
2859                 awindow->gui->show_window();
2860                 awindow->gui->unlock_window();
2861         }
2862
2863         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2864         if(session->show_lwindow)
2865         {
2866                 lwindow->gui->lock_window("MWindow::create_objects 1");
2867                 lwindow->gui->show_window();
2868                 lwindow->gui->unlock_window();
2869         }
2870
2871         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2872                 __LINE__,
2873                 (int)timer.get_difference(),
2874                 gwindow->gui);
2875         if(session->show_gwindow)
2876         {
2877                 gwindow->gui->lock_window("MWindow::create_objects 1");
2878                 gwindow->gui->show_window();
2879                 gwindow->gui->unlock_window();
2880         }
2881
2882         if(debug) PRINT_TRACE
2883
2884         gui->lock_window("MWindow::create_objects 1");
2885         gui->mainmenu->load_defaults(defaults);
2886         gui->mainmenu->update_toggles(0);
2887         gui->update_patchbay();
2888         gui->draw_canvas(0, 0);
2889         gui->draw_cursor(1);
2890         gui->show_window();
2891         gui->raise_window();
2892         gui->unlock_window();
2893         cwindow->gui->lock_window("MWindow::create_objects 1");
2894         cwindow->gui->tool_panel->raise_tool();
2895         cwindow->gui->unlock_window();
2896         if(debug) PRINT_TRACE
2897
2898         if(preferences->use_tipwindow)
2899                 init_tipwindow();
2900         if(debug) PRINT_TRACE
2901
2902         gui->add_keyboard_listener(
2903                 (int (BC_WindowBase::*)(BC_WindowBase *))
2904                 &MWindowGUI::keyboard_listener);
2905
2906         hide_splash();
2907         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2908         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2909         if(debug) PRINT_TRACE
2910
2911         BC_WindowBase::get_resources()->vframe_shm = 1;
2912 }
2913
2914 int MWindow::uses_opengl()
2915 {
2916         if( !playback_3d || !playback_3d->running() ) return 0;
2917         PlaybackConfig *playback_config = edl->session->playback_config;
2918         return playback_config->vconfig->driver == PLAYBACK_X11_GL ? 1 : 0;
2919 }
2920
2921 void MWindow::show_splash()
2922 {
2923 #include "data/heroine_logo9_png.h"
2924         VFrame *frame = new VFramePng(heroine_logo9_png);
2925         BC_DisplayInfo dpyi;
2926         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2927         int rr = (rw < rh ? rw : rh) / 4;
2928         splash_window = new SplashGUI(frame, rr, rr);
2929         splash_window->create_objects();
2930 }
2931
2932 void MWindow::hide_splash()
2933 {
2934         if(splash_window)
2935                 delete splash_window;
2936         splash_window = 0;
2937 }
2938
2939
2940 void MWindow::start()
2941 {
2942 ENABLE_BUFFER
2943 //PRINT_TRACE
2944 //      vwindows[DEFAULT_VWINDOW]->start();
2945         awindow->start();
2946 //PRINT_TRACE
2947         cwindow->start();
2948 //PRINT_TRACE
2949         lwindow->start();
2950 //PRINT_TRACE
2951         gwindow->start();
2952 //PRINT_TRACE
2953 //      Thread::start();
2954 //PRINT_TRACE
2955         playback_3d->start();
2956 //PRINT_TRACE
2957 }
2958
2959 void MWindow::run()
2960 {
2961         run_lock->lock("MWindow::run");
2962         gui->run_window();
2963         stop_playback(1);
2964
2965         brender_lock->lock("MWindow::run 1");
2966         delete brender;         brender = 0;
2967         brender_lock->unlock();
2968
2969         interrupt_indexes();
2970         clean_indexes();
2971         save_defaults();
2972         run_lock->unlock();
2973 }
2974
2975 void MWindow::show_vwindow(int raise)
2976 {
2977         int total_running = 0;
2978         session->show_vwindow = 1;
2979
2980 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2981 // Raise all windows which are visible
2982         for(int j = 0; j < vwindows.size(); j++) {
2983                 VWindow *vwindow = vwindows[j];
2984                 if( !vwindow->is_running() ) continue;
2985                 total_running++;
2986                 if( !raise && !vwindow->gui->is_hidden() ) continue;
2987                 vwindow->gui->lock_window("MWindow::show_vwindow");
2988                 vwindow->gui->show_window(0);
2989                 vwindow->gui->raise_window();
2990                 vwindow->gui->flush();
2991                 vwindow->gui->unlock_window();
2992         }
2993 // If no windows visible
2994         if( !total_running )
2995                 get_viewer(1, DEFAULT_VWINDOW);
2996
2997         gui->mainmenu->show_vwindow->set_checked(1);
2998 }
2999
3000
3001 void MWindow::hide_vwindow(int raise)
3002 {
3003         session->show_vwindow = 0;
3004         int total_running = 0;
3005
3006         for(int j = 0; j < vwindows.size(); j++) {
3007                 VWindow *vwindow = vwindows[j];
3008                 if( !vwindow->is_running() ) continue;
3009                 total_running++;
3010                 if( !raise && !vwindow->gui->is_hidden() ) continue;
3011                 vwindow->gui->lock_window("MWindow::show_vwindow");
3012                 vwindow->gui->hide_window(0);
3013                 vwindow->gui->unlock_window();
3014         }
3015         gui->mainmenu->show_vwindow->set_checked(0);
3016 }
3017
3018
3019 void MWindow::show_awindow()
3020 {
3021         session->show_awindow = 1;
3022         awindow->gui->lock_window("MWindow::show_awindow");
3023         awindow->gui->show_window();
3024         awindow->gui->raise_window();
3025         awindow->gui->flush();
3026         awindow->gui->unlock_window();
3027         gui->mainmenu->show_awindow->set_checked(1);
3028 }
3029
3030 void MWindow::hide_awindow()
3031 {
3032         session->show_awindow = 0;
3033
3034         awindow->gui->lock_window("MWindow::show_awindow");
3035         awindow->gui->hide_window();
3036         awindow->gui->unlock_window();
3037         gui->mainmenu->show_awindow->set_checked(0);
3038 }
3039
3040
3041 char *MWindow::get_cwindow_display()
3042 {
3043         char *x11_host = screens < 2 || session->window_config == 0 ?
3044                 session->a_x11_host : session->b_x11_host;
3045         return *x11_host ? x11_host : 0;
3046 }
3047
3048 void MWindow::show_cwindow()
3049 {
3050         session->show_cwindow = 1;
3051         cwindow->show_window();
3052         cwindow->gui->tool_panel->raise_tool();
3053         gui->mainmenu->show_cwindow->set_checked(1);
3054 }
3055
3056
3057 void MWindow::hide_cwindow()
3058 {
3059         session->show_cwindow = 0;
3060
3061         cwindow->gui->lock_window("MWindow::show_cwindow");
3062         cwindow->gui->hide_window();
3063         cwindow->gui->unlock_window();
3064         gui->mainmenu->show_cwindow->set_checked(0);
3065 }
3066
3067
3068 void MWindow::show_gwindow()
3069 {
3070         session->show_gwindow = 1;
3071
3072         gwindow->gui->lock_window("MWindow::show_gwindow");
3073         gwindow->gui->show_window();
3074         gwindow->gui->raise_window();
3075         gwindow->gui->flush();
3076         gwindow->gui->unlock_window();
3077
3078         gui->mainmenu->show_gwindow->set_checked(1);
3079 }
3080
3081 void MWindow::hide_gwindow()
3082 {
3083         session->show_gwindow = 0;
3084
3085         gwindow->gui->lock_window("MWindow::show_gwindow");
3086         gwindow->gui->hide_window();
3087         gwindow->gui->unlock_window();
3088         gui->mainmenu->show_gwindow->set_checked(0);
3089 }
3090
3091 void MWindow::show_lwindow()
3092 {
3093         session->show_lwindow = 1;
3094         lwindow->gui->lock_window("MWindow::show_lwindow");
3095         lwindow->gui->show_window();
3096         lwindow->gui->raise_window();
3097         lwindow->gui->flush();
3098         lwindow->gui->unlock_window();
3099         gui->mainmenu->show_lwindow->set_checked(1);
3100 }
3101
3102 void MWindow::hide_lwindow()
3103 {
3104         session->show_lwindow = 0;
3105
3106         lwindow->gui->lock_window("MWindow::show_lwindow");
3107         lwindow->gui->hide_window();
3108         lwindow->gui->unlock_window();
3109         gui->mainmenu->show_lwindow->set_checked(0);
3110 }
3111
3112
3113 void MWindow::restore_windows()
3114 {
3115         gui->unlock_window();
3116         if( !session->show_vwindow ) {
3117                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
3118                         VWindow *vwindow = vwindows[i];
3119                         if( !vwindow || !vwindow->is_running() ) continue;
3120                         vwindow->gui->lock_window("MWindow::restore_windows");
3121                         vwindow->gui->close(1);
3122                         vwindow->gui->unlock_window();
3123                 }
3124         }
3125         else 
3126                 show_vwindow(0);
3127
3128         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
3129                 awindow->gui->lock_window("MWindow::restore_windows");
3130                 awindow->gui->close_event();
3131                 awindow->gui->unlock_window();
3132         }
3133         else if( session->show_awindow && awindow->gui->is_hidden() )
3134                 show_awindow();
3135
3136         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
3137                 cwindow->gui->lock_window("MWindow::restore_windows");
3138                 cwindow->hide_window();
3139                 cwindow->gui->unlock_window();
3140         }
3141         else if( session->show_cwindow && cwindow->gui->is_hidden() )
3142                 show_cwindow();
3143
3144         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
3145                 gwindow->gui->lock_window("MWindow::restore_windows");
3146                 gwindow->gui->close_event();
3147                 gwindow->gui->unlock_window();
3148         }
3149         else if( session->show_gwindow && gwindow->gui->is_hidden() )
3150                 show_gwindow();
3151
3152         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
3153                 lwindow->gui->lock_window("MWindow::restore_windows");
3154                 lwindow->gui->close_event();
3155                 lwindow->gui->unlock_window();
3156         }
3157         else if( session->show_lwindow && lwindow->gui->is_hidden() )
3158                 show_lwindow();
3159
3160         tile_mixers();
3161         gui->lock_window("MWindow::restore_windows");
3162         gui->focus();
3163 }
3164
3165 void MWindow::load_layout(const char *layout)
3166 {
3167         char path[BCTEXTLEN];
3168         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3169         session->load_file(path);
3170         restore_windows();
3171         gui->default_positions();
3172         save_defaults();
3173 }
3174
3175 void MWindow::save_layout(const char *layout)
3176 {
3177         char path[BCTEXTLEN];
3178         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3179         session->save_file(path);
3180 }
3181
3182 void MWindow::delete_layout(const char *layout)
3183 {
3184         char path[BCTEXTLEN];
3185         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3186         unlink(path);
3187 }
3188
3189 int MWindow::tile_windows(int window_config)
3190 {
3191         int need_reload = 0;
3192         int play_config = window_config==0 ? 0 : 1;
3193         edl->session->playback_config->load_defaults(defaults, play_config);
3194         session->default_window_positions(window_config);
3195         if( screens == 1 ) {
3196                 gui->default_positions();
3197                 sync_parameters(CHANGE_ALL);
3198         }
3199         else
3200                 need_reload = 1;
3201         return need_reload;
3202 }
3203
3204 void MWindow::toggle_loop_playback()
3205 {
3206         edl->local_session->loop_playback = !edl->local_session->loop_playback;
3207         set_loop_boundaries();
3208         save_backup();
3209
3210         gui->draw_overlays(1);
3211         sync_parameters(CHANGE_PARAMS);
3212 }
3213
3214 void MWindow::set_screens(int value)
3215 {
3216         screens = value;
3217 }
3218
3219 void MWindow::set_auto_keyframes(int value)
3220 {
3221         edl->session->auto_keyframes = value;
3222         gui->mbuttons->edit_panel->keyframe->update(value);
3223         gui->flush();
3224         cwindow->gui->lock_window("MWindow::set_auto_keyframes");
3225         cwindow->gui->flush();
3226         cwindow->gui->unlock_window();
3227 }
3228
3229 void MWindow::set_span_keyframes(int value)
3230 {
3231         edl->session->span_keyframes = value;
3232         gui->mbuttons->edit_panel->span_keyframe->update(value);
3233         gui->flush();
3234         cwindow->gui->lock_window("MWindow::set_span_keyframes");
3235         cwindow->gui->flush();
3236         cwindow->gui->unlock_window();
3237 }
3238
3239 void MWindow::set_auto_visibility(Autos *autos, int value)
3240 {
3241         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
3242                 edl->session->auto_conf->plugins = value;
3243         else if( autos->autoidx >= 0 )
3244                 edl->session->auto_conf->autos[autos->autoidx] = value;
3245         else
3246                 return;
3247
3248         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3249         gui->mainmenu->update_toggles(1);
3250         gui->unlock_window();
3251         gwindow->gui->update_toggles(1);
3252         gui->lock_window("MWindow::set_auto_visibility");
3253 }
3254
3255 void MWindow::set_keyframe_type(int mode)
3256 {
3257         gui->lock_window("MWindow::set_keyframe_type");
3258         edl->local_session->floatauto_type = mode;
3259         gui->mainmenu->update_toggles(0);
3260         gui->unlock_window();
3261 }
3262
3263 int MWindow::set_editing_mode(int new_editing_mode)
3264 {
3265         edl->session->editing_mode = new_editing_mode;
3266         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
3267         gui->mbuttons->edit_panel->update();
3268         gui->set_editing_mode(1);
3269
3270         cwindow->gui->lock_window("MWindow::set_editing_mode");
3271         cwindow->gui->edit_panel->update();
3272         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
3273         cwindow->gui->unlock_window();
3274         return 0;
3275 }
3276
3277 void MWindow::toggle_editing_mode()
3278 {
3279         int mode = edl->session->editing_mode;
3280         if( mode == EDITING_ARROW )
3281                 set_editing_mode(EDITING_IBEAM);
3282         else
3283                 set_editing_mode(EDITING_ARROW);
3284 }
3285
3286 void MWindow::toggle_camera_xyz()
3287 {
3288         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3289         gwindow->gui->toggle_camera_xyz();
3290         gwindow->gui->unlock_window();
3291 }
3292
3293 void MWindow::toggle_projector_xyz()
3294 {
3295         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3296         gwindow->gui->toggle_projector_xyz();
3297         gwindow->gui->unlock_window();
3298 }
3299
3300 void MWindow::set_labels_follow_edits(int value)
3301 {
3302         edl->session->labels_follow_edits = value;
3303         gui->mbuttons->edit_panel->locklabels->update(value);
3304         gui->mainmenu->labels_follow_edits->set_checked(value);
3305         gui->flush();
3306 }
3307
3308 void MWindow::sync_parameters(int change_type)
3309 {
3310         if( in_destructor ) return;
3311
3312 // Sync engines which are playing back
3313         if( cwindow->playback_engine->is_playing_back ) {
3314                 if( change_type == CHANGE_PARAMS ) {
3315 // TODO: block keyframes until synchronization is done
3316                         cwindow->playback_engine->sync_parameters(edl);
3317                 }
3318                 else {
3319 // Stop and restart
3320                         int command = cwindow->playback_engine->command->command;
3321 // Waiting for tracking to finish would make the restart position more
3322 // accurate but it can't lock the window to stop tracking for some reason.
3323 // Not waiting for tracking gives a faster response but restart position is
3324 // only as accurate as the last tracking update.
3325                         cwindow->playback_engine->transport_stop(0);
3326                         cwindow->playback_engine->next_command->realtime = 1;
3327                         cwindow->playback_engine->transport_command(command, change_type, edl, 0);
3328                 }
3329         }
3330         else {
3331                 cwindow->refresh_frame(change_type);
3332         }
3333 }
3334
3335 void MWindow::age_caches()
3336 {
3337 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3338 // __LINE__,
3339 // preferences->cache_size,
3340 // audio_cache->get_memory_usage(1),
3341 // video_cache->get_memory_usage(1),
3342 // frame_cache->get_memory_usage(),
3343 // wave_cache->get_memory_usage(),
3344 // memory_usage);
3345         frame_cache->age_cache(512);
3346         wave_cache->age_cache(8192);
3347
3348         int64_t memory_usage;
3349         int64_t prev_memory_usage = 0;
3350         int result = 0;
3351         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3352         while( !result && prev_memory_usage !=
3353                 (memory_usage=video_cache->get_memory_usage(1)) &&
3354                 memory_usage > video_size ) {
3355                 video_cache->delete_oldest();
3356                 prev_memory_usage = memory_usage;
3357         }
3358
3359         prev_memory_usage = 0;
3360         result = 0;
3361         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3362         while( !result && prev_memory_usage !=
3363                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3364                 memory_usage > audio_size ) {
3365                 audio_cache->delete_oldest();
3366                 prev_memory_usage = memory_usage;
3367         }
3368 }
3369
3370 void MWindow::reset_android_remote()
3371 {
3372         gui->use_android_remote(preferences->android_remote);
3373 }
3374
3375
3376 void MWindow::show_keyframe_gui(Plugin *plugin)
3377 {
3378         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3379 // Find existing thread
3380         for( int i=0; i<keyframe_threads->size(); ++i ) {
3381                 int plugin_id = keyframe_threads->get(i)->plugin_id;
3382                 if( plugin_id == plugin->orig_id ) {
3383                         keyframe_threads->get(i)->start_window(plugin, 0);
3384                         keyframe_gui_lock->unlock();
3385                         return;
3386                 }
3387         }
3388
3389 // Find unused thread
3390         for( int i=0; i<keyframe_threads->size(); ++i ) {
3391                 if( keyframe_threads->get(i)->plugin_id < 0 ) {
3392                         keyframe_threads->get(i)->start_window(plugin, 0);
3393                         keyframe_gui_lock->unlock();
3394                         return;
3395                 }
3396         }
3397
3398 // Create new thread
3399         KeyFrameThread *thread = new KeyFrameThread(this);
3400         keyframe_threads->append(thread);
3401         thread->start_window(plugin, 0);
3402         keyframe_gui_lock->unlock();
3403 }
3404
3405
3406 void MWindow::show_plugin(Plugin *plugin)
3407 {
3408         int done = 0;
3409
3410 SET_TRACE
3411 // Remove previously deleted plugin GUIs
3412         dead_plugin_lock->lock("MWindow::show_plugin");
3413         dead_plugins->remove_all_objects();
3414         dead_plugin_lock->unlock();
3415
3416 //printf("MWindow::show_plugin %d\n", __LINE__);
3417 SET_TRACE
3418
3419         plugin_gui_lock->lock("MWindow::show_plugin");
3420         for( int i=0; i<plugin_guis->total; ++i ) {
3421 // Pointer/id comparison
3422                 PluginServer *plugin_gui = plugin_guis->get(i);
3423                 if( plugin_gui->plugin_id == plugin->orig_id ) {
3424                         plugin_gui->raise_window();
3425                         done = 1;
3426                         break;
3427                 }
3428         }
3429 SET_TRACE
3430
3431 //printf("MWindow::show_plugin 1\n");
3432         if( !done && !plugin->track ) {
3433                 printf("MWindow::show_plugin track not defined.\n");
3434                 done = 1;
3435         }
3436         if( !done ) {
3437                 PluginServer *server = scan_plugindb(plugin->title,
3438                         plugin->track->data_type);
3439
3440 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3441                 if(server && server->uses_gui)
3442                 {
3443                         PluginServer *gui = new PluginServer(*server);
3444                         plugin_guis->append(gui);
3445 // Needs mwindow to do GUI
3446                         gui->set_mwindow(this);
3447                         gui->open_plugin(0, preferences, edl, plugin);
3448                         plugin->show = 1;
3449                         gui->show_gui();
3450                 }
3451         }
3452         plugin_gui_lock->unlock();
3453 // update show/gui_id
3454         sync_parameters(CHANGE_PARAMS);
3455 //printf("MWindow::show_plugin %d\n", __LINE__);
3456 SET_TRACE
3457 //sleep(1);
3458 //printf("MWindow::show_plugin 2\n");
3459 }
3460
3461 void MWindow::hide_plugin(Plugin *plugin, int lock)
3462 {
3463         plugin->show = 0;
3464         return hide_plugin(plugin->orig_id, lock);
3465 }
3466
3467 void MWindow::hide_plugin(int plugin_id, int lock)
3468 {
3469 // Update the toggle
3470         gui->lock_window("MWindow::hide_plugin");
3471         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3472         gui->unlock_window();
3473
3474         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3475         for( int i=0; i<plugin_guis->total; ++i ) {
3476                 PluginServer *plugin_gui = plugin_guis->get(i);
3477                 if( plugin_gui->plugin_id == plugin_id ) {
3478                         plugin_guis->remove(plugin_gui);
3479                         if(lock) plugin_gui_lock->unlock();
3480 // Last command executed in client side close
3481 // Schedule for deletion
3482                         plugin_gui->hide_gui();
3483                         delete_plugin(plugin_gui);
3484 //sleep(1);
3485                         return;
3486                 }
3487         }
3488         if(lock) plugin_gui_lock->unlock();
3489 // update show/gui_id
3490         sync_parameters(CHANGE_PARAMS);
3491 }
3492
3493 void MWindow::delete_plugin(PluginServer *plugin)
3494 {
3495         dead_plugin_lock->lock("MWindow::delete_plugin");
3496         dead_plugins->append(plugin);
3497         dead_plugin_lock->unlock();
3498 }
3499
3500 void MWindow::hide_plugins()
3501 {
3502         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3503         while(plugin_guis->size())
3504         {
3505                 PluginServer *ptr = plugin_guis->get(0);
3506                 plugin_guis->remove(ptr);
3507                 plugin_gui_lock->unlock();
3508 // Last command executed in client side close
3509 // Schedule for deletion
3510                 ptr->hide_gui();
3511                 delete_plugin(ptr);
3512                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3513         }
3514         plugin_gui_lock->unlock();
3515
3516         hide_keyframe_guis();
3517 }
3518
3519 void MWindow::hide_keyframe_guis()
3520 {
3521         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3522         for(int i = 0; i < keyframe_threads->size(); i++)
3523         {
3524                 keyframe_threads->get(i)->close_window();
3525         }
3526         keyframe_gui_lock->unlock();
3527 }
3528
3529 void MWindow::hide_keyframe_gui(Plugin *plugin)
3530 {
3531         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3532         for( int i = 0; i < keyframe_threads->size(); i++) {
3533                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3534                 if( keyframe_gui->plugin_id == plugin->orig_id ) {
3535                         keyframe_gui->close_window();
3536                         break;
3537                 }
3538         }
3539         keyframe_gui_lock->unlock();
3540 }
3541
3542 int MWindow::get_hash_color(Edit *edit)
3543 {
3544         Indexable *idxbl = edit->asset ?
3545                 (Indexable*)edit->asset : (Indexable*)edit->nested_edl;
3546         if( !idxbl ) return 0;
3547         char path[BCTEXTLEN];
3548 // map proxy colors to unproxy colors
3549         if( edl->session->proxy_state != PROXY_ACTIVE ||
3550             !edit->asset || edit->track->data_type != TRACK_VIDEO ||
3551             ProxyRender::from_proxy_path(path, (Asset*)idxbl, edl->session->proxy_scale) )
3552                 strcpy(path, idxbl->path);
3553         char *cp = strrchr(path, '/');
3554         cp = !cp ? path : cp+1;
3555         uint8_t *bp = (uint8_t*)cp;
3556         int v = 0;
3557         while( *bp ) v += *bp++;
3558         return get_hash_color(v);
3559 }
3560
3561 int MWindow::get_hash_color(int v)
3562 {
3563         int hash = 0x303030;
3564         if( v & 0x01 ) hash ^= 0x000040;
3565         if( v & 0x02 ) hash ^= 0x004000;
3566         if( v & 0x04 ) hash ^= 0x400000;
3567         if( v & 0x08 ) hash ^= 0x080000;
3568         if( v & 0x10 ) hash ^= 0x000800;
3569         if( v & 0x20 ) hash ^= 0x000008;
3570         if( v & 0x40 ) hash ^= 0x404040;
3571         if( v & 0x80 ) hash ^= 0x080808;
3572         return hash;
3573 }
3574
3575 int MWindow::get_group_color(int v)
3576 {
3577         int color = 0x606060;
3578         if( v & 0x01 ) color ^= 0x000080;
3579         if( v & 0x02 ) color ^= 0x008000;
3580         if( v & 0x04 ) color ^= 0x800000;
3581         if( v & 0x08 ) color ^= 0x100000;
3582         if( v & 0x10 ) color ^= 0x001000;
3583         if( v & 0x20 ) color ^= 0x000010;
3584         if( v & 0x40 ) color ^= 0x080808;
3585         if( v & 0x80 ) color ^= 0x909090;
3586         return color;
3587 }
3588
3589 int MWindow::get_title_color(Edit *edit)
3590 {
3591         unsigned color = edit->color & 0xffffff;
3592         unsigned alpha = (~edit->color>>24) & 0xff;
3593         if( !color ) {
3594                 if( edit->group_id )
3595                         color = get_group_color(edit->group_id);
3596                 else if( preferences->autocolor_assets )
3597                         color = get_hash_color(edit);
3598                 else
3599                         return 0;
3600         }
3601         if( alpha == 0xff )
3602                 alpha = session->title_bar_alpha*255;
3603         return color | (~alpha<<24);
3604 }
3605
3606 void MWindow::update_keyframe_guis()
3607 {
3608 // Send new configuration to keyframe GUI's
3609         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3610         for( int i=0; i<keyframe_threads->size(); ++i ) {
3611                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3612                 Plugin *plugin = edl->tracks->plugin_exists(keyframe_gui->plugin_id);
3613                 if( plugin )
3614                         keyframe_gui->update_gui(1);
3615                 else
3616                         keyframe_gui->close_window();
3617         }
3618         keyframe_gui_lock->unlock();
3619 }
3620
3621 void MWindow::update_plugin_guis(int do_keyframe_guis)
3622 {
3623 // Send new configuration to plugin GUI's
3624         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3625
3626         for( int i=0; i<plugin_guis->size(); ++i ) {
3627                 PluginServer *plugin_gui = plugin_guis->get(i);
3628                 Plugin *plugin = edl->tracks->plugin_exists(plugin_gui->plugin_id);
3629                 if( plugin && plugin->show )
3630                         plugin_gui->update_gui();
3631                 else {
3632 // Schedule for deletion if no plugin or not shown
3633                         plugin_guis->remove_number(i--);
3634                         plugin_gui->hide_gui();
3635                         delete_plugin(plugin_gui);
3636                 }
3637         }
3638
3639
3640 // Change plugin variable if not visible
3641         Track *track = edl->tracks->first;
3642         for( ; track; track=track->next ) {
3643                 for( int i=0; i < track->plugin_set.size(); ++i ) {
3644                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3645                         for( ; plugin; plugin = (Plugin*)plugin->next ) {
3646                                 int got_it = 0;
3647                                 for( int i=0; i<plugin_guis->size(); ++i ) {
3648                                         PluginServer *server = plugin_guis->get(i);
3649                                         if( server->plugin_id == plugin->orig_id ) {
3650                                                 got_it = 1;
3651                                                 break;
3652                                         }
3653                                 }
3654                                 if( !got_it ) plugin->show = 0;
3655                         }
3656                 }
3657         }
3658
3659         plugin_gui_lock->unlock();
3660         if( do_keyframe_guis )
3661                 update_keyframe_guis();
3662 }
3663
3664 void MWindow::stop_plugin_guis()
3665 {
3666 // Send new configuration to plugin GUI's
3667         plugin_gui_lock->lock("MWindow::stop_plugin_guis");
3668
3669         for( int i=0; i<plugin_guis->size(); ++i ) {
3670                 PluginServer *plugin_gui = plugin_guis->get(i);
3671                 plugin_gui->render_stop();
3672         }
3673         plugin_gui_lock->unlock(); 
3674 }
3675
3676 int MWindow::plugin_gui_open(Plugin *plugin)
3677 {
3678         int gui_id = plugin->gui_id;
3679         if( gui_id < 0 ) return 0;
3680         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3681         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3682         int result = plugin_server ? 1 : 0;
3683         plugin_gui_lock->unlock();
3684         return result;
3685 }
3686
3687
3688 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3689 {
3690         int gui_id = plugin->gui_id;
3691         if( gui_id < 0 ) return;
3692         plugin_gui_lock->lock("MWindow::render_plugin_gui 0");
3693         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3694         if( plugin_server )
3695                 plugin_server->render_gui(data);
3696         plugin_gui_lock->unlock();
3697 }
3698
3699 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3700 {
3701         int gui_id = plugin->gui_id;
3702         if( gui_id < 0 ) return;
3703         plugin_gui_lock->lock("MWindow::render_plugin_gui 1");
3704         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3705         if( plugin_server )
3706                 plugin_server->render_gui(data, size);
3707         plugin_gui_lock->unlock();
3708 }
3709
3710 void MWindow::reset_plugin_gui_frames(Plugin *plugin)
3711 {
3712         int gui_id = plugin->gui_id;
3713         if( gui_id < 0 ) return;
3714         plugin_gui_lock->lock("MWindow::reset_plugin_gui_frames");
3715         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3716         if( plugin_server )
3717                 plugin_server->reset_plugin_gui_frames();
3718         plugin_gui_lock->unlock();
3719 }
3720
3721 void MWindow::render_plugin_gui_frames(PluginClientFrames *frames, Plugin *plugin)
3722 {
3723         int gui_id = plugin->gui_id;
3724         if( gui_id < 0 ) return;
3725         plugin_gui_lock->lock("MWindow::render_plugin_gui_frames");
3726         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3727         if( plugin_server )
3728                 plugin_server->render_plugin_gui_frames(frames);
3729         plugin_gui_lock->unlock();
3730 }
3731
3732 double MWindow::get_tracking_position()
3733 {
3734         return edl->local_session->get_selectionstart(1);
3735 }
3736
3737 int MWindow::get_tracking_direction()
3738 {
3739         return cwindow->playback_engine->get_direction();
3740 }
3741
3742 void MWindow::update_plugin_states()
3743 {
3744         plugin_gui_lock->lock("MWindow::update_plugin_states");
3745         for( int i=0; i<plugin_guis->total; ++i ) {
3746 // Get a plugin GUI
3747                 PluginServer *src_plugingui = plugin_guis->get(i);
3748                 int plugin_id = src_plugingui->plugin_id;
3749                 Plugin *src_plugin = edl->tracks->plugin_exists(plugin_id);
3750 // Doesn't exist anymore
3751                 if( !src_plugin ) {
3752                         hide_plugin(plugin_id, 0);
3753                         --i;
3754                 }
3755         }
3756         plugin_gui_lock->unlock();
3757 }
3758
3759
3760 void MWindow::update_plugin_titles()
3761 {
3762         for( int i=0; i<plugin_guis->total; ++i )
3763                 plugin_guis->get(i)->update_title();
3764 }
3765
3766 int MWindow::asset_to_edl(EDL *new_edl,
3767         Asset *new_asset,
3768         RecordLabels *labels)
3769 {
3770 const int debug = 0;
3771 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3772 __LINE__,
3773 new_asset->layers);
3774 // Keep frame rate, sample rate, and output size unchanged.
3775 // These parameters would revert the project if VWindow displayed an asset
3776 // of different size than the project.
3777         if(new_asset->video_data)
3778         {
3779                 new_edl->session->video_tracks = new_asset->layers;
3780         }
3781         else
3782                 new_edl->session->video_tracks = 0;
3783
3784 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3785
3786
3787
3788
3789
3790         if(new_asset->audio_data)
3791         {
3792                 new_edl->session->audio_tracks = new_asset->channels;
3793         }
3794         else
3795                 new_edl->session->audio_tracks = 0;
3796 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3797
3798 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3799         new_edl->create_default_tracks();
3800 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3801 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3802
3803
3804
3805 //printf("MWindow::asset_to_edl 3\n");
3806         new_edl->insert_asset(new_asset,
3807                 0,
3808                 0,
3809                 0,
3810                 labels);
3811 //printf("MWindow::asset_to_edl 3\n");
3812 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3813
3814 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3815         if(edl->session->cursor_on_frames)
3816         {
3817                 double length = new_edl->tracks->total_length();
3818                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3819                 new_edl->tracks->clear(length, edl_length, 1, 1);
3820         }
3821
3822
3823
3824
3825         char string[BCTEXTLEN];
3826         FileSystem fs;
3827         fs.extract_name(string, new_asset->path);
3828 //printf("MWindow::asset_to_edl 3\n");
3829
3830         strcpy(new_edl->local_session->clip_title, string);
3831 //printf("MWindow::asset_to_edl 4 %s\n", string);
3832 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3833
3834         new_edl->local_session->asset2edl = 1;
3835         return 0;
3836 }
3837
3838
3839 // Reset everything after a load.
3840 void MWindow::update_project(int load_mode)
3841 {
3842         const int debug = 0;
3843
3844         if(debug) PRINT_TRACE
3845         edl->tracks->update_y_pixels(theme);
3846         session->update_clip_number();
3847
3848         if(debug) PRINT_TRACE
3849
3850         if( load_mode == LOADMODE_REPLACE ||
3851             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3852                 edl->session->timecode_offset = 0;
3853                 gui->close_keyvalue_popup();
3854                 gui->load_panes();
3855         }
3856
3857         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 1);
3858         if(debug) PRINT_TRACE
3859         gui->unlock_window();
3860         init_brender();
3861
3862         cwindow->update(0, 0, 1, 1, 1);
3863
3864         if(debug) PRINT_TRACE
3865
3866 // Close all the vwindows
3867         if( load_mode == LOADMODE_REPLACE ||
3868             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3869                 if(debug) PRINT_TRACE
3870                 int first_vwindow = 0;
3871                 if(session->show_vwindow) first_vwindow = 1;
3872 // Change visible windows to no source
3873                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3874                         VWindow *vwindow = vwindows[i];
3875                         if( !vwindow->is_running() ) continue;
3876                         vwindow->change_source(-1);
3877                 }
3878
3879 // Close remaining windows
3880                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3881                         VWindow *vwindow = vwindows[i];
3882                         if( !vwindow->is_running() ) continue;
3883                         vwindow->close_window();
3884                 }
3885                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3886                         VWindow *vwindow = get_viewer(1, -1);
3887                         vwindow->change_source(i);
3888                 }
3889                 if(debug) PRINT_TRACE
3890                 select_zwindow(0);
3891                 close_mixers(0);
3892
3893                 for( int i=0; i<edl->mixers.size(); ++i ) {
3894                         Mixer *mixer = edl->mixers[i];
3895                         if( !mixer->show ) continue;
3896                         ZWindow *zwindow = get_mixer(mixer);
3897                         zwindow->set_title(mixer->title);
3898                         zwindow->start();
3899                 }
3900                 cwindow->gui->canvas->set_zoom(edl, 0);
3901         }
3902         update_vwindow();
3903
3904         if(debug) PRINT_TRACE
3905         cwindow->gui->lock_window("MWindow::update_project 2");
3906         cwindow->gui->timebar->update(0);
3907         Track *track = cwindow->calculate_affected_track();
3908         cwindow->mask_track_id = track ? track->get_id() : -1;
3909         cwindow->gui->tool_panel->raise_tool();
3910         cwindow->gui->update_canvas(0);
3911         cwindow->gui->unlock_window();
3912
3913         if(debug) PRINT_TRACE
3914         cwindow->refresh_frame(CHANGE_ALL);
3915
3916         awindow->gui->async_update_assets();
3917         if(debug) PRINT_TRACE
3918
3919         gui->lock_window("MWindow::update_project");
3920         gui->update_mixers(0, 0);
3921         gui->flush();
3922         if(debug) PRINT_TRACE
3923 }
3924
3925 void MWindow::stack_push(EDL *new_edl, Indexable *idxbl)
3926 {
3927         int got_indexes = 0;
3928         for( int i=0; i<new_edl->nested_edls.size(); ++i ) {
3929                 EDL *nested_edl = new_edl->nested_edls[i];
3930                 mainindexes->add_indexable(nested_edl);
3931                 edl->nested_edls.update_index(nested_edl);
3932                 got_indexes = 1;
3933         }
3934         for( Asset *asset=new_edl->assets->first; asset; asset=asset->next ) {
3935                 mainindexes->add_indexable(asset);
3936                 edl->assets->update(asset);
3937                 got_indexes = 1;
3938         }
3939 // Start examining next batch of index files
3940         if( got_indexes )
3941                 mainindexes->start_build();
3942
3943 // needs gui lock
3944         gui->lock_window("MWindow::stack_push");
3945         if( stack.size() < 9 ) {
3946                 save_backup();
3947                 hide_plugins();
3948                 undo_before();
3949                 StackItem &item = stack.append();
3950                 item.edl = edl;
3951                 item.new_edl = new_edl;
3952                 item.duration = new_edl->tracks->total_length();
3953                 item.undo = undo;
3954                 item.idxbl = idxbl;
3955                 item.mtime = 0;
3956                 if( idxbl && idxbl->is_asset ) {
3957                         struct stat st;
3958                         Asset *asset = (Asset *)idxbl;
3959                         if( asset->format == FILE_REF &&
3960                             !stat(asset->path, &st) )
3961                                 item.mtime = st.st_mtime;
3962                 }
3963                 edl = new_edl;
3964                 edl->add_user();
3965                 strcpy(session->filename, edl->path);
3966                 undo = new MainUndo(this);
3967                 gui->stack_button->update();
3968                 update_project(LOADMODE_REPLACE);
3969         }
3970         gui->unlock_window();
3971         show_plugins();
3972 }
3973
3974 void MWindow::stack_pop()
3975 {
3976         if( !stack.size() ) return;
3977 // writes on config_path/backup%d.xml
3978         save_backup();
3979         hide_plugins();
3980 // already have gui lock
3981         StackItem &item = stack.last();
3982 // session edl replaced, overwrite and save clip data
3983         if( item.new_edl != edl )
3984                 item.new_edl->overwrite_clip(edl);
3985         Indexable *idxbl = item.idxbl;
3986         if( idxbl && idxbl->is_asset && item.mtime ) {
3987                 Asset *asset = (Asset *)idxbl;
3988                 if( asset->format == FILE_REF ) {
3989                         char *path = asset->path;
3990                         struct stat st;
3991                         if( stat(path, &st) || item.mtime == st.st_mtime ) {
3992                                 int cw = xS(250), ch = yS(150), px, py;
3993                                 gui->get_pop_cursor(px, py);
3994                                 px -= cw/2;  py -= ch/2;
3995                                 ConfirmRefWindow confirm(this, path, px, py, cw, ch);
3996                                 confirm.create_objects();
3997                                 int result = confirm.run_window();
3998                                 if( !result ) {
3999                                         FileXML file;
4000                                         item.new_edl->save_xml(&file, path);
4001                                         file.terminate_string();
4002                                         if(file.write_to_file(path))
4003                                                 eprintf(_("Cant write FileREF: %s"), path);
4004                                 }
4005                         }
4006                 }
4007         }
4008         edl->remove_user();
4009         edl = item.edl;
4010         delete undo;
4011         undo = item.undo;
4012         stack.remove();
4013         if( idxbl ) {
4014 // resize the indexable edits if the new_edl duration changed
4015                 double duration = item.new_edl->tracks->total_length();
4016                 double dt = duration - item.duration;
4017                 if( fabs(dt) > 1e-4 )
4018                         edl->tracks->update_idxbl_length(idxbl->id, dt);
4019                 gui->unlock_window();
4020                 gui->resource_thread->close_indexable(idxbl);
4021                 remove_from_caches(idxbl);
4022                 IndexFile::delete_index_files(preferences, idxbl);
4023                 mainindexes->add_indexable(idxbl);
4024                 mainindexes->start_build();
4025                 awindow->gui->async_update_assets();
4026                 gui->lock_window("MWindow::stack_pop");
4027         }
4028         strcpy(session->filename, edl->path);
4029         update_project(LOADMODE_REPLACE);
4030         undo_after(_("open edl"), LOAD_ALL);
4031         show_plugins();
4032         gui->stack_button->update();
4033 }
4034
4035 int MWindow::save(EDL *edl, char *filename, int stat)
4036 {
4037         FileXML file;
4038         edl->save_xml(&file, filename);
4039         file.terminate_string();
4040         if( file.write_to_file(filename) ) {
4041                 eprintf(_("Couldn't open %s"), filename);
4042                 return 1;
4043         }
4044         if( stat ) {
4045                 char string[BCTEXTLEN];
4046                 char *filename = stack.size() ?
4047                         stack[0].edl->path : session->filename;
4048                 sprintf(string, _("\"%s\" %jdC written"),
4049                          filename, file.length());
4050                 gui->lock_window("SaveAs::run");
4051                 gui->show_message(string);
4052                 gui->unlock_window();
4053         }
4054         return 0;
4055 }
4056
4057 int MWindow::save(int save_as)
4058 {
4059         char new_path[BCTEXTLEN];  new_path[0] = 0;
4060         char *path = stack.size() ? stack[0].edl->path : session->filename;
4061         if( save_as || !path[0] ) {
4062                 if( ConfirmSave::get_save_path(this, new_path) )
4063                         return 1;
4064                 if( stack.size() ) {
4065                         strcpy(path, new_path);
4066                         set_titlebar(new_path);
4067                 }
4068                 else
4069                         set_filename(new_path);
4070                 gui->mainmenu->add_load(new_path);
4071                 path = new_path;
4072         }
4073         for( int i=stack.size(); --i>=0;  ) {
4074                 StackItem &item = stack[i];
4075                 Indexable *idxbl = item.idxbl;
4076                 if( !idxbl ) continue;
4077                 if( idxbl->is_asset ) {
4078                         Asset *asset = (Asset *)idxbl;
4079                         if( asset->format == FILE_REF ) {
4080                                 if( save(item.new_edl, asset->path, 0) )
4081                                         return 1;
4082                         }
4083                 }
4084                 else if( item.new_edl != idxbl )
4085                         item.new_edl->overwrite_clip((EDL*)idxbl);
4086         }
4087         EDL *new_edl = stack.size() ? stack[0].edl : edl;
4088         save(new_edl, path, 1);
4089         return 0;
4090 }
4091
4092 void MWindow::show_plugins()
4093 {
4094         for( Track *track=edl->tracks->first; track; track=track->next ) {
4095                 for( int i=0; i<track->plugin_set.size(); ++i ) {
4096                         PluginSet *plugins = track->plugin_set[i];
4097                         Plugin *plugin = plugins->get_first_plugin();
4098                         for( ; plugin; plugin=(Plugin*)plugin->next ) {
4099                                 if( plugin->plugin_type == PLUGIN_STANDALONE &&
4100                                     plugin->show )
4101                                         show_plugin(plugin);
4102                         }
4103                 }
4104         }
4105 }
4106
4107 void MWindow::clip_to_media()
4108 {
4109         if( edl->session->proxy_scale != 1 ) {
4110                 eprintf("Nesting not allowed when proxy scale != 1");
4111                 return;
4112         }
4113         undo_before();
4114         awindow->gui->stop_vicon_drawing();
4115         int clips_total = session->drag_clips->total;
4116         for( int i=0; i<clips_total; ++i ) {
4117                 EDL *clip = session->drag_clips->values[i];
4118                 time_t dt;      time(&dt);
4119                 struct tm dtm;  localtime_r(&dt, &dtm);
4120                 char path[BCTEXTLEN], *cp = path, *ep = cp+sizeof(path)-1;
4121 // path_basename = "Nested_<date>-<time>_<basename>"
4122                 cp += snprintf(cp, ep-cp, _("Nested_%02d%02d%02d-%02d%02d%02d_"),
4123                         dtm.tm_year+1900, dtm.tm_mon+1, dtm.tm_mday,
4124                         dtm.tm_hour, dtm.tm_min, dtm.tm_sec);
4125                 char *bp = strrchr(clip->local_session->clip_title, '/');
4126                 bp = bp ? bp+1 : clip->local_session->clip_title;
4127                 cp += snprintf(cp, ep-cp, "%s", bp);
4128                 EDL *nested = edl->new_nested_clip(clip, path);
4129                 edl->clips.remove(clip);
4130                 clip->remove_user();
4131                 mainindexes->add_indexable(nested);
4132         }
4133         undo_after(_("clip2media"), LOAD_ALL);
4134         mainindexes->start_build();
4135         awindow->gui->async_update_assets();
4136 }
4137
4138 void MWindow::media_to_clip()
4139 {
4140         undo_before();
4141         int assets_total = session->drag_assets->total;
4142         for( int i=0; i<assets_total; ++i ) {
4143                 Indexable *idxbl = session->drag_assets->values[i];
4144                 if( idxbl->is_asset ) {
4145                         eprintf(_("media is not EDL:\n%s"), idxbl->path);
4146                         continue;
4147                 }
4148                 char clip_title[BCSTRLEN];
4149                 int name_ok = 0;
4150                 while( !name_ok ) {
4151                         name_ok = 1;
4152                         sprintf(clip_title, _("Clip %d"), session->clip_number++);
4153                         for( int i=0; name_ok && i<edl->clips.size(); ++i ) {
4154                                 char *title = edl->clips[i]->local_session->clip_title;
4155                                 if( !strcasecmp(clip_title, title) ) name_ok = 0;
4156                         }
4157                 }
4158                 EDL *nested = (EDL *)idxbl;
4159                 EDL *clip = edl->add_clip(nested);
4160                 strcpy(clip->local_session->clip_title, clip_title);
4161                 snprintf(clip->local_session->clip_notes,
4162                         sizeof(clip->local_session->clip_notes),
4163                         _("From: %s"), nested->path);
4164         }
4165         undo_after(_("media2clip"), LOAD_ALL);
4166         awindow->gui->async_update_assets();
4167 }
4168
4169 int MWindow::create_ref(Asset *asset, EDL *ref)
4170 {
4171         asset->format = FILE_REF;
4172         double secs = ref->tracks->total_length();
4173         int audio_channels = ref->session->audio_channels;
4174         asset->audio_data = audio_channels > 0 ? 1 : 0;
4175         asset->channels = audio_channels;
4176         asset->sample_rate = ref->session->sample_rate;
4177         asset->audio_length = audio_channels > 0 && secs > 0 ?
4178                  secs * asset->sample_rate : 0;
4179         strcpy(asset->acodec, _("reference"));
4180
4181         int video_layers = ref->session->video_channels;
4182         asset->video_data = video_layers > 0 ? 1 : 0;
4183         asset->layers = video_layers > 0 ? 1 : 0;
4184         asset->actual_width = ref->session->output_w;
4185         asset->actual_height = ref->session->output_h;
4186         asset->width = asset->actual_width;
4187         asset->height = asset->actual_height;
4188         asset->frame_rate = ref->session->frame_rate;
4189         asset->video_length = video_layers > 0 && secs > 0 ?
4190                 secs * asset->frame_rate : 0;
4191         strcpy(asset->vcodec, _("reference"));
4192         return 0;
4193 }
4194
4195 void MWindow::update_preferences(Preferences *prefs)
4196 {
4197         if( prefs != preferences )
4198                 preferences->copy_from(prefs);
4199         if( cwindow->playback_engine )
4200                 cwindow->playback_engine->update_preferences(prefs);
4201         for(int i = 0; i < vwindows.size(); i++) {
4202                 VWindow *vwindow = vwindows[i];
4203                 if( !vwindow->is_running() ) continue;
4204                 if( vwindow->playback_engine )
4205                         vwindow->playback_engine->update_preferences(prefs);
4206         }
4207         for(int i = 0; i < zwindows.size(); i++) {
4208                 ZWindow *zwindow = zwindows[i];
4209                 if( !zwindow->is_running() ) continue;
4210                 if( zwindow->zgui->playback_engine )
4211                         zwindow->zgui->playback_engine->update_preferences(prefs);
4212         }
4213 }
4214
4215 void MWindow::update_vwindow()
4216 {
4217         for( int i=0; i<vwindows.size(); ++i ) {
4218                 VWindow *vwindow = vwindows[i];
4219                 if( vwindow->is_running() ) {
4220                         vwindow->gui->lock_window("MWindow::update_vwindow");
4221                         vwindow->update(1);
4222                         vwindow->gui->unlock_window();
4223                 }
4224         }
4225 }
4226
4227 void MWindow::remove_indexfile(Indexable *indexable)
4228 {
4229         if( !indexable->is_asset ) return;
4230 // Erase file
4231         IndexFile::delete_index_files(preferences, indexable);
4232 }
4233
4234 void MWindow::rebuild_indices()
4235 {
4236         for(int i = 0; i < session->drag_assets->total; i++)
4237         {
4238                 Indexable *indexable = session->drag_assets->get(i);
4239 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4240                 remove_indexfile(indexable);
4241 // Schedule index build
4242                 indexable->index_state->remove_user();
4243                 indexable->index_state = new IndexState;
4244                 IndexFile::delete_index_files(preferences, indexable);
4245                 if( indexable->is_asset ) {
4246                         Asset *asset = (Asset *)indexable;
4247                         if( asset->format != FILE_PCM ) {
4248                                 asset->format = FILE_UNKNOWN;
4249                                 asset->reset_audio();
4250                         }
4251                         asset->reset_video();
4252                         remove_from_caches(asset);
4253 //                      File file; // re-probe the asset
4254 //                      file.open_file(preferences, asset, 1, 0);
4255                 }
4256                 mainindexes->add_indexable(indexable);
4257         }
4258 // still in render engine
4259         sync_parameters(CHANGE_ALL);
4260         awindow->gui->async_update_assets();
4261         mainindexes->start_build();
4262 }
4263
4264
4265 void MWindow::get_backup_path(char *path, int len)
4266 {
4267         char *cp = path, *ep = cp + len-1;
4268         cp += snprintf(cp, ep-cp, "%s/", File::get_config_path());
4269         int idx = stack.size();
4270         cp += snprintf(cp, ep-cp, idx ? BACKUPn_FILE : BACKUP_FILE, idx);
4271 }
4272
4273 void MWindow::save_backup()
4274 {
4275         FileXML file;
4276         edl->optimize();
4277         edl->set_path(session->filename);
4278
4279         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
4280         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
4281                 File::get_config_path(), BACKUP_FILE1);
4282         get_backup_path(backup_path, sizeof(backup_path));
4283         rename(backup_path, backup_path1);
4284         edl->save_xml(&file, backup_path);
4285         file.terminate_string();
4286         FileSystem fs;
4287         fs.complete_path(backup_path);
4288
4289         if(file.write_to_file(backup_path)) {
4290                 char string2[256];
4291                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
4292                 gui->show_message(string2);
4293         }
4294         save_undo_data();
4295 }
4296
4297 void MWindow::load_backup()
4298 {
4299         ArrayList<char*> path_list;
4300         path_list.set_array_delete();
4301         char *out_path;
4302         char backup_path[BCTEXTLEN];
4303         get_backup_path(backup_path, sizeof(backup_path));
4304         FileSystem fs;
4305         fs.complete_path(backup_path);
4306
4307         path_list.append(out_path = new char[strlen(backup_path) + 1]);
4308         strcpy(out_path, backup_path);
4309
4310         load_filenames(&path_list, LOADMODE_REPLACE, LOADMODE_EDL_CLIP, 0);
4311         edl->local_session->clip_title[0] = 0;
4312 // This is unique to backups since the path of the backup is different than the
4313 // path of the project.
4314         set_filename(edl->path);
4315         path_list.remove_all_objects();
4316         save_backup();
4317 }
4318
4319
4320 void MWindow::save_undo_data()
4321 {
4322         if( stack.size() > 0 ) return;
4323         if( !preferences->perpetual_session ) return;
4324         char perpetual_path[BCTEXTLEN];
4325         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4326                 File::get_config_path(), PERPETUAL_FILE);
4327         FILE *fp = fopen(perpetual_path,"w");
4328         if( !fp ) return;
4329         undo->save(fp);
4330         fclose(fp);
4331 }
4332
4333 void MWindow::load_undo_data()
4334 {
4335         if( stack.size() > 0 ) return;
4336         if( !preferences->perpetual_session ) return;
4337         char perpetual_path[BCTEXTLEN];
4338         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4339                 File::get_config_path(), PERPETUAL_FILE);
4340         FILE *fp = fopen(perpetual_path,"r");
4341         if( !fp ) return;
4342         undo->load(fp);
4343         undo_before();
4344         undo_after(_("perpetual load"), LOAD_ALL);
4345         fclose(fp);
4346 }
4347
4348 void MWindow::remove_undo_data()
4349 {
4350         if( stack.size() > 0 ) return;
4351         char perpetual_path[BCTEXTLEN];
4352         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4353                 File::get_config_path(), PERPETUAL_FILE);
4354         ::remove(perpetual_path);
4355 }
4356
4357 int MWindow::copy_target(const char *path, const char *target)
4358 {
4359         int ifd = ::open(path, O_RDONLY);
4360         if( ifd < 0 ) {
4361                 eprintf("Cannot open asset: %s", path);
4362                 return 1;
4363         }
4364         int ret = 0;
4365         int ofd = ::open(target, O_CREAT+O_TRUNC+O_WRONLY, 0777);
4366         if( ofd >= 0 ) {
4367                 struct stat st;
4368                 int64_t total_bytes = !fstat(ifd, &st) ? st.st_size : 0;
4369                 char progress_title[BCTEXTLEN];
4370                 sprintf(progress_title, _("Copying: %s\n"), target);
4371                 BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
4372
4373                 int64_t count = 0, len = -1;
4374                 int bfrsz = 0x100000;
4375                 uint8_t *bfr = new uint8_t[bfrsz];
4376                 while( (len=::read(ifd, bfr, bfrsz)) > 0 ) {
4377                         if( len != ::write(ofd, bfr, len) ) {
4378                                 eprintf("Error writing: %s", target);
4379                                 break;
4380                         }
4381                         if( progress.is_cancelled() ) {
4382                                 ret = 1;
4383                                 break;
4384                         }
4385                         progress.update(count += len, 1);
4386                 }
4387                 delete [] bfr;
4388                 ::close(ofd);
4389
4390                 progress.stop_progress();
4391                 if( len < 0 ) {
4392                         eprintf("Error reading: %s", path);
4393                         ret = 1;
4394                 }
4395         }
4396         else
4397                 eprintf("Cannot create asset target: %s", target);
4398         ::close(ifd);
4399         return ret;
4400 }
4401
4402 int MWindow::link_target(const char *real_path, const char *link_path, int relative)
4403 {
4404         char target[BCTEXTLEN];
4405         if( relative ) {
4406                 const char *bp = real_path, *cp = bp;
4407                 const char *lp = link_path, *np = lp;
4408                 char *tp = target, *ep = tp+sizeof(target)-1, lch;
4409                 while( *lp && *bp && (lch=*lp++) == *bp++ ) {
4410                         if( lch == '/' ) { np = lp;  cp = bp; }
4411                 }
4412                 while( tp<ep && *np ) {
4413                         if( *np++ != '/' ) continue;
4414                         *tp++ = '.';  *tp++ = '.';  *tp++ = '/';
4415                 }
4416                 while( tp<ep && *cp ) *tp++ = *cp++;
4417                 *tp = 0;
4418         }
4419         else
4420                 strcpy(target, real_path);
4421         if( symlink(target, link_path) ) {
4422                 eprintf("Cannot create symlink: %s", link_path);
4423                 return 1;
4424         }
4425         return 0;
4426 }
4427
4428 void MWindow::save_project(const char *dir, int save_mode, int overwrite, int reload)
4429 {
4430         char dir_path[BCTEXTLEN];
4431         strcpy(dir_path, dir);
4432         FileSystem fs;
4433         fs.complete_path(dir_path);
4434
4435         struct stat st;
4436         if( !stat(dir_path, &st) ) {
4437                 if( !S_ISDIR(st.st_mode) ) {
4438                         eprintf("Path exists and is not a directory\n%s", dir_path);
4439                         return;
4440                 }
4441         }
4442         else {
4443                 if( mkdir(dir_path, S_IRWXU | S_IRWXG | S_IRWXO) ) {
4444                         eprintf("Cannot create directory\n%s", dir_path);
4445                         return;
4446                 }
4447         }
4448         char *real_dir = realpath(dir_path, 0);
4449         strcpy(dir_path, real_dir);
4450         free(real_dir);
4451
4452         EDL *save_edl = new EDL;
4453         save_edl->create_objects();
4454         save_edl->copy_all(edl);
4455
4456         char progress_title[BCTEXTLEN];
4457         sprintf(progress_title, _("Saving to %s:\n"), dir);
4458         int total_assets = save_edl->assets->total();
4459         gui->lock_window("MWindow::save_project");
4460         MainProgressBar *progress = mainprogress->start_progress(progress_title, total_assets);
4461         gui->unlock_window();
4462
4463         int ret = 0;
4464         Asset *current = save_edl->assets->first;
4465         for( int i=0; !ret && current; ++i, current=NEXT ) {
4466                 char *path = current->path;
4467                 if( ::stat(path, &st) ) {
4468                         eprintf("Asset not found: %s", path);
4469                         continue;
4470                 }
4471                 char *real_path = realpath(path, 0);
4472                 const char *cp = strrchr(path, '/'), *bp = !cp ? path : cp+1;
4473                 char link_path[BCTEXTLEN];
4474                 snprintf(link_path, sizeof(link_path), "%s/%s", dir_path, bp);
4475                 int skip = 0;
4476                 if( strcmp(real_path, link_path) ) {
4477                         if( !::lstat(link_path, &st) ) {
4478                                 if( overwrite )
4479                                         ::remove(link_path);
4480                                 else
4481                                         skip = 1;
4482                         }
4483                 }
4484                 else {
4485                         eprintf("copy/link to self, skippped: %s", path);
4486                         skip = 1;
4487                 }
4488                 if( !skip ) {
4489                         if( save_mode == SAVE_PROJECT_COPY ) {
4490                                 if( copy_target(real_path, link_path) )
4491                                         ret = 1;
4492                         }
4493                         else {
4494                                 link_target(real_path, link_path,
4495                                         save_mode == SAVE_PROJECT_RELLINK ? 1 : 0);
4496                         }
4497                 }
4498                 free(real_path);
4499                 strcpy(path, link_path);
4500
4501                 if( progress->is_cancelled() ) break;
4502                 progress->update(i);
4503         }
4504
4505         progress->stop_progress();
4506         delete progress;
4507
4508         char *cp = strrchr(dir_path,'/');
4509         char *bp = cp ? cp+1 : dir_path;
4510         char filename[BCTEXTLEN];
4511         snprintf(filename, sizeof(filename), "%s/%s.xml", dir_path, bp);
4512         save_edl->set_path(filename);
4513         FileXML file;
4514         save_edl->save_xml(&file, filename);
4515         file.terminate_string();
4516
4517         if( !file.write_to_file(filename) ) {
4518                 char string[BCTEXTLEN];
4519                 sprintf(string, _("\"%s\" %dC written"), filename, (int)strlen(file.string()));
4520                 gui->lock_window("SaveProject::run 2");
4521                 gui->show_message(string);
4522                 gui->unlock_window();
4523                 gui->mainmenu->add_load(filename);
4524         }
4525         else
4526                 eprintf(_("Couldn't open %s."), filename);
4527
4528         save_edl->remove_user();
4529
4530         if( reload ) {
4531                 gui->lock_window("MWindow::save_project");
4532                 ArrayList<char*> filenames;
4533                 filenames.append(filename);
4534                 load_filenames(&filenames);
4535                 gui->unlock_window();
4536         }
4537 }
4538
4539
4540 static inline int gcd(int m, int n)
4541 {
4542         int r;
4543         if( m < n ) { r = m;  m = n;  n = r; }
4544         while( (r = m % n) != 0 ) { m = n;  n = r; }
4545         return n;
4546 }
4547
4548 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
4549 {
4550         w = 1;  h = 1;
4551         double ar;
4552         
4553         if(!width || !height) return 1;
4554         if( width == 720 && (height == 480 || height == 576) ) {
4555                 w = 4;  h = 3;  return 0; // for NTSC and PAL
4556         }
4557         
4558         ar = (double)width / height;
4559 // square-ish pixels
4560         if( EQUIV(ar, 1.0000) ) return 0;
4561         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
4562         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
4563         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
4564         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
4565         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
4566         if( EQUIV(ar, 2.37037) ) { w = 64; h = 27;  return 0; }
4567
4568         int ww = width, hh = height;
4569         // numerator, denominator must be under mx
4570         int mx = 255, n = gcd(ww, hh);
4571         if( n > 1 ) { ww /= n; hh /= n; }
4572         // search near height in case extra/missing lines
4573         if( ww >= mx || hh >= mx ) {
4574                 double err = height;  // +/- 2 percent height
4575                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
4576                         int iw = width, ih = height+i;
4577                         if( (n=gcd(iw, ih)) > 1 ) {
4578                                 int u = iw/n;  if( u >= mx ) continue;
4579                                 int v = ih/n;  if( v >= mx ) continue;
4580                                 double r = (double) u/v, er = fabs(ar-r);
4581                                 if( er >= err ) continue;
4582                                 err = er;  ww = u;  hh = v;
4583                         }
4584                 }
4585         }
4586
4587         w = ww;  h = hh;
4588         return 0;
4589 }
4590
4591 void MWindow::reset_caches(int locked)
4592 {
4593         if( locked ) gui->unlock_window();
4594         awindow->gui->stop_vicon_drawing(1);
4595         if( cwindow->playback_engine )
4596                 cwindow->playback_engine->create_cache();
4597         for(int i = 0; i < vwindows.size(); i++) {
4598                 VWindow *vwindow = vwindows[i];
4599                 if( !vwindow->is_running() ) continue;
4600                 if( !vwindow->playback_engine ) continue;
4601                 vwindow->playback_engine->create_cache();
4602         }
4603         gui->lock_window("MWindow::reset_caches");
4604         frame_cache->remove_all();
4605         wave_cache->remove_all();
4606         audio_cache->remove_all();
4607         video_cache->remove_all();
4608         if( !locked ) gui->unlock_window();
4609 }
4610
4611 void MWindow::remove_from_caches(Indexable *idxbl)
4612 {
4613         awindow->gui->stop_vicon_drawing(1);
4614         frame_cache->remove_item(idxbl);
4615         wave_cache->remove_item(idxbl);
4616         if( gui->render_engine &&
4617             gui->render_engine_id == idxbl->id ) {
4618                 delete gui->render_engine;
4619                 gui->render_engine = 0;
4620         }
4621         gui->resource_thread->close_indexable(idxbl);
4622         if( !idxbl->is_asset ) return;
4623         Asset *asset = (Asset *)idxbl;
4624         audio_cache->delete_entry(asset);
4625         video_cache->delete_entry(asset);
4626         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
4627                 cwindow->playback_engine->audio_cache->delete_entry(asset);
4628         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
4629                 cwindow->playback_engine->video_cache->delete_entry(asset);
4630         for(int i = 0; i < vwindows.size(); i++) {
4631                 VWindow *vwindow = vwindows[i];
4632                 if( !vwindow->is_running() ) continue;
4633                 if( !vwindow->playback_engine ) continue;
4634                 if( vwindow->playback_engine->audio_cache )
4635                         vwindow->playback_engine->audio_cache->delete_entry(asset);
4636                 if( vwindow->playback_engine->video_cache )
4637                         vwindow->playback_engine->video_cache->delete_entry(asset);
4638         }
4639         for(int i = 0; i < zwindows.size(); i++) {
4640                 ZWindow *zwindow = zwindows[i];
4641                 if( !zwindow->is_running() ) continue;
4642                 if( zwindow->zgui->playback_engine->audio_cache )
4643                         zwindow->zgui->playback_engine->audio_cache->delete_entry(asset);
4644                 if( zwindow->zgui->playback_engine->video_cache )
4645                         zwindow->zgui->playback_engine->video_cache->delete_entry(asset);
4646         }
4647         awindow->gui->start_vicon_drawing();
4648 }
4649
4650 void MWindow::remove_assets_from_project(int push_undo, int redraw, int delete_indexes,
4651                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
4652 {
4653         awindow->gui->stop_vicon_drawing(1);
4654
4655 // Remove from VWindow.
4656         if( drag_clips ) {
4657                 for(int i = 0; i < drag_clips->total; i++) {
4658                         for(int j = 0; j < vwindows.size(); j++) {
4659                                 VWindow *vwindow = vwindows[j];
4660                                 if( !vwindow->is_running() ) continue;
4661                                 if(drag_clips->get(i) == vwindow->get_edl()) {
4662                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
4663                                         vwindow->delete_source(1, 1);
4664                                         vwindow->gui->unlock_window();
4665                                 }
4666                         }
4667                 }
4668         }
4669
4670         if( drag_assets ) {
4671                 for(int i = 0; i < drag_assets->size(); i++) {
4672                         for(int j = 0; j < vwindows.size(); j++) {
4673                                 VWindow *vwindow = vwindows[j];
4674                                 if( !vwindow->is_running() ) continue;
4675                                 if(drag_assets->get(i) == vwindow->get_source()) {
4676                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
4677                                         vwindow->delete_source(1, 1);
4678                                         vwindow->gui->unlock_window();
4679                                 }
4680                         }
4681                 }
4682
4683                 for(int i = 0; i < drag_assets->total; i++) {
4684                         Indexable *indexable = drag_assets->get(i);
4685                         if(indexable->is_asset) remove_from_caches(indexable);
4686                 }
4687
4688                 if( delete_indexes ) {
4689                         for(int i = 0; i < drag_assets->size(); i++) {
4690                                 Indexable *indexable = drag_assets->get(i);
4691                                 remove_indexfile(indexable);
4692                         }
4693                 }
4694         }
4695
4696 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4697         if(push_undo) undo_before();
4698         if(drag_assets) edl->remove_from_project(drag_assets);
4699         if(drag_clips) edl->remove_from_project(drag_clips);
4700         if(redraw) save_backup();
4701         if(push_undo) undo_after(_("remove assets"), LOAD_ALL);
4702         if(redraw) {
4703                 restart_brender();
4704
4705                 gui->lock_window("MWindow::remove_assets_from_project 3");
4706                 gui->update(1, NORMAL_DRAW, 1, 1, 0, 1, 0);
4707                 gui->unlock_window();
4708
4709         // Removes from playback here
4710                 sync_parameters(CHANGE_ALL);
4711         }
4712
4713         awindow->gui->async_update_assets();
4714 }
4715
4716 void MWindow::remove_assets_from_disk()
4717 {
4718         remove_assets_from_project(1, 1, 1,
4719                 session->drag_assets, session->drag_clips);
4720
4721 // Remove from disk
4722         for(int i = 0; i < session->drag_assets->total; i++)
4723         {
4724                 remove(session->drag_assets->get(i)->path);
4725         }
4726 }
4727
4728 void MWindow::dump_plugins(FILE *fp)
4729 {
4730         if( !plugindb ) return;
4731         for(int i = 0; i < plugindb->total; i++)
4732         {
4733                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
4734                         " synth=%d transition=%d theme=%d %s\n",
4735                         plugindb->get(i)->plugin_type,
4736                         plugindb->get(i)->audio,
4737                         plugindb->get(i)->video,
4738                         plugindb->get(i)->realtime,
4739                         plugindb->get(i)->multichannel,
4740                         plugindb->get(i)->get_synthesis(),
4741                         plugindb->get(i)->transition,
4742                         plugindb->get(i)->theme,
4743                         plugindb->get(i)->title);
4744         }
4745 }
4746
4747 void MWindow::dump_edl(FILE *fp)
4748 {
4749         if( !edl ) return;
4750         edl->dump(fp);
4751 }
4752
4753 void MWindow::dump_undo(FILE *fp)
4754 {
4755         if( !undo ) return;
4756         undo->dump(fp);
4757 }
4758
4759 void MWindow::dump_exe(FILE *fp)
4760 {
4761         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
4762         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
4763
4764         int ret = -1, n = 100;
4765         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
4766                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
4767                 ret = 0;
4768         }
4769         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
4770
4771         struct stat st;
4772         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
4773         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
4774         struct tm *tm = localtime(&st.st_mtime);
4775         char mtime[256];
4776         strftime(mtime, sizeof(mtime), "%F %T", tm);
4777         fprintf(fp,"mtime: %s\n", mtime);
4778 #if 0
4779 // people hit ctl-c waiting for this
4780         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
4781         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
4782         uint8_t *bfr = 0;
4783         int64_t bfrsz = 0;
4784         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
4785         int64_t maxsz = 1024*pagsz;
4786         int64_t size = st.st_size, pos = 0;
4787         SHA1 sha1;
4788         while( (bfrsz = size-pos) > 0 ) {
4789                 if( bfrsz > maxsz ) bfrsz = maxsz;
4790                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
4791                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
4792                 if( bfr == MAP_FAILED ) break;
4793                 sha1.addBytes(bfr, bfrsz);
4794                 munmap(bfr, bfrsz);
4795                 pos += bfrsz;
4796         }
4797         close(fd);
4798         ret = pos < size ? EIO : 0;
4799         fprintf(fp, "SHA1: ");
4800         uint8_t digest[20];  sha1.computeHash(digest);
4801         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
4802         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
4803         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
4804 #endif
4805         fprintf(fp, "\n");
4806 }
4807
4808 void MWindow::dump_caches(FILE *fp)
4809 {
4810         fprintf(fp, "audio cache: ");
4811         audio_cache->dump(fp);
4812         fprintf(fp, "video cache: ");
4813         video_cache->dump(fp);
4814 }
4815
4816 void MWindow::trap_hook(FILE *fp, void *vp)
4817 {
4818         MWindow *mwindow = (MWindow *)vp;
4819 //      fprintf(fp, "\nPLUGINS:\n");
4820 //      mwindow->dump_plugins(fp);
4821         fprintf(fp, "\nEDL:\n");
4822         mwindow->dump_edl(fp);
4823         fprintf(fp, "\nUNDO:\n");
4824         mwindow->dump_undo(fp);
4825         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
4826         mwindow->dump_exe(fp);
4827         fprintf(fp, "\nCACHES:\n");
4828         mwindow->dump_caches(fp);
4829 }
4830
4831
4832
4833
4834
4835
4836 int MWindow::save_defaults()
4837 {
4838         gui->save_defaults(defaults);
4839         edl->save_defaults(defaults);
4840         session->save_defaults(defaults);
4841         preferences->save_defaults(defaults);
4842
4843         for(int i = 0; i < plugin_guis->total; i++)
4844         {
4845 // Pointer comparison
4846                 plugin_guis->get(i)->save_defaults();
4847         }
4848         awindow->save_defaults(defaults);
4849
4850         defaults->save();
4851         return 0;
4852 }
4853
4854 int MWindow::run_script(FileXML *script)
4855 {
4856         int result = 0, result2 = 0;
4857         while(!result && !result2)
4858         {
4859                 result = script->read_tag();
4860                 if(!result)
4861                 {
4862                         if(script->tag.title_is("new_project"))
4863                         {
4864 // Run new in immediate mode.
4865 //                              gui->mainmenu->new_project->run_script(script);
4866                         }
4867                         else
4868                         if(script->tag.title_is("record"))
4869                         {
4870 // Run record as a thread.  It is a terminal command.
4871                                 ;
4872 // Will read the complete scipt file without letting record read it if not
4873 // terminated.
4874                                 result2 = 1;
4875                         }
4876                         else
4877                         {
4878                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
4879                         }
4880                 }
4881         }
4882         return result2;
4883 }
4884
4885 // ================================= synchronization
4886
4887
4888 int MWindow::interrupt_indexes()
4889 {
4890         mainprogress->cancelled = 1;
4891         mainindexes->interrupt_build();
4892         return 0;
4893 }
4894
4895
4896
4897 void MWindow::next_time_format()
4898 {
4899         switch( edl->session->time_format ) {
4900         case TIME_HMS:          edl->session->time_format = TIME_HMSF;         break;
4901         case TIME_HMSF:         edl->session->time_format = TIME_TIMECODE;     break;
4902         case TIME_TIMECODE:     edl->session->time_format = TIME_FRAMES;       break;
4903         case TIME_FRAMES:       edl->session->time_format = TIME_SAMPLES;      break;
4904         case TIME_SAMPLES:      edl->session->time_format = TIME_SAMPLES_HEX;  break;
4905         case TIME_SAMPLES_HEX:  edl->session->time_format = TIME_SECONDS;      break;
4906         case TIME_SECONDS:      edl->session->time_format = TIME_FEET_FRAMES;  break;
4907         case TIME_FEET_FRAMES:  edl->session->time_format = TIME_HMS;          break;
4908         }
4909         time_format_common();
4910 }
4911
4912 void MWindow::prev_time_format()
4913 {
4914         switch( edl->session->time_format ) {
4915         case TIME_HMS:          edl->session->time_format = TIME_FEET_FRAMES;  break;
4916         case TIME_HMSF:         edl->session->time_format = TIME_HMS;          break;
4917         case TIME_TIMECODE:     edl->session->time_format = TIME_HMSF;         break;
4918         case TIME_FRAMES:       edl->session->time_format = TIME_TIMECODE;     break;
4919         case TIME_SAMPLES:      edl->session->time_format = TIME_FRAMES;       break;
4920         case TIME_SAMPLES_HEX:  edl->session->time_format = TIME_SAMPLES;      break;
4921         case TIME_SECONDS:      edl->session->time_format = TIME_SAMPLES_HEX;  break;
4922         case TIME_FEET_FRAMES:  edl->session->time_format = TIME_SECONDS;      break;
4923         }
4924
4925         time_format_common();
4926 }
4927
4928 void MWindow::time_format_common()
4929 {
4930         gui->lock_window("MWindow::next_time_format");
4931         gui->redraw_time_dependancies();
4932
4933
4934         char string[BCTEXTLEN], string2[BCTEXTLEN];
4935         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
4936         gui->show_message(string);
4937         gui->flush();
4938         gui->unlock_window();
4939 }
4940
4941
4942 int MWindow::set_filename(const char *filename)
4943 {
4944         if( filename != session->filename )
4945                 strcpy(session->filename, filename);
4946         if( filename != edl->path )
4947                 strcpy(edl->path, filename);
4948         return set_titlebar(filename);
4949 }
4950
4951 int MWindow::set_titlebar(const char *filename)
4952 {
4953         if( !gui ) return 0;
4954         if( filename[0] ) {
4955                 FileSystem dir;
4956                 char string[BCTEXTLEN], string2[BCTEXTLEN];
4957                 dir.extract_name(string, filename);
4958                 sprintf(string2, PROGRAM_NAME ": %s", string);
4959                 gui->set_title(string2);
4960         }
4961         else
4962                 gui->set_title(PROGRAM_NAME);
4963         return 0;
4964 }
4965
4966
4967 int MWindow::set_loop_boundaries()
4968 {
4969         double start = edl->local_session->get_selectionstart();
4970         double end = edl->local_session->get_selectionend();
4971
4972         if(start !=
4973                 end)
4974         {
4975                 ;
4976         }
4977         else
4978         if(edl->tracks->total_length())
4979         {
4980                 start = 0;
4981                 end = edl->tracks->total_length();
4982         }
4983         else
4984         {
4985                 start = end = 0;
4986         }
4987
4988         if(edl->local_session->loop_playback && start != end)
4989         {
4990                 edl->local_session->loop_start = start;
4991                 edl->local_session->loop_end = end;
4992         }
4993         return 0;
4994 }
4995
4996
4997
4998
4999
5000
5001
5002 int MWindow::reset_meters()
5003 {
5004         cwindow->gui->lock_window("MWindow::reset_meters 1");
5005         cwindow->gui->meters->reset_meters();
5006         cwindow->gui->unlock_window();
5007
5008         for(int j = 0; j < vwindows.size(); j++) {
5009                 VWindow *vwindow = vwindows[j];
5010                 if( !vwindow->is_running() ) continue;
5011                 vwindow->gui->lock_window("MWindow::reset_meters 2");
5012                 vwindow->gui->meters->reset_meters();
5013                 vwindow->gui->unlock_window();
5014         }
5015
5016         lwindow->gui->lock_window("MWindow::reset_meters 3");
5017         lwindow->gui->panel->reset_meters();
5018         lwindow->gui->unlock_window();
5019
5020         gui->lock_window("MWindow::reset_meters 4");
5021         gui->reset_meters();
5022         gui->unlock_window();
5023         return 0;
5024 }
5025
5026
5027 void MWindow::resync_guis()
5028 {
5029 // Update GUIs
5030         restart_brender();
5031         gui->lock_window("MWindow::resync_guis");
5032         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 0);
5033         gui->unlock_window();
5034
5035         cwindow->gui->lock_window("MWindow::resync_guis");
5036         cwindow->gui->resize_event(cwindow->gui->get_w(),
5037                 cwindow->gui->get_h());
5038         int channels = edl->session->audio_channels;
5039         cwindow->gui->meters->set_meters(channels, 1);
5040         cwindow->gui->flush();
5041         cwindow->gui->unlock_window();
5042
5043         for(int i = 0; i < vwindows.size(); i++) {
5044                 VWindow *vwindow = vwindows[i];
5045                 if( !vwindow->is_running() ) continue;
5046                 vwindow->gui->lock_window("MWindow::resync_guis");
5047                 vwindow->gui->resize_event(vwindow->gui->get_w(),
5048                         vwindow->gui->get_h());
5049                 vwindow->gui->meters->set_meters(channels, 1);
5050                 vwindow->gui->flush();
5051                 vwindow->gui->unlock_window();
5052         }
5053
5054         lwindow->gui->lock_window("MWindow::resync_guis");
5055         lwindow->gui->panel->set_meters(channels, 1);
5056         lwindow->gui->flush();
5057         lwindow->gui->unlock_window();
5058 #ifdef GLx4
5059 // Warn user
5060         if(((edl->session->output_w % 4) ||
5061                 (edl->session->output_h % 4)) &&
5062                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
5063         {
5064                 MainError::show_error(
5065                         _("This project's dimensions are not multiples of 4 so\n"
5066                         "it can't be rendered by OpenGL."));
5067         }
5068 #endif
5069
5070 // Flash frame
5071         sync_parameters(CHANGE_ALL);
5072 }
5073
5074 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
5075 {
5076         File *file = new File;
5077         EDLSession *session = edl->session;
5078         double old_framerate = session->frame_rate;
5079         double old_samplerate = session->sample_rate;
5080         int old_auto_keyframes = session->auto_keyframes;
5081         session->auto_keyframes = 0;
5082         int result = file->open_file(preferences, asset, 1, 0);
5083         if( !result && delete_tracks > 0 )
5084                 undo_before();
5085         int video_layers = asset->get_video_layers();
5086         if( !result && asset->video_data && vstream < video_layers ) {
5087                 // try to get asset up to date, may fail
5088                 file->select_video_stream(asset, vstream);
5089                 // either way use what was/is there.
5090                 double framerate = asset->get_frame_rate();
5091                 int width = asset->get_w();
5092                 int height = asset->get_h();
5093 #ifdef GLx4
5094                 // must be multiple of 4 for opengl
5095                 width = (width+3) & ~3;  height = (height+3) & ~3;
5096 #endif
5097                 int driver = session->playback_config->vconfig->driver;
5098                 int color_model = file->get_best_colormodel(asset, driver);
5099 //              color_model = BC_CModels::is_yuv(color_model) ?
5100 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
5101 //                      BC_CModels::is_float(color_model) ?
5102 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
5103 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
5104 // have alpha for now
5105                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
5106                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
5107                 session->color_model = color_model;
5108                 session->output_w = width;
5109                 session->output_h = height;
5110                 session->frame_rate = framerate;
5111                 session->interlace_mode = asset->interlace_mode;
5112                 // not, asset->actual_width/actual_height
5113                 asset->width = session->output_w;
5114                 asset->height = session->output_h;
5115                 asset->frame_rate = session->frame_rate;
5116                 
5117                 create_aspect_ratio(session->aspect_w, session->aspect_h,
5118                         session->output_w, session->output_h);
5119         float ar = asset->aspect_ratio;
5120         if (ar) {
5121         //printf ("Aspect ratio from asset: %f \n", ar);
5122         if( EQUIV(ar, 1.3333) ) { session->aspect_w = 4;  session->aspect_h = 3;  }
5123         if( EQUIV(ar, 1.7777) ) { session->aspect_w = 16; session->aspect_h = 9;   }
5124         if( EQUIV(ar, 2.1111) ) { session->aspect_w = 19; session->aspect_h = 9;  }
5125         if( EQUIV(ar, 2.2222) ) { session->aspect_w = 20; session->aspect_h = 9;   }
5126         if( EQUIV(ar, 2.3333) ) { session->aspect_w = 21; session->aspect_h = 9;   }
5127         if( EQUIV(ar, 2.370370) ) { session->aspect_w = 64; session->aspect_h = 27; }
5128         }
5129                         
5130                         
5131                 Track *track = edl->tracks->first;
5132                 for( Track *next_track=0; track; track=next_track ) {
5133                         next_track = track->next;
5134                         if( track->data_type != TRACK_VIDEO ) continue;
5135                         if( delete_tracks ) {
5136                                 Edit *edit = track->edits->first;
5137                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
5138                                         next_edit = edit->next;
5139                                         if( edit->channel != vstream ||
5140                                             !edit->asset || !edit->asset->is_asset ||
5141                                             !asset->equivalent(*edit->asset,1,1,edl) )
5142                                                 delete edit;
5143                                 }
5144                         }
5145                         if( track->edits->first ) {
5146                                 track->track_w = edl->session->output_w;
5147                                 track->track_h = edl->session->output_h;
5148                         }
5149                         else if( delete_tracks )
5150                                 edl->tracks->delete_track(track, 0);
5151                 }
5152                 edl->retrack();
5153                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
5154         }
5155         if( !result && asset->audio_data && asset->channels > 0 ) {
5156                 session->sample_rate = asset->get_sample_rate();
5157                 int64_t channel_mask = 0;
5158                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
5159                         file->get_audio_for_video(vstream, astream, channel_mask);
5160                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
5161                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
5162                 int channels = 0;
5163                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
5164                 if( channels < 1 ) channels = 1;
5165                 if( channels > 6 ) channels = 6;
5166                 session->audio_tracks = session->audio_channels = channels;
5167
5168                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
5169                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
5170                 remap_audio(MWindow::AUDIO_1_TO_1);
5171
5172                 if( delete_tracks ) {
5173                         Track *track = edl->tracks->first;
5174                         for( Track *next_track=0; track; track=next_track ) {
5175                                 next_track = track->next;
5176                                 if( track->data_type != TRACK_AUDIO ) continue;
5177                                 Edit *edit = track->edits->first;
5178                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
5179                                         next_edit = edit->next;
5180                                         if( !((1<<edit->channel) & channel_mask) ||
5181                                             !edit->asset || !edit->asset->is_asset ||
5182                                             !asset->equivalent(*edit->asset,1,1,edl) )
5183                                                 delete edit;
5184                                 }
5185                                 if( !track->edits->first )
5186                                         edl->tracks->delete_track(track, 0);
5187                         }
5188                 }
5189                 edl->rechannel();
5190                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
5191         }
5192         delete file;
5193         session->auto_keyframes = old_auto_keyframes;
5194         if( !result && delete_tracks > 0 ) {
5195                 save_backup();
5196                 undo_after(_("select asset"), LOAD_ALL);
5197         }
5198         resync_guis();
5199         return result;
5200 }
5201
5202 int MWindow::select_asset(int vtrack, int delete_tracks)
5203 {
5204         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
5205         if( !track )
5206                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
5207         if( !track ) return 1;
5208         Edit *edit = track->edits->first;
5209         if( !edit ) return 1;
5210         Asset *asset = edit->asset;
5211         if( !asset || !asset->is_asset ) return 1;
5212         return select_asset(asset, edit->channel, 0, delete_tracks);
5213 }
5214
5215 void MWindow::dump_plugindb(FILE *fp)
5216 {
5217         if( !plugindb ) return;
5218         for(int i = 0; i < plugindb->total; i++)
5219                 plugindb->get(i)->dump(fp);
5220 }
5221
5222 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
5223 {
5224         Auto *current = 0;
5225         double unit_position = edl->local_session->get_selectionstart(1);
5226         unit_position = patch->track->to_units(unit_position, 0);
5227
5228         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
5229         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5230 }
5231
5232 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
5233 {
5234         Auto *current = 0;
5235         double unit_position = edl->local_session->get_selectionstart(1);
5236         unit_position = patch->track->to_units(unit_position, 0);
5237
5238         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
5239         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5240 }
5241
5242 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
5243 {
5244         Auto *current = 0;
5245         double unit_position = edl->local_session->get_selectionstart(1);
5246         unit_position = patch->track->to_units(unit_position, 0);
5247
5248         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
5249         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5250 }
5251
5252 PatchGUI *MWindow::get_patchgui(Track *track)
5253 {
5254         PatchGUI *patchgui = 0;
5255         TimelinePane **panes = gui->pane;
5256         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
5257                 if( !panes[i] ) continue;
5258                 PatchBay *patchbay = panes[i]->patchbay;
5259                 if( !patchbay ) continue;
5260                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
5261                         if( patchbay->patches.values[j]->track == track )
5262                                 patchgui = patchbay->patches.values[j];
5263                 }
5264         }
5265         return patchgui;
5266 }
5267
5268 int MWindow::get_cpus(int out_w, int out_h)
5269 {
5270         if( !out_w ) out_w = edl->session->output_w;
5271         if( !out_h ) out_h = edl->session->output_h;
5272         int cpus = out_w*out_h/0x80000 + 1;
5273         if( cpus > preferences->processors )
5274                 cpus = preferences->processors;
5275         return cpus;
5276 }
5277 int MWindow::get_cpus()
5278 {
5279         return get_cpus(edl->session->output_w, edl->session->output_h);
5280 }
5281
5282 void MWindow::draw_trackmovement()
5283 {
5284         if( !redraw_tracks )
5285                 redraw_tracks = new DrawTrackMovement(this);
5286         redraw_tracks->start();
5287 }
5288
5289 DrawTrackMovement::DrawTrackMovement(MWindow *mwindow)
5290  : Thread(1, 0, 0)
5291 {
5292         this->mwindow = mwindow;
5293 }
5294 DrawTrackMovement::~DrawTrackMovement()
5295 {
5296         join();
5297 }
5298
5299 void DrawTrackMovement::run()
5300 {
5301         mwindow->gui->lock_window("DrawTrackMovement::run");
5302         mwindow->edl->tracks->update_y_pixels(mwindow->theme);
5303         mwindow->gui->draw_trackmovement();
5304         mwindow->gui->unlock_window();
5305 }
5306
5307
5308 ConfirmRefWindow::ConfirmRefWindow(MWindow *mwindow, char *path,
5309                 int px, int py, int cw, int ch)
5310  : BC_Window(_(PROGRAM_NAME ": Confirm update"), px, py, cw, ch, cw, ch)
5311 {
5312         this->mwindow = mwindow;
5313         this->path = path;
5314 }
5315
5316 ConfirmRefWindow::~ConfirmRefWindow()
5317 {
5318 }
5319
5320 void ConfirmRefWindow::create_objects()
5321 {
5322         lock_window("ConfirmRefWindow::create_objects()");
5323         int x = xS(10), y = yS(10), pad = yS(5);
5324         BC_Title *title;
5325         add_subwindow(title = new BC_Title(x, y, _("FileREF not updated:")));
5326         y += title->get_h() + pad;
5327         BC_TextBox *text_box;
5328         add_subwindow(text_box = new BC_TextBox(x,y, get_w()-2*x, 1, path));
5329         y += text_box->get_h() + 2*pad;
5330         add_subwindow(title = new BC_Title(x, y, _("Save file ref changes?")));
5331         add_subwindow(new BC_OKButton(this));
5332         add_subwindow(new BC_CancelButton(this));
5333         show_window();
5334         unlock_window();
5335 }
5336