rework proxy for 1:1 and new layout, fix proxy for resized assets, change track gang_...
[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 nz = 0;
1473         for( int i=0; i<zwindows.size(); ++i ) {
1474                 ZWindow *zwindow = zwindows[i];
1475                 if( zwindow->idx < 0 ) continue;
1476                 ++nz;
1477         }
1478         if( !nz ) return;
1479         int zn = ceil(sqrt(nz));
1480         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1481         int y1 = 1, y2 = gui->get_y();
1482         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1483         if( x1 < 0 ) x1 = 0;
1484         if( y1 < 0 ) y1 = 0;
1485         if( x2 > rw ) x2 = rw;
1486         if( y2 > rh ) y2 = rh;
1487         int dx = x2 - x1, dy = y2 - y1;
1488         int zw = dx / zn;
1489         int lt = BC_DisplayInfo::get_left_border();
1490         int top = BC_DisplayInfo::get_top_border();
1491         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1492         int bh = top + BC_DisplayInfo::get_bottom_border();
1493         int zx = 0, zy = 0;  // window origins
1494         int mw = xS(10+10), mh = yS(10+10); // canvas margins
1495         int rsz = 0, n = 0, dz = 0;
1496         int ow = edl->session->output_w, oh = edl->session->output_h;
1497         for( int i=0; i<zwindows.size(); ++i ) {
1498                 ZWindow *zwindow = zwindows[i];
1499                 if( zwindow->idx < 0 ) continue;
1500                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1501                 if( rsz < hh ) rsz = hh;
1502                 int xx = zx + x1, yy = zy + y1;
1503                 int mx = x2 - zw, my = y2 - zh;
1504                 if( xx > mx ) xx = mx;
1505                 if( yy > my ) yy = my;
1506                 xx += lt + xS(dz);  yy += top + yS(dz);
1507                 zwindow->reposition(xx,yy, ww,hh);
1508                 if( zwindow->running() ) {
1509                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1510                         gui->lock_window("MWindow::tile_mixers");
1511                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1512                         gui->unlock_window();
1513                 }
1514                 if( ++n >= zn ) {
1515                         n = 0;  rsz += bh;
1516                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1517                         rsz = 0;
1518                         zx = 0;
1519                 }
1520                 else
1521                         zx += zw;
1522         }
1523 }
1524
1525 void MWindow::set_gang_tracks(int v)
1526 {
1527         edl->local_session->gang_tracks = v;
1528         sync_parameters(CHANGE_PARAMS);
1529         gui->update(1, 1, 0, 0, 1, 0, 0);
1530         gui->flush();
1531 }
1532
1533
1534 void MWindow::init_cache()
1535 {
1536         audio_cache = new CICache(preferences);
1537         video_cache = new CICache(preferences);
1538         frame_cache = new FrameCache;
1539         wave_cache = new WaveCache;
1540 }
1541
1542 void MWindow::init_channeldb()
1543 {
1544         channeldb_buz->load("channeldb_buz");
1545         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1546 }
1547
1548 void MWindow::init_menus()
1549 {
1550         char string[BCTEXTLEN];
1551
1552         // Color Models
1553         BC_CModels::to_text(string, BC_RGB888);
1554         colormodels.append(new ColormodelItem(string, BC_RGB888));
1555         BC_CModels::to_text(string, BC_RGBA8888);
1556         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1557 //      BC_CModels::to_text(string, BC_RGB161616);
1558 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1559 //      BC_CModels::to_text(string, BC_RGBA16161616);
1560 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1561         BC_CModels::to_text(string, BC_RGB_FLOAT);
1562         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1563         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1564         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1565         BC_CModels::to_text(string, BC_YUV888);
1566         colormodels.append(new ColormodelItem(string, BC_YUV888));
1567         BC_CModels::to_text(string, BC_YUVA8888);
1568         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1569 //      BC_CModels::to_text(string, BC_YUV161616);
1570 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1571 //      BC_CModels::to_text(string, BC_YUVA16161616);
1572 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1573
1574 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1575                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1576
1577 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1578                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1579
1580         // Interlacing Modes
1581         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1582
1583         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1584         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1585
1586         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1587         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1588
1589         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1590         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1591
1592         mixers_align = new MixersAlign(this);
1593 }
1594
1595 void MWindow::init_indexes()
1596 {
1597         mainindexes = new MainIndexes(this);
1598         mainindexes->start_loop();
1599 }
1600
1601 void MWindow::init_gui()
1602 {
1603         gui = new MWindowGUI(this);
1604         gui->create_objects();
1605         gui->load_defaults(defaults);
1606 }
1607
1608 void MWindow::init_signals()
1609 {
1610         sighandler = new SigHandler;
1611         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1612 ENABLE_BUFFER
1613 }
1614
1615 void MWindow::init_render()
1616 {
1617         render = new Render(this);
1618         create_bd = new CreateBD_Thread(this);
1619         create_dvd = new CreateDVD_Thread(this);
1620         batch_render = new BatchRenderThread(this);
1621 }
1622
1623 void MWindow::init_exportedl()
1624 {
1625         exportedl = new ExportEDL(this);
1626 }
1627
1628
1629 void MWindow::init_shuttle()
1630 {
1631 #ifdef HAVE_SHUTTLE
1632         int ret = Shuttle::probe();
1633         if( ret >= 0 ) {
1634                 shuttle = new Shuttle(this);
1635                 if( shuttle->read_config_file() > 0 ) {
1636                         printf("shuttle: bad config file\n");
1637                         delete shuttle;  shuttle = 0;
1638                         return;
1639                 }
1640                 shuttle->start(ret);
1641         }
1642 #endif
1643 }
1644 void MWindow::init_wintv()
1645 {
1646 #ifdef HAVE_WINTV
1647         wintv = WinTV::probe(this);
1648         if( wintv )
1649                 wintv->start();
1650 #endif
1651 }
1652 void MWindow::init_x10tv()
1653 {
1654 #ifdef HAVE_X10TV
1655         x10tv = X10TV::probe(this);
1656         if( x10tv )
1657                 x10tv->start();
1658 #endif
1659 }
1660
1661
1662 void MWindow::init_brender()
1663 {
1664         if(preferences->use_brender && !brender)
1665         {
1666                 brender_lock->lock("MWindow::init_brender 1");
1667                 brender = new BRender(this);
1668                 brender->initialize();
1669                 session->brender_end = 0;
1670                 brender_lock->unlock();
1671         }
1672         else
1673         if(!preferences->use_brender && brender)
1674         {
1675                 brender_lock->lock("MWindow::init_brender 2");
1676                 delete brender;
1677                 brender = 0;
1678                 session->brender_end = 0;
1679                 brender_lock->unlock();
1680         }
1681         brender_active = 0;
1682         stop_brender();
1683 }
1684
1685 void MWindow::restart_brender()
1686 {
1687 //printf("MWindow::restart_brender 1\n");
1688         if( !brender_active || !preferences->use_brender ) return;
1689         if( !brender ) return;
1690         brender->restart(edl);
1691 }
1692
1693 void MWindow::stop_brender()
1694 {
1695         if( !brender ) return;
1696 // cannot be holding mwindow->gui display lock
1697         brender->stop();
1698 }
1699
1700 int MWindow::brender_available(int position)
1701 {
1702         int result = 0;
1703         brender_lock->lock("MWindow::brender_available 1");
1704         if(brender && brender_active)
1705         {
1706                 if(brender->map_valid)
1707                 {
1708                         brender->map_lock->lock("MWindow::brender_available 2");
1709                         if(position < brender->map_size &&
1710                                 position >= 0)
1711                         {
1712 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1713                                 if(brender->map[position] == BRender::RENDERED)
1714                                         result = 1;
1715                         }
1716                         brender->map_lock->unlock();
1717                 }
1718         }
1719         brender_lock->unlock();
1720         return result;
1721 }
1722
1723 void MWindow::set_brender_active(int v, int update)
1724 {
1725         if( !preferences->use_brender ) v = 0;
1726         brender_active = v;
1727         gui->mainmenu->brender_active->set_checked(v);
1728         if( v != 0 ) {
1729                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1730                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1731
1732                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1733                         edl->session->brender_end = edl->tracks->total_video_length();
1734                 }
1735                 restart_brender();
1736         }
1737         else {
1738                 edl->session->brender_start = edl->session->brender_end = 0;
1739                 gui->unlock_window();
1740                 stop_brender();
1741                 gui->lock_window("MWindow::set_brender_active");
1742         }
1743         if( update ) {
1744                 gui->update_timebar(0);
1745                 gui->draw_overlays(1);
1746         }
1747 }
1748
1749 int MWindow::has_commercials()
1750 {
1751 #ifdef HAVE_COMMERCIAL
1752         return theme->use_commercials;
1753 #else
1754         return 0;
1755 #endif
1756 }
1757
1758 void MWindow::init_commercials()
1759 {
1760 #ifdef HAVE_COMMERCIAL
1761         if( !commercials ) {
1762                 commercials = new Commercials(this);
1763                 commercial_active = 0;
1764         }
1765         else
1766                 commercials->add_user();
1767 #endif
1768 }
1769
1770 void MWindow::commit_commercial()
1771 {
1772 #ifdef HAVE_COMMERCIAL
1773         if( !commercial_active ) return;
1774         commercial_active = 0;
1775         if( !commercials ) return;
1776         commercials->commitDb();
1777 #endif
1778 }
1779
1780 void MWindow::undo_commercial()
1781 {
1782 #ifdef HAVE_COMMERCIAL
1783         if( !commercial_active ) return;
1784         commercial_active = 0;
1785         if( !commercials ) return;
1786         commercials->undoDb();
1787 #endif
1788 }
1789
1790 int MWindow::put_commercial()
1791 {
1792         int result = 0;
1793 #ifdef HAVE_COMMERCIAL
1794         double start = edl->local_session->get_selectionstart();
1795         double end = edl->local_session->get_selectionend();
1796         if( start >= end ) return 0;
1797
1798         const char *errmsg = 0;
1799         int count = 0;
1800         Tracks *tracks = edl->tracks;
1801         //check it
1802         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1803                 if( track->data_type != TRACK_VIDEO ) continue;
1804                 if( !track->armed ) continue;
1805                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1806                 ++count;
1807                 int64_t units_start = track->to_units(start,0);
1808                 int64_t units_end = track->to_units(end,0);
1809                 Edits *edits = track->edits;
1810                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1811                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1812                 if(!edit1 && !edit2) continue;  // nothing selected
1813                 if(!edit2) {                    // edit2 beyond end of track
1814                         edit2 = edits->last;
1815                         units_end = edits->length();
1816                 }
1817                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1818                 Indexable *indexable = edit1->get_source();
1819                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1820         }
1821         //run it
1822         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1823                 if( track->data_type != TRACK_VIDEO ) continue;
1824                 if( !track->armed ) continue;
1825                 int64_t units_start = track->to_units(start,0);
1826                 int64_t units_end = track->to_units(end,0);
1827                 Edits *edits = track->edits;
1828                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1829                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1830                 if(!edit1 && !edit2) continue;  // nothing selected
1831                 if(!edit2) {                    // edit2 beyond end of track
1832                         edit2 = edits->last;
1833                         units_end = edits->length();
1834                 }
1835                 Indexable *indexable = edit1->get_source();
1836                 Asset *asset = (Asset *)indexable;
1837                 File *file = video_cache->check_out(asset, edl);
1838                 if( !file ) { errmsg = _("no file"); break; }
1839                 int64_t edit_length = units_end - units_start;
1840                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1841                 result = commercials->put_clip(file, edit1->channel,
1842                         track->from_units(edit_start), track->from_units(edit_length));
1843                 video_cache->check_in(asset);
1844                 if( result ) { errmsg = _("db failed"); break; }
1845         }
1846         if( errmsg ) {
1847                 char string[BCTEXTLEN];
1848                 sprintf(string, _("put_commercial: %s"), errmsg);
1849                 MainError::show_error(string);
1850                 undo_commercial();
1851                 result = 1;
1852         }
1853 #endif
1854         return result;
1855 }
1856
1857 void MWindow::stop_playback(int wait)
1858 {
1859         gui->stop_drawing();
1860
1861         cwindow->stop_playback(wait);
1862
1863         for(int i = 0; i < vwindows.size(); i++) {
1864                 VWindow *vwindow = vwindows[i];
1865                 if( !vwindow->is_running() ) continue;
1866                 vwindow->stop_playback(wait);
1867         }
1868         for(int i = 0; i < zwindows.size(); i++) {
1869                 ZWindow *zwindow = zwindows[i];
1870                 if( zwindow->idx < 0 ) continue;
1871                 zwindow->stop_playback(wait);
1872         }
1873 }
1874
1875 void MWindow::stop_transport()
1876 {
1877         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1878 }
1879
1880 void MWindow::undo_before(const char *description, void *creator)
1881 {
1882         undo->update_undo_before(description, creator);
1883 }
1884
1885 void MWindow::undo_after(const char *description, uint32_t load_flags, int changes_made)
1886 {
1887         undo->update_undo_after(description, load_flags, changes_made);
1888 }
1889
1890 void MWindow::beep(double freq, double secs, double gain)
1891 {
1892         if( !beeper ) beeper = new Beeper(this);
1893         beeper->tone(freq, secs, gain);
1894 }
1895
1896 Beeper::Beeper(MWindow *mwindow)
1897  : Thread(1, 0, 0)
1898 {
1899         this->mwindow = mwindow;
1900         audio = new AudioDevice(mwindow);
1901         playing_audio = 0;
1902         interrupted = -1;
1903 }
1904
1905 Beeper::~Beeper()
1906 {
1907         stop(0);
1908         delete audio;
1909 }
1910
1911 void Beeper::run()
1912 {
1913         int channels = 2;
1914         int64_t bfrsz = BEEP_SAMPLE_RATE;
1915         EDL *edl = mwindow->edl;
1916         EDLSession *session = edl->session;
1917         AudioOutConfig *aconfig = session->playback_config->aconfig;
1918         audio->open_output(aconfig, BEEP_SAMPLE_RATE, bfrsz, channels, 0);
1919         audio->start_playback();
1920
1921         double out0[bfrsz], out1[bfrsz], *out[2] = { out0, out1 };
1922         const double two_pi = 2*M_PI;
1923         int64_t audio_len = BEEP_SAMPLE_RATE * secs;
1924         const double dt = two_pi * freq/BEEP_SAMPLE_RATE;
1925         double th = 0;
1926
1927         audio_pos = 0;
1928         playing_audio = 1;
1929         while( !interrupted ) {
1930                 int len = audio_len - audio_pos;
1931                 if( len <= 0 ) break;
1932                 if( len > bfrsz ) len = bfrsz;
1933                 int k = audio_pos;
1934                 for( int i=0; i<len; ++i,++k,th+=dt ) {
1935                         double t = th - two_pi;
1936                         if( t >= 0 ) th = t;
1937                         out0[i] = out1[i] = sin(th) * gain;
1938                 }
1939                 audio->write_buffer(out, channels, len);
1940                 audio_pos = k;
1941         }
1942
1943         if( !interrupted )
1944                 audio->set_last_buffer();
1945         audio->stop_audio(interrupted ? 0 : 1);
1946         playing_audio = 0;
1947
1948         audio->close_all();
1949 }
1950
1951 void Beeper::start()
1952 {
1953         if( running() ) return;
1954         audio_pos = -1;
1955         interrupted = 0;
1956         Thread::start();
1957 }
1958
1959 void Beeper::stop(int wait)
1960 {
1961         if( running() && !interrupted ) {
1962                 interrupted = 1;
1963                 audio->stop_audio(wait);
1964         }
1965         Thread::join();
1966 }
1967
1968 void Beeper::tone(double freq, double secs, double gain)
1969 {
1970         stop(0);
1971         this->freq = freq;
1972         this->secs = secs;
1973         this->gain = gain;
1974         start();
1975 }
1976
1977
1978 int MWindow::load_filenames(ArrayList<char*> *filenames,
1979                 int load_mode, int edl_mode, int update_filename)
1980 {
1981         ArrayList<EDL*> new_edls;
1982         ArrayList<Asset*> new_assets;
1983         ArrayList<File*> new_files;
1984
1985 //      save_defaults();
1986         gui->start_hourglass();
1987
1988 // Need to stop playback since tracking depends on the EDL not getting
1989 // deleted.
1990         gui->unlock_window();
1991         stop_playback(1);
1992         gui->lock_window("MWindow::load_filenames 0");
1993         undo_before();
1994
1995 const int debug = 0;
1996 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1997
1998 // Define new_edls and new_assets to load
1999         int result = 0, ftype = -1;
2000
2001         for( int i=0; i<filenames->size(); ++i ) {
2002 // Get type of file
2003                 File *new_file = new File;
2004                 Asset *new_asset = new Asset(filenames->get(i));
2005                 EDL *new_edl = new EDL;
2006                 new_edl->create_objects();
2007                 new_edl->copy_session(edl, -1);
2008                 new_file->set_program(edl->session->program_no);
2009
2010                 char string[BCTEXTLEN];
2011                 sprintf(string, _("Loading %s"), new_asset->path);
2012                 gui->show_message(string);
2013
2014                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
2015
2016                 result = 1;
2017                 switch( ftype ) {
2018 // Convert media file to EDL
2019                 case FILE_OK: {
2020 // Warn about odd image dimensions
2021                         if( new_asset->video_data &&
2022                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
2023                                 eprintf(_("%s's resolution is %dx%d.\n"
2024                                         "Images with odd dimensions may not decode properly."),
2025                                         new_asset->path, new_asset->width, new_asset->height);
2026                         }
2027
2028                         if( new_asset->program >= 0 &&
2029                             edl->session->program_no != new_asset->program ) {
2030                                 eprintf(_("%s's index was built for program number %d\n"
2031                                         "Playback preference is %d.\n  Using program %d."),
2032                                         new_asset->path, new_asset->program,
2033                                         edl->session->program_no, new_asset->program);
2034                         }
2035
2036                         if( load_mode == LOADMODE_RESOURCESONLY ) {
2037                                 new_assets.append(new_asset);
2038                                 new_asset->add_user();
2039                                 result = 0;
2040                                 break;
2041                         }
2042
2043                         RecordLabels *labels = edl->session->label_cells ?
2044                                 new RecordLabels(new_file) : 0;
2045                         asset_to_edl(new_edl, new_asset, labels);
2046                         new_edls.append(new_edl);
2047                         new_edl->add_user();
2048                         delete labels;
2049
2050                         if( load_mode == LOADMODE_REPLACE ||
2051                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2052 // Set filename to nothing for assets since save EDL would overwrite them.
2053                                 set_filename("");
2054 // Reset timeline position
2055                                 for( int i=0; i<TOTAL_PANES; ++i ) {
2056                                         new_edl->local_session->view_start[i] = 0;
2057                                         new_edl->local_session->track_start[i] = 0;
2058                                 }
2059                         }
2060                         result = 0;
2061                         break; }
2062
2063                 case FILE_NOT_FOUND: {
2064                         eprintf(_("Failed to open %s"), new_asset->path);
2065                         sprintf(string, _("Failed to open %s"), new_asset->path);
2066                         gui->show_message(string, theme->message_error);
2067                         gui->update_default_message();
2068                         break; }
2069
2070 // Unknown format
2071                 case FILE_UNRECOGNIZED_CODEC: {
2072 // Test index file
2073                         { IndexFile indexfile(this, new_asset);
2074                         if( !(result = indexfile.open_index()) )
2075                                 indexfile.close_index(); }
2076
2077 // Test existing EDLs
2078                         for( int j=0; result && j<new_edls.total; ++j ) {
2079                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
2080                                 if( old_asset ) {
2081                                         new_asset->copy_from(old_asset,1);
2082                                         result = 0;
2083                                 }
2084                         }
2085                         if( result ) {
2086                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
2087                                 if( old_asset ) {
2088                                         new_asset->copy_from(old_asset,1);
2089                                         result = 0;
2090                                 }
2091                         }
2092
2093 // Prompt user
2094                         if( result ) {
2095                                 new_asset->audio_data = 1;
2096                                 new_asset->format = FILE_PCM;
2097                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
2098                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
2099                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
2100                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
2101                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
2102                                 new_asset->header = defaults->get("HEADER", 0);
2103
2104                                 FileSystem fs;
2105                                 fs.extract_name(string, new_asset->path);
2106                                 strcat(string, _("'s format couldn't be determined."));
2107                                 FileFormat fwindow(this);
2108                                 fwindow.create_objects(new_asset, string);
2109                                 result = fwindow.run_window();
2110
2111                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
2112                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
2113                                 defaults->update("AUDIO_BITS", new_asset->bits);
2114                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
2115                                 defaults->update("SIGNED_", new_asset->signed_);
2116                                 defaults->update("HEADER", new_asset->header);
2117                                 save_defaults();
2118                         }
2119 // Append to list
2120                         if( !result ) {
2121 // Recalculate length
2122                                 delete new_file;
2123                                 new_file = new File;
2124                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2125
2126                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
2127                                         RecordLabels *labels = edl->session->label_cells ?
2128                                                 new RecordLabels(new_file) : 0;
2129                                         asset_to_edl(new_edl, new_asset, labels);
2130                                         new_edls.append(new_edl);
2131                                         new_edl->add_user();
2132                                         delete labels;
2133                                 }
2134                                 else {
2135                                         new_assets.append(new_asset);
2136                                         new_asset->add_user();
2137                                 }
2138                         }
2139                         break; }
2140
2141                 case FILE_IS_XML: {
2142                         FileXML xml_file;
2143                         const char *filename = filenames->get(i);
2144                         if( xml_file.read_from_file(filename, 1) ) {
2145                                 eprintf(_("Error: unable to open:\n  %s"), filename);
2146                                 break;
2147                         }
2148                         const char *cin_version = 0;
2149                         while( !xml_file.read_tag() ) {
2150                                 if( xml_file.tag.title_is("EDL") ) {
2151                                         cin_version = xml_file.tag.get_property("VERSION");
2152                                         break;
2153                                 }
2154                         }
2155                         xml_file.rewind();
2156                         if( !cin_version ) {
2157                                 eprintf(_("XML file %s\n not from cinelerra."),filename);
2158                                 char string[BCTEXTLEN];
2159                                 sprintf(string,_("Unknown %s"), filename);
2160                                 gui->show_message(string);
2161                                 break;
2162                         }
2163                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2164                             strcmp(cin_version, "Unify") &&
2165                             strcmp(cin_version, "5.1") ) {
2166                                 eprintf(_("Warning: XML from cinelerra version %s\n"
2167                                         "Session data may be incompatible."), cin_version);
2168                         }
2169                         if( new_edl->load_xml(&xml_file, LOAD_ALL) ) {
2170                                 eprintf(_("Error: unable to load:\n  %s"), filename);
2171                                 break;
2172                         }
2173                         test_plugins(new_edl, filename);
2174                         int groups = new_edl->regroup(session->group_number);
2175                         session->group_number += groups;
2176                         switch( edl_mode ) {
2177                         case LOADMODE_EDL_CLIP: {
2178                                 strcpy(new_edl->local_session->clip_title,
2179                                         filenames->get(i));
2180                                 struct stat st;
2181                                 time_t t = !stat(filenames->get(i),&st) ?
2182                                         st.st_mtime : time(&t);
2183                                 ctime_r(&t, new_edl->local_session->clip_notes);
2184                                 switch( load_mode ) {
2185                                 case LOADMODE_REPLACE:
2186                                 case LOADMODE_REPLACE_CONCATENATE:
2187                                         strcpy(session->filename, filename);
2188                                         if( update_filename ) set_filename(filename);
2189                                         break;
2190                                 }
2191                                 result = 0;
2192                                 break; }
2193                         case LOADMODE_EDL_NESTED: {
2194                                 EDL *nested_edl = new EDL;
2195                                 nested_edl->create_objects();
2196                                 nested_edl->copy_session(edl, -1);
2197                                 nested_edl->create_nested(new_edl);
2198                                 nested_edl->set_path(filename);
2199                                 new_edl->remove_user();
2200                                 new_edl = nested_edl;
2201                                 result = 0;
2202                                 break; }
2203                         case LOADMODE_EDL_FILEREF: {
2204                                 result = create_ref(new_asset, new_edl);
2205                                 if( result ) break;
2206                                 new_assets.append(new_asset);
2207                                 new_asset->add_user();
2208                                 new_edl->remove_user();
2209                                 new_edl = new EDL;
2210                                 new_edl->create_objects();
2211                                 new_edl->copy_session(edl, -1);
2212                                 asset_to_edl(new_edl, new_asset);
2213                                 delete new_file;
2214                                 new_file = new File;
2215                                 result = new_file->open_file(preferences, new_asset, 1, 0);
2216                                 break; }
2217                         }
2218                         if( !result ) {
2219                                 new_edls.append(new_edl);
2220                                 new_edl->add_user();
2221                         }
2222                         else
2223                                 eprintf(_("Error: Unable to load xml:\n  %s"), new_asset->path);
2224                         break; }
2225                 }
2226
2227                 new_edl->Garbage::remove_user();
2228                 new_asset->Garbage::remove_user();
2229
2230 // Store for testing index
2231                 new_files.append(new_file);
2232         }
2233
2234 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2235
2236         if(!result) {
2237                 gui->reset_default_message();
2238                 gui->default_message();
2239         }
2240
2241 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2242
2243 // Paste them.
2244 // Don't back up here.
2245         if( new_edls.size() ) {
2246 // For pasting, clear the active region
2247                 if( load_mode == LOADMODE_PASTE ) {
2248                         double start = edl->local_session->get_selectionstart();
2249                         double end = edl->local_session->get_selectionend();
2250                         if(!EQUIV(start, end))
2251                                 edl->clear(start, end,
2252                                         edl->session->labels_follow_edits,
2253                                         edl->session->plugins_follow_edits,
2254                                         edl->session->autos_follow_edits);
2255
2256                         paste_edls(&new_edls, load_mode, 0, -1,
2257                                 edl->session->labels_follow_edits,
2258                                 edl->session->plugins_follow_edits,
2259                                 edl->session->autos_follow_edits,
2260                                 0); // overwrite
2261                 }
2262                 else if( load_mode == LOADMODE_NEW_TRACKS &&
2263                          edl_mode != LOADMODE_EDL_CLIP )
2264                         paste_edls(&new_edls, load_mode, 0, -1, 0, 0, 0, 0);
2265                 else if( load_mode != LOADMODE_RESOURCESONLY ||
2266                          edl_mode == LOADMODE_EDL_CLIP )
2267                         paste_edls(&new_edls, load_mode, 0, -1, 1, 1, 1, 0);
2268                 else
2269                         paste_edls(&new_edls, LOADMODE_NOTHING, 0, -1, 0, 0, 0, 0);
2270
2271         }
2272
2273 // Add new assets to EDL and schedule assets for index building.
2274         int got_indexes = 0;
2275         for( int i=0; i<new_edls.size(); ++i ) {
2276                 EDL *new_edl = new_edls[i];
2277                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2278                         mainindexes->add_indexable(new_edl->nested_edls[j]);
2279                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2280                         got_indexes = 1;
2281                 }
2282
2283         }
2284
2285         for( int i=0; i<new_assets.size(); ++i ) {
2286                 Asset *new_asset = new_assets[i];
2287                 mainindexes->add_indexable(new_asset);
2288                 edl->assets->update(new_asset);
2289                 got_indexes = 1;
2290         }
2291
2292 // Start examining next batch of index files
2293         if(got_indexes) mainindexes->start_build();
2294
2295 // reload renderengine edl or the plugin guis will flip out
2296         sync_parameters(CHANGE_ALL);
2297 // Open plugin GUIs
2298         show_plugins();
2299
2300         // opening new session
2301         if( ( load_mode == LOADMODE_REPLACE ||
2302               load_mode == LOADMODE_REPLACE_CONCATENATE ) &&
2303             (ftype != FILE_IS_XML || edl_mode != LOADMODE_EDL_CLIP) ) {
2304                 select_asset(0, 0);
2305                 edl->session->proxy_state = PROXY_INACTIVE;
2306                 edl->session->proxy_scale = 1;
2307                 edl->session->proxy_disabled_scale = 1;
2308                 edl->session->proxy_use_scaler = 0;
2309                 edl->session->proxy_auto_scale = 0;
2310                 edl->session->proxy_beep = 0;
2311                 edl->local_session->preview_start = 0;
2312                 edl->local_session->preview_end = -1;
2313                 edl->local_session->loop_playback = 0;
2314                 edl->local_session->set_selectionstart(0);
2315                 edl->local_session->set_selectionend(0);
2316                 edl->local_session->unset_inpoint();
2317                 edl->local_session-> unset_outpoint();
2318                 set_brender_active(0, 0);
2319                 fit_selection();
2320                 goto_start();
2321         }
2322
2323         if( edl->session->proxy_state != PROXY_INACTIVE && edl->session->proxy_auto_scale &&
2324             load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) {
2325                 ArrayList<Indexable *> orig_idxbls;
2326                 for( int i=0; i<new_assets.size(); ++i )
2327                         orig_idxbls.append(new_assets.get(i));
2328                 for( int i=0; i<new_edls.size(); ++i ) {
2329                         EDL *new_edl = new_edls[i];
2330                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2331                                 if( track->data_type != TRACK_VIDEO ) continue;
2332                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2333                                         Indexable *idxbl = (Indexable *)edit->asset;
2334                                         if( !idxbl ) continue;
2335                                         if( !idxbl->have_video() ) continue;
2336                                         if( edit->channel != 0 ) continue; // first layer only
2337                                         orig_idxbls.append(edit->asset);
2338                                 }
2339                         }
2340                 }
2341                 gui->unlock_window(); // to update progress bar
2342                 int ret = render_proxy(orig_idxbls);
2343                 gui->lock_window("MWindow::load_filenames");
2344                 float gain = edl->session->proxy_beep;
2345                 if( ret >= 0 && gain > 0 ) {
2346                         if( ret > 0 )
2347                                 beep(2000., 1.5, gain);
2348                         else
2349                                 beep(4000., 0.25, gain);
2350                 }
2351         }
2352
2353 // need to update undo before project, since mwindow is unlocked & a new load
2354 // can begin here.  Should really prevent loading until we're done.
2355 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2356         undo_after(_("load"), LOAD_ALL);
2357
2358         for(int i = 0; i < new_edls.size(); i++)
2359         {
2360                 new_edls[i]->remove_user();
2361         }
2362 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2363
2364         new_edls.remove_all();
2365
2366         for(int i = 0; i < new_assets.size(); i++)
2367         {
2368                 new_assets[i]->Garbage::remove_user();
2369         }
2370
2371         new_assets.remove_all();
2372         new_files.remove_all_objects();
2373
2374
2375 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2376         if(load_mode == LOADMODE_REPLACE ||
2377                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2378         {
2379                 session->changes_made = 0;
2380         }
2381         else
2382         {
2383                 session->changes_made = 1;
2384         }
2385
2386         gui->stop_hourglass();
2387
2388
2389 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2390         update_project(load_mode);
2391
2392 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2393
2394         return 0;
2395 }
2396
2397 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2398 {
2399         Asset *format_asset = new Asset;
2400         format_asset->format = FILE_FFMPEG;
2401         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2402         int new_scale = edl->session->proxy_scale;
2403         ProxyRender proxy_render(this, format_asset, new_scale);
2404
2405         for( int i=0; i<new_idxbls.size(); ++i ) {
2406                 Indexable *orig = new_idxbls.get(i);
2407                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2408                 if( !proxy ) continue;
2409                 FileSystem fs;
2410                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2411                 int got_it = exists && // if proxy exists, and is newer than orig
2412                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2413                 if( got_it ) continue;
2414                 proxy_render.add_needed(orig, proxy);
2415         }
2416
2417 // render needed proxies
2418         int result = proxy_render.create_needed_proxies(new_scale);
2419         if( !result ) {
2420                 add_proxy(&proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2421         }
2422         format_asset->remove_user();
2423         return !result ? proxy_render.needed_proxies.size() : -1;
2424 }
2425
2426 int MWindow::enable_proxy()
2427 {
2428         int ret = 0;
2429         if( edl->session->proxy_state == PROXY_DISABLED ) {
2430                 int new_scale = edl->session->proxy_disabled_scale;
2431                 int new_use_scaler = edl->session->proxy_use_scaler;
2432                 Asset *asset = new Asset;
2433                 asset->format = FILE_FFMPEG;
2434                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2435                 ret = to_proxy(asset, new_scale, new_use_scaler);
2436                 asset->remove_user();
2437                 if( ret > 0 ) {
2438                         float gain = edl->session->proxy_beep;
2439                         beep(2000., 1.5, gain);
2440                 }
2441                 edl->session->proxy_disabled_scale = 1;
2442                 edl->session->proxy_state = PROXY_ACTIVE;
2443                 gui->lock_window("MWindow::to_proxy");
2444                 update_project(LOADMODE_REPLACE);
2445                 gui->unlock_window();
2446         }
2447         return 1;
2448 }
2449
2450 int MWindow::disable_proxy()
2451 {
2452         if( edl->session->proxy_state == PROXY_ACTIVE ) {
2453                 int old_scale = edl->session->proxy_scale, new_scale = 0;
2454                 int new_use_scaler = edl->session->proxy_use_scaler;
2455                 Asset *asset = new Asset;
2456                 asset->format = FILE_FFMPEG;
2457                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2458                 to_proxy(asset, new_scale, new_use_scaler);
2459                 asset->remove_user();
2460                 edl->session->proxy_state = PROXY_DISABLED;
2461                 edl->session->proxy_disabled_scale = old_scale;
2462                 gui->lock_window("MWindow::to_proxy");
2463                 update_project(LOADMODE_REPLACE);
2464                 gui->unlock_window();
2465         }
2466         return 1;
2467 }
2468
2469 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2470 {
2471         ArrayList<Indexable*> orig_idxbls;
2472         ArrayList<Indexable*> proxy_assets;
2473
2474         edl->Garbage::add_user();
2475         save_backup();
2476         undo_before(_("proxy"), this);
2477         int asset_scale = !new_scale ? 0 :
2478                         !new_use_scaler ? 1 : new_scale;
2479         ProxyRender proxy_render(this, asset, asset_scale);
2480
2481 // revert project to original size from current size
2482 // remove all session proxy assets at the at the current proxy_scale
2483         int proxy_scale = edl->session->proxy_scale;
2484
2485         if( edl->session->proxy_state == PROXY_ACTIVE ) {
2486                 Asset *orig_asset = edl->assets->first;
2487                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2488                         char new_path[BCTEXTLEN];
2489                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2490 // test if proxy asset was already added to proxy_assets
2491                         int got_it = 0;
2492                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2493                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2494                         if( got_it ) continue;
2495                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2496                         if( !proxy_asset ) continue;
2497 // add pointer to existing EDL asset if it exists
2498 // EDL won't delete it unless it's the same pointer.
2499                         proxy_assets.append(proxy_asset);
2500                         proxy_asset->add_user();
2501                         orig_idxbls.append(orig_asset);
2502                         orig_asset->add_user();
2503                 }
2504                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2505                         EDL *orig_nested = edl->nested_edls[i];
2506                         char new_path[BCTEXTLEN];
2507                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2508 // test if proxy asset was already added to proxy_assets
2509                         int got_it = 0;
2510                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2511                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2512                         if( got_it ) continue;
2513                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2514                         if( !proxy_nested ) continue;
2515 // add pointer to existing EDL asset if it exists
2516 // EDL won't delete it unless it's the same pointer.
2517                         proxy_assets.append(proxy_nested);
2518                         proxy_nested->add_user();
2519                         orig_idxbls.append(orig_nested);
2520                         orig_nested->add_user();
2521                 }
2522
2523 // convert from the proxy assets to the original assets
2524                 edl->set_proxy(0, 0, &proxy_assets, &orig_idxbls);
2525
2526 // remove the references
2527                 for( int i=0; i<proxy_assets.size(); ++i ) {
2528                         Asset *proxy = (Asset *) proxy_assets[i];
2529                         proxy->width = proxy->actual_width;
2530                         proxy->height = proxy->actual_height;
2531                         proxy->remove_user();
2532                         edl->assets->remove_pointer(proxy);
2533                         proxy->remove_user();
2534                 }
2535                 proxy_assets.remove_all();
2536                 for( int i = 0; i < orig_idxbls.size(); i++ )
2537                         orig_idxbls[i]->remove_user();
2538                 orig_idxbls.remove_all();
2539         }
2540
2541         ArrayList<char *> confirm_paths;    // test for new files
2542         confirm_paths.set_array_delete();
2543
2544 // convert to new size if not original size
2545         if( new_scale ) {
2546                 FileSystem fs;
2547                 Asset *orig = edl->assets->first;
2548                 for( ; orig; orig=orig->next ) {
2549                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2550                         if( !proxy ) continue;
2551                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2552                         int got_it = exists && // if proxy exists, and is newer than orig
2553                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2554                         if( !got_it ) {
2555                                 if( exists ) // prompt user to overwrite
2556                                         confirm_paths.append(cstrdup(proxy->path));
2557                                 proxy_render.add_needed(orig, proxy);
2558                         }
2559                 }
2560                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2561                         EDL *orig_nested = edl->nested_edls[i];
2562                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2563                         if( !proxy ) continue;
2564                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2565                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2566                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2567                         if( !got_it ) {
2568                                 if( exists ) // prompt user to overwrite
2569                                         confirm_paths.append(cstrdup(proxy->path));
2570                                 proxy_render.add_needed(orig_nested, proxy);
2571                         }
2572                 }
2573                 edl->session->proxy_state = PROXY_ACTIVE;
2574         }
2575         else
2576                 edl->session->proxy_state = PROXY_INACTIVE;
2577
2578         int result = 0;
2579 // test for existing files
2580         if( confirm_paths.size() ) {
2581                 result = ConfirmSave::test_files(this, &confirm_paths);
2582                 confirm_paths.remove_all_objects();
2583         }
2584
2585         if( !result && new_scale )
2586                 result = proxy_render.create_needed_proxies(new_scale);
2587
2588         if( !result ) { // resize project
2589                 edl->set_proxy(new_scale, new_use_scaler,
2590                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2591         }
2592         undo_after(_("proxy"), LOAD_ALL);
2593         edl->Garbage::remove_user();
2594         restart_brender();
2595
2596         return !result ? proxy_render.needed_proxies.size() : -1;
2597 }
2598
2599 void MWindow::test_plugins(EDL *new_edl, const char *path)
2600 {
2601         char string[BCTEXTLEN];
2602
2603 // Do a check whether plugins exist
2604         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2605                 for( int k=0; k<track->plugin_set.total; ++k ) {
2606                         PluginSet *plugin_set = track->plugin_set[k];
2607                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2608                                         plugin; plugin = (Plugin*)plugin->next ) {
2609                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2610 // ok we need to find it in plugindb
2611                                 PluginServer *server =
2612                                         scan_plugindb(plugin->title, track->data_type);
2613                                 if( !server || server->transition ) {
2614                                         sprintf(string,
2615         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2616           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2617                                                 "effect", _(plugin->title), path);
2618                                         MainError::show_error(string);
2619                                 }
2620                         }
2621                 }
2622
2623                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2624                         if( !edit->transition ) continue;
2625 // ok we need to find transition in plugindb
2626                         PluginServer *server =
2627                                 scan_plugindb(edit->transition->title, track->data_type);
2628                         if( !server || !server->transition ) {
2629                                 sprintf(string,
2630         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2631           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2632                                         "transition", _(edit->transition->title), path);
2633                                 MainError::show_error(string);
2634                         }
2635                 }
2636         }
2637 }
2638
2639
2640 void MWindow::init_shm(const char *pfn, int64_t min)
2641 {
2642         int64_t result = 0;
2643 // Fix shared memory
2644         FILE *fd = fopen(pfn, "r");
2645         if( fd ) {
2646                 fscanf(fd, "%jd", &result);
2647                 fclose(fd);
2648                 if( result >= min ) return;
2649         }
2650
2651         fd = fopen(pfn, "w");
2652         if( !fd ) return;
2653         fprintf(fd, "0x%jx", min);
2654         fclose(fd);
2655
2656         fd = fopen(pfn, "r");
2657         if( !fd ) {
2658                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2659                 return;
2660         }
2661
2662         fscanf(fd, "%jd", &result);
2663         fclose(fd);
2664         if( result < min ) {
2665                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2666                         "you probably need to be root, or:\n"
2667                         "as root, run: echo 0x%jx > %s\n"
2668                         "before trying to start cinelerra.\n"
2669                         "It should be at least 0x%jx for Cinelerra.\n"),
2670                         pfn, (void *)result, min, pfn, min);
2671         }
2672 }
2673
2674 void MWindow::create_objects(int want_gui,
2675         int want_new,
2676         char *config_path)
2677 {
2678         const int debug = 0;
2679         if(debug) PRINT_TRACE
2680
2681 // For some reason, init_signals must come after show_splash or the signals won't
2682 // get trapped.
2683         init_signals();
2684         if(debug) PRINT_TRACE
2685         init_3d();
2686
2687         if(debug) PRINT_TRACE
2688
2689         if(debug) PRINT_TRACE
2690         default_standard = default_std();
2691         init_defaults(defaults, config_path);
2692         check_language();
2693         show_splash();
2694         init_preferences();
2695         if(splash_window)
2696                 splash_window->update_status(_("Initializing Plugins"));
2697         init_plugins(this, preferences);
2698         if(debug) PRINT_TRACE
2699         init_ladspa_plugins(this, preferences);
2700         if(debug) PRINT_TRACE
2701         init_plugin_tips(*plugindb, cin_lang);
2702         if(splash_window)
2703                 splash_window->update_status(_("Initializing GUI"));
2704         if(debug) PRINT_TRACE
2705         init_theme();
2706
2707         if(debug) PRINT_TRACE
2708         init_error();
2709
2710         if(splash_window)
2711                 splash_window->update_status(_("Initializing Fonts"));
2712         char string[BCTEXTLEN];
2713         strcpy(string, preferences->plugin_dir);
2714         strcat(string, "/" FONT_SEARCHPATH);
2715         BC_Resources::init_fontconfig(string);
2716         if(debug) PRINT_TRACE
2717 // use if plugged
2718         init_x10tv();
2719         if( !x10tv )
2720                 init_wintv();
2721
2722 // Default project created here
2723         init_edl();
2724         if(debug) PRINT_TRACE
2725
2726         init_cache();
2727         if(debug) PRINT_TRACE
2728
2729         Timer timer;
2730
2731         init_awindow();
2732         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2733
2734         init_compositor();
2735         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2736
2737 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2738         if(session->show_vwindow)
2739                 get_viewer(1, DEFAULT_VWINDOW);
2740         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2741
2742         init_gui();
2743         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2744
2745         init_levelwindow();
2746         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2747
2748         init_indexes();
2749         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2750
2751         init_channeldb();
2752         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2753
2754         init_gwindow();
2755         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2756
2757         init_render();
2758         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2759
2760         init_shuttle();
2761         init_brender();
2762         init_exportedl();
2763         init_commercials();
2764         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2765         mainprogress = new MainProgress(this, gui);
2766         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2767         undo = new MainUndo(this);
2768
2769         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2770
2771         plugin_guis = new PluginGUIs(this);
2772         dead_plugins = new ArrayList<PluginServer*>;
2773         keyframe_threads = new ArrayList<KeyFrameThread*>;
2774
2775         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2776                 __LINE__,
2777                 vwindows.size(),
2778                 session->show_vwindow);
2779
2780 // Show all vwindows
2781 //      if(session->show_vwindow) {
2782 //              for(int j = 0; j < vwindows.size(); j++) {
2783 //                      VWindow *vwindow = vwindows[j];
2784 //                      if( !vwindow->is_running() ) continue;
2785 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2786 //                              __LINE__,
2787 //                              vwindow);
2788 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2789 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2790 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2791 //                      vwindow->gui->show_window();
2792 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2793 //                      vwindow->gui->unlock_window();
2794 //              }
2795 //      }
2796
2797
2798         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2799
2800         if(session->show_cwindow)
2801         {
2802                 cwindow->gui->lock_window("MWindow::create_objects 1");
2803                 cwindow->gui->show_window();
2804                 cwindow->gui->unlock_window();
2805         }
2806
2807         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2808         if(session->show_awindow)
2809         {
2810                 awindow->gui->lock_window("MWindow::create_objects 1");
2811                 awindow->gui->show_window();
2812                 awindow->gui->unlock_window();
2813         }
2814
2815         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2816         if(session->show_lwindow)
2817         {
2818                 lwindow->gui->lock_window("MWindow::create_objects 1");
2819                 lwindow->gui->show_window();
2820                 lwindow->gui->unlock_window();
2821         }
2822
2823         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2824                 __LINE__,
2825                 (int)timer.get_difference(),
2826                 gwindow->gui);
2827         if(session->show_gwindow)
2828         {
2829                 gwindow->gui->lock_window("MWindow::create_objects 1");
2830                 gwindow->gui->show_window();
2831                 gwindow->gui->unlock_window();
2832         }
2833
2834         if(debug) PRINT_TRACE
2835
2836         gui->lock_window("MWindow::create_objects 1");
2837         gui->mainmenu->load_defaults(defaults);
2838         gui->mainmenu->update_toggles(0);
2839         gui->update_patchbay();
2840         gui->draw_canvas(0, 0);
2841         gui->draw_cursor(1);
2842         gui->show_window();
2843         gui->raise_window();
2844         gui->unlock_window();
2845         cwindow->gui->lock_window("MWindow::create_objects 1");
2846         cwindow->gui->tool_panel->raise_tool();
2847         cwindow->gui->unlock_window();
2848         if(debug) PRINT_TRACE
2849
2850         if(preferences->use_tipwindow)
2851                 init_tipwindow();
2852         if(debug) PRINT_TRACE
2853
2854         gui->add_keyboard_listener(
2855                 (int (BC_WindowBase::*)(BC_WindowBase *))
2856                 &MWindowGUI::keyboard_listener);
2857
2858         hide_splash();
2859         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2860         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2861         if(debug) PRINT_TRACE
2862
2863         BC_WindowBase::get_resources()->vframe_shm = 1;
2864 }
2865
2866 int MWindow::uses_opengl()
2867 {
2868         if( !playback_3d || !playback_3d->running() ) return 0;
2869         PlaybackConfig *playback_config = edl->session->playback_config;
2870         return playback_config->vconfig->driver == PLAYBACK_X11_GL ? 1 : 0;
2871 }
2872
2873 void MWindow::show_splash()
2874 {
2875 #include "data/heroine_logo9_png.h"
2876         VFrame *frame = new VFramePng(heroine_logo9_png);
2877         BC_DisplayInfo dpyi;
2878         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2879         int rr = (rw < rh ? rw : rh) / 4;
2880         splash_window = new SplashGUI(frame, rr, rr);
2881         splash_window->create_objects();
2882 }
2883
2884 void MWindow::hide_splash()
2885 {
2886         if(splash_window)
2887                 delete splash_window;
2888         splash_window = 0;
2889 }
2890
2891
2892 void MWindow::start()
2893 {
2894 ENABLE_BUFFER
2895 //PRINT_TRACE
2896 //      vwindows[DEFAULT_VWINDOW]->start();
2897         awindow->start();
2898 //PRINT_TRACE
2899         cwindow->start();
2900 //PRINT_TRACE
2901         lwindow->start();
2902 //PRINT_TRACE
2903         gwindow->start();
2904 //PRINT_TRACE
2905 //      Thread::start();
2906 //PRINT_TRACE
2907         playback_3d->start();
2908 //PRINT_TRACE
2909 }
2910
2911 void MWindow::run()
2912 {
2913         run_lock->lock("MWindow::run");
2914         gui->run_window();
2915         stop_playback(1);
2916
2917         brender_lock->lock("MWindow::run 1");
2918         delete brender;         brender = 0;
2919         brender_lock->unlock();
2920
2921         interrupt_indexes();
2922         clean_indexes();
2923         save_defaults();
2924         run_lock->unlock();
2925 }
2926
2927 void MWindow::show_vwindow(int raise)
2928 {
2929         int total_running = 0;
2930         session->show_vwindow = 1;
2931
2932 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2933 // Raise all windows which are visible
2934         for(int j = 0; j < vwindows.size(); j++) {
2935                 VWindow *vwindow = vwindows[j];
2936                 if( !vwindow->is_running() ) continue;
2937                 total_running++;
2938                 if( !raise && !vwindow->gui->is_hidden() ) continue;
2939                 vwindow->gui->lock_window("MWindow::show_vwindow");
2940                 vwindow->gui->show_window(0);
2941                 vwindow->gui->raise_window();
2942                 vwindow->gui->flush();
2943                 vwindow->gui->unlock_window();
2944         }
2945 // If no windows visible
2946         if( !total_running )
2947                 get_viewer(1, DEFAULT_VWINDOW);
2948
2949         gui->mainmenu->show_vwindow->set_checked(1);
2950 }
2951
2952 void MWindow::show_awindow()
2953 {
2954         session->show_awindow = 1;
2955         awindow->gui->lock_window("MWindow::show_awindow");
2956         awindow->gui->show_window();
2957         awindow->gui->raise_window();
2958         awindow->gui->flush();
2959         awindow->gui->unlock_window();
2960         gui->mainmenu->show_awindow->set_checked(1);
2961 }
2962
2963 char *MWindow::get_cwindow_display()
2964 {
2965         char *x11_host = screens < 2 || session->window_config == 0 ?
2966                 session->a_x11_host : session->b_x11_host;
2967         return *x11_host ? x11_host : 0;
2968 }
2969
2970 void MWindow::show_cwindow()
2971 {
2972         session->show_cwindow = 1;
2973         cwindow->show_window();
2974         cwindow->gui->tool_panel->raise_tool();
2975         gui->mainmenu->show_cwindow->set_checked(1);
2976 }
2977
2978 void MWindow::show_gwindow()
2979 {
2980         session->show_gwindow = 1;
2981
2982         gwindow->gui->lock_window("MWindow::show_gwindow");
2983         gwindow->gui->show_window();
2984         gwindow->gui->raise_window();
2985         gwindow->gui->flush();
2986         gwindow->gui->unlock_window();
2987
2988         gui->mainmenu->show_gwindow->set_checked(1);
2989 }
2990 void MWindow::hide_gwindow()
2991 {
2992         session->show_gwindow = 0;
2993
2994         gwindow->gui->lock_window("MWindow::show_gwindow");
2995         gwindow->gui->hide_window();
2996         gwindow->gui->unlock_window();
2997 }
2998
2999 void MWindow::show_lwindow()
3000 {
3001         session->show_lwindow = 1;
3002         lwindow->gui->lock_window("MWindow::show_lwindow");
3003         lwindow->gui->show_window();
3004         lwindow->gui->raise_window();
3005         lwindow->gui->flush();
3006         lwindow->gui->unlock_window();
3007         gui->mainmenu->show_lwindow->set_checked(1);
3008 }
3009
3010 void MWindow::restore_windows()
3011 {
3012         gui->unlock_window();
3013         if( !session->show_vwindow ) {
3014                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
3015                         VWindow *vwindow = vwindows[i];
3016                         if( !vwindow || !vwindow->is_running() ) continue;
3017                         vwindow->gui->lock_window("MWindow::restore_windows");
3018                         vwindow->gui->close(1);
3019                         vwindow->gui->unlock_window();
3020                 }
3021         }
3022         else 
3023                 show_vwindow(0);
3024
3025         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
3026                 awindow->gui->lock_window("MWindow::restore_windows");
3027                 awindow->gui->close_event();
3028                 awindow->gui->unlock_window();
3029         }
3030         else if( session->show_awindow && awindow->gui->is_hidden() )
3031                 show_awindow();
3032
3033         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
3034                 cwindow->gui->lock_window("MWindow::restore_windows");
3035                 cwindow->hide_window();
3036                 cwindow->gui->unlock_window();
3037         }
3038         else if( session->show_cwindow && cwindow->gui->is_hidden() )
3039                 cwindow->show_window();
3040
3041         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
3042                 gwindow->gui->lock_window("MWindow::restore_windows");
3043                 gwindow->gui->close_event();
3044                 gwindow->gui->unlock_window();
3045         }
3046         else if( session->show_gwindow && gwindow->gui->is_hidden() )
3047                 show_gwindow();
3048
3049         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
3050                 lwindow->gui->lock_window("MWindow::restore_windows");
3051                 lwindow->gui->close_event();
3052                 lwindow->gui->unlock_window();
3053         }
3054         else if( session->show_lwindow && lwindow->gui->is_hidden() )
3055                 show_lwindow();
3056
3057         gui->lock_window("MWindow::restore_windows");
3058         gui->focus();
3059 }
3060
3061 void MWindow::load_layout(const char *layout)
3062 {
3063         char path[BCTEXTLEN];
3064         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3065         session->load_file(path);
3066         restore_windows();
3067         gui->default_positions();
3068         save_defaults();
3069 }
3070
3071 void MWindow::save_layout(const char *layout)
3072 {
3073         char path[BCTEXTLEN];
3074         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3075         session->save_file(path);
3076 }
3077
3078 void MWindow::delete_layout(const char *layout)
3079 {
3080         char path[BCTEXTLEN];
3081         snprintf(path, sizeof(path), "%s/%s", File::get_config_path(), layout);
3082         unlink(path);
3083 }
3084
3085 int MWindow::tile_windows(int window_config)
3086 {
3087         int need_reload = 0;
3088         int play_config = window_config==0 ? 0 : 1;
3089         edl->session->playback_config->load_defaults(defaults, play_config);
3090         session->default_window_positions(window_config);
3091         if( screens == 1 ) {
3092                 gui->default_positions();
3093                 sync_parameters(CHANGE_ALL);
3094         }
3095         else
3096                 need_reload = 1;
3097         return need_reload;
3098 }
3099
3100 void MWindow::toggle_loop_playback()
3101 {
3102         edl->local_session->loop_playback = !edl->local_session->loop_playback;
3103         set_loop_boundaries();
3104         save_backup();
3105
3106         gui->draw_overlays(1);
3107         sync_parameters(CHANGE_PARAMS);
3108 }
3109
3110 void MWindow::set_screens(int value)
3111 {
3112         screens = value;
3113 }
3114
3115 void MWindow::set_auto_keyframes(int value)
3116 {
3117         edl->session->auto_keyframes = value;
3118         gui->mbuttons->edit_panel->keyframe->update(value);
3119         gui->flush();
3120         cwindow->gui->lock_window("MWindow::set_auto_keyframes");
3121         cwindow->gui->flush();
3122         cwindow->gui->unlock_window();
3123 }
3124
3125 void MWindow::set_span_keyframes(int value)
3126 {
3127         edl->session->span_keyframes = value;
3128         gui->mbuttons->edit_panel->span_keyframe->update(value);
3129         gui->flush();
3130         cwindow->gui->lock_window("MWindow::set_span_keyframes");
3131         cwindow->gui->flush();
3132         cwindow->gui->unlock_window();
3133 }
3134
3135 void MWindow::set_auto_visibility(Autos *autos, int value)
3136 {
3137         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
3138                 edl->session->auto_conf->plugins = value;
3139         else if( autos->autoidx >= 0 )
3140                 edl->session->auto_conf->autos[autos->autoidx] = value;
3141         else
3142                 return;
3143
3144         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3145         gui->mainmenu->update_toggles(1);
3146         gui->unlock_window();
3147         gwindow->gui->update_toggles(1);
3148         gui->lock_window("MWindow::set_auto_visibility");
3149 }
3150
3151 void MWindow::set_keyframe_type(int mode)
3152 {
3153         gui->lock_window("MWindow::set_keyframe_type");
3154         edl->local_session->floatauto_type = mode;
3155         gui->mainmenu->update_toggles(0);
3156         gui->unlock_window();
3157 }
3158
3159 int MWindow::set_editing_mode(int new_editing_mode)
3160 {
3161         edl->session->editing_mode = new_editing_mode;
3162         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
3163         gui->mbuttons->edit_panel->update();
3164         gui->set_editing_mode(1);
3165
3166         cwindow->gui->lock_window("MWindow::set_editing_mode");
3167         cwindow->gui->edit_panel->update();
3168         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
3169         cwindow->gui->unlock_window();
3170         return 0;
3171 }
3172
3173 void MWindow::toggle_editing_mode()
3174 {
3175         int mode = edl->session->editing_mode;
3176         if( mode == EDITING_ARROW )
3177                 set_editing_mode(EDITING_IBEAM);
3178         else
3179                 set_editing_mode(EDITING_ARROW);
3180 }
3181
3182 void MWindow::toggle_camera_xyz()
3183 {
3184         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3185         gwindow->gui->toggle_camera_xyz();
3186         gwindow->gui->unlock_window();
3187 }
3188
3189 void MWindow::toggle_projector_xyz()
3190 {
3191         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3192         gwindow->gui->toggle_projector_xyz();
3193         gwindow->gui->unlock_window();
3194 }
3195
3196 void MWindow::set_labels_follow_edits(int value)
3197 {
3198         edl->session->labels_follow_edits = value;
3199         gui->mbuttons->edit_panel->locklabels->update(value);
3200         gui->mainmenu->labels_follow_edits->set_checked(value);
3201         gui->flush();
3202 }
3203
3204 void MWindow::sync_parameters(int change_type)
3205 {
3206         if( in_destructor ) return;
3207
3208 // Sync engines which are playing back
3209         if( cwindow->playback_engine->is_playing_back ) {
3210                 if( change_type == CHANGE_PARAMS ) {
3211 // TODO: block keyframes until synchronization is done
3212                         cwindow->playback_engine->sync_parameters(edl);
3213                 }
3214                 else {
3215 // Stop and restart
3216                         int command = cwindow->playback_engine->command->command;
3217 // Waiting for tracking to finish would make the restart position more
3218 // accurate but it can't lock the window to stop tracking for some reason.
3219 // Not waiting for tracking gives a faster response but restart position is
3220 // only as accurate as the last tracking update.
3221                         cwindow->playback_engine->transport_stop(0);
3222                         cwindow->playback_engine->next_command->realtime = 1;
3223                         cwindow->playback_engine->transport_command(command, change_type, edl, 0);
3224                 }
3225         }
3226         else {
3227                 cwindow->refresh_frame(change_type);
3228         }
3229 }
3230
3231 void MWindow::age_caches()
3232 {
3233 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3234 // __LINE__,
3235 // preferences->cache_size,
3236 // audio_cache->get_memory_usage(1),
3237 // video_cache->get_memory_usage(1),
3238 // frame_cache->get_memory_usage(),
3239 // wave_cache->get_memory_usage(),
3240 // memory_usage);
3241         frame_cache->age_cache(512);
3242         wave_cache->age_cache(8192);
3243
3244         int64_t memory_usage;
3245         int64_t prev_memory_usage = 0;
3246         int result = 0;
3247         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3248         while( !result && prev_memory_usage !=
3249                 (memory_usage=video_cache->get_memory_usage(1)) &&
3250                 memory_usage > video_size ) {
3251                 video_cache->delete_oldest();
3252                 prev_memory_usage = memory_usage;
3253         }
3254
3255         prev_memory_usage = 0;
3256         result = 0;
3257         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3258         while( !result && prev_memory_usage !=
3259                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3260                 memory_usage > audio_size ) {
3261                 audio_cache->delete_oldest();
3262                 prev_memory_usage = memory_usage;
3263         }
3264 }
3265
3266 void MWindow::reset_android_remote()
3267 {
3268         gui->use_android_remote(preferences->android_remote);
3269 }
3270
3271
3272 void MWindow::show_keyframe_gui(Plugin *plugin)
3273 {
3274         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3275 // Find existing thread
3276         for( int i=0; i<keyframe_threads->size(); ++i ) {
3277                 int plugin_id = keyframe_threads->get(i)->plugin_id;
3278                 if( plugin_id == plugin->orig_id ) {
3279                         keyframe_threads->get(i)->start_window(plugin, 0);
3280                         keyframe_gui_lock->unlock();
3281                         return;
3282                 }
3283         }
3284
3285 // Find unused thread
3286         for( int i=0; i<keyframe_threads->size(); ++i ) {
3287                 if( keyframe_threads->get(i)->plugin_id < 0 ) {
3288                         keyframe_threads->get(i)->start_window(plugin, 0);
3289                         keyframe_gui_lock->unlock();
3290                         return;
3291                 }
3292         }
3293
3294 // Create new thread
3295         KeyFrameThread *thread = new KeyFrameThread(this);
3296         keyframe_threads->append(thread);
3297         thread->start_window(plugin, 0);
3298         keyframe_gui_lock->unlock();
3299 }
3300
3301
3302 void MWindow::show_plugin(Plugin *plugin)
3303 {
3304         int done = 0;
3305
3306 SET_TRACE
3307 // Remove previously deleted plugin GUIs
3308         dead_plugin_lock->lock("MWindow::show_plugin");
3309         dead_plugins->remove_all_objects();
3310         dead_plugin_lock->unlock();
3311
3312 //printf("MWindow::show_plugin %d\n", __LINE__);
3313 SET_TRACE
3314
3315         plugin_gui_lock->lock("MWindow::show_plugin");
3316         for( int i=0; i<plugin_guis->total; ++i ) {
3317 // Pointer/id comparison
3318                 PluginServer *plugin_gui = plugin_guis->get(i);
3319                 if( plugin_gui->plugin_id == plugin->orig_id ) {
3320                         plugin_gui->raise_window();
3321                         done = 1;
3322                         break;
3323                 }
3324         }
3325 SET_TRACE
3326
3327 //printf("MWindow::show_plugin 1\n");
3328         if( !done && !plugin->track ) {
3329                 printf("MWindow::show_plugin track not defined.\n");
3330                 done = 1;
3331         }
3332         if( !done ) {
3333                 PluginServer *server = scan_plugindb(plugin->title,
3334                         plugin->track->data_type);
3335
3336 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3337                 if(server && server->uses_gui)
3338                 {
3339                         PluginServer *gui = new PluginServer(*server);
3340                         plugin_guis->append(gui);
3341 // Needs mwindow to do GUI
3342                         gui->set_mwindow(this);
3343                         gui->open_plugin(0, preferences, edl, plugin);
3344                         plugin->show = 1;
3345                         gui->show_gui();
3346                 }
3347         }
3348         plugin_gui_lock->unlock();
3349 // update show/gui_id
3350         sync_parameters(CHANGE_PARAMS);
3351 //printf("MWindow::show_plugin %d\n", __LINE__);
3352 SET_TRACE
3353 //sleep(1);
3354 //printf("MWindow::show_plugin 2\n");
3355 }
3356
3357 void MWindow::hide_plugin(Plugin *plugin, int lock)
3358 {
3359         plugin->show = 0;
3360         return hide_plugin(plugin->orig_id, lock);
3361 }
3362
3363 void MWindow::hide_plugin(int plugin_id, int lock)
3364 {
3365 // Update the toggle
3366         gui->lock_window("MWindow::hide_plugin");
3367         gui->update(0, NORMAL_DRAW, 0, 0, 0, 0, 0);
3368         gui->unlock_window();
3369
3370         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3371         for( int i=0; i<plugin_guis->total; ++i ) {
3372                 PluginServer *plugin_gui = plugin_guis->get(i);
3373                 if( plugin_gui->plugin_id == plugin_id ) {
3374                         plugin_guis->remove(plugin_gui);
3375                         if(lock) plugin_gui_lock->unlock();
3376 // Last command executed in client side close
3377 // Schedule for deletion
3378                         plugin_gui->hide_gui();
3379                         delete_plugin(plugin_gui);
3380 //sleep(1);
3381                         return;
3382                 }
3383         }
3384         if(lock) plugin_gui_lock->unlock();
3385 // update show/gui_id
3386         sync_parameters(CHANGE_PARAMS);
3387 }
3388
3389 void MWindow::delete_plugin(PluginServer *plugin)
3390 {
3391         dead_plugin_lock->lock("MWindow::delete_plugin");
3392         dead_plugins->append(plugin);
3393         dead_plugin_lock->unlock();
3394 }
3395
3396 void MWindow::hide_plugins()
3397 {
3398         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3399         while(plugin_guis->size())
3400         {
3401                 PluginServer *ptr = plugin_guis->get(0);
3402                 plugin_guis->remove(ptr);
3403                 plugin_gui_lock->unlock();
3404 // Last command executed in client side close
3405 // Schedule for deletion
3406                 ptr->hide_gui();
3407                 delete_plugin(ptr);
3408                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3409         }
3410         plugin_gui_lock->unlock();
3411
3412         hide_keyframe_guis();
3413 }
3414
3415 void MWindow::hide_keyframe_guis()
3416 {
3417         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3418         for(int i = 0; i < keyframe_threads->size(); i++)
3419         {
3420                 keyframe_threads->get(i)->close_window();
3421         }
3422         keyframe_gui_lock->unlock();
3423 }
3424
3425 void MWindow::hide_keyframe_gui(Plugin *plugin)
3426 {
3427         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3428         for( int i = 0; i < keyframe_threads->size(); i++) {
3429                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3430                 if( keyframe_gui->plugin_id == plugin->orig_id ) {
3431                         keyframe_gui->close_window();
3432                         break;
3433                 }
3434         }
3435         keyframe_gui_lock->unlock();
3436 }
3437
3438 int MWindow::get_hash_color(Edit *edit)
3439 {
3440         Indexable *idxbl = edit->asset ?
3441                 (Indexable*)edit->asset : (Indexable*)edit->nested_edl;
3442         if( !idxbl ) return 0;
3443         char path[BCTEXTLEN];
3444 // map proxy colors to unproxy colors
3445         if( edl->session->proxy_state != PROXY_ACTIVE ||
3446             !edit->asset || edit->track->data_type != TRACK_VIDEO ||
3447             ProxyRender::from_proxy_path(path, (Asset*)idxbl, edl->session->proxy_scale) )
3448                 strcpy(path, idxbl->path);
3449         char *cp = strrchr(path, '/');
3450         cp = !cp ? path : cp+1;
3451         uint8_t *bp = (uint8_t*)cp;
3452         int v = 0;
3453         while( *bp ) v += *bp++;
3454         return get_hash_color(v);
3455 }
3456
3457 int MWindow::get_hash_color(int v)
3458 {
3459         int hash = 0x303030;
3460         if( v & 0x01 ) hash ^= 0x000040;
3461         if( v & 0x02 ) hash ^= 0x004000;
3462         if( v & 0x04 ) hash ^= 0x400000;
3463         if( v & 0x08 ) hash ^= 0x080000;
3464         if( v & 0x10 ) hash ^= 0x000800;
3465         if( v & 0x20 ) hash ^= 0x000008;
3466         if( v & 0x40 ) hash ^= 0x404040;
3467         if( v & 0x80 ) hash ^= 0x080808;
3468         return hash;
3469 }
3470
3471 int MWindow::get_group_color(int v)
3472 {
3473         int color = 0x606060;
3474         if( v & 0x01 ) color ^= 0x000080;
3475         if( v & 0x02 ) color ^= 0x008000;
3476         if( v & 0x04 ) color ^= 0x800000;
3477         if( v & 0x08 ) color ^= 0x100000;
3478         if( v & 0x10 ) color ^= 0x001000;
3479         if( v & 0x20 ) color ^= 0x000010;
3480         if( v & 0x40 ) color ^= 0x080808;
3481         if( v & 0x80 ) color ^= 0x909090;
3482         return color;
3483 }
3484
3485 int MWindow::get_title_color(Edit *edit)
3486 {
3487         unsigned color = edit->color & 0xffffff;
3488         unsigned alpha = (~edit->color>>24) & 0xff;
3489         if( !color ) {
3490                 if( edit->group_id )
3491                         color = get_group_color(edit->group_id);
3492                 else if( preferences->autocolor_assets )
3493                         color = get_hash_color(edit);
3494                 else
3495                         return 0;
3496         }
3497         if( alpha == 0xff )
3498                 alpha = session->title_bar_alpha*255;
3499         return color | (~alpha<<24);
3500 }
3501
3502 void MWindow::update_keyframe_guis()
3503 {
3504 // Send new configuration to keyframe GUI's
3505         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3506         for( int i=0; i<keyframe_threads->size(); ++i ) {
3507                 KeyFrameThread *keyframe_gui = keyframe_threads->get(i);
3508                 Plugin *plugin = edl->tracks->plugin_exists(keyframe_gui->plugin_id);
3509                 if( plugin )
3510                         keyframe_gui->update_gui(1);
3511                 else
3512                         keyframe_gui->close_window();
3513         }
3514         keyframe_gui_lock->unlock();
3515 }
3516
3517 void MWindow::update_plugin_guis(int do_keyframe_guis)
3518 {
3519 // Send new configuration to plugin GUI's
3520         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3521
3522         for( int i=0; i<plugin_guis->size(); ++i ) {
3523                 PluginServer *plugin_gui = plugin_guis->get(i);
3524                 Plugin *plugin = edl->tracks->plugin_exists(plugin_gui->plugin_id);
3525                 if( plugin && plugin->show )
3526                         plugin_gui->update_gui();
3527                 else {
3528 // Schedule for deletion if no plugin or not shown
3529                         plugin_guis->remove_number(i--);
3530                         plugin_gui->hide_gui();
3531                         delete_plugin(plugin_gui);
3532                 }
3533         }
3534
3535
3536 // Change plugin variable if not visible
3537         Track *track = edl->tracks->first;
3538         for( ; track; track=track->next ) {
3539                 for( int i=0; i < track->plugin_set.size(); ++i ) {
3540                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3541                         for( ; plugin; plugin = (Plugin*)plugin->next ) {
3542                                 int got_it = 0;
3543                                 for( int i=0; i<plugin_guis->size(); ++i ) {
3544                                         PluginServer *server = plugin_guis->get(i);
3545                                         if( server->plugin_id == plugin->orig_id ) {
3546                                                 got_it = 1;
3547                                                 break;
3548                                         }
3549                                 }
3550                                 if( !got_it ) plugin->show = 0;
3551                         }
3552                 }
3553         }
3554
3555         plugin_gui_lock->unlock();
3556         if( do_keyframe_guis )
3557                 update_keyframe_guis();
3558 }
3559
3560 void MWindow::stop_plugin_guis()
3561 {
3562 // Send new configuration to plugin GUI's
3563         plugin_gui_lock->lock("MWindow::stop_plugin_guis");
3564
3565         for( int i=0; i<plugin_guis->size(); ++i ) {
3566                 PluginServer *plugin_gui = plugin_guis->get(i);
3567                 plugin_gui->render_stop();
3568         }
3569         plugin_gui_lock->unlock(); 
3570 }
3571
3572 int MWindow::plugin_gui_open(Plugin *plugin)
3573 {
3574         int gui_id = plugin->gui_id;
3575         if( gui_id < 0 ) return 0;
3576         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3577         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3578         int result = plugin_server ? 1 : 0;
3579         plugin_gui_lock->unlock();
3580         return result;
3581 }
3582
3583
3584 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3585 {
3586         int gui_id = plugin->gui_id;
3587         if( gui_id < 0 ) return;
3588         plugin_gui_lock->lock("MWindow::render_plugin_gui 0");
3589         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3590         if( plugin_server )
3591                 plugin_server->render_gui(data);
3592         plugin_gui_lock->unlock();
3593 }
3594
3595 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3596 {
3597         int gui_id = plugin->gui_id;
3598         if( gui_id < 0 ) return;
3599         plugin_gui_lock->lock("MWindow::render_plugin_gui 1");
3600         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3601         if( plugin_server )
3602                 plugin_server->render_gui(data, size);
3603         plugin_gui_lock->unlock();
3604 }
3605
3606 void MWindow::reset_plugin_gui_frames(Plugin *plugin)
3607 {
3608         int gui_id = plugin->gui_id;
3609         if( gui_id < 0 ) return;
3610         plugin_gui_lock->lock("MWindow::reset_plugin_gui_frames");
3611         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3612         if( plugin_server )
3613                 plugin_server->reset_plugin_gui_frames();
3614         plugin_gui_lock->unlock();
3615 }
3616
3617 void MWindow::render_plugin_gui_frames(PluginClientFrames *frames, Plugin *plugin)
3618 {
3619         int gui_id = plugin->gui_id;
3620         if( gui_id < 0 ) return;
3621         plugin_gui_lock->lock("MWindow::render_plugin_gui_frames");
3622         PluginServer *plugin_server = plugin_guis->gui_server(gui_id);
3623         if( plugin_server )
3624                 plugin_server->render_plugin_gui_frames(frames);
3625         plugin_gui_lock->unlock();
3626 }
3627
3628 double MWindow::get_tracking_position()
3629 {
3630         return edl->local_session->get_selectionstart(1);
3631 }
3632
3633 int MWindow::get_tracking_direction()
3634 {
3635         return cwindow->playback_engine->get_direction();
3636 }
3637
3638 void MWindow::update_plugin_states()
3639 {
3640         plugin_gui_lock->lock("MWindow::update_plugin_states");
3641         for( int i=0; i<plugin_guis->total; ++i ) {
3642 // Get a plugin GUI
3643                 PluginServer *src_plugingui = plugin_guis->get(i);
3644                 int plugin_id = src_plugingui->plugin_id;
3645                 Plugin *src_plugin = edl->tracks->plugin_exists(plugin_id);
3646 // Doesn't exist anymore
3647                 if( !src_plugin ) {
3648                         hide_plugin(plugin_id, 0);
3649                         --i;
3650                 }
3651         }
3652         plugin_gui_lock->unlock();
3653 }
3654
3655
3656 void MWindow::update_plugin_titles()
3657 {
3658         for( int i=0; i<plugin_guis->total; ++i )
3659                 plugin_guis->get(i)->update_title();
3660 }
3661
3662 int MWindow::asset_to_edl(EDL *new_edl,
3663         Asset *new_asset,
3664         RecordLabels *labels)
3665 {
3666 const int debug = 0;
3667 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3668 __LINE__,
3669 new_asset->layers);
3670 // Keep frame rate, sample rate, and output size unchanged.
3671 // These parameters would revert the project if VWindow displayed an asset
3672 // of different size than the project.
3673         if(new_asset->video_data)
3674         {
3675                 new_edl->session->video_tracks = new_asset->layers;
3676         }
3677         else
3678                 new_edl->session->video_tracks = 0;
3679
3680 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3681
3682
3683
3684
3685
3686         if(new_asset->audio_data)
3687         {
3688                 new_edl->session->audio_tracks = new_asset->channels;
3689         }
3690         else
3691                 new_edl->session->audio_tracks = 0;
3692 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3693
3694 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3695         new_edl->create_default_tracks();
3696 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3697 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3698
3699
3700
3701 //printf("MWindow::asset_to_edl 3\n");
3702         new_edl->insert_asset(new_asset,
3703                 0,
3704                 0,
3705                 0,
3706                 labels);
3707 //printf("MWindow::asset_to_edl 3\n");
3708 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3709
3710 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3711         if(edl->session->cursor_on_frames)
3712         {
3713                 double length = new_edl->tracks->total_length();
3714                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3715                 new_edl->tracks->clear(length, edl_length, 1, 1);
3716         }
3717
3718
3719
3720
3721         char string[BCTEXTLEN];
3722         FileSystem fs;
3723         fs.extract_name(string, new_asset->path);
3724 //printf("MWindow::asset_to_edl 3\n");
3725
3726         strcpy(new_edl->local_session->clip_title, string);
3727 //printf("MWindow::asset_to_edl 4 %s\n", string);
3728 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3729
3730         new_edl->local_session->asset2edl = 1;
3731         return 0;
3732 }
3733
3734
3735 // Reset everything after a load.
3736 void MWindow::update_project(int load_mode)
3737 {
3738         const int debug = 0;
3739
3740         if(debug) PRINT_TRACE
3741         edl->tracks->update_y_pixels(theme);
3742         session->update_clip_number();
3743
3744         if(debug) PRINT_TRACE
3745
3746         if( load_mode == LOADMODE_REPLACE ||
3747             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3748                 edl->session->timecode_offset = 0;
3749                 gui->close_keyvalue_popup();
3750                 gui->load_panes();
3751         }
3752
3753         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 1);
3754         if(debug) PRINT_TRACE
3755         gui->unlock_window();
3756         init_brender();
3757
3758         cwindow->update(0, 0, 1, 1, 1);
3759
3760         if(debug) PRINT_TRACE
3761
3762 // Close all the vwindows
3763         if( load_mode == LOADMODE_REPLACE ||
3764             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3765                 if(debug) PRINT_TRACE
3766                 int first_vwindow = 0;
3767                 if(session->show_vwindow) first_vwindow = 1;
3768 // Change visible windows to no source
3769                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3770                         VWindow *vwindow = vwindows[i];
3771                         if( !vwindow->is_running() ) continue;
3772                         vwindow->change_source(-1);
3773                 }
3774
3775 // Close remaining windows
3776                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3777                         VWindow *vwindow = vwindows[i];
3778                         if( !vwindow->is_running() ) continue;
3779                         vwindow->close_window();
3780                 }
3781                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3782                         VWindow *vwindow = get_viewer(1, -1);
3783                         vwindow->change_source(i);
3784                 }
3785                 if(debug) PRINT_TRACE
3786                 select_zwindow(0);
3787                 close_mixers(0);
3788
3789                 for( int i=0; i<edl->mixers.size(); ++i ) {
3790                         Mixer *mixer = edl->mixers[i];
3791                         if( !mixer->show ) continue;
3792                         ZWindow *zwindow = get_mixer(mixer);
3793                         zwindow->set_title(mixer->title);
3794                         zwindow->start();
3795                 }
3796                 cwindow->gui->canvas->set_zoom(edl, 0);
3797         }
3798         update_vwindow();
3799
3800         if(debug) PRINT_TRACE
3801         cwindow->gui->lock_window("MWindow::update_project 2");
3802         cwindow->gui->timebar->update(0);
3803         Track *track = cwindow->calculate_affected_track();
3804         cwindow->mask_track_id = track ? track->get_id() : -1;
3805         cwindow->gui->tool_panel->raise_tool();
3806         cwindow->gui->update_canvas(0);
3807         cwindow->gui->unlock_window();
3808
3809         if(debug) PRINT_TRACE
3810         cwindow->refresh_frame(CHANGE_ALL);
3811
3812         awindow->gui->async_update_assets();
3813         if(debug) PRINT_TRACE
3814
3815         gui->lock_window("MWindow::update_project");
3816         gui->update_mixers(0, 0);
3817         gui->flush();
3818         if(debug) PRINT_TRACE
3819 }
3820
3821 void MWindow::stack_push(EDL *new_edl, Indexable *idxbl)
3822 {
3823         int got_indexes = 0;
3824         for( int i=0; i<new_edl->nested_edls.size(); ++i ) {
3825                 EDL *nested_edl = new_edl->nested_edls[i];
3826                 mainindexes->add_indexable(nested_edl);
3827                 edl->nested_edls.update_index(nested_edl);
3828                 got_indexes = 1;
3829         }
3830         for( Asset *asset=new_edl->assets->first; asset; asset=asset->next ) {
3831                 mainindexes->add_indexable(asset);
3832                 edl->assets->update(asset);
3833                 got_indexes = 1;
3834         }
3835 // Start examining next batch of index files
3836         if( got_indexes )
3837                 mainindexes->start_build();
3838
3839 // needs gui lock
3840         gui->lock_window("MWindow::stack_push");
3841         if( stack.size() < 9 ) {
3842                 save_backup();
3843                 hide_plugins();
3844                 undo_before();
3845                 StackItem &item = stack.append();
3846                 item.edl = edl;
3847                 item.new_edl = new_edl;
3848                 item.duration = new_edl->tracks->total_length();
3849                 item.undo = undo;
3850                 item.idxbl = idxbl;
3851                 item.mtime = 0;
3852                 if( idxbl && idxbl->is_asset ) {
3853                         struct stat st;
3854                         Asset *asset = (Asset *)idxbl;
3855                         if( asset->format == FILE_REF &&
3856                             !stat(asset->path, &st) )
3857                                 item.mtime = st.st_mtime;
3858                 }
3859                 edl = new_edl;
3860                 edl->add_user();
3861                 strcpy(session->filename, edl->path);
3862                 undo = new MainUndo(this);
3863                 gui->stack_button->update();
3864                 update_project(LOADMODE_REPLACE);
3865         }
3866         gui->unlock_window();
3867         show_plugins();
3868 }
3869
3870 void MWindow::stack_pop()
3871 {
3872         if( !stack.size() ) return;
3873 // writes on config_path/backup%d.xml
3874         save_backup();
3875         hide_plugins();
3876 // already have gui lock
3877         StackItem &item = stack.last();
3878 // session edl replaced, overwrite and save clip data
3879         if( item.new_edl != edl )
3880                 item.new_edl->overwrite_clip(edl);
3881         Indexable *idxbl = item.idxbl;
3882         if( idxbl && idxbl->is_asset && item.mtime ) {
3883                 Asset *asset = (Asset *)idxbl;
3884                 if( asset->format == FILE_REF ) {
3885                         char *path = asset->path;
3886                         struct stat st;
3887                         if( stat(path, &st) || item.mtime == st.st_mtime ) {
3888                                 int cw = xS(250), ch = yS(150), px, py;
3889                                 gui->get_pop_cursor(px, py);
3890                                 px -= cw/2;  py -= ch/2;
3891                                 ConfirmRefWindow confirm(this, path, px, py, cw, ch);
3892                                 confirm.create_objects();
3893                                 int result = confirm.run_window();
3894                                 if( !result ) {
3895                                         FileXML file;
3896                                         item.new_edl->save_xml(&file, path);
3897                                         file.terminate_string();
3898                                         if(file.write_to_file(path))
3899                                                 eprintf(_("Cant write FileREF: %s"), path);
3900                                 }
3901                         }
3902                 }
3903         }
3904         edl->remove_user();
3905         edl = item.edl;
3906         delete undo;
3907         undo = item.undo;
3908         stack.remove();
3909         if( idxbl ) {
3910 // resize the indexable edits if the new_edl duration changed
3911                 double duration = item.new_edl->tracks->total_length();
3912                 double dt = duration - item.duration;
3913                 if( fabs(dt) > 1e-4 )
3914                         edl->tracks->update_idxbl_length(idxbl->id, dt);
3915                 gui->unlock_window();
3916                 gui->resource_thread->close_indexable(idxbl);
3917                 remove_from_caches(idxbl);
3918                 IndexFile::delete_index_files(preferences, idxbl);
3919                 mainindexes->add_indexable(idxbl);
3920                 mainindexes->start_build();
3921                 awindow->gui->async_update_assets();
3922                 gui->lock_window("MWindow::stack_pop");
3923         }
3924         strcpy(session->filename, edl->path);
3925         update_project(LOADMODE_REPLACE);
3926         undo_after(_("open edl"), LOAD_ALL);
3927         show_plugins();
3928         gui->stack_button->update();
3929 }
3930
3931 int MWindow::save(EDL *edl, char *filename, int stat)
3932 {
3933         FileXML file;
3934         edl->save_xml(&file, filename);
3935         file.terminate_string();
3936         if( file.write_to_file(filename) ) {
3937                 eprintf(_("Couldn't open %s"), filename);
3938                 return 1;
3939         }
3940         if( stat ) {
3941                 char string[BCTEXTLEN];
3942                 char *filename = stack.size() ?
3943                         stack[0].edl->path : session->filename;
3944                 sprintf(string, _("\"%s\" %jdC written"),
3945                          filename, file.length());
3946                 gui->lock_window("SaveAs::run");
3947                 gui->show_message(string);
3948                 gui->unlock_window();
3949         }
3950         return 0;
3951 }
3952
3953 int MWindow::save(int save_as)
3954 {
3955         char new_path[BCTEXTLEN];  new_path[0] = 0;
3956         char *path = stack.size() ? stack[0].edl->path : session->filename;
3957         if( save_as || !path[0] ) {
3958                 if( ConfirmSave::get_save_path(this, new_path) )
3959                         return 1;
3960                 if( stack.size() ) {
3961                         strcpy(path, new_path);
3962                         set_titlebar(new_path);
3963                 }
3964                 else
3965                         set_filename(new_path);
3966                 gui->mainmenu->add_load(new_path);
3967                 path = new_path;
3968         }
3969         for( int i=stack.size(); --i>=0;  ) {
3970                 StackItem &item = stack[i];
3971                 Indexable *idxbl = item.idxbl;
3972                 if( !idxbl ) continue;
3973                 if( idxbl->is_asset ) {
3974                         Asset *asset = (Asset *)idxbl;
3975                         if( asset->format == FILE_REF ) {
3976                                 if( save(item.new_edl, asset->path, 0) )
3977                                         return 1;
3978                         }
3979                 }
3980                 else if( item.new_edl != idxbl )
3981                         item.new_edl->overwrite_clip((EDL*)idxbl);
3982         }
3983         EDL *new_edl = stack.size() ? stack[0].edl : edl;
3984         save(new_edl, path, 1);
3985         return 0;
3986 }
3987
3988 void MWindow::show_plugins()
3989 {
3990         for( Track *track=edl->tracks->first; track; track=track->next ) {
3991                 for( int i=0; i<track->plugin_set.size(); ++i ) {
3992                         PluginSet *plugins = track->plugin_set[i];
3993                         Plugin *plugin = plugins->get_first_plugin();
3994                         for( ; plugin; plugin=(Plugin*)plugin->next ) {
3995                                 if( plugin->plugin_type == PLUGIN_STANDALONE &&
3996                                     plugin->show )
3997                                         show_plugin(plugin);
3998                         }
3999                 }
4000         }
4001 }
4002
4003 void MWindow::clip_to_media()
4004 {
4005         if( edl->session->proxy_scale != 1 ) {
4006                 eprintf("Nesting not allowed when proxy scale != 1");
4007                 return;
4008         }
4009         undo_before();
4010         awindow->gui->stop_vicon_drawing();
4011         int clips_total = session->drag_clips->total;
4012         for( int i=0; i<clips_total; ++i ) {
4013                 EDL *clip = session->drag_clips->values[i];
4014                 time_t dt;      time(&dt);
4015                 struct tm dtm;  localtime_r(&dt, &dtm);
4016                 char path[BCTEXTLEN], *cp = path, *ep = cp+sizeof(path)-1;
4017 // path_basename = "Nested_<date>-<time>_<basename>"
4018                 cp += snprintf(cp, ep-cp, _("Nested_%02d%02d%02d-%02d%02d%02d_"),
4019                         dtm.tm_year+1900, dtm.tm_mon+1, dtm.tm_mday,
4020                         dtm.tm_hour, dtm.tm_min, dtm.tm_sec);
4021                 char *bp = strrchr(clip->local_session->clip_title, '/');
4022                 bp = bp ? bp+1 : clip->local_session->clip_title;
4023                 cp += snprintf(cp, ep-cp, "%s", bp);
4024                 EDL *nested = edl->new_nested_clip(clip, path);
4025                 edl->clips.remove(clip);
4026                 clip->remove_user();
4027                 mainindexes->add_indexable(nested);
4028         }
4029         undo_after(_("clip2media"), LOAD_ALL);
4030         mainindexes->start_build();
4031         awindow->gui->async_update_assets();
4032 }
4033
4034 void MWindow::media_to_clip()
4035 {
4036         undo_before();
4037         int assets_total = session->drag_assets->total;
4038         for( int i=0; i<assets_total; ++i ) {
4039                 Indexable *idxbl = session->drag_assets->values[i];
4040                 if( idxbl->is_asset ) {
4041                         eprintf(_("media is not EDL:\n%s"), idxbl->path);
4042                         continue;
4043                 }
4044                 char clip_title[BCSTRLEN];
4045                 int name_ok = 0;
4046                 while( !name_ok ) {
4047                         name_ok = 1;
4048                         sprintf(clip_title, _("Clip %d"), session->clip_number++);
4049                         for( int i=0; name_ok && i<edl->clips.size(); ++i ) {
4050                                 char *title = edl->clips[i]->local_session->clip_title;
4051                                 if( !strcasecmp(clip_title, title) ) name_ok = 0;
4052                         }
4053                 }
4054                 EDL *nested = (EDL *)idxbl;
4055                 EDL *clip = edl->add_clip(nested);
4056                 strcpy(clip->local_session->clip_title, clip_title);
4057                 snprintf(clip->local_session->clip_notes,
4058                         sizeof(clip->local_session->clip_notes),
4059                         _("From: %s"), nested->path);
4060         }
4061         undo_after(_("media2clip"), LOAD_ALL);
4062         awindow->gui->async_update_assets();
4063 }
4064
4065 int MWindow::create_ref(Asset *asset, EDL *ref)
4066 {
4067         asset->format = FILE_REF;
4068         double secs = ref->tracks->total_length();
4069         int audio_channels = ref->session->audio_channels;
4070         asset->audio_data = audio_channels > 0 ? 1 : 0;
4071         asset->channels = audio_channels;
4072         asset->sample_rate = ref->session->sample_rate;
4073         asset->audio_length = audio_channels > 0 && secs > 0 ?
4074                  secs * asset->sample_rate : 0;
4075         strcpy(asset->acodec, _("reference"));
4076
4077         int video_layers = ref->session->video_channels;
4078         asset->video_data = video_layers > 0 ? 1 : 0;
4079         asset->layers = video_layers > 0 ? 1 : 0;
4080         asset->actual_width = ref->session->output_w;
4081         asset->actual_height = ref->session->output_h;
4082         asset->width = asset->actual_width;
4083         asset->height = asset->actual_height;
4084         asset->frame_rate = ref->session->frame_rate;
4085         asset->video_length = video_layers > 0 && secs > 0 ?
4086                 secs * asset->frame_rate : 0;
4087         strcpy(asset->vcodec, _("reference"));
4088         return 0;
4089 }
4090
4091 void MWindow::update_preferences(Preferences *prefs)
4092 {
4093         if( prefs != preferences )
4094                 preferences->copy_from(prefs);
4095         if( cwindow->playback_engine )
4096                 cwindow->playback_engine->update_preferences(prefs);
4097         for(int i = 0; i < vwindows.size(); i++) {
4098                 VWindow *vwindow = vwindows[i];
4099                 if( !vwindow->is_running() ) continue;
4100                 if( vwindow->playback_engine )
4101                         vwindow->playback_engine->update_preferences(prefs);
4102         }
4103         for(int i = 0; i < zwindows.size(); i++) {
4104                 ZWindow *zwindow = zwindows[i];
4105                 if( !zwindow->is_running() ) continue;
4106                 if( zwindow->zgui->playback_engine )
4107                         zwindow->zgui->playback_engine->update_preferences(prefs);
4108         }
4109 }
4110
4111 void MWindow::update_vwindow()
4112 {
4113         for( int i=0; i<vwindows.size(); ++i ) {
4114                 VWindow *vwindow = vwindows[i];
4115                 if( vwindow->is_running() ) {
4116                         vwindow->gui->lock_window("MWindow::update_vwindow");
4117                         vwindow->update(1);
4118                         vwindow->gui->unlock_window();
4119                 }
4120         }
4121 }
4122
4123 void MWindow::remove_indexfile(Indexable *indexable)
4124 {
4125         if( !indexable->is_asset ) return;
4126 // Erase file
4127         IndexFile::delete_index_files(preferences, indexable);
4128 }
4129
4130 void MWindow::rebuild_indices()
4131 {
4132         for(int i = 0; i < session->drag_assets->total; i++)
4133         {
4134                 Indexable *indexable = session->drag_assets->get(i);
4135 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4136                 remove_indexfile(indexable);
4137 // Schedule index build
4138                 indexable->index_state->remove_user();
4139                 indexable->index_state = new IndexState;
4140                 IndexFile::delete_index_files(preferences, indexable);
4141                 if( indexable->is_asset ) {
4142                         Asset *asset = (Asset *)indexable;
4143                         if( asset->format != FILE_PCM ) {
4144                                 asset->format = FILE_UNKNOWN;
4145                                 asset->reset_audio();
4146                         }
4147                         asset->reset_video();
4148                         remove_from_caches(asset);
4149 //                      File file; // re-probe the asset
4150 //                      file.open_file(preferences, asset, 1, 0);
4151                 }
4152                 mainindexes->add_indexable(indexable);
4153         }
4154 // still in render engine
4155         sync_parameters(CHANGE_ALL);
4156         awindow->gui->async_update_assets();
4157         mainindexes->start_build();
4158 }
4159
4160
4161 void MWindow::get_backup_path(char *path, int len)
4162 {
4163         char *cp = path, *ep = cp + len-1;
4164         cp += snprintf(cp, ep-cp, "%s/", File::get_config_path());
4165         int idx = stack.size();
4166         cp += snprintf(cp, ep-cp, idx ? BACKUPn_FILE : BACKUP_FILE, idx);
4167 }
4168
4169 void MWindow::save_backup()
4170 {
4171         FileXML file;
4172         edl->optimize();
4173         edl->set_path(session->filename);
4174
4175         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
4176         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
4177                 File::get_config_path(), BACKUP_FILE1);
4178         get_backup_path(backup_path, sizeof(backup_path));
4179         rename(backup_path, backup_path1);
4180         edl->save_xml(&file, backup_path);
4181         file.terminate_string();
4182         FileSystem fs;
4183         fs.complete_path(backup_path);
4184
4185         if(file.write_to_file(backup_path)) {
4186                 char string2[256];
4187                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
4188                 gui->show_message(string2);
4189         }
4190         save_undo_data();
4191 }
4192
4193 void MWindow::load_backup()
4194 {
4195         ArrayList<char*> path_list;
4196         path_list.set_array_delete();
4197         char *out_path;
4198         char backup_path[BCTEXTLEN];
4199         get_backup_path(backup_path, sizeof(backup_path));
4200         FileSystem fs;
4201         fs.complete_path(backup_path);
4202
4203         path_list.append(out_path = new char[strlen(backup_path) + 1]);
4204         strcpy(out_path, backup_path);
4205
4206         load_filenames(&path_list, LOADMODE_REPLACE, LOADMODE_EDL_CLIP, 0);
4207         edl->local_session->clip_title[0] = 0;
4208 // This is unique to backups since the path of the backup is different than the
4209 // path of the project.
4210         set_filename(edl->path);
4211         path_list.remove_all_objects();
4212         save_backup();
4213 }
4214
4215
4216 void MWindow::save_undo_data()
4217 {
4218         if( stack.size() > 0 ) return;
4219         if( !preferences->perpetual_session ) return;
4220         char perpetual_path[BCTEXTLEN];
4221         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4222                 File::get_config_path(), PERPETUAL_FILE);
4223         FILE *fp = fopen(perpetual_path,"w");
4224         if( !fp ) return;
4225         undo->save(fp);
4226         fclose(fp);
4227 }
4228
4229 void MWindow::load_undo_data()
4230 {
4231         if( stack.size() > 0 ) return;
4232         if( !preferences->perpetual_session ) return;
4233         char perpetual_path[BCTEXTLEN];
4234         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4235                 File::get_config_path(), PERPETUAL_FILE);
4236         FILE *fp = fopen(perpetual_path,"r");
4237         if( !fp ) return;
4238         undo->load(fp);
4239         undo_before();
4240         undo_after(_("perpetual load"), LOAD_ALL);
4241         fclose(fp);
4242 }
4243
4244 void MWindow::remove_undo_data()
4245 {
4246         if( stack.size() > 0 ) return;
4247         char perpetual_path[BCTEXTLEN];
4248         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
4249                 File::get_config_path(), PERPETUAL_FILE);
4250         ::remove(perpetual_path);
4251 }
4252
4253 int MWindow::copy_target(const char *path, const char *target)
4254 {
4255         int ifd = ::open(path, O_RDONLY);
4256         if( ifd < 0 ) {
4257                 eprintf("Cannot open asset: %s", path);
4258                 return 1;
4259         }
4260         int ret = 0;
4261         int ofd = ::open(target, O_CREAT+O_TRUNC+O_WRONLY, 0777);
4262         if( ofd >= 0 ) {
4263                 struct stat st;
4264                 int64_t total_bytes = !fstat(ifd, &st) ? st.st_size : 0;
4265                 char progress_title[BCTEXTLEN];
4266                 sprintf(progress_title, _("Copying: %s\n"), target);
4267                 BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
4268
4269                 int64_t count = 0, len = -1;
4270                 int bfrsz = 0x100000;
4271                 uint8_t *bfr = new uint8_t[bfrsz];
4272                 while( (len=::read(ifd, bfr, bfrsz)) > 0 ) {
4273                         if( len != ::write(ofd, bfr, len) ) {
4274                                 eprintf("Error writing: %s", target);
4275                                 break;
4276                         }
4277                         if( progress.is_cancelled() ) {
4278                                 ret = 1;
4279                                 break;
4280                         }
4281                         progress.update(count += len, 1);
4282                 }
4283                 delete [] bfr;
4284                 ::close(ofd);
4285
4286                 progress.stop_progress();
4287                 if( len < 0 ) {
4288                         eprintf("Error reading: %s", path);
4289                         ret = 1;
4290                 }
4291         }
4292         else
4293                 eprintf("Cannot create asset target: %s", target);
4294         ::close(ifd);
4295         return ret;
4296 }
4297
4298 int MWindow::link_target(const char *real_path, const char *link_path, int relative)
4299 {
4300         char target[BCTEXTLEN];
4301         if( relative ) {
4302                 const char *bp = real_path, *cp = bp;
4303                 const char *lp = link_path, *np = lp;
4304                 char *tp = target, *ep = tp+sizeof(target)-1, lch;
4305                 while( *lp && *bp && (lch=*lp++) == *bp++ ) {
4306                         if( lch == '/' ) { np = lp;  cp = bp; }
4307                 }
4308                 while( tp<ep && *np ) {
4309                         if( *np++ != '/' ) continue;
4310                         *tp++ = '.';  *tp++ = '.';  *tp++ = '/';
4311                 }
4312                 while( tp<ep && *cp ) *tp++ = *cp++;
4313                 *tp = 0;
4314         }
4315         else
4316                 strcpy(target, real_path);
4317         if( symlink(target, link_path) ) {
4318                 eprintf("Cannot create symlink: %s", link_path);
4319                 return 1;
4320         }
4321         return 0;
4322 }
4323
4324 void MWindow::save_project(const char *dir, int save_mode, int overwrite, int reload)
4325 {
4326         char dir_path[BCTEXTLEN];
4327         strcpy(dir_path, dir);
4328         FileSystem fs;
4329         fs.complete_path(dir_path);
4330
4331         struct stat st;
4332         if( !stat(dir_path, &st) ) {
4333                 if( !S_ISDIR(st.st_mode) ) {
4334                         eprintf("Path exists and is not a directory\n%s", dir_path);
4335                         return;
4336                 }
4337         }
4338         else {
4339                 if( mkdir(dir_path, S_IRWXU | S_IRWXG | S_IRWXO) ) {
4340                         eprintf("Cannot create directory\n%s", dir_path);
4341                         return;
4342                 }
4343         }
4344         char *real_dir = realpath(dir_path, 0);
4345         strcpy(dir_path, real_dir);
4346         free(real_dir);
4347
4348         EDL *save_edl = new EDL;
4349         save_edl->create_objects();
4350         save_edl->copy_all(edl);
4351
4352         char progress_title[BCTEXTLEN];
4353         sprintf(progress_title, _("Saving to %s:\n"), dir);
4354         int total_assets = save_edl->assets->total();
4355         gui->lock_window("MWindow::save_project");
4356         MainProgressBar *progress = mainprogress->start_progress(progress_title, total_assets);
4357         gui->unlock_window();
4358
4359         int ret = 0;
4360         Asset *current = save_edl->assets->first;
4361         for( int i=0; !ret && current; ++i, current=NEXT ) {
4362                 char *path = current->path;
4363                 if( ::stat(path, &st) ) {
4364                         eprintf("Asset not found: %s", path);
4365                         continue;
4366                 }
4367                 char *real_path = realpath(path, 0);
4368                 const char *cp = strrchr(path, '/'), *bp = !cp ? path : cp+1;
4369                 char link_path[BCTEXTLEN];
4370                 snprintf(link_path, sizeof(link_path), "%s/%s", dir_path, bp);
4371                 int skip = 0;
4372                 if( strcmp(real_path, link_path) ) {
4373                         if( !::lstat(link_path, &st) ) {
4374                                 if( overwrite )
4375                                         ::remove(link_path);
4376                                 else
4377                                         skip = 1;
4378                         }
4379                 }
4380                 else {
4381                         eprintf("copy/link to self, skippped: %s", path);
4382                         skip = 1;
4383                 }
4384                 if( !skip ) {
4385                         if( save_mode == SAVE_PROJECT_COPY ) {
4386                                 if( copy_target(real_path, link_path) )
4387                                         ret = 1;
4388                         }
4389                         else {
4390                                 link_target(real_path, link_path,
4391                                         save_mode == SAVE_PROJECT_RELLINK ? 1 : 0);
4392                         }
4393                 }
4394                 free(real_path);
4395                 strcpy(path, link_path);
4396
4397                 if( progress->is_cancelled() ) break;
4398                 progress->update(i);
4399         }
4400
4401         progress->stop_progress();
4402         delete progress;
4403
4404         char *cp = strrchr(dir_path,'/');
4405         char *bp = cp ? cp+1 : dir_path;
4406         char filename[BCTEXTLEN];
4407         snprintf(filename, sizeof(filename), "%s/%s.xml", dir_path, bp);
4408         save_edl->set_path(filename);
4409         FileXML file;
4410         save_edl->save_xml(&file, filename);
4411         file.terminate_string();
4412
4413         if( !file.write_to_file(filename) ) {
4414                 char string[BCTEXTLEN];
4415                 sprintf(string, _("\"%s\" %dC written"), filename, (int)strlen(file.string()));
4416                 gui->lock_window("SaveProject::run 2");
4417                 gui->show_message(string);
4418                 gui->unlock_window();
4419                 gui->mainmenu->add_load(filename);
4420         }
4421         else
4422                 eprintf(_("Couldn't open %s."), filename);
4423
4424         save_edl->remove_user();
4425
4426         if( reload ) {
4427                 gui->lock_window("MWindow::save_project");
4428                 ArrayList<char*> filenames;
4429                 filenames.append(filename);
4430                 load_filenames(&filenames);
4431                 gui->unlock_window();
4432         }
4433 }
4434
4435
4436 static inline int gcd(int m, int n)
4437 {
4438         int r;
4439         if( m < n ) { r = m;  m = n;  n = r; }
4440         while( (r = m % n) != 0 ) { m = n;  n = r; }
4441         return n;
4442 }
4443
4444 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
4445 {
4446         w = 1;  h = 1;
4447         if(!width || !height) return 1;
4448         if( width == 720 && (height == 480 || height == 576) ) {
4449                 w = 4;  h = 3;  return 0; // for NTSC and PAL
4450         }
4451         double ar = (double)width / height;
4452 // square-ish pixels
4453         if( EQUIV(ar, 1.0000) ) return 0;
4454         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
4455         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
4456         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
4457         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
4458         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
4459         int ww = width, hh = height;
4460         // numerator, denominator must be under mx
4461         int mx = 255, n = gcd(ww, hh);
4462         if( n > 1 ) { ww /= n; hh /= n; }
4463         // search near height in case extra/missing lines
4464         if( ww >= mx || hh >= mx ) {
4465                 double err = height;  // +/- 2 percent height
4466                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
4467                         int iw = width, ih = height+i;
4468                         if( (n=gcd(iw, ih)) > 1 ) {
4469                                 int u = iw/n;  if( u >= mx ) continue;
4470                                 int v = ih/n;  if( v >= mx ) continue;
4471                                 double r = (double) u/v, er = fabs(ar-r);
4472                                 if( er >= err ) continue;
4473                                 err = er;  ww = u;  hh = v;
4474                         }
4475                 }
4476         }
4477
4478         w = ww;  h = hh;
4479         return 0;
4480 }
4481
4482 void MWindow::reset_caches(int locked)
4483 {
4484         if( locked ) gui->unlock_window();
4485         awindow->gui->stop_vicon_drawing(1);
4486         if( cwindow->playback_engine )
4487                 cwindow->playback_engine->create_cache();
4488         for(int i = 0; i < vwindows.size(); i++) {
4489                 VWindow *vwindow = vwindows[i];
4490                 if( !vwindow->is_running() ) continue;
4491                 if( !vwindow->playback_engine ) continue;
4492                 vwindow->playback_engine->create_cache();
4493         }
4494         gui->lock_window("MWindow::reset_caches");
4495         frame_cache->remove_all();
4496         wave_cache->remove_all();
4497         audio_cache->remove_all();
4498         video_cache->remove_all();
4499         if( !locked ) gui->unlock_window();
4500 }
4501
4502 void MWindow::remove_from_caches(Indexable *idxbl)
4503 {
4504         awindow->gui->stop_vicon_drawing(1);
4505         frame_cache->remove_item(idxbl);
4506         wave_cache->remove_item(idxbl);
4507         if( gui->render_engine &&
4508             gui->render_engine_id == idxbl->id ) {
4509                 delete gui->render_engine;
4510                 gui->render_engine = 0;
4511         }
4512         gui->resource_thread->close_indexable(idxbl);
4513         if( !idxbl->is_asset ) return;
4514         Asset *asset = (Asset *)idxbl;
4515         audio_cache->delete_entry(asset);
4516         video_cache->delete_entry(asset);
4517         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
4518                 cwindow->playback_engine->audio_cache->delete_entry(asset);
4519         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
4520                 cwindow->playback_engine->video_cache->delete_entry(asset);
4521         for(int i = 0; i < vwindows.size(); i++) {
4522                 VWindow *vwindow = vwindows[i];
4523                 if( !vwindow->is_running() ) continue;
4524                 if( !vwindow->playback_engine ) continue;
4525                 if( vwindow->playback_engine->audio_cache )
4526                         vwindow->playback_engine->audio_cache->delete_entry(asset);
4527                 if( vwindow->playback_engine->video_cache )
4528                         vwindow->playback_engine->video_cache->delete_entry(asset);
4529         }
4530         for(int i = 0; i < zwindows.size(); i++) {
4531                 ZWindow *zwindow = zwindows[i];
4532                 if( !zwindow->is_running() ) continue;
4533                 if( zwindow->zgui->playback_engine->audio_cache )
4534                         zwindow->zgui->playback_engine->audio_cache->delete_entry(asset);
4535                 if( zwindow->zgui->playback_engine->video_cache )
4536                         zwindow->zgui->playback_engine->video_cache->delete_entry(asset);
4537         }
4538         awindow->gui->start_vicon_drawing();
4539 }
4540
4541 void MWindow::remove_assets_from_project(int push_undo, int redraw, int delete_indexes,
4542                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
4543 {
4544         awindow->gui->stop_vicon_drawing(1);
4545
4546 // Remove from VWindow.
4547         if( drag_clips ) {
4548                 for(int i = 0; i < drag_clips->total; i++) {
4549                         for(int j = 0; j < vwindows.size(); j++) {
4550                                 VWindow *vwindow = vwindows[j];
4551                                 if( !vwindow->is_running() ) continue;
4552                                 if(drag_clips->get(i) == vwindow->get_edl()) {
4553                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
4554                                         vwindow->delete_source(1, 1);
4555                                         vwindow->gui->unlock_window();
4556                                 }
4557                         }
4558                 }
4559         }
4560
4561         if( drag_assets ) {
4562                 for(int i = 0; i < drag_assets->size(); i++) {
4563                         for(int j = 0; j < vwindows.size(); j++) {
4564                                 VWindow *vwindow = vwindows[j];
4565                                 if( !vwindow->is_running() ) continue;
4566                                 if(drag_assets->get(i) == vwindow->get_source()) {
4567                                         vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
4568                                         vwindow->delete_source(1, 1);
4569                                         vwindow->gui->unlock_window();
4570                                 }
4571                         }
4572                 }
4573
4574                 for(int i = 0; i < drag_assets->total; i++) {
4575                         Indexable *indexable = drag_assets->get(i);
4576                         if(indexable->is_asset) remove_from_caches(indexable);
4577                 }
4578
4579                 if( delete_indexes ) {
4580                         for(int i = 0; i < drag_assets->size(); i++) {
4581                                 Indexable *indexable = drag_assets->get(i);
4582                                 remove_indexfile(indexable);
4583                         }
4584                 }
4585         }
4586
4587 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4588         if(push_undo) undo_before();
4589         if(drag_assets) edl->remove_from_project(drag_assets);
4590         if(drag_clips) edl->remove_from_project(drag_clips);
4591         if(redraw) save_backup();
4592         if(push_undo) undo_after(_("remove assets"), LOAD_ALL);
4593         if(redraw) {
4594                 restart_brender();
4595
4596                 gui->lock_window("MWindow::remove_assets_from_project 3");
4597                 gui->update(1, NORMAL_DRAW, 1, 1, 0, 1, 0);
4598                 gui->unlock_window();
4599
4600         // Removes from playback here
4601                 sync_parameters(CHANGE_ALL);
4602         }
4603
4604         awindow->gui->async_update_assets();
4605 }
4606
4607 void MWindow::remove_assets_from_disk()
4608 {
4609         remove_assets_from_project(1, 1, 1,
4610                 session->drag_assets, session->drag_clips);
4611
4612 // Remove from disk
4613         for(int i = 0; i < session->drag_assets->total; i++)
4614         {
4615                 remove(session->drag_assets->get(i)->path);
4616         }
4617 }
4618
4619 void MWindow::dump_plugins(FILE *fp)
4620 {
4621         if( !plugindb ) return;
4622         for(int i = 0; i < plugindb->total; i++)
4623         {
4624                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
4625                         " synth=%d transition=%d theme=%d %s\n",
4626                         plugindb->get(i)->plugin_type,
4627                         plugindb->get(i)->audio,
4628                         plugindb->get(i)->video,
4629                         plugindb->get(i)->realtime,
4630                         plugindb->get(i)->multichannel,
4631                         plugindb->get(i)->get_synthesis(),
4632                         plugindb->get(i)->transition,
4633                         plugindb->get(i)->theme,
4634                         plugindb->get(i)->title);
4635         }
4636 }
4637
4638 void MWindow::dump_edl(FILE *fp)
4639 {
4640         if( !edl ) return;
4641         edl->dump(fp);
4642 }
4643
4644 void MWindow::dump_undo(FILE *fp)
4645 {
4646         if( !undo ) return;
4647         undo->dump(fp);
4648 }
4649
4650 void MWindow::dump_exe(FILE *fp)
4651 {
4652         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
4653         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
4654
4655         int ret = -1, n = 100;
4656         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
4657                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
4658                 ret = 0;
4659         }
4660         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
4661
4662         struct stat st;
4663         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
4664         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
4665         struct tm *tm = localtime(&st.st_mtime);
4666         char mtime[256];
4667         strftime(mtime, sizeof(mtime), "%F %T", tm);
4668         fprintf(fp,"mtime: %s\n", mtime);
4669 #if 0
4670 // people hit ctl-c waiting for this
4671         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
4672         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
4673         uint8_t *bfr = 0;
4674         int64_t bfrsz = 0;
4675         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
4676         int64_t maxsz = 1024*pagsz;
4677         int64_t size = st.st_size, pos = 0;
4678         SHA1 sha1;
4679         while( (bfrsz = size-pos) > 0 ) {
4680                 if( bfrsz > maxsz ) bfrsz = maxsz;
4681                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
4682                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
4683                 if( bfr == MAP_FAILED ) break;
4684                 sha1.addBytes(bfr, bfrsz);
4685                 munmap(bfr, bfrsz);
4686                 pos += bfrsz;
4687         }
4688         close(fd);
4689         ret = pos < size ? EIO : 0;
4690         fprintf(fp, "SHA1: ");
4691         uint8_t digest[20];  sha1.computeHash(digest);
4692         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
4693         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
4694         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
4695 #endif
4696         fprintf(fp, "\n");
4697 }
4698
4699 void MWindow::dump_caches(FILE *fp)
4700 {
4701         fprintf(fp, "audio cache: ");
4702         audio_cache->dump(fp);
4703         fprintf(fp, "video cache: ");
4704         video_cache->dump(fp);
4705 }
4706
4707 void MWindow::trap_hook(FILE *fp, void *vp)
4708 {
4709         MWindow *mwindow = (MWindow *)vp;
4710 //      fprintf(fp, "\nPLUGINS:\n");
4711 //      mwindow->dump_plugins(fp);
4712         fprintf(fp, "\nEDL:\n");
4713         mwindow->dump_edl(fp);
4714         fprintf(fp, "\nUNDO:\n");
4715         mwindow->dump_undo(fp);
4716         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
4717         mwindow->dump_exe(fp);
4718         fprintf(fp, "\nCACHES:\n");
4719         mwindow->dump_caches(fp);
4720 }
4721
4722
4723
4724
4725
4726
4727 int MWindow::save_defaults()
4728 {
4729         gui->save_defaults(defaults);
4730         edl->save_defaults(defaults);
4731         session->save_defaults(defaults);
4732         preferences->save_defaults(defaults);
4733
4734         for(int i = 0; i < plugin_guis->total; i++)
4735         {
4736 // Pointer comparison
4737                 plugin_guis->get(i)->save_defaults();
4738         }
4739         awindow->save_defaults(defaults);
4740
4741         defaults->save();
4742         return 0;
4743 }
4744
4745 int MWindow::run_script(FileXML *script)
4746 {
4747         int result = 0, result2 = 0;
4748         while(!result && !result2)
4749         {
4750                 result = script->read_tag();
4751                 if(!result)
4752                 {
4753                         if(script->tag.title_is("new_project"))
4754                         {
4755 // Run new in immediate mode.
4756 //                              gui->mainmenu->new_project->run_script(script);
4757                         }
4758                         else
4759                         if(script->tag.title_is("record"))
4760                         {
4761 // Run record as a thread.  It is a terminal command.
4762                                 ;
4763 // Will read the complete scipt file without letting record read it if not
4764 // terminated.
4765                                 result2 = 1;
4766                         }
4767                         else
4768                         {
4769                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
4770                         }
4771                 }
4772         }
4773         return result2;
4774 }
4775
4776 // ================================= synchronization
4777
4778
4779 int MWindow::interrupt_indexes()
4780 {
4781         mainprogress->cancelled = 1;
4782         mainindexes->interrupt_build();
4783         return 0;
4784 }
4785
4786
4787
4788 void MWindow::next_time_format()
4789 {
4790         switch( edl->session->time_format ) {
4791         case TIME_HMS:          edl->session->time_format = TIME_HMSF;         break;
4792         case TIME_HMSF:         edl->session->time_format = TIME_TIMECODE;     break;
4793         case TIME_TIMECODE:     edl->session->time_format = TIME_FRAMES;       break;
4794         case TIME_FRAMES:       edl->session->time_format = TIME_SAMPLES;      break;
4795         case TIME_SAMPLES:      edl->session->time_format = TIME_SAMPLES_HEX;  break;
4796         case TIME_SAMPLES_HEX:  edl->session->time_format = TIME_SECONDS;      break;
4797         case TIME_SECONDS:      edl->session->time_format = TIME_FEET_FRAMES;  break;
4798         case TIME_FEET_FRAMES:  edl->session->time_format = TIME_HMS;          break;
4799         }
4800         time_format_common();
4801 }
4802
4803 void MWindow::prev_time_format()
4804 {
4805         switch( edl->session->time_format ) {
4806         case TIME_HMS:          edl->session->time_format = TIME_FEET_FRAMES;  break;
4807         case TIME_HMSF:         edl->session->time_format = TIME_HMS;          break;
4808         case TIME_TIMECODE:     edl->session->time_format = TIME_HMSF;         break;
4809         case TIME_FRAMES:       edl->session->time_format = TIME_TIMECODE;     break;
4810         case TIME_SAMPLES:      edl->session->time_format = TIME_FRAMES;       break;
4811         case TIME_SAMPLES_HEX:  edl->session->time_format = TIME_SAMPLES;      break;
4812         case TIME_SECONDS:      edl->session->time_format = TIME_SAMPLES_HEX;  break;
4813         case TIME_FEET_FRAMES:  edl->session->time_format = TIME_SECONDS;      break;
4814         }
4815
4816         time_format_common();
4817 }
4818
4819 void MWindow::time_format_common()
4820 {
4821         gui->lock_window("MWindow::next_time_format");
4822         gui->redraw_time_dependancies();
4823
4824
4825         char string[BCTEXTLEN], string2[BCTEXTLEN];
4826         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
4827         gui->show_message(string);
4828         gui->flush();
4829         gui->unlock_window();
4830 }
4831
4832
4833 int MWindow::set_filename(const char *filename)
4834 {
4835         if( filename != session->filename )
4836                 strcpy(session->filename, filename);
4837         if( filename != edl->path )
4838                 strcpy(edl->path, filename);
4839         return set_titlebar(filename);
4840 }
4841
4842 int MWindow::set_titlebar(const char *filename)
4843 {
4844         if( !gui ) return 0;
4845         if( filename[0] ) {
4846                 FileSystem dir;
4847                 char string[BCTEXTLEN], string2[BCTEXTLEN];
4848                 dir.extract_name(string, filename);
4849                 sprintf(string2, PROGRAM_NAME ": %s", string);
4850                 gui->set_title(string2);
4851         }
4852         else
4853                 gui->set_title(PROGRAM_NAME);
4854         return 0;
4855 }
4856
4857
4858 int MWindow::set_loop_boundaries()
4859 {
4860         double start = edl->local_session->get_selectionstart();
4861         double end = edl->local_session->get_selectionend();
4862
4863         if(start !=
4864                 end)
4865         {
4866                 ;
4867         }
4868         else
4869         if(edl->tracks->total_length())
4870         {
4871                 start = 0;
4872                 end = edl->tracks->total_length();
4873         }
4874         else
4875         {
4876                 start = end = 0;
4877         }
4878
4879         if(edl->local_session->loop_playback && start != end)
4880         {
4881                 edl->local_session->loop_start = start;
4882                 edl->local_session->loop_end = end;
4883         }
4884         return 0;
4885 }
4886
4887
4888
4889
4890
4891
4892
4893 int MWindow::reset_meters()
4894 {
4895         cwindow->gui->lock_window("MWindow::reset_meters 1");
4896         cwindow->gui->meters->reset_meters();
4897         cwindow->gui->unlock_window();
4898
4899         for(int j = 0; j < vwindows.size(); j++) {
4900                 VWindow *vwindow = vwindows[j];
4901                 if( !vwindow->is_running() ) continue;
4902                 vwindow->gui->lock_window("MWindow::reset_meters 2");
4903                 vwindow->gui->meters->reset_meters();
4904                 vwindow->gui->unlock_window();
4905         }
4906
4907         lwindow->gui->lock_window("MWindow::reset_meters 3");
4908         lwindow->gui->panel->reset_meters();
4909         lwindow->gui->unlock_window();
4910
4911         gui->lock_window("MWindow::reset_meters 4");
4912         gui->reset_meters();
4913         gui->unlock_window();
4914         return 0;
4915 }
4916
4917
4918 void MWindow::resync_guis()
4919 {
4920 // Update GUIs
4921         restart_brender();
4922         gui->lock_window("MWindow::resync_guis");
4923         gui->update(1, NORMAL_DRAW, 1, 1, 1, 1, 0);
4924         gui->unlock_window();
4925
4926         cwindow->gui->lock_window("MWindow::resync_guis");
4927         cwindow->gui->resize_event(cwindow->gui->get_w(),
4928                 cwindow->gui->get_h());
4929         int channels = edl->session->audio_channels;
4930         cwindow->gui->meters->set_meters(channels, 1);
4931         cwindow->gui->flush();
4932         cwindow->gui->unlock_window();
4933
4934         for(int i = 0; i < vwindows.size(); i++) {
4935                 VWindow *vwindow = vwindows[i];
4936                 if( !vwindow->is_running() ) continue;
4937                 vwindow->gui->lock_window("MWindow::resync_guis");
4938                 vwindow->gui->resize_event(vwindow->gui->get_w(),
4939                         vwindow->gui->get_h());
4940                 vwindow->gui->meters->set_meters(channels, 1);
4941                 vwindow->gui->flush();
4942                 vwindow->gui->unlock_window();
4943         }
4944
4945         lwindow->gui->lock_window("MWindow::resync_guis");
4946         lwindow->gui->panel->set_meters(channels, 1);
4947         lwindow->gui->flush();
4948         lwindow->gui->unlock_window();
4949 #ifdef GLx4
4950 // Warn user
4951         if(((edl->session->output_w % 4) ||
4952                 (edl->session->output_h % 4)) &&
4953                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
4954         {
4955                 MainError::show_error(
4956                         _("This project's dimensions are not multiples of 4 so\n"
4957                         "it can't be rendered by OpenGL."));
4958         }
4959 #endif
4960
4961 // Flash frame
4962         sync_parameters(CHANGE_ALL);
4963 }
4964
4965 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
4966 {
4967         File *file = new File;
4968         EDLSession *session = edl->session;
4969         double old_framerate = session->frame_rate;
4970         double old_samplerate = session->sample_rate;
4971         int old_auto_keyframes = session->auto_keyframes;
4972         session->auto_keyframes = 0;
4973         int result = file->open_file(preferences, asset, 1, 0);
4974         if( !result && delete_tracks > 0 )
4975                 undo_before();
4976         int video_layers = asset->get_video_layers();
4977         if( !result && asset->video_data && vstream < video_layers ) {
4978                 // try to get asset up to date, may fail
4979                 file->select_video_stream(asset, vstream);
4980                 // either way use what was/is there.
4981                 double framerate = asset->get_frame_rate();
4982                 int width = asset->get_w();
4983                 int height = asset->get_h();
4984 #ifdef GLx4
4985                 // must be multiple of 4 for opengl
4986                 width = (width+3) & ~3;  height = (height+3) & ~3;
4987 #endif
4988                 int driver = session->playback_config->vconfig->driver;
4989                 int color_model = file->get_best_colormodel(asset, driver);
4990 //              color_model = BC_CModels::is_yuv(color_model) ?
4991 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
4992 //                      BC_CModels::is_float(color_model) ?
4993 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
4994 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
4995 // have alpha for now
4996                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
4997                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
4998                 session->color_model = color_model;
4999                 session->output_w = width;
5000                 session->output_h = height;
5001                 session->frame_rate = framerate;
5002                 // not, asset->actual_width/actual_height
5003                 asset->width = session->output_w;
5004                 asset->height = session->output_h;
5005                 asset->frame_rate = session->frame_rate;
5006                 create_aspect_ratio(session->aspect_w, session->aspect_h,
5007                         session->output_w, session->output_h);
5008                 Track *track = edl->tracks->first;
5009                 for( Track *next_track=0; track; track=next_track ) {
5010                         next_track = track->next;
5011                         if( track->data_type != TRACK_VIDEO ) continue;
5012                         if( delete_tracks ) {
5013                                 Edit *edit = track->edits->first;
5014                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
5015                                         next_edit = edit->next;
5016                                         if( edit->channel != vstream ||
5017                                             !edit->asset || !edit->asset->is_asset ||
5018                                             !asset->equivalent(*edit->asset,1,1,edl) )
5019                                                 delete edit;
5020                                 }
5021                         }
5022                         if( track->edits->first ) {
5023                                 track->track_w = edl->session->output_w;
5024                                 track->track_h = edl->session->output_h;
5025                         }
5026                         else if( delete_tracks )
5027                                 edl->tracks->delete_track(track, 0);
5028                 }
5029                 edl->retrack();
5030                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
5031         }
5032         if( !result && asset->audio_data && asset->channels > 0 ) {
5033                 session->sample_rate = asset->get_sample_rate();
5034                 int64_t channel_mask = 0;
5035                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
5036                         file->get_audio_for_video(vstream, astream, channel_mask);
5037                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
5038                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
5039                 int channels = 0;
5040                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
5041                 if( channels < 1 ) channels = 1;
5042                 if( channels > 6 ) channels = 6;
5043                 session->audio_tracks = session->audio_channels = channels;
5044
5045                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
5046                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
5047                 remap_audio(MWindow::AUDIO_1_TO_1);
5048
5049                 if( delete_tracks ) {
5050                         Track *track = edl->tracks->first;
5051                         for( Track *next_track=0; track; track=next_track ) {
5052                                 next_track = track->next;
5053                                 if( track->data_type != TRACK_AUDIO ) continue;
5054                                 Edit *edit = track->edits->first;
5055                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
5056                                         next_edit = edit->next;
5057                                         if( !((1<<edit->channel) & channel_mask) ||
5058                                             !edit->asset || !edit->asset->is_asset ||
5059                                             !asset->equivalent(*edit->asset,1,1,edl) )
5060                                                 delete edit;
5061                                 }
5062                                 if( !track->edits->first )
5063                                         edl->tracks->delete_track(track, 0);
5064                         }
5065                 }
5066                 edl->rechannel();
5067                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
5068         }
5069         delete file;
5070         session->auto_keyframes = old_auto_keyframes;
5071         if( !result && delete_tracks > 0 ) {
5072                 save_backup();
5073                 undo_after(_("select asset"), LOAD_ALL);
5074         }
5075         resync_guis();
5076         return result;
5077 }
5078
5079 int MWindow::select_asset(int vtrack, int delete_tracks)
5080 {
5081         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
5082         if( !track )
5083                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
5084         if( !track ) return 1;
5085         Edit *edit = track->edits->first;
5086         if( !edit ) return 1;
5087         Asset *asset = edit->asset;
5088         if( !asset || !asset->is_asset ) return 1;
5089         return select_asset(asset, edit->channel, 0, delete_tracks);
5090 }
5091
5092 void MWindow::dump_plugindb(FILE *fp)
5093 {
5094         if( !plugindb ) return;
5095         for(int i = 0; i < plugindb->total; i++)
5096                 plugindb->get(i)->dump(fp);
5097 }
5098
5099 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
5100 {
5101         Auto *current = 0;
5102         double unit_position = edl->local_session->get_selectionstart(1);
5103         unit_position = patch->track->to_units(unit_position, 0);
5104
5105         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
5106         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5107 }
5108
5109 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
5110 {
5111         Auto *current = 0;
5112         double unit_position = edl->local_session->get_selectionstart(1);
5113         unit_position = patch->track->to_units(unit_position, 0);
5114
5115         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
5116         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5117 }
5118
5119 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
5120 {
5121         Auto *current = 0;
5122         double unit_position = edl->local_session->get_selectionstart(1);
5123         unit_position = patch->track->to_units(unit_position, 0);
5124
5125         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
5126         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
5127 }
5128
5129 PatchGUI *MWindow::get_patchgui(Track *track)
5130 {
5131         PatchGUI *patchgui = 0;
5132         TimelinePane **panes = gui->pane;
5133         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
5134                 if( !panes[i] ) continue;
5135                 PatchBay *patchbay = panes[i]->patchbay;
5136                 if( !patchbay ) continue;
5137                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
5138                         if( patchbay->patches.values[j]->track == track )
5139                                 patchgui = patchbay->patches.values[j];
5140                 }
5141         }
5142         return patchgui;
5143 }
5144
5145 int MWindow::get_cpus(int out_w, int out_h)
5146 {
5147         if( !out_w ) out_w = edl->session->output_w;
5148         if( !out_h ) out_h = edl->session->output_h;
5149         int cpus = out_w*out_h/0x80000 + 1;
5150         if( cpus > preferences->processors )
5151                 cpus = preferences->processors;
5152         return cpus;
5153 }
5154 int MWindow::get_cpus()
5155 {
5156         return get_cpus(edl->session->output_w, edl->session->output_h);
5157 }
5158
5159 void MWindow::draw_trackmovement()
5160 {
5161         if( !redraw_tracks )
5162                 redraw_tracks = new DrawTrackMovement(this);
5163         redraw_tracks->start();
5164 }
5165
5166 DrawTrackMovement::DrawTrackMovement(MWindow *mwindow)
5167  : Thread(1, 0, 0)
5168 {
5169         this->mwindow = mwindow;
5170 }
5171 DrawTrackMovement::~DrawTrackMovement()
5172 {
5173         join();
5174 }
5175
5176 void DrawTrackMovement::run()
5177 {
5178         mwindow->gui->lock_window("DrawTrackMovement::run");
5179         mwindow->edl->tracks->update_y_pixels(mwindow->theme);
5180         mwindow->gui->draw_trackmovement();
5181         mwindow->gui->unlock_window();
5182 }
5183
5184
5185 ConfirmRefWindow::ConfirmRefWindow(MWindow *mwindow, char *path,
5186                 int px, int py, int cw, int ch)
5187  : BC_Window(_(PROGRAM_NAME ": Confirm update"), px, py, cw, ch, cw, ch)
5188 {
5189         this->mwindow = mwindow;
5190         this->path = path;
5191 }
5192
5193 ConfirmRefWindow::~ConfirmRefWindow()
5194 {
5195 }
5196
5197 void ConfirmRefWindow::create_objects()
5198 {
5199         lock_window("ConfirmRefWindow::create_objects()");
5200         int x = xS(10), y = yS(10), pad = yS(5);
5201         BC_Title *title;
5202         add_subwindow(title = new BC_Title(x, y, _("FileREF not updated:")));
5203         y += title->get_h() + pad;
5204         BC_TextBox *text_box;
5205         add_subwindow(text_box = new BC_TextBox(x,y, get_w()-2*x, 1, path));
5206         y += text_box->get_h() + 2*pad;
5207         add_subwindow(title = new BC_Title(x, y, _("Save file ref changes?")));
5208         add_subwindow(new BC_OKButton(this));
5209         add_subwindow(new BC_CancelButton(this));
5210         show_window();
5211         unlock_window();
5212 }
5213