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