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