blade and hard egdes, undo cache reset bug, sams ladspa icons, theme image access...
[goodguy/history.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 "bcdisplayinfo.h"
31 #include "bcsignals.h"
32 #include "bctimer.h"
33 #include "bctrace.h"
34 #include "bdcreate.h"
35 #include "brender.h"
36 #include "cache.h"
37 #include "channel.h"
38 #include "channeldb.h"
39 #include "channelinfo.h"
40 #include "clip.h"
41 #include "bccmodels.h"
42 #include "commercials.h"
43 #include "cplayback.h"
44 #include "ctimebar.h"
45 #include "cwindowgui.h"
46 #include "cwindow.h"
47 #include "cwindowtool.h"
48 #include "bchash.h"
49 #include "devicedvbinput.inc"
50 #include "dvdcreate.h"
51 #include "editpanel.h"
52 #include "edl.h"
53 #include "edlsession.h"
54 #include "errorbox.h"
55 #include "fileformat.h"
56 #include "file.h"
57 #include "filesystem.h"
58 #include "filexml.h"
59 #include "floatautos.h"
60 #include "framecache.h"
61 #include "gwindow.h"
62 #include "gwindowgui.h"
63 #include "keyframegui.h"
64 #include "indexfile.h"
65 #include "intautos.h"
66 #include "interlacemodes.h"
67 #include "language.h"
68 #include "levelwindowgui.h"
69 #include "levelwindow.h"
70 #include "loadfile.inc"
71 #include "localsession.h"
72 #include "maincursor.h"
73 #include "mainerror.h"
74 #include "mainindexes.h"
75 #include "mainmenu.h"
76 #include "mainprogress.h"
77 #include "mainsession.h"
78 #include "mainundo.h"
79 #include "mbuttons.h"
80 #include "mutex.h"
81 #include "mwindowgui.h"
82 #include "mwindow.h"
83 #include "nestededls.h"
84 #include "new.h"
85 #include "panautos.h"
86 #include "patchbay.h"
87 #include "playback3d.h"
88 #include "playbackengine.h"
89 #include "plugin.h"
90 #include "pluginserver.h"
91 #include "pluginset.h"
92 #include "preferences.h"
93 #include "proxy.h"
94 #include "record.h"
95 #include "recordmonitor.h"
96 #include "recordlabel.h"
97 #include "removefile.h"
98 #include "render.h"
99 #include "resourcethread.h"
100 #include "samplescroll.h"
101 #include "sha1.h"
102 #include "sighandler.h"
103 #include "splashgui.h"
104 #include "statusbar.h"
105 #include "theme.h"
106 #include "threadloader.h"
107 #include "timebar.h"
108 #include "timelinepane.h"
109 #include "tipwindow.h"
110 #include "trackcanvas.h"
111 #include "track.h"
112 #include "tracking.h"
113 #include "trackscroll.h"
114 #include "tracks.h"
115 #include "transition.h"
116 #include "transportque.h"
117 #include "vframe.h"
118 #include "vtrack.h"
119 #include "versioninfo.h"
120 #include "videodevice.inc"
121 #include "videowindow.h"
122 #include "vplayback.h"
123 #include "vwindowgui.h"
124 #include "vwindow.h"
125 #include "wavecache.h"
126 #include "wwindow.h"
127 #include "zoombar.h"
128 #include "zwindow.h"
129 #include "zwindowgui.h"
130 #include "exportedl.h"
131
132 #include "defaultformats.h"
133 #include "ntsczones.h"
134
135 #include <stdint.h>
136 #include <stdlib.h>
137 #include <unistd.h>
138 #include <fcntl.h>
139 #include <string.h>
140 #include <sys/types.h>
141 #include <sys/stat.h>
142 #include <sys/time.h>
143 #include <sys/mman.h>
144 #include <limits.h>
145 #include <errno.h>
146
147
148 extern "C"
149 {
150
151
152
153
154 // Hack for libdv to remove glib dependancy
155
156 // void
157 // g_log (const char    *log_domain,
158 //        int  log_level,
159 //        const char    *format,
160 //        ...)
161 // {
162 // }
163 //
164 // void
165 // g_logv (const char    *log_domain,
166 //        int  log_level,
167 //        const char    *format,
168 //        ...)
169 // {
170 // }
171 //
172
173 }
174
175
176
177 ArrayList<PluginServer*>* MWindow::plugindb = 0;
178 Commercials* MWindow::commercials = 0;
179
180
181 MWindow::MWindow()
182  : Thread(1, 0, 0)
183 {
184         run_lock = new Mutex("MWindow::run_lock");
185         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
186         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
187         vwindows_lock = new Mutex("MWindow::vwindows_lock");
188         zwindows_lock = new Mutex("MWindow::zwindows_lock");
189         brender_lock = new Mutex("MWindow::brender_lock");
190         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
191
192         playback_3d = 0;
193         splash_window = 0;
194         undo = 0;
195         defaults = 0;
196         assets = 0;
197         //commercials = 0;
198         commercial_active = 0;
199         audio_cache = 0;
200         video_cache = 0;
201         frame_cache = 0;
202         wave_cache = 0;
203         preferences = 0;
204         session = 0;
205         theme = 0;
206         mainindexes = 0;
207         mainprogress = 0;
208         brender = 0;
209         brender_active = 0;
210         strcpy(cin_lang,"en");
211         channeldb_buz =  new ChannelDB;
212         channeldb_v4l2jpeg =  new ChannelDB;
213         //file_server = 0;
214         plugin_guis = 0;
215         dead_plugins = 0;
216         keyframe_threads = 0;
217         create_bd = 0;
218         create_dvd = 0;
219         batch_render = 0;
220         render = 0;
221         edl = 0;
222         gui = 0;
223         cwindow = 0;
224         awindow = 0;
225         gwindow = 0;
226         twindow = 0;
227         wwindow = 0;
228         lwindow = 0;
229         sighandler = 0;
230         restart_status = 0;
231         screens = 1;
232         in_destructor = 0;
233 }
234
235
236 // Need to delete brender temporary here.
237 MWindow::~MWindow()
238 {
239         run_lock->lock("MWindow::~MWindow");
240         stop_playback(1);
241         in_destructor = 1;
242 //printf("MWindow::~MWindow %d\n", __LINE__);
243         gui->stop_drawing();
244         gui->remote_control->deactivate();
245         gui->record->stop();
246 #ifdef HAVE_DVB
247         gui->channel_info->stop();
248 #endif
249         delete create_bd;       create_bd = 0;
250         delete create_dvd;      create_dvd = 0;
251         delete batch_render;    batch_render = 0;
252         delete render;          render = 0;
253         commit_commercial();
254         if( commercials && !commercials->remove_user() ) commercials = 0;
255
256 // Save defaults for open plugins
257         plugin_gui_lock->lock("MWindow::~MWindow");
258         for(int i = 0; i < plugin_guis->size(); i++) {
259                 plugin_guis->get(i)->hide_gui();
260                 delete_plugin(plugin_guis->get(i));
261         }
262         plugin_gui_lock->unlock();
263         hide_keyframe_guis();
264         clean_indexes();
265         save_defaults();
266 // Give up and go to a movie
267 //  cant run valgrind if this is used
268
269         gui->del_keyboard_listener(
270                 (int (BC_WindowBase::*)(BC_WindowBase *))
271                 &MWindowGUI::keyboard_listener);
272 #if 0
273 // release the hounds
274         if( awindow && awindow->gui ) awindow->gui->close(0);
275         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
276         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
277         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
278         if( twindow && twindow->is_running() ) twindow->close_window();
279         if( wwindow && wwindow->is_running() ) wwindow->close_window();
280         vwindows.remove_all_objects();
281         zwindows.remove_all_objects();
282         gui->close(0);
283         if( awindow ) awindow->join();
284         if( cwindow ) cwindow->join();
285         if( lwindow ) lwindow->join();
286         if( twindow ) twindow->join();
287         if( wwindow ) wwindow->join();
288         if( gwindow ) gwindow->join();
289         join();
290 #else
291 // one at a time, or nouveau chokes
292 #define close_gui(win) if( win ) { \
293   if( win->gui ) win->gui->close(0); \
294   win->join(); }
295         close_gui(awindow);
296         close_gui(cwindow);
297         close_gui(lwindow);
298         close_gui(gwindow);
299         close_gui(twindow);
300         close_gui(wwindow);
301         vwindows.remove_all_objects();
302         zwindows.remove_all_objects();
303         gui->close(0);
304         join();
305 #endif
306         reset_caches();
307         dead_plugins->remove_all_objects();
308 // must delete theme before destroying plugindb
309 //  theme destructor will be deleted by delete_plugins
310         delete theme;           theme = 0;
311         delete_plugins();
312         finit_error();
313         keyframe_threads->remove_all_objects();
314         colormodels.remove_all_objects();
315         delete awindow;         awindow = 0;
316         delete lwindow;         lwindow = 0;
317         delete twindow;         twindow = 0;
318         delete wwindow;         wwindow = 0;
319         delete gwindow;         gwindow = 0;
320         delete cwindow;         cwindow = 0;
321         delete gui;             gui = 0;
322         //delete file_server;  file_server = 0; // reusable
323         delete mainindexes;     mainindexes = 0;
324         delete mainprogress;    mainprogress = 0;
325         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
326         delete video_cache;     video_cache = 0;  // delete the cache after the assets
327         delete frame_cache;     frame_cache = 0;
328         delete wave_cache;      wave_cache = 0;
329         delete plugin_guis;     plugin_guis = 0;
330         delete dead_plugins;    dead_plugins = 0;
331         delete keyframe_threads;  keyframe_threads = 0;
332         delete undo;            undo = 0;
333         delete preferences;     preferences = 0;
334         delete exportedl;       exportedl = 0;
335         delete session;         session = 0;
336         delete defaults;        defaults = 0;
337         delete assets;          assets = 0;
338         delete splash_window;   splash_window = 0;
339         if( !edl->Garbage::remove_user() ) edl = 0;
340         delete channeldb_buz;
341         delete channeldb_v4l2jpeg;
342 // This must be last thread to exit
343         delete playback_3d;     playback_3d = 0;
344         delete dead_plugin_lock;
345         delete plugin_gui_lock;
346         delete vwindows_lock;
347         delete zwindows_lock;
348         delete brender_lock;
349         delete keyframe_gui_lock;
350         colormodels.remove_all_objects();
351         interlace_project_modes.remove_all_objects();
352         interlace_asset_modes.remove_all_objects();
353         interlace_asset_fixmethods.remove_all_objects();
354         sighandler->terminate();
355         delete sighandler;
356         delete run_lock;
357 }
358
359
360 void MWindow::quit()
361 {
362         gui->set_done(0);
363 }
364
365 void MWindow::init_error()
366 {
367         MainError::init_error(this);
368 }
369
370 void MWindow::finit_error()
371 {
372         MainError::finit_error();
373 }
374
375 void MWindow::create_defaults_path(char *string, const char *config_file)
376 {
377 // set the .bcast path
378         FileSystem fs;
379
380         sprintf(string, "%s/", File::get_config_path());
381         fs.complete_path(string);
382         if(!fs.is_dir(string))
383                 fs.create_dir(string);
384
385 // load the defaults
386         strcat(string, config_file);
387 }
388 const char *MWindow::default_std()
389 {
390         char buf[BCTEXTLEN], *p = 0;
391
392         int fd = open(TIMEZONE_NAME, O_RDONLY);
393         if( fd >= 0 ) {
394                 int l = read(fd, buf, sizeof(buf)-1);
395                 close(fd);
396                 if( l > 0 ) {
397                         if( buf[l-1] == '\n' ) --l;
398                         buf[l] = 0;
399                         p = buf;
400                 }
401         }
402         if( !p ) {
403                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
404                 if( l > 0 ) {
405                         buf[l] = 0;
406                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
407                         p += strlen(ZONEINFO_STR);
408                 }
409         }
410
411         if( p ) {
412                 for( int i=0; ntsc_zones[i]; ++i ) {
413                         if( !strcmp(ntsc_zones[i], p) )
414                                 return "NTSC";
415                 }
416         }
417
418         p = getenv("TZ");
419         if( p ) {
420                 for( int i=0; ntsc_zones[i]; ++i ) {
421                         if( !strcmp(ntsc_zones[i], p) )
422                                 return "NTSC";
423                 }
424         }
425
426 //__timezone: Seconds west of UTC.  240sec/deg
427         double tz_deg = -__timezone / 240.;
428 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
429         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
430 }
431
432 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
433 {
434         struct formatpresets *fpr;
435
436         for(fpr = &format_presets[0]; fpr->name; fpr++)
437         {
438                 if(strcmp(_(fpr->name), preset) == 0)
439                 {
440                         session->audio_channels = fpr->audio_channels;
441                         session->audio_tracks = fpr->audio_tracks;
442                         session->sample_rate = fpr->sample_rate;
443                         session->video_channels = fpr->video_channels;
444                         session->video_tracks = fpr->video_tracks;
445                         session->frame_rate = fpr->frame_rate;
446                         session->output_w = fpr->output_w;
447                         session->output_h = fpr->output_h;
448                         session->aspect_w = fpr->aspect_w;
449                         session->aspect_h = fpr->aspect_h;
450                         session->interlace_mode = fpr->interlace_mode;
451                         session->color_model = fpr->color_model;
452                         return;
453                 }
454         }
455 }
456
457 const char *MWindow::get_preset_name(int index)
458 {
459         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
460                 return "Error";
461         return _(format_presets[index].name);
462 }
463
464
465 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
466 {
467         char path[BCTEXTLEN];
468 // Use user supplied path
469         if(config_path[0])
470                 strcpy(path, config_path);
471         else
472                 create_defaults_path(path, CONFIG_FILE);
473
474         defaults = new BC_Hash(path);
475         defaults->load();
476 }
477
478
479 void MWindow::check_language()
480 {
481         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
482         const char *env_lang = getenv("LANGUAGE");
483         if( !env_lang ) env_lang = getenv("LC_ALL");
484         if( !env_lang ) env_lang = getenv("LANG");
485         if( !env_lang ) {
486                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
487                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
488                 env_lang = curr_lang;
489         }
490         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
491         defaults->get("LAST_LANG",last_lang);
492         if( strcmp(env_lang,last_lang)) {
493                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
494                 defaults->update("LAST_LANG",env_lang);
495                 char plugin_path[BCTEXTLEN];
496                 create_defaults_path(plugin_path, PLUGIN_FILE);
497                 ::remove(plugin_path);
498                 char ladspa_path[BCTEXTLEN];
499                 create_defaults_path(ladspa_path, LADSPA_FILE);
500                 ::remove(ladspa_path);
501                 defaults->save();
502         }
503         if( strlen(env_lang) > 1 &&
504             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
505                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
506         }
507         else
508                 strcpy(cin_lang, "en");
509 }
510
511 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
512 {
513         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
514         if( plug_dir ) {
515                 const char *dp = plug_dir;
516                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
517                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
518         }
519         strcpy(path, bp);
520         delete [] base_path;
521 }
522
523 int MWindow::load_plugin_index(MWindow *mwindow, const char *index_path, const char *plugin_dir)
524 {
525 // load index
526         FILE *fp = fopen(index_path, "r");
527         if( !fp ) return -1;
528
529         int ret = 0;
530         char index_line[BCTEXTLEN];
531         int index_version = -1, len = strlen(plugin_dir);
532         if( !fgets(index_line, BCTEXTLEN, fp) ||
533             sscanf(index_line, "%d", &index_version) != 1 ||
534             index_version != PLUGIN_FILE_VERSION ||
535             !fgets(index_line, BCTEXTLEN, fp) ||
536             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
537             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
538
539         ArrayList<PluginServer*> plugins;
540         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
541                 if( index_line[0] == ';' ) continue;
542                 if( index_line[0] == '#' ) continue;
543                 int type = PLUGIN_TYPE_UNKNOWN;
544                 char path[BCTEXTLEN], title[BCTEXTLEN];
545                 int64_t mtime = 0;
546                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
547                         ret = 1; continue;
548                 }
549                 PluginServer *server = 0;
550                 switch( type ) {
551                 case PLUGIN_TYPE_BUILTIN:
552                 case PLUGIN_TYPE_EXECUTABLE:
553                 case PLUGIN_TYPE_LADSPA: {
554                         char plugin_path[BCTEXTLEN];  struct stat st;
555                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
556                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
557                                 ret = 1; continue;
558                         }
559                         server = new PluginServer(mwindow, plugin_path, type);
560                         break; }
561                 case PLUGIN_TYPE_FFMPEG: {
562                         server = new_ffmpeg_server(mwindow, path);
563                         break; }
564                 }
565                 if( !server ) continue;
566                 plugins.append(server);
567 // Create plugin server from index entry
568                 server->set_title(title);
569                 if( server->read_table(index_line) ) {
570                         ret = 1;  continue;
571                 }
572         }
573         fclose(fp);
574
575         if( !ret )
576                 ret = check_plugin_index(plugins, plugin_dir, ".");
577
578         if( !ret )
579                 add_plugins(plugins);
580         else
581                 plugins.remove_all_objects();
582
583         return ret;
584 }
585
586 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
587         const char *plug_dir, const char *plug_path)
588 {
589         char plugin_path[BCTEXTLEN];
590         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
591         FileSystem fs;
592         fs.set_filter( "[*.plugin][*.so]" );
593         if( fs.update(plugin_path) )
594                 return 1;
595
596         for( int i=0; i<fs.dir_list.total; ++i ) {
597                 char fs_path[BCTEXTLEN];
598                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
599                 if( fs.is_dir(fs_path) ) {
600                         get_plugin_path(plugin_path, plug_dir, fs_path);
601                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
602                                 return 1;
603                 }
604                 else if( !plugin_exists(fs_path, plugins) )
605                         return 1;
606         }
607         return 0;
608 }
609
610
611 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
612 {
613         if( !plugindb )
614                 plugindb = new ArrayList<PluginServer*>;
615         init_ffmpeg();
616         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
617         create_defaults_path(index_path, PLUGIN_FILE);
618         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
619         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
620         if( !load_plugin_index(mwindow, index_path, plugin_path) ) return 1;
621         printf("init plugin index: %s\n", plugin_path);
622         FILE *fp = fopen(index_path,"w");
623         if( !fp ) {
624                 fprintf(stderr,_("MWindow::init_plugins: "
625                         "can't create plugin index: %s\n"), index_path);
626                 return 1;
627         }
628         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
629         fprintf(fp, "%s\n", plugin_path);
630         init_plugin_index(mwindow, preferences, fp, plugin_path);
631         init_ffmpeg_index(mwindow, preferences, fp);
632         fclose(fp);
633         return load_plugin_index(mwindow, index_path, plugin_path);
634 }
635
636 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
637 {
638         char *path = getenv("LADSPA_PATH");
639         char ladspa_path[BCTEXTLEN];
640         if( !path ) {
641                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
642                 path = ladspa_path;
643         }
644         for( int len=0; *path; path+=len ) {
645                 char *cp = strchr(path,':');
646                 len = !cp ? strlen(path) : cp-path;
647                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
648                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
649                 if( cp ) ++len;
650                 char *plugin_dir = FileSystem::basepath(plugin_path);
651                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
652                 create_defaults_path(index_path, LADSPA_FILE);
653                 cp = index_path + strlen(index_path);
654                 for( char *bp=plugin_path; *bp!=0; ++bp )
655                         *cp++ = *bp=='/' ? '_' : *bp;
656                 *cp = 0;
657                 if( !load_plugin_index(mwindow, index_path, plugin_path) ) continue;
658                 if( init_ladspa_index(mwindow, preferences, index_path, plugin_path) ) continue;
659                 load_plugin_index(mwindow, index_path, plugin_path);
660         }
661         return 1;
662 }
663
664 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
665         FILE *fp, const char *plugin_dir)
666 {
667         int idx = PLUGIN_IDS;
668         if( plugindb ) {
669                 for( int i=0; i<plugindb->size(); ++i ) {
670                         PluginServer *server = plugindb->get(i);
671                         if( server->dir_idx >= idx )
672                                 idx = server->dir_idx+1;
673                 }
674         }
675         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
676 }
677
678 int MWindow::init_ladspa_index(MWindow *mwindow, Preferences *preferences,
679         const char *index_path, const char *plugin_dir)
680 {
681         char plugin_path[BCTEXTLEN], *path = FileSystem::basepath(plugin_dir);
682         strcpy(plugin_path, path);  delete [] path;
683         printf("init ladspa index: %s\n", plugin_dir);
684         FILE *fp = fopen(index_path,"w");
685         if( !fp ) {
686                 fprintf(stderr,_("MWindow::init_ladspa_index: "
687                         "can't create plugin index: %s\n"), index_path);
688                 return 1;
689         }
690         fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
691         fprintf(fp, "%s\n", plugin_dir);
692         init_plugin_index(mwindow, preferences, fp, plugin_path);
693         fclose(fp);
694         return 0;
695 }
696
697 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
698         const char *plug_dir, const char *plug_path, int &idx)
699 {
700         char plugin_path[BCTEXTLEN];
701         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
702         FileSystem fs;
703         fs.set_filter( "[*.plugin][*.so]" );
704         int result = fs.update(plugin_path);
705         if( result || !fs.dir_list.total ) return;
706         int vis_id = idx++;
707
708         for( int i=0; i<fs.dir_list.total; ++i ) {
709                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
710                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
711                 get_plugin_path(path, plug_dir, fs_path);
712                 if( fs.is_dir(fs_path) ) {
713                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
714                         continue;
715                 }
716                 if( plugin_exists(path) ) continue;
717                 struct stat st;
718                 if( stat(fs_path, &st) ) continue;
719                 int64_t mtime = st.st_mtime;
720                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
721                 result = server.open_plugin(1, preferences, 0, 0);
722                 if( !result ) {
723                         server.write_table(fp, path, vis_id, mtime);
724                         server.close_plugin();
725                 }
726                 else if( result == PLUGINSERVER_IS_LAD ) {
727                         int lad_index = 0;
728                         for(;;) {
729                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
730                                 ladspa.set_lad_index(lad_index++);
731                                 result = ladspa.open_plugin(1, preferences, 0, 0);
732                                 if( result ) break;
733                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
734                                 ladspa.close_plugin();
735                         }
736                 }
737         }
738 }
739
740 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
741 {
742         for( int i=0; i<plugins.size(); ++i )
743                 plugindb->append(plugins[i]);
744         plugins.remove_all();
745 }
746
747 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
748 {
749         const char *cfg_path = File::get_cindat_path();
750         char msg_path[BCTEXTLEN];  int txt = 0;
751         FILE *fp = 0;
752         if( BC_Resources::language[0] ) {
753                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
754                         cfg_path, lang);
755                 fp = fopen(msg_path, "r");
756         }
757         if( !fp ) {
758                 txt = 1;
759                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
760                         cfg_path);
761                 fp = fopen(msg_path, "r");
762         }
763         if( !fp ) return;
764         char text[BCTEXTLEN];
765         char *tp = text, *ep = tp + sizeof(text)-1;
766         char title[BCTEXTLEN];
767         title[0] = 0;
768         int no = 0;
769         for(;;) {
770                 ++no;  int done = 1;
771                 char line[BCTEXTLEN], *cp = line;
772                 if( fgets(line,sizeof(line)-1,fp) ) {
773                         if( *cp == '#' ) continue;
774                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
775                 }
776                 if( done ) {
777                         if( tp > text && *--tp == '\n' ) *tp = 0;
778                         if( title[0] ) {
779                                 tp = !txt ? title : _(title);
780                                 int idx = plugins.size();
781                                 while( --idx>=0 && strcmp(plugins[idx]->title, tp) );
782                                 if( idx >= 0 ) {
783                                         delete [] plugins[idx]->tip;
784                                         plugins[idx]->tip = cstrdup(text);
785                                 }
786                                 title[0] = 0;
787                         }
788                         if( done > 0 ) break;
789                         tp = text;  *tp = 0;
790                         char *dp = strchr(cp, ':');
791                         if( !dp ) {
792                                 printf("plugin tips: error on line %d\n", no);
793                                 continue;
794                         }
795                         char *bp = title;
796                         while( cp < dp ) *bp++ = *cp++;
797                         *bp = 0;
798                         ++cp;
799                 }
800
801                 while( *cp == ' ' || *cp == '\t' ) ++cp;
802                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
803         }
804         fclose(fp);
805 }
806
807 void MWindow::delete_plugins()
808 {
809         plugindb->remove_all_objects();
810         delete plugindb;
811         plugindb = 0;
812 }
813
814 void MWindow::search_plugindb(int do_audio,
815                 int do_video,
816                 int is_realtime,
817                 int is_transition,
818                 int is_theme,
819                 ArrayList<PluginServer*> &results)
820 {
821 // Get plugins
822         for(int i = 0; i < MWindow::plugindb->total; i++)
823         {
824                 PluginServer *current = MWindow::plugindb->get(i);
825
826                 if(current->audio == do_audio &&
827                         current->video == do_video &&
828                         (current->realtime == is_realtime || is_realtime < 0) &&
829                         current->transition == is_transition &&
830                         current->theme == is_theme)
831                         results.append(current);
832         }
833
834 // Alphabetize list by title
835         int done = 0;
836         while(!done)
837         {
838                 done = 1;
839
840                 for(int i = 0; i < results.total - 1; i++)
841                 {
842                         PluginServer *value1 = results[i];
843                         PluginServer *value2 = results[i + 1];
844                         if(strcmp(_(value1->title), _(value2->title)) > 0)
845                         {
846                                 done = 0;
847                                 results[i] = value2;
848                                 results[i + 1] = value1;
849                         }
850                 }
851         }
852 }
853
854 PluginServer* MWindow::scan_plugindb(char *title,
855                 int data_type)
856 {
857 //      if(data_type < 0)
858 //      {
859 //              printf("MWindow::scan_plugindb data_type < 0\n");
860 //              return 0;
861 //      }
862
863         for(int i = 0; i < plugindb->total; i++)
864         {
865                 PluginServer *server = plugindb->get(i);
866                 if(server->title &&
867                         !strcasecmp(server->title, title) &&
868                         (data_type < 0 ||
869                                 (data_type == TRACK_AUDIO && server->audio) ||
870                                 (data_type == TRACK_VIDEO && server->video)))
871                         return plugindb->get(i);
872         }
873         return 0;
874 }
875
876 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
877 {
878         for( int i=0; i<plugins.size(); ++i )
879                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
880         return 0;
881 }
882
883 int MWindow::plugin_exists(char *plugin_path)
884 {
885         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
886 }
887
888 void MWindow::init_preferences()
889 {
890         preferences = new Preferences;
891         preferences->load_defaults(defaults);
892         session = new MainSession(this);
893         session->load_defaults(defaults);
894         // set x11_host, screens, window_config
895         screens = session->set_default_x11_host();
896         BC_Signals::set_trap_hook(trap_hook, this);
897         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
898         BC_Signals::set_catch_intr(preferences->trap_sigintr);
899         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
900                 BC_Trace::enable_locks();
901         }
902         else {
903                 BC_Trace::disable_locks();
904         }
905         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
906         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
907         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
908 }
909
910 void MWindow::clean_indexes()
911 {
912         FileSystem fs;
913         int total_excess;
914         long oldest = 0;
915         int oldest_item = -1;
916         int result;
917         char string[BCTEXTLEN];
918         char string2[BCTEXTLEN];
919
920 // Delete extra indexes
921         fs.set_filter("*.idx");
922         fs.complete_path(preferences->index_directory);
923         fs.update(preferences->index_directory);
924 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
925
926 // Eliminate directories
927         result = 1;
928         while(result)
929         {
930                 result = 0;
931                 for(int i = 0; i < fs.dir_list.total && !result; i++)
932                 {
933                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
934                         if(fs.is_dir(string))
935                         {
936                                 delete fs.dir_list[i];
937                                 fs.dir_list.remove_number(i);
938                                 result = 1;
939                         }
940                 }
941         }
942         total_excess = fs.dir_list.total - preferences->index_count;
943
944 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
945         while(total_excess > 0)
946         {
947 // Get oldest
948                 for(int i = 0; i < fs.dir_list.total; i++)
949                 {
950                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
951
952                         if(i == 0 || fs.get_date(string) <= oldest)
953                         {
954                                 oldest = fs.get_date(string);
955                                 oldest_item = i;
956                         }
957                 }
958
959                 if(oldest_item >= 0)
960                 {
961 // Remove index file
962                         fs.join_names(string,
963                                 preferences->index_directory,
964                                 fs.dir_list[oldest_item]->name);
965 //printf("MWindow::clean_indexes 1 %s\n", string);
966                         if(remove(string))
967                                 perror("delete_indexes");
968                         delete fs.dir_list[oldest_item];
969                         fs.dir_list.remove_number(oldest_item);
970
971 // Remove table of contents if it exists
972                         strcpy(string2, string);
973                         char *ptr = strrchr(string2, '.');
974                         if(ptr)
975                         {
976 //printf("MWindow::clean_indexes 2 %s\n", string2);
977                                 sprintf(ptr, ".toc");
978                                 remove(string2);
979                                 sprintf(ptr, ".mkr");
980                                 remove(string2);
981                         }
982                 }
983
984                 total_excess--;
985         }
986 }
987
988 void MWindow::init_awindow()
989 {
990         awindow = new AWindow(this);
991         awindow->create_objects();
992 }
993
994 void MWindow::init_gwindow()
995 {
996         gwindow = new GWindow(this);
997         gwindow->create_objects();
998 }
999
1000 void MWindow::init_tipwindow()
1001 {
1002         TipWindow::load_tips(cin_lang);
1003         if( !twindow )
1004                 twindow = new TipWindow(this);
1005         twindow->start();
1006 }
1007
1008 void MWindow::show_warning(int *do_warning, const char *text)
1009 {
1010         if( do_warning && !*do_warning ) return;
1011         if( !wwindow )
1012                 wwindow = new WWindow(this);
1013         wwindow->show_warning(do_warning, text);
1014 }
1015
1016 int MWindow::wait_warning()
1017 {
1018         return wwindow->wait_result();
1019 }
1020
1021 void MWindow::init_theme()
1022 {
1023         Timer timer;
1024         theme = 0;
1025
1026         PluginServer *theme_plugin = 0;
1027         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1028                 if( plugindb->get(i)->theme &&
1029                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1030                         theme_plugin = plugindb->get(i);
1031         }
1032
1033         if( !theme_plugin )
1034                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1035                          preferences->theme);
1036
1037         const char *default_theme = _(DEFAULT_THEME);
1038         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1039                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1040                         default_theme);
1041                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1042                         if( plugindb->get(i)->theme &&
1043                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1044                                 theme_plugin = plugindb->get(i);
1045                 }
1046         }
1047
1048         if(!theme_plugin) {
1049                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1050                 exit(1);
1051         }
1052
1053         PluginServer *plugin = new PluginServer(*theme_plugin);
1054         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1055                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1056                         theme_plugin->title);
1057                 exit(1);
1058         }
1059
1060         theme = plugin->new_theme();
1061         theme->mwindow = this;
1062         strcpy(theme->path, plugin->path);
1063         delete plugin;
1064
1065 // Load default images & settings
1066         theme->Theme::initialize();
1067 // Load user images & settings
1068         theme->initialize();
1069 // Create menus with user colors
1070         theme->build_menus();
1071         init_menus();
1072
1073         theme->sort_image_sets();
1074         theme->check_used();
1075 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1076 }
1077
1078 void MWindow::init_3d()
1079 {
1080         playback_3d = new Playback3D(this);
1081         playback_3d->create_objects();
1082 }
1083
1084 void MWindow::init_edl()
1085 {
1086         edl = new EDL;
1087         edl->create_objects();
1088         fill_preset_defaults(default_standard, edl->session);
1089         edl->load_defaults(defaults);
1090         edl->session->brender_start = edl->session->brender_end = 0;
1091         edl->create_default_tracks();
1092         edl->tracks->update_y_pixels(theme);
1093 }
1094
1095 void MWindow::init_compositor()
1096 {
1097         cwindow = new CWindow(this);
1098         cwindow->create_objects();
1099 }
1100
1101 void MWindow::init_levelwindow()
1102 {
1103         lwindow = new LevelWindow(this);
1104         lwindow->create_objects();
1105 }
1106
1107 VWindow *MWindow::get_viewer(int start_it, int idx)
1108 {
1109         vwindows_lock->lock("MWindow::get_viewer");
1110         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1111         if( !vwindow ) idx = vwindows.size();
1112         while( !vwindow && --idx >= 0 ) {
1113                 VWindow *vwin = vwindows[idx];
1114                 if( !vwin->is_running() || !vwin->get_edl() )
1115                         vwindow = vwin;
1116         }
1117         if( !vwindow ) {
1118                 vwindow = new VWindow(this);
1119                 vwindow->load_defaults();
1120                 vwindow->create_objects();
1121                 vwindows.append(vwindow);
1122         }
1123         vwindows_lock->unlock();
1124         if( start_it ) vwindow->start();
1125         return vwindow;
1126 }
1127
1128 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1129 {
1130         zwindows_lock->lock("MWindow::get_mixer");
1131         if( !mixer ) mixer = edl->mixers.new_mixer();
1132         ZWindow *zwindow = 0;
1133         for( int i=0; !zwindow && i<zwindows.size(); ++i )
1134                 if( !zwindows[i]->is_running() ) zwindow = zwindows[i];
1135         if( !zwindow )
1136                 zwindows.append(zwindow = new ZWindow(this));
1137         zwindow->idx = mixer->idx;
1138         zwindows_lock->unlock();
1139         return zwindow;
1140 }
1141
1142 void MWindow::del_mixer(ZWindow *zwindow)
1143 {
1144         zwindows_lock->lock("MWindow::del_mixer 0");
1145         edl->mixers.del_mixer(zwindow->idx);
1146         zwindow->idx = -1;
1147         if( session->selected_zwindow >= 0 ) {
1148                 int i = zwindows.number_of(zwindow);
1149                 if( i >= 0 && i < session->selected_zwindow )
1150                         --session->selected_zwindow;
1151                 else if( i == session->selected_zwindow )
1152                         session->selected_zwindow = -1;
1153         }
1154         zwindows_lock->unlock();
1155         gui->lock_window("MWindow::del_mixer 1");
1156         gui->update_mixers(0, -1);
1157         gui->unlock_window();
1158 }
1159
1160 void MWindow::start_mixer()
1161 {
1162         Mixer *mixer = 0;
1163         ZWindow *zwindow = get_mixer(mixer);
1164         const char *title = 0;
1165
1166         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1167                 PatchGUI *patchgui = get_patchgui(track);
1168                 if( !patchgui || !patchgui->mixer ) continue;
1169                 mixer->mixer_ids.append(track->get_mixer_id());
1170                 if( !title ) title = track->title;
1171         }
1172
1173         session->selected_zwindow = -1;
1174         gui->lock_window("MWindow::start_mixer");
1175         gui->update_mixers(0, 0);
1176         gui->unlock_window();
1177
1178         zwindow->set_title(title);
1179         zwindow->start();
1180         queue_mixers(edl,CURRENT_FRAME,0,0,1,0);
1181 }
1182
1183 int MWindow::mixer_track_active(Track *track)
1184 {
1185         int i = session->selected_zwindow;
1186         if( i < 0 || i >= zwindows.size() ) return 0;
1187         ZWindow *zwindow = zwindows[i];
1188         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1189         if( !mixer ) return 0;
1190         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1191         return n >= 0 ? 1 : 0;
1192 }
1193
1194 void MWindow::update_mixer_tracks()
1195 {
1196         zwindows_lock->lock("MixPatch::handle_event");
1197         int i = session->selected_zwindow;
1198         if( i >= 0 && i < zwindows.size() ) {
1199                 ZWindow *zwindow = zwindows[i];
1200                 zwindow->update_mixer_ids();
1201         }
1202         zwindows_lock->unlock();
1203 }
1204
1205 void MWindow::queue_mixers(EDL *edl, int command, int wait_tracking,
1206                 int use_inout, int update_refresh, int toggle_audio)
1207 {
1208         zwindows_lock->lock("MWindow::queue_mixers");
1209         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1210                 ZWindow *zwindow = zwindows[vidx];
1211                 if( !zwindow->running() ) continue;
1212                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1213                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1214                 int k = -1;
1215                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1216                         if( track->data_type != TRACK_VIDEO ) continue;
1217                         int mixer_id = track->get_mixer_id();
1218                         k = mixer->mixer_ids.size();
1219                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1220                 }
1221                 if( k < 0 ) continue;
1222                 EDL *mixer_edl = new EDL(this->edl);
1223                 mixer_edl->create_objects();
1224                 mixer_edl->copy_all(edl);
1225                 mixer_edl->remove_vwindow_edls();
1226                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1227                         k = mixer->mixer_ids.size();
1228                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1229                         if( k >= 0 ) {
1230                                 track->record = 1;
1231                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1232                         }
1233                         else
1234                                 track->record = track->play = 0;
1235                 }
1236                 zwindow->change_source(mixer_edl);
1237                 zwindow->issue_command(command,
1238                         wait_tracking, use_inout, update_refresh, toggle_audio);
1239         }
1240         zwindows_lock->unlock();
1241 }
1242
1243 void MWindow::stop_mixers()
1244 {
1245         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1246                 ZWindow *zwindow = zwindows[vidx];
1247                 if( !zwindow->running() ) continue;
1248                 zwindow->issue_command(STOP, 0, 0, 0, 0);
1249         }
1250 }
1251
1252 int MWindow::select_zwindow(ZWindow *zwindow)
1253 {
1254         int ret = 0, n = zwindows.number_of(zwindow);
1255         if( session->selected_zwindow != n ) {
1256                 session->selected_zwindow = n;
1257                 for( int i=0; i<zwindows.size(); ++i ) {
1258                         ZWindow *zwindow = zwindows[i];
1259                         if( !zwindow->running() ) continue;
1260                         ZWindowGUI *zgui = zwindow->zgui;
1261                         zgui->lock_window("MWindow::select_zwindow 0");
1262                         zwindow->highlighted = i == n ? 1 : 0;
1263                         if( zgui->draw_overlays() )
1264                                 zgui->canvas->get_canvas()->flash(1);
1265                         zgui->unlock_window();
1266                 }
1267                 ret = 1;
1268                 gui->lock_window("MWindow::select_window 1");
1269                 gui->update_mixers(0, -1);
1270                 gui->unlock_window();
1271         }
1272         return ret;
1273 }
1274
1275
1276 void MWindow::init_cache()
1277 {
1278         audio_cache = new CICache(preferences);
1279         video_cache = new CICache(preferences);
1280         frame_cache = new FrameCache;
1281         wave_cache = new WaveCache;
1282 }
1283
1284 void MWindow::init_channeldb()
1285 {
1286         channeldb_buz->load("channeldb_buz");
1287         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1288 }
1289
1290 void MWindow::init_menus()
1291 {
1292         char string[BCTEXTLEN];
1293
1294         // Color Models
1295         BC_CModels::to_text(string, BC_RGB888);
1296         colormodels.append(new ColormodelItem(string, BC_RGB888));
1297         BC_CModels::to_text(string, BC_RGBA8888);
1298         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1299 //      BC_CModels::to_text(string, BC_RGB161616);
1300 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1301 //      BC_CModels::to_text(string, BC_RGBA16161616);
1302 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1303         BC_CModels::to_text(string, BC_RGB_FLOAT);
1304         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1305         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1306         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1307         BC_CModels::to_text(string, BC_YUV888);
1308         colormodels.append(new ColormodelItem(string, BC_YUV888));
1309         BC_CModels::to_text(string, BC_YUVA8888);
1310         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1311 //      BC_CModels::to_text(string, BC_YUV161616);
1312 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1313 //      BC_CModels::to_text(string, BC_YUVA16161616);
1314 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1315
1316 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1317                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1318
1319 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1320                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1321
1322 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1323                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1324
1325         // Interlacing Modes
1326         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1327
1328         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1329         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1330
1331         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1332         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1333
1334         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1335         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1336
1337         // Interlacing Fixing Methods
1338         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1339         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1340         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1341 }
1342
1343 void MWindow::init_indexes()
1344 {
1345         mainindexes = new MainIndexes(this);
1346         mainindexes->start_loop();
1347 }
1348
1349 void MWindow::init_gui()
1350 {
1351         gui = new MWindowGUI(this);
1352         gui->lock_window("MWindow::init_gui");
1353         gui->create_objects();
1354         gui->unlock_window();
1355         gui->load_defaults(defaults);
1356 }
1357
1358 void MWindow::init_signals()
1359 {
1360         sighandler = new SigHandler;
1361         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1362 ENABLE_BUFFER
1363 }
1364
1365 void MWindow::init_render()
1366 {
1367         render = new Render(this);
1368         create_bd = new CreateBD_Thread(this);
1369         create_dvd = new CreateDVD_Thread(this);
1370         batch_render = new BatchRenderThread(this);
1371 }
1372
1373 void MWindow::init_exportedl()
1374 {
1375         exportedl = new ExportEDL(this);
1376 }
1377
1378 void MWindow::init_brender()
1379 {
1380         if(preferences->use_brender && !brender)
1381         {
1382                 brender_lock->lock("MWindow::init_brender 1");
1383                 brender = new BRender(this);
1384                 brender->initialize();
1385                 session->brender_end = 0;
1386                 brender_lock->unlock();
1387         }
1388         else
1389         if(!preferences->use_brender && brender)
1390         {
1391                 brender_lock->lock("MWindow::init_brender 2");
1392                 delete brender;
1393                 brender = 0;
1394                 session->brender_end = 0;
1395                 brender_lock->unlock();
1396         }
1397         brender_active = 0;
1398         stop_brender();
1399 }
1400
1401 void MWindow::restart_brender()
1402 {
1403 //printf("MWindow::restart_brender 1\n");
1404         if( !brender_active || !preferences->use_brender ) return;
1405         if( !brender ) return;
1406         int locked  = gui->get_window_lock();
1407         if( locked ) gui->unlock_window();
1408         brender->restart(edl);
1409         if( locked ) gui->lock_window("MWindow::restart_brender");
1410 }
1411
1412 void MWindow::stop_brender()
1413 {
1414         if( !brender ) return;
1415         int locked  = gui->get_window_lock();
1416         if( locked ) gui->unlock_window();
1417         brender->stop();
1418         if( locked ) gui->lock_window("MWindow::stop_brender");
1419 }
1420
1421 int MWindow::brender_available(int position)
1422 {
1423         int result = 0;
1424         brender_lock->lock("MWindow::brender_available 1");
1425         if(brender && brender_active)
1426         {
1427                 if(brender->map_valid)
1428                 {
1429                         brender->map_lock->lock("MWindow::brender_available 2");
1430                         if(position < brender->map_size &&
1431                                 position >= 0)
1432                         {
1433 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1434                                 if(brender->map[position] == BRender::RENDERED)
1435                                         result = 1;
1436                         }
1437                         brender->map_lock->unlock();
1438                 }
1439         }
1440         brender_lock->unlock();
1441         return result;
1442 }
1443
1444 void MWindow::set_brender_active(int v, int update)
1445 {
1446         if( !preferences->use_brender ) v = 0;
1447         brender_active = v;
1448         gui->mainmenu->brender_active->set_checked(v);
1449         if( v != 0 ) {
1450                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1451                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1452
1453                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1454                         edl->session->brender_end = edl->tracks->total_video_length();
1455                 }
1456                 restart_brender();
1457         }
1458         else {
1459                 edl->session->brender_start = edl->session->brender_end = 0;
1460                 stop_brender();
1461         }
1462         if( update ) {
1463                 gui->update_timebar(0);
1464                 gui->draw_overlays(1);
1465         }
1466 }
1467
1468 int MWindow::has_commercials()
1469 {
1470         return theme->use_commercials;
1471 }
1472
1473 void MWindow::init_commercials()
1474 {
1475         if( !commercials ) {
1476                 commercials = new Commercials(this);
1477                 commercial_active = 0;
1478         }
1479         else
1480                 commercials->add_user();
1481 }
1482
1483 void MWindow::commit_commercial()
1484 {
1485         if( !commercial_active ) return;
1486         commercial_active = 0;
1487         if( !commercials ) return;
1488         commercials->commitDb();
1489 }
1490
1491 void MWindow::undo_commercial()
1492 {
1493         if( !commercial_active ) return;
1494         commercial_active = 0;
1495         if( !commercials ) return;
1496         commercials->undoDb();
1497 }
1498
1499 int MWindow::put_commercial()
1500 {
1501         double start = edl->local_session->get_selectionstart();
1502         double end = edl->local_session->get_selectionend();
1503         if( start >= end ) return 0;
1504
1505         const char *errmsg = 0;
1506         int count = 0;
1507         Tracks *tracks = edl->tracks;
1508         int result = 0;
1509         //check it
1510         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1511                 if( track->data_type != TRACK_VIDEO ) continue;
1512                 if( !track->record ) continue;
1513                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1514                 ++count;
1515                 int64_t units_start = track->to_units(start,0);
1516                 int64_t units_end = track->to_units(end,0);
1517                 Edits *edits = track->edits;
1518                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1519                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1520                 if(!edit1 && !edit2) continue;  // nothing selected
1521                 if(!edit2) {                    // edit2 beyond end of track
1522                         edit2 = edits->last;
1523                         units_end = edits->length();
1524                 }
1525                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1526                 Indexable *indexable = edit1->get_source();
1527                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1528         }
1529         //run it
1530         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1531                 if( track->data_type != TRACK_VIDEO ) continue;
1532                 if( !track->record ) continue;
1533                 int64_t units_start = track->to_units(start,0);
1534                 int64_t units_end = track->to_units(end,0);
1535                 Edits *edits = track->edits;
1536                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1537                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1538                 if(!edit1 && !edit2) continue;  // nothing selected
1539                 if(!edit2) {                    // edit2 beyond end of track
1540                         edit2 = edits->last;
1541                         units_end = edits->length();
1542                 }
1543                 Indexable *indexable = edit1->get_source();
1544                 Asset *asset = (Asset *)indexable;
1545                 File *file = video_cache->check_out(asset, edl);
1546                 if( !file ) { errmsg = _("no file"); break; }
1547                 int64_t edit_length = units_end - units_start;
1548                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1549                 result = commercials->put_clip(file, edit1->channel,
1550                         track->from_units(edit_start), track->from_units(edit_length));
1551                 video_cache->check_in(asset);
1552                 if( result ) { errmsg = _("db failed"); break; }
1553         }
1554         if( errmsg ) {
1555                 char string[BCTEXTLEN];
1556                 sprintf(string, _("put_commercial: %s"), errmsg);
1557                 MainError::show_error(string);
1558                 undo_commercial();
1559                 result = 1;
1560         }
1561         return result;
1562 }
1563
1564 void MWindow::stop_playback(int wait)
1565 {
1566         int locked  = gui->get_window_lock();
1567         if( locked ) gui->unlock_window();
1568         gui->stop_drawing();
1569
1570         cwindow->stop_playback();
1571
1572         for(int i = 0; i < vwindows.size(); i++) {
1573                 VWindow *vwindow = vwindows[i];
1574                 if( !vwindow->is_running() ) continue;
1575                 vwindow->stop_playback();
1576         }
1577         for(int i = 0; i < zwindows.size(); i++) {
1578                 ZWindow *zwindow = zwindows[i];
1579                 if( !zwindow->is_running() ) continue;
1580                 zwindow->stop_playback();
1581         }
1582         if( locked ) gui->lock_window("MWindow::stop_playback");
1583 }
1584
1585 int MWindow::load_filenames(ArrayList<char*> *filenames,
1586         int load_mode,
1587         int update_filename)
1588 {
1589         ArrayList<EDL*> new_edls;
1590         ArrayList<Asset*> new_assets;
1591         ArrayList<File*> new_files;
1592         const int debug = 0;
1593 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1594
1595 //      save_defaults();
1596         gui->start_hourglass();
1597
1598 // Need to stop playback since tracking depends on the EDL not getting
1599 // deleted.
1600         stop_playback(1);
1601
1602 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1603         undo->update_undo_before();
1604
1605
1606 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1607
1608 // Define new_edls and new_assets to load
1609         int result = 0, ftype = -1;
1610         for(int i = 0; i < filenames->size(); i++)
1611         {
1612 // Get type of file
1613                 File *new_file = new File;
1614                 Asset *new_asset = new Asset(filenames->get(i));
1615                 EDL *new_edl = new EDL;
1616                 char string[BCTEXTLEN];
1617
1618                 new_edl->create_objects();
1619                 new_edl->copy_session(edl);
1620                 new_file->set_program(edl->session->program_no);
1621
1622                 sprintf(string, _("Loading %s"), new_asset->path);
1623                 gui->show_message(string);
1624 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1625
1626                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1627 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1628
1629                 result = 1;
1630                 switch(ftype)
1631                 {
1632 // Convert media file to EDL
1633                         case FILE_OK:
1634 // Warn about odd image dimensions
1635                                 if(new_asset->video_data &&
1636                                         ((new_asset->width % 2) ||
1637                                         (new_asset->height % 2)))
1638                                 {
1639                                         char string[BCTEXTLEN];
1640                                         sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1641                                                 new_asset->path,
1642                                                 new_asset->width,
1643                                                 new_asset->height);
1644                                         MainError::show_error(string);
1645                                 }
1646
1647                                 if(new_asset->program >= 0 &&
1648                                         edl->session->program_no != new_asset->program)
1649                                 {
1650                                         char string[BCTEXTLEN];
1651                                         sprintf(string, _("%s's index was built for program number %d\n"
1652                                                 "Playback preference is %d.\n  Using program %d."),
1653                                                 new_asset->path, new_asset->program,
1654                                                 edl->session->program_no, new_asset->program);
1655                                         MainError::show_error(string);
1656                                 }
1657
1658
1659                                 if(load_mode != LOADMODE_RESOURCESONLY)
1660                                 {
1661                                         RecordLabels *labels = edl->session->label_cells ?
1662                                                 new RecordLabels(new_file) : 0;
1663                                         asset_to_edl(new_edl, new_asset, labels);
1664                                         new_edls.append(new_edl);
1665                                         new_asset->Garbage::remove_user();
1666                                         delete labels;
1667                                         new_asset = 0;
1668                                 }
1669                                 else
1670                                 {
1671                                         new_assets.append(new_asset);
1672                                         new_asset = 0;
1673                                 }
1674
1675 // Set filename to nothing for assets since save EDL would overwrite them.
1676                                 if(load_mode == LOADMODE_REPLACE ||
1677                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1678                                 {
1679                                         set_filename("");
1680 // Reset timeline position
1681                                         for(int i = 0; i < TOTAL_PANES; i++)
1682                                         {
1683                                                 new_edl->local_session->view_start[i] = 0;
1684                                                 new_edl->local_session->track_start[i] = 0;
1685                                         }
1686                                 }
1687
1688                                 result = 0;
1689                                 break;
1690
1691 // File not found
1692                         case FILE_NOT_FOUND:
1693                                 sprintf(string, _("Failed to open %s"), new_asset->path);
1694                                 gui->show_message(string, theme->message_error);
1695                                 gui->update_default_message();
1696                                 break;
1697
1698 // Unknown format
1699                         case FILE_UNRECOGNIZED_CODEC:
1700                         {
1701 // Test index file
1702                                 {       IndexFile indexfile(this, new_asset);
1703                                         if( !(result = indexfile.open_index()) )
1704                                                 indexfile.close_index();
1705                                 }
1706
1707 // Test existing EDLs
1708                                 for(int j = 0; result && j <= new_edls.total; j++) {
1709                                         Asset *old_asset = j < new_edls.total ?
1710                                                 new_edls[j]->assets->get_asset(new_asset->path) :
1711                                                 edl->assets->get_asset(new_asset->path);
1712                                         if( old_asset ) {
1713                                                 new_asset->copy_from(old_asset,1);
1714                                                 result = 0;
1715                                         }
1716                                 }
1717
1718 // Prompt user
1719                                 if(result)
1720                                 {
1721                                         char string[BCTEXTLEN];
1722                                         FileSystem fs;
1723                                         fs.extract_name(string, new_asset->path);
1724
1725                                         strcat(string, _("'s format couldn't be determined."));
1726                                         new_asset->audio_data = 1;
1727                                         new_asset->format = FILE_PCM;
1728                                         new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1729                                         new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1730                                         new_asset->bits = defaults->get("AUDIO_BITS", 16);
1731                                         new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1732                                         new_asset->signed_ = defaults->get("SIGNED_", 1);
1733                                         new_asset->header = defaults->get("HEADER", 0);
1734
1735                                         FileFormat fwindow(this);
1736                                         fwindow.create_objects(new_asset, string);
1737                                         result = fwindow.run_window();
1738
1739
1740                                         defaults->update("AUDIO_CHANNELS", new_asset->channels);
1741                                         defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1742                                         defaults->update("AUDIO_BITS", new_asset->bits);
1743                                         defaults->update("BYTE_ORDER", new_asset->byte_order);
1744                                         defaults->update("SIGNED_", new_asset->signed_);
1745                                         defaults->update("HEADER", new_asset->header);
1746                                         save_defaults();
1747                                 }
1748
1749 // Append to list
1750                                 if(!result)
1751                                 {
1752 // Recalculate length
1753                                         delete new_file;
1754                                         new_file = new File;
1755                                         result = new_file->open_file(preferences, new_asset, 1, 0);
1756
1757                                         if(load_mode != LOADMODE_RESOURCESONLY)
1758                                         {
1759                                                 RecordLabels *labels = edl->session->label_cells ?
1760                                                         new RecordLabels(new_file) : 0;
1761                                                 asset_to_edl(new_edl, new_asset, labels);
1762                                                 new_edls.append(new_edl);
1763                                                 new_asset->Garbage::remove_user();
1764                                                 delete labels;
1765                                                 new_asset = 0;
1766                                         }
1767                                         else
1768                                         {
1769                                                 new_assets.append(new_asset);
1770                                                 new_asset = 0;
1771                                         }
1772                                 }
1773                                 else
1774                                 {
1775                                         result = 1;
1776                                 }
1777                                 break;
1778                         }
1779
1780                         case FILE_IS_XML:
1781                         {
1782                                 FileXML xml_file;
1783 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1784                                 xml_file.read_from_file(filenames->get(i));
1785 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1786                                 const char *cin_version = 0;
1787                                 while( !xml_file.read_tag() ) {
1788                                         if( xml_file.tag.title_is("EDL") ) {
1789                                                 cin_version = xml_file.tag.get_property("VERSION");
1790                                                 break;
1791                                         }
1792                                 }
1793                                 xml_file.rewind();
1794                                 if( !cin_version ) {
1795                                         eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
1796                                         char string[BCTEXTLEN];
1797                                         sprintf(string,_("Unknown %s"), filenames->get(i));
1798                                         gui->show_message(string);
1799                                         result = 1;
1800                                         break;
1801                                 }
1802                                 if( strcmp(cin_version, CINELERRA_VERSION) ) {
1803                                         char string[BCTEXTLEN];
1804                                         snprintf(string, sizeof(string),
1805                                                  _("Warning: XML from cinelerra version %s\n"
1806                                                 "Session data may be incompatible."), cin_version);
1807                                         show_warning(&preferences->warn_version, string);
1808                                 }
1809                                 if(load_mode == LOADMODE_NESTED)
1810                                 {
1811 // Load temporary EDL for nesting.
1812                                         EDL *nested_edl = new EDL;
1813                                         nested_edl->create_objects();
1814                                         nested_edl->set_path(filenames->get(i));
1815                                         nested_edl->load_xml(&xml_file, LOAD_ALL);
1816 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
1817                                         edl_to_nested(new_edl, nested_edl);
1818                                         nested_edl->Garbage::remove_user();
1819                                 }
1820                                 else
1821                                 {
1822 // Load EDL for pasting
1823                                         new_edl->load_xml(&xml_file, LOAD_ALL);
1824 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1825                                         test_plugins(new_edl, filenames->get(i));
1826 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1827
1828                                         if(load_mode == LOADMODE_REPLACE ||
1829                                                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1830                                         {
1831                                                 strcpy(session->filename, filenames->get(i));
1832                                                 strcpy(new_edl->local_session->clip_title,
1833                                                         filenames->get(i));
1834                                                 if(update_filename)
1835                                                         set_filename(new_edl->local_session->clip_title);
1836                                         }
1837                                         else
1838                                         if( load_mode == LOADMODE_RESOURCESONLY ) {
1839                                                 strcpy(new_edl->local_session->clip_title,
1840                                                         filenames->get(i));
1841                                                 struct stat st;
1842                                                 time_t t = !stat(filenames->get(i),&st) ?
1843                                                         st.st_mtime : time(&t);
1844                                                 ctime_r(&t, new_edl->local_session->clip_notes);
1845                                         }
1846                                 }
1847
1848                                 new_edls.append(new_edl);
1849                                 result = 0;
1850                                 break;
1851                         }
1852                 }
1853
1854 // edls are in new_edls
1855                 if( result && new_edl ) new_edl->Garbage::remove_user();
1856 // assets are copied
1857                 if( new_asset ) new_asset->Garbage::remove_user();
1858
1859 // Store for testing index
1860                 new_files.append(new_file);
1861         }
1862
1863 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1864
1865
1866         if(!result) {
1867                 gui->reset_default_message();
1868                 gui->default_message();
1869         }
1870
1871
1872 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1873
1874 // Paste them.
1875 // Don't back up here.
1876         if(new_edls.size())
1877         {
1878 // For pasting, clear the active region
1879                 if(load_mode == LOADMODE_PASTE ||
1880                         load_mode == LOADMODE_NESTED)
1881                 {
1882                         double start = edl->local_session->get_selectionstart();
1883                         double end = edl->local_session->get_selectionend();
1884                         if(!EQUIV(start, end))
1885                                 edl->clear(start,
1886                                         end,
1887                                         edl->session->labels_follow_edits,
1888                                         edl->session->plugins_follow_edits,
1889                                         edl->session->autos_follow_edits);
1890                 }
1891
1892                 paste_edls(&new_edls, load_mode, 0, -1,
1893                         edl->session->labels_follow_edits,
1894                         edl->session->plugins_follow_edits,
1895                         edl->session->autos_follow_edits,
1896                         0); // overwrite
1897         }
1898
1899
1900
1901
1902 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1903
1904 // Add new assets to EDL and schedule assets for index building.
1905         int got_indexes = 0;
1906         for(int i = 0; i < new_edls.size(); i++)
1907         {
1908                 EDL *new_edl = new_edls[i];
1909                 for(int j = 0; j < new_edl->nested_edls->size(); j++)
1910                 {
1911                         mainindexes->add_next_asset(0,
1912                                 new_edl->nested_edls->get(j));
1913                         got_indexes = 1;
1914                         edl->nested_edls->update_index(new_edl->nested_edls->get(j));
1915                 }
1916
1917         }
1918
1919 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1920         for(int i = 0; i < new_assets.size(); i++)
1921         {
1922                 Asset *new_asset = new_assets[i];
1923
1924                 File *new_file = 0;
1925                 int got_it = 0;
1926                 for(int j = 0; j < new_files.size(); j++)
1927                 {
1928                         new_file = new_files[j];
1929                         if(!strcmp(new_file->asset->path,
1930                                 new_asset->path))
1931                         {
1932                                 got_it = 1;
1933                                 break;
1934                         }
1935                 }
1936
1937                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
1938                 got_indexes = 1;
1939                 edl->assets->update(new_asset);
1940         }
1941 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1942
1943 // Start examining next batch of index files
1944         if(got_indexes) mainindexes->start_build();
1945 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1946
1947 // Open plugin GUIs
1948         Track *track = edl->tracks->first;
1949         while(track)
1950         {
1951                 for(int j = 0; j < track->plugin_set.size(); j++)
1952                 {
1953                         PluginSet *plugins = track->plugin_set[j];
1954                         Plugin *plugin = plugins->get_first_plugin();
1955
1956                         while(plugin)
1957                         {
1958                                 if(load_mode == LOADMODE_REPLACE ||
1959                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
1960                                 {
1961                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
1962                                                 plugin->show)
1963                                         {
1964                                                 show_plugin(plugin);
1965                                         }
1966                                 }
1967
1968                                 plugin = (Plugin*)plugin->next;
1969                         }
1970                 }
1971
1972                 track = track->next;
1973         }
1974
1975         // if just opening one new resource in replace mode
1976         if( ftype != FILE_IS_XML &&
1977             ( load_mode == LOADMODE_REPLACE ||
1978               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
1979                 select_asset(0, 0);
1980                 edl->session->proxy_scale = 1;
1981                 edl->session->proxy_use_scaler = 0;
1982                 edl->session->proxy_auto_scale = 0;
1983                 edl->local_session->preview_start = 0;
1984                 edl->local_session->preview_end = edl->tracks->total_length();
1985                 edl->local_session->loop_playback = 0;
1986                 edl->local_session->set_selectionstart(0);
1987                 edl->local_session->set_selectionend(0);
1988                 set_brender_active(0, 0);
1989                 fit_selection();
1990                 goto_start();
1991         }
1992
1993         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
1994             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
1995                 ArrayList<Indexable *> orig_idxbls;
1996                 for( int i=0; i<new_assets.size(); ++i )
1997                         orig_idxbls.append(new_assets.get(i));
1998                 for( int i=0; i<new_edls.size(); ++i ) {
1999                         EDL *new_edl = new_edls[i];
2000                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2001                                 if( track->data_type != TRACK_VIDEO ) continue;
2002                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2003                                         Indexable *idxbl = (Indexable *)edit->asset;
2004                                         if( !idxbl ) continue;
2005                                         if( !idxbl->have_video() ) continue;
2006                                         if( edit->channel != 0 ) continue; // first layer only
2007                                         orig_idxbls.append(edit->asset);
2008                                 }
2009                         }
2010                 }
2011                 gui->unlock_window(); // to update progress bar
2012                 render_proxy(orig_idxbls);
2013                 gui->lock_window("MWindow::load_filenames");
2014         }
2015
2016 // need to update undo before project, since mwindow is unlocked & a new load
2017 // can begin here.  Should really prevent loading until we're done.
2018 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2019         undo->update_undo_after(_("load"), LOAD_ALL);
2020
2021         for(int i = 0; i < new_edls.size(); i++)
2022         {
2023                 new_edls[i]->remove_user();
2024         }
2025 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2026
2027         new_edls.remove_all();
2028
2029         for(int i = 0; i < new_assets.size(); i++)
2030         {
2031                 new_assets[i]->Garbage::remove_user();
2032         }
2033
2034         new_assets.remove_all();
2035         new_files.remove_all_objects();
2036
2037
2038 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2039         if(load_mode == LOADMODE_REPLACE ||
2040                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2041         {
2042                 session->changes_made = 0;
2043         }
2044         else
2045         {
2046                 session->changes_made = 1;
2047         }
2048
2049         gui->stop_hourglass();
2050
2051
2052 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2053         update_project(load_mode);
2054
2055 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2056
2057         return 0;
2058 }
2059
2060 void MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2061 {
2062         Asset *format_asset = new Asset;
2063         format_asset->format = FILE_FFMPEG;
2064         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2065         ProxyRender proxy_render(this, format_asset);
2066         int new_scale = edl->session->proxy_scale;
2067         int use_scaler = edl->session->proxy_use_scaler;
2068
2069         for( int i=0; i<new_idxbls.size(); ++i ) {
2070                 Indexable *orig = new_idxbls.get(i);
2071                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2072                 if( !proxy ) continue;
2073                 FileSystem fs;
2074                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2075                 int got_it = exists && // if proxy exists, and is newer than orig
2076                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2077                 if( got_it ) continue;
2078                 proxy_render.add_needed(orig, proxy);
2079         }
2080
2081 // render needed proxies
2082         int result = proxy_render.create_needed_proxies(new_scale);
2083         if( !result ) {
2084                 add_proxy(use_scaler,
2085                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2086         }
2087         format_asset->remove_user();
2088 }
2089
2090 void MWindow::test_plugins(EDL *new_edl, char *path)
2091 {
2092         char string[BCTEXTLEN];
2093
2094 // Do a check weather plugins exist
2095         for(Track *track = new_edl->tracks->first; track; track = track->next)
2096         {
2097                 for(int k = 0; k < track->plugin_set.total; k++)
2098                 {
2099                         PluginSet *plugin_set = track->plugin_set[k];
2100                         for(Plugin *plugin = (Plugin*)plugin_set->first;
2101                                 plugin;
2102                                 plugin = (Plugin*)plugin->next)
2103                         {
2104                                 if(plugin->plugin_type == PLUGIN_STANDALONE)
2105                                 {
2106 // ok we need to find it in plugindb
2107                                         int plugin_found = 0;
2108
2109                                         for(int j = 0; j < plugindb->size(); j++)
2110                                         {
2111                                                 PluginServer *server = plugindb->get(j);
2112                                                 if(server->title &&
2113                                                         !strcasecmp(server->title, plugin->title) &&
2114                                                         ((track->data_type == TRACK_AUDIO && server->audio) ||
2115                                                         (track->data_type == TRACK_VIDEO && server->video)) &&
2116                                                         (!server->transition))
2117                                                         plugin_found = 1;
2118                                         }
2119
2120                                         if (!plugin_found)
2121                                         {
2122                                                 sprintf(string,
2123         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2124           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2125                                                         "effect", plugin->title,
2126                                                         path);
2127                                                 MainError::show_error(string);
2128                                         }
2129                                 }
2130                         }
2131                 }
2132
2133                 for(Edit *edit = (Edit*)track->edits->first;
2134                         edit;
2135                         edit = (Edit*)edit->next)
2136                 {
2137                         if (edit->transition)
2138                         {
2139 // ok we need to find transition in plugindb
2140
2141                                 int transition_found = 0;
2142                                 for(int j = 0; j < plugindb->size(); j++)
2143                                 {
2144                                         PluginServer *server = plugindb->get(j);
2145                                         if(server->title &&
2146                                                 !strcasecmp(server->title, edit->transition->title) &&
2147                                                 ((track->data_type == TRACK_AUDIO && server->audio) ||
2148                                                 (track->data_type == TRACK_VIDEO && server->video)) &&
2149                                                 (server->transition))
2150                                                 transition_found = 1;
2151                                 }
2152
2153                                 if (!transition_found)
2154                                 {
2155                                         sprintf(string,
2156         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2157           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2158                                                 "transition", edit->transition->title,
2159                                                 path);
2160                                         MainError::show_error(string);
2161                                 }
2162                         }
2163                 }
2164         }
2165 }
2166
2167
2168 void MWindow::init_shm()
2169 {
2170 // Fix shared memory
2171         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
2172         if(fd) {
2173                 fprintf(fd, "0x7fffffff");
2174                 fclose(fd);
2175         }
2176         fd = 0;
2177
2178         fd = fopen("/proc/sys/kernel/shmmax", "r");
2179         if(!fd) {
2180                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
2181                 return;
2182         }
2183
2184         int64_t result = 0;
2185         fscanf(fd, "%jd", &result);
2186         fclose(fd);
2187         fd = 0;
2188         if(result < 0x7fffffff) {
2189                 eprintf(_("MWindow::init_shm: /proc/sys/kernel/shmmax is %p.\n"
2190                         "you probably need to be root, or:\n"
2191                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
2192                         "before trying to start cinelerra.\n"
2193                         "It should be at least 0x7fffffff for Cinelerra.\n"), (void *)result);
2194         }
2195 }
2196
2197 void MWindow::create_objects(int want_gui,
2198         int want_new,
2199         char *config_path)
2200 {
2201         const int debug = 0;
2202         if(debug) PRINT_TRACE
2203
2204 // For some reason, init_signals must come after show_splash or the signals won't
2205 // get trapped.
2206         init_signals();
2207         if(debug) PRINT_TRACE
2208         init_3d();
2209
2210         if(debug) PRINT_TRACE
2211         show_splash();
2212
2213         if(debug) PRINT_TRACE
2214         default_standard = default_std();
2215         init_defaults(defaults, config_path);
2216         check_language();
2217         init_preferences();
2218         if(splash_window)
2219                 splash_window->operation->update(_("Initializing Plugins"));
2220         init_plugins(this, preferences);
2221         if(debug) PRINT_TRACE
2222         init_ladspa_plugins(this, preferences);
2223         if(debug) PRINT_TRACE
2224         init_plugin_tips(*plugindb, cin_lang);
2225         if(splash_window)
2226                 splash_window->operation->update(_("Initializing GUI"));
2227         if(debug) PRINT_TRACE
2228         init_theme();
2229
2230         if(debug) PRINT_TRACE
2231         init_error();
2232
2233         if(splash_window)
2234                 splash_window->operation->update(_("Initializing Fonts"));
2235         char string[BCTEXTLEN];
2236         strcpy(string, preferences->plugin_dir);
2237         strcat(string, "/" FONT_SEARCHPATH);
2238         BC_Resources::init_fontconfig(string);
2239         if(debug) PRINT_TRACE
2240
2241 // Initialize before too much else is running
2242 // Preferences & theme are required for building MPEG table of contents
2243
2244 // Default project created here
2245         init_edl();
2246         if(debug) PRINT_TRACE
2247
2248         init_cache();
2249         if(debug) PRINT_TRACE
2250
2251         Timer timer;
2252
2253         init_awindow();
2254         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2255
2256         init_compositor();
2257         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2258
2259 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2260         if(session->show_vwindow)
2261                 get_viewer(1, DEFAULT_VWINDOW);
2262         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2263
2264         init_gui();
2265         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2266
2267         init_levelwindow();
2268         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2269
2270         init_indexes();
2271         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2272
2273         init_channeldb();
2274         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2275
2276         init_gwindow();
2277         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2278
2279         init_render();
2280         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2281
2282         init_brender();
2283         init_exportedl();
2284         init_commercials();
2285         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2286         mainprogress = new MainProgress(this, gui);
2287         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2288         undo = new MainUndo(this);
2289
2290         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2291
2292         plugin_guis = new ArrayList<PluginServer*>;
2293         dead_plugins = new ArrayList<PluginServer*>;
2294         keyframe_threads = new ArrayList<KeyFrameThread*>;
2295
2296         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2297                 __LINE__,
2298                 vwindows.size(),
2299                 session->show_vwindow);
2300
2301 // Show all vwindows
2302 //      if(session->show_vwindow) {
2303 //              for(int j = 0; j < vwindows.size(); j++) {
2304 //                      VWindow *vwindow = vwindows[j];
2305 //                      if( !vwindow->is_running() ) continue;
2306 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2307 //                              __LINE__,
2308 //                              vwindow);
2309 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2310 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2311 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2312 //                      vwindow->gui->show_window();
2313 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2314 //                      vwindow->gui->unlock_window();
2315 //              }
2316 //      }
2317
2318
2319         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2320
2321         if(session->show_cwindow)
2322         {
2323                 cwindow->gui->lock_window("MWindow::create_objects 1");
2324                 cwindow->gui->show_window();
2325                 cwindow->gui->unlock_window();
2326         }
2327
2328         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2329         if(session->show_awindow)
2330         {
2331                 awindow->gui->lock_window("MWindow::create_objects 1");
2332                 awindow->gui->show_window();
2333                 awindow->gui->unlock_window();
2334         }
2335
2336         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2337         if(session->show_lwindow)
2338         {
2339                 lwindow->gui->lock_window("MWindow::create_objects 1");
2340                 lwindow->gui->show_window();
2341                 lwindow->gui->unlock_window();
2342         }
2343
2344         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2345                 __LINE__,
2346                 (int)timer.get_difference(),
2347                 gwindow->gui);
2348         if(session->show_gwindow)
2349         {
2350                 gwindow->gui->lock_window("MWindow::create_objects 1");
2351                 gwindow->gui->show_window();
2352                 gwindow->gui->unlock_window();
2353         }
2354
2355         if(debug) PRINT_TRACE
2356
2357         gui->lock_window("MWindow::create_objects 1");
2358         gui->mainmenu->load_defaults(defaults);
2359         gui->mainmenu->update_toggles(0);
2360         gui->update_patchbay();
2361         gui->draw_canvas(0, 0);
2362         gui->draw_cursor(1);
2363         gui->show_window();
2364         gui->raise_window();
2365         gui->unlock_window();
2366
2367         if(debug) PRINT_TRACE
2368
2369         if(preferences->use_tipwindow)
2370                 init_tipwindow();
2371         if(debug) PRINT_TRACE
2372
2373         gui->add_keyboard_listener(
2374                 (int (BC_WindowBase::*)(BC_WindowBase *))
2375                 &MWindowGUI::keyboard_listener);
2376
2377         hide_splash();
2378         init_shm();
2379         if(debug) PRINT_TRACE
2380
2381         BC_WindowBase::get_resources()->vframe_shm = 1;
2382 }
2383
2384
2385 void MWindow::show_splash()
2386 {
2387 #include "data/heroine_logo9_png.h"
2388         VFrame *frame = new VFramePng(heroine_logo9_png);
2389         BC_DisplayInfo dpyi;
2390         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2391         int rr = (rw < rh ? rw : rh) / 4;
2392         splash_window = new SplashGUI(frame, rr, rr);
2393         splash_window->create_objects();
2394 }
2395
2396 void MWindow::hide_splash()
2397 {
2398         if(splash_window)
2399                 delete splash_window;
2400         splash_window = 0;
2401 }
2402
2403
2404 void MWindow::start()
2405 {
2406 ENABLE_BUFFER
2407 //PRINT_TRACE
2408 //      vwindows[DEFAULT_VWINDOW]->start();
2409         awindow->start();
2410 //PRINT_TRACE
2411         cwindow->start();
2412 //PRINT_TRACE
2413         lwindow->start();
2414 //PRINT_TRACE
2415         gwindow->start();
2416 //PRINT_TRACE
2417 //      Thread::start();
2418 //PRINT_TRACE
2419         playback_3d->start();
2420 //PRINT_TRACE
2421 }
2422
2423 void MWindow::run()
2424 {
2425         run_lock->lock("MWindow::run");
2426         gui->run_window();
2427         stop_playback(1);
2428
2429         brender_lock->lock("MWindow::run 1");
2430         delete brender;         brender = 0;
2431         brender_lock->unlock();
2432
2433         interrupt_indexes();
2434         clean_indexes();
2435         save_defaults();
2436         run_lock->unlock();
2437 }
2438
2439 void MWindow::show_vwindow()
2440 {
2441         int total_running = 0;
2442         session->show_vwindow = 1;
2443
2444 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2445 // Raise all windows which are visible
2446         for(int j = 0; j < vwindows.size(); j++) {
2447                 VWindow *vwindow = vwindows[j];
2448                 if( !vwindow->is_running() ) continue;
2449                 vwindow->gui->lock_window("MWindow::show_vwindow");
2450                 vwindow->gui->show_window(0);
2451                 vwindow->gui->raise_window();
2452                 vwindow->gui->flush();
2453                 vwindow->gui->unlock_window();
2454                 total_running++;
2455         }
2456
2457 // If no windows visible
2458         if(!total_running)
2459         {
2460                 get_viewer(1, DEFAULT_VWINDOW);
2461         }
2462
2463         gui->mainmenu->show_vwindow->set_checked(1);
2464 }
2465
2466 void MWindow::show_awindow()
2467 {
2468         session->show_awindow = 1;
2469         awindow->gui->lock_window("MWindow::show_awindow");
2470         awindow->gui->show_window();
2471         awindow->gui->raise_window();
2472         awindow->gui->flush();
2473         awindow->gui->unlock_window();
2474         gui->mainmenu->show_awindow->set_checked(1);
2475 }
2476
2477 char *MWindow::get_cwindow_display()
2478 {
2479         char *x11_host = screens < 2 || session->window_config == 0 ?
2480                 session->a_x11_host : session->b_x11_host;
2481         return *x11_host ? x11_host : 0;
2482 }
2483
2484 void MWindow::show_cwindow()
2485 {
2486         session->show_cwindow = 1;
2487         cwindow->show_window();
2488         gui->mainmenu->show_cwindow->set_checked(1);
2489 }
2490
2491 void MWindow::show_gwindow()
2492 {
2493         session->show_gwindow = 1;
2494
2495         gwindow->gui->lock_window("MWindow::show_gwindow");
2496         gwindow->gui->show_window();
2497         gwindow->gui->raise_window();
2498         gwindow->gui->flush();
2499         gwindow->gui->unlock_window();
2500
2501         gui->mainmenu->show_gwindow->set_checked(1);
2502 }
2503 void MWindow::hide_gwindow()
2504 {
2505         session->show_gwindow = 0;
2506
2507         gwindow->gui->lock_window("MWindow::show_gwindow");
2508         gwindow->gui->hide_window();
2509         gwindow->gui->unlock_window();
2510 }
2511
2512 void MWindow::show_lwindow()
2513 {
2514         session->show_lwindow = 1;
2515         lwindow->gui->lock_window("MWindow::show_lwindow");
2516         lwindow->gui->show_window();
2517         lwindow->gui->raise_window();
2518         lwindow->gui->flush();
2519         lwindow->gui->unlock_window();
2520         gui->mainmenu->show_lwindow->set_checked(1);
2521 }
2522
2523 int MWindow::tile_windows(int window_config)
2524 {
2525         int need_reload = 0;
2526         int play_config = window_config==0 ? 0 : 1;
2527         edl->session->playback_config->load_defaults(defaults, play_config);
2528         session->default_window_positions(window_config);
2529         if( screens == 1 ) {
2530                 gui->default_positions();
2531                 sync_parameters(CHANGE_ALL);
2532         }
2533         else
2534                 need_reload = 1;
2535         return need_reload;
2536 }
2537
2538 void MWindow::toggle_loop_playback()
2539 {
2540         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2541         set_loop_boundaries();
2542         save_backup();
2543
2544         gui->draw_overlays(1);
2545         sync_parameters(CHANGE_PARAMS);
2546 }
2547
2548 //void MWindow::set_titles(int value)
2549 //{
2550 //      edl->session->show_titles = value;
2551 //      trackmovement(edl->local_session->track_start);
2552 //}
2553
2554 void MWindow::set_screens(int value)
2555 {
2556         screens = value;
2557 }
2558
2559 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2560 {
2561         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2562         edl->session->auto_keyframes = value;
2563         gui->mbuttons->edit_panel->keyframe->update(value);
2564         gui->flush();
2565         if(lock_mwindow) gui->unlock_window();
2566
2567         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2568         cwindow->gui->edit_panel->keyframe->update(value);
2569         cwindow->gui->flush();
2570         if(lock_cwindow) cwindow->gui->unlock_window();
2571 }
2572
2573 void MWindow::set_auto_visibility(Autos *autos, int value)
2574 {
2575         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2576                 edl->session->auto_conf->plugins = value;
2577         else if( autos->autoidx >= 0 )
2578                 edl->session->auto_conf->autos[autos->autoidx] = value;
2579         else
2580                 return;
2581
2582         gui->update(0, 1, 0, 0, 0, 0, 0);
2583         gui->mainmenu->update_toggles(1);
2584         gui->unlock_window();
2585         gwindow->gui->update_toggles(1);
2586         gui->lock_window("MWindow::set_auto_visibility");
2587 }
2588
2589 void MWindow::set_keyframe_type(int mode)
2590 {
2591         gui->lock_window("MWindow::set_keyframe_type");
2592         edl->local_session->floatauto_type = mode;
2593         gui->mainmenu->update_toggles(0);
2594         gui->unlock_window();
2595 }
2596
2597 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2598 {
2599         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2600         edl->session->editing_mode = new_editing_mode;
2601         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2602         gui->mbuttons->edit_panel->update();
2603         gui->set_editing_mode(1);
2604         if(lock_mwindow) gui->unlock_window();
2605
2606
2607         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2608         cwindow->gui->edit_panel->update();
2609         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2610         if(lock_cwindow) cwindow->gui->unlock_window();
2611         return 0;
2612 }
2613
2614 void MWindow::toggle_editing_mode()
2615 {
2616         int mode = edl->session->editing_mode;
2617         if( mode == EDITING_ARROW )
2618                 set_editing_mode(EDITING_IBEAM, 0, 1);
2619         else
2620                 set_editing_mode(EDITING_ARROW, 0, 1);
2621 }
2622
2623
2624 void MWindow::set_labels_follow_edits(int value)
2625 {
2626         gui->lock_window("MWindow::set_labels_follow_edits");
2627         edl->session->labels_follow_edits = value;
2628         gui->mbuttons->edit_panel->locklabels->update(value);
2629         gui->mainmenu->labels_follow_edits->set_checked(value);
2630         gui->flush();
2631         gui->unlock_window();
2632 }
2633
2634 void MWindow::sync_parameters(int change_type)
2635 {
2636         if( in_destructor ) return;
2637
2638 // Sync engines which are playing back
2639         if(cwindow->playback_engine->is_playing_back)
2640         {
2641                 if(change_type == CHANGE_PARAMS)
2642                 {
2643 // TODO: block keyframes until synchronization is done
2644                         cwindow->playback_engine->sync_parameters(edl);
2645                 }
2646                 else
2647 // Stop and restart
2648                 {
2649                         int command = cwindow->playback_engine->command->command;
2650                         cwindow->playback_engine->que->send_command(STOP,
2651                                 CHANGE_NONE,
2652                                 0,
2653                                 0);
2654 // Waiting for tracking to finish would make the restart position more
2655 // accurate but it can't lock the window to stop tracking for some reason.
2656 // Not waiting for tracking gives a faster response but restart position is
2657 // only as accurate as the last tracking update.
2658                         cwindow->playback_engine->interrupt_playback(0);
2659                         cwindow->playback_engine->que->send_command(command,
2660                                         change_type,
2661                                         edl,
2662                                         1,
2663                                         0);
2664                 }
2665         }
2666         else
2667         {
2668                 queue_mixers(edl,CURRENT_FRAME,0,0,1,0);
2669                 cwindow->playback_engine->que->send_command(CURRENT_FRAME,
2670                                                         change_type,
2671                                                         edl,
2672                                                         1);
2673         }
2674 }
2675
2676 void MWindow::age_caches()
2677 {
2678 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
2679 // __LINE__,
2680 // preferences->cache_size,
2681 // audio_cache->get_memory_usage(1),
2682 // video_cache->get_memory_usage(1),
2683 // frame_cache->get_memory_usage(),
2684 // wave_cache->get_memory_usage(),
2685 // memory_usage);
2686         frame_cache->age_cache(512);
2687         wave_cache->age_cache(8192);
2688
2689         int64_t memory_usage;
2690         int64_t prev_memory_usage = 0;
2691         int result = 0;
2692         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2693         while( !result && prev_memory_usage !=
2694                 (memory_usage=video_cache->get_memory_usage(1)) &&
2695                 memory_usage > video_size ) {
2696                 video_cache->delete_oldest();
2697                 prev_memory_usage = memory_usage;
2698         }
2699
2700         prev_memory_usage = 0;
2701         result = 0;
2702         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2703         while( !result && prev_memory_usage !=
2704                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2705                 memory_usage > audio_size ) {
2706                 audio_cache->delete_oldest();
2707                 prev_memory_usage = memory_usage;
2708         }
2709 }
2710
2711 void MWindow::reset_android_remote()
2712 {
2713         gui->use_android_remote(preferences->android_remote);
2714 }
2715
2716
2717 void MWindow::show_keyframe_gui(Plugin *plugin)
2718 {
2719         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2720 // Find existing thread
2721         for(int i = 0; i < keyframe_threads->size(); i++)
2722         {
2723                 if(keyframe_threads->get(i)->plugin == plugin)
2724                 {
2725                         keyframe_threads->get(i)->start_window(plugin, 0);
2726                         keyframe_gui_lock->unlock();
2727                         return;
2728                 }
2729         }
2730
2731 // Find unused thread
2732         for(int i = 0; i < keyframe_threads->size(); i++)
2733         {
2734                 if(!keyframe_threads->get(i)->plugin)
2735                 {
2736                         keyframe_threads->get(i)->start_window(plugin, 0);
2737                         keyframe_gui_lock->unlock();
2738                         return;
2739                 }
2740         }
2741
2742 // Create new thread
2743         KeyFrameThread *thread = new KeyFrameThread(this);
2744         keyframe_threads->append(thread);
2745         thread->start_window(plugin, 0);
2746
2747         keyframe_gui_lock->unlock();
2748 }
2749
2750
2751
2752
2753
2754 void MWindow::show_plugin(Plugin *plugin)
2755 {
2756         int done = 0;
2757
2758 SET_TRACE
2759 // Remove previously deleted plugin GUIs
2760         dead_plugin_lock->lock("MWindow::show_plugin");
2761         dead_plugins->remove_all_objects();
2762         dead_plugin_lock->unlock();
2763
2764 //printf("MWindow::show_plugin %d\n", __LINE__);
2765 SET_TRACE
2766
2767
2768         plugin_gui_lock->lock("MWindow::show_plugin");
2769         for(int i = 0; i < plugin_guis->total; i++)
2770         {
2771 // Pointer comparison
2772                 if(plugin_guis->get(i)->plugin == plugin)
2773                 {
2774                         plugin_guis->get(i)->raise_window();
2775                         done = 1;
2776                         break;
2777                 }
2778         }
2779 SET_TRACE
2780
2781 //printf("MWindow::show_plugin 1\n");
2782         if( !done && !plugin->track ) {
2783                 printf("MWindow::show_plugin track not defined.\n");
2784                 done = 1;
2785         }
2786         if( !done ) {
2787                 PluginServer *server = scan_plugindb(plugin->title,
2788                         plugin->track->data_type);
2789
2790 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2791                 if(server && server->uses_gui)
2792                 {
2793                         PluginServer *gui = new PluginServer(*server);
2794                         plugin_guis->append(gui);
2795 // Needs mwindow to do GUI
2796                         gui->set_mwindow(this);
2797                         gui->open_plugin(0, preferences, edl, plugin);
2798                         plugin->show = 1;
2799                         gui->show_gui();
2800                 }
2801         }
2802         plugin_gui_lock->unlock();
2803 //printf("MWindow::show_plugin %d\n", __LINE__);
2804 SET_TRACE
2805 //sleep(1);
2806 //printf("MWindow::show_plugin 2\n");
2807 }
2808
2809 void MWindow::hide_plugin(Plugin *plugin, int lock)
2810 {
2811         plugin->show = 0;
2812 // Update the toggle
2813         gui->lock_window("MWindow::hide_plugin");
2814         gui->update(0, 1, 0, 0, 0, 0, 0);
2815         gui->unlock_window();
2816
2817         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2818         for(int i = 0; i < plugin_guis->total; i++)
2819         {
2820                 if(plugin_guis->get(i)->plugin == plugin)
2821                 {
2822                         PluginServer *ptr = plugin_guis->get(i);
2823                         plugin_guis->remove(ptr);
2824                         if(lock) plugin_gui_lock->unlock();
2825 // Last command executed in client side close
2826 // Schedule for deletion
2827                         ptr->hide_gui();
2828                         delete_plugin(ptr);
2829 //sleep(1);
2830                         return;
2831                 }
2832         }
2833         if(lock) plugin_gui_lock->unlock();
2834 }
2835
2836 void MWindow::delete_plugin(PluginServer *plugin)
2837 {
2838         dead_plugin_lock->lock("MWindow::delete_plugin");
2839         dead_plugins->append(plugin);
2840         dead_plugin_lock->unlock();
2841 }
2842
2843 void MWindow::hide_plugins()
2844 {
2845         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2846         while(plugin_guis->size())
2847         {
2848                 PluginServer *ptr = plugin_guis->get(0);
2849                 plugin_guis->remove(ptr);
2850                 plugin_gui_lock->unlock();
2851 // Last command executed in client side close
2852 // Schedule for deletion
2853                 ptr->hide_gui();
2854                 delete_plugin(ptr);
2855                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2856         }
2857         plugin_gui_lock->unlock();
2858
2859         hide_keyframe_guis();
2860 }
2861
2862 void MWindow::hide_keyframe_guis()
2863 {
2864         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2865         for(int i = 0; i < keyframe_threads->size(); i++)
2866         {
2867                 keyframe_threads->get(i)->close_window();
2868         }
2869         keyframe_gui_lock->unlock();
2870 }
2871
2872 void MWindow::hide_keyframe_gui(Plugin *plugin)
2873 {
2874         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2875         for(int i = 0; i < keyframe_threads->size(); i++)
2876         {
2877                 if(keyframe_threads->get(i)->plugin == plugin)
2878                 {
2879                         keyframe_threads->get(i)->close_window();
2880                         break;
2881                 }
2882         }
2883         keyframe_gui_lock->unlock();
2884 }
2885
2886 void MWindow::update_keyframe_guis()
2887 {
2888 // Send new configuration to keyframe GUI's
2889         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2890         for(int i = 0; i < keyframe_threads->size(); i++)
2891         {
2892                 KeyFrameThread *ptr = keyframe_threads->get(i);
2893                 if(edl->tracks->plugin_exists(ptr->plugin))
2894                         ptr->update_gui(1);
2895                 else
2896                 {
2897                         ptr->close_window();
2898                 }
2899         }
2900         keyframe_gui_lock->unlock();
2901 }
2902
2903 void MWindow::update_plugin_guis(int do_keyframe_guis)
2904 {
2905 // Send new configuration to plugin GUI's
2906         plugin_gui_lock->lock("MWindow::update_plugin_guis");
2907
2908         for(int i = 0; i < plugin_guis->size(); i++)
2909         {
2910                 PluginServer *ptr = plugin_guis->get(i);
2911                 if(edl->tracks->plugin_exists(ptr->plugin))
2912                         ptr->update_gui();
2913                 else
2914                 {
2915 // Schedule for deletion if no plugin
2916                         plugin_guis->remove_number(i);
2917                         i--;
2918
2919                         ptr->hide_gui();
2920                         delete_plugin(ptr);
2921                 }
2922         }
2923
2924
2925 // Change plugin variable if not visible
2926         Track *track = edl->tracks->first;
2927         while(track)
2928         {
2929                 for(int i = 0; i < track->plugin_set.size(); i++)
2930                 {
2931                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
2932                         while(plugin)
2933                         {
2934                                 int got_it = 0;
2935                                 for(int i = 0; i < plugin_guis->size(); i++)
2936                                 {
2937                                         PluginServer *server = plugin_guis->get(i);
2938                                         if(server->plugin == plugin)
2939                                         {
2940                                                 got_it = 1;
2941                                                 break;
2942                                         }
2943                                 }
2944
2945                                 if(!got_it) plugin->show = 0;
2946
2947                                 plugin = (Plugin*)plugin->next;
2948                         }
2949                 }
2950
2951                 track = track->next;
2952         }
2953
2954         plugin_gui_lock->unlock();
2955
2956
2957         if(do_keyframe_guis) update_keyframe_guis();
2958 }
2959
2960 int MWindow::plugin_gui_open(Plugin *plugin)
2961 {
2962         int result = 0;
2963         plugin_gui_lock->lock("MWindow::plugin_gui_open");
2964         for(int i = 0; i < plugin_guis->total; i++)
2965         {
2966                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2967                 {
2968                         result = 1;
2969                         break;
2970                 }
2971         }
2972         plugin_gui_lock->unlock();
2973         return result;
2974 }
2975
2976 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
2977 {
2978         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2979         for(int i = 0; i < plugin_guis->total; i++)
2980         {
2981                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2982                 {
2983                         plugin_guis->get(i)->render_gui(data);
2984                         break;
2985                 }
2986         }
2987         plugin_gui_lock->unlock();
2988 }
2989
2990 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
2991 {
2992         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2993         for(int i = 0; i < plugin_guis->total; i++)
2994         {
2995                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2996                 {
2997                         plugin_guis->get(i)->render_gui(data, size);
2998                         break;
2999                 }
3000         }
3001         plugin_gui_lock->unlock();
3002 }
3003
3004
3005 void MWindow::update_plugin_states()
3006 {
3007         plugin_gui_lock->lock("MWindow::update_plugin_states");
3008         for(int i = 0; i < plugin_guis->total; i++)
3009         {
3010                 int result = 0;
3011 // Get a plugin GUI
3012                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
3013                 PluginServer *src_plugingui = plugin_guis->get(i);
3014
3015 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
3016                 for(Track *track = edl->tracks->first;
3017                         track && !result;
3018                         track = track->next)
3019                 {
3020                         for(int j = 0;
3021                                 j < track->plugin_set.total && !result;
3022                                 j++)
3023                         {
3024                                 PluginSet *plugin_set = track->plugin_set[j];
3025                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
3026                                         plugin && !result;
3027                                         plugin = (Plugin*)plugin->next)
3028                                 {
3029                                         if(plugin == src_plugin &&
3030                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
3031                                 }
3032                         }
3033                 }
3034
3035
3036 // Doesn't exist anymore
3037                 if(!result)
3038                 {
3039                         hide_plugin(src_plugin, 0);
3040                         i--;
3041                 }
3042         }
3043         plugin_gui_lock->unlock();
3044 }
3045
3046
3047 void MWindow::update_plugin_titles()
3048 {
3049         for(int i = 0; i < plugin_guis->total; i++)
3050         {
3051                 plugin_guis->get(i)->update_title();
3052         }
3053 }
3054
3055 int MWindow::asset_to_edl(EDL *new_edl,
3056         Asset *new_asset,
3057         RecordLabels *labels)
3058 {
3059 const int debug = 0;
3060 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3061 __LINE__,
3062 new_asset->layers);
3063 // Keep frame rate, sample rate, and output size unchanged.
3064 // These parameters would revert the project if VWindow displayed an asset
3065 // of different size than the project.
3066         if(new_asset->video_data)
3067         {
3068                 new_edl->session->video_tracks = new_asset->layers;
3069         }
3070         else
3071                 new_edl->session->video_tracks = 0;
3072
3073 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3074
3075
3076
3077
3078
3079         if(new_asset->audio_data)
3080         {
3081                 new_edl->session->audio_tracks = new_asset->channels;
3082         }
3083         else
3084                 new_edl->session->audio_tracks = 0;
3085 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3086
3087 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3088         new_edl->create_default_tracks();
3089 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3090 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3091
3092
3093
3094 //printf("MWindow::asset_to_edl 3\n");
3095         new_edl->insert_asset(new_asset,
3096                 0,
3097                 0,
3098                 0,
3099                 labels);
3100 //printf("MWindow::asset_to_edl 3\n");
3101 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3102
3103 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3104         if(edl->session->cursor_on_frames)
3105         {
3106                 double length = new_edl->tracks->total_length();
3107                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3108                 new_edl->tracks->clear(length, edl_length, 1, 1);
3109         }
3110
3111
3112
3113
3114         char string[BCTEXTLEN];
3115         FileSystem fs;
3116         fs.extract_name(string, new_asset->path);
3117 //printf("MWindow::asset_to_edl 3\n");
3118
3119         strcpy(new_edl->local_session->clip_title, string);
3120 //printf("MWindow::asset_to_edl 4 %s\n", string);
3121 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3122
3123         return 0;
3124 }
3125
3126 int MWindow::edl_to_nested(EDL *new_edl,
3127         EDL *nested_edl)
3128 {
3129
3130 // Keep frame rate, sample rate, and output size unchanged.
3131 // These parameters would revert the project if VWindow displayed an asset
3132 // of different size than the project.
3133
3134
3135
3136 // Nest all video & audio outputs
3137         new_edl->session->video_tracks = 1;
3138         new_edl->session->audio_tracks = nested_edl->session->audio_channels;
3139         new_edl->create_default_tracks();
3140
3141
3142
3143         new_edl->insert_asset(0,
3144                 nested_edl,
3145                 0,
3146                 0,
3147                 0);
3148
3149         char string[BCTEXTLEN];
3150         FileSystem fs;
3151         fs.extract_name(string, nested_edl->path);
3152 //printf("MWindow::edl_to_nested %p %s\n", nested_edl, nested_edl->path);
3153
3154         strcpy(new_edl->local_session->clip_title, string);
3155
3156         return 0;
3157 }
3158
3159 // Reset everything after a load.
3160 void MWindow::update_project(int load_mode)
3161 {
3162         const int debug = 0;
3163
3164         if(debug) PRINT_TRACE
3165         init_brender();
3166         edl->tracks->update_y_pixels(theme);
3167
3168         if(debug) PRINT_TRACE
3169
3170         if(load_mode == LOADMODE_REPLACE ||
3171                 load_mode == LOADMODE_REPLACE_CONCATENATE)
3172         {
3173                 gui->load_panes();
3174         }
3175
3176         gui->update(1, 1, 1, 1, 1, 1, 1);
3177         if(debug) PRINT_TRACE
3178         gui->unlock_window();
3179
3180         cwindow->gui->lock_window("MWindow::update_project 1");
3181         cwindow->update(0, 0, 1, 1, 1);
3182         cwindow->gui->unlock_window();
3183
3184         if(debug) PRINT_TRACE
3185
3186 // Close all the vwindows
3187         if( load_mode == LOADMODE_REPLACE ||
3188             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3189                 if(debug) PRINT_TRACE
3190                 int first_vwindow = 0;
3191                 if(session->show_vwindow) first_vwindow = 1;
3192 // Change visible windows to no source
3193                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3194                         VWindow *vwindow = vwindows[i];
3195                         if( !vwindow->is_running() ) continue;
3196                         vwindow->change_source(-1);
3197                 }
3198
3199 // Close remaining windows
3200                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3201                         VWindow *vwindow = vwindows[i];
3202                         if( !vwindow->is_running() ) continue;
3203                         vwindow->close_window();
3204                 }
3205                 if(debug) PRINT_TRACE
3206                 select_zwindow(0);
3207                 for( int i=0; i<zwindows.size(); ++i ) {
3208                         ZWindow *zwindow = zwindows[i];
3209                         if( !zwindow->is_running() ) continue;
3210                         zwindow->close_window();
3211                 }
3212
3213                 for( int i=0; i<edl->mixers.size(); ++i ) {
3214                         Mixer *mixer = edl->mixers[i];
3215                         ZWindow *zwindow = get_mixer(mixer);
3216                         zwindow->set_title(mixer->title);
3217                         zwindow->start();
3218                 }
3219         }
3220         else {
3221                 if(vwindows.size()) {
3222                         VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
3223                         if( vwindow->is_running() ) {
3224                                 vwindow->gui->lock_window("MWindow::update_project");
3225                                 vwindow->update(1);
3226                                 vwindow->gui->unlock_window();
3227                         }
3228                 }
3229         }
3230
3231         if(debug) PRINT_TRACE
3232         cwindow->gui->lock_window("MWindow::update_project 2");
3233         cwindow->gui->timebar->update(0);
3234         cwindow->gui->unlock_window();
3235
3236         if(debug) PRINT_TRACE
3237         cwindow->playback_engine->que->send_command(CURRENT_FRAME,
3238                 CHANGE_ALL,
3239                 edl,
3240                 1);
3241
3242         awindow->gui->async_update_assets();
3243         if(debug) PRINT_TRACE
3244
3245         gui->lock_window("MWindow::update_project");
3246         gui->update_mixers(0, 0);
3247         gui->flush();
3248         if(debug) PRINT_TRACE
3249 }
3250
3251 void MWindow::remove_indexfile(Indexable *indexable)
3252 {
3253         if( !indexable->is_asset ) return;
3254         Asset *asset = (Asset *)indexable;
3255 // Erase file
3256         IndexFile::delete_index(preferences, asset, ".toc");
3257         IndexFile::delete_index(preferences, asset, ".idx");
3258         IndexFile::delete_index(preferences, asset, ".mkr");
3259 }
3260
3261 void MWindow::rebuild_indices()
3262 {
3263         for(int i = 0; i < session->drag_assets->total; i++)
3264         {
3265                 Indexable *indexable = session->drag_assets->get(i);
3266 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3267                 remove_indexfile(indexable);
3268 // Schedule index build
3269                 IndexState *index_state = indexable->index_state;
3270                 index_state->index_status = INDEX_NOTTESTED;
3271                 if( indexable->is_asset ) {
3272                         Asset *asset = (Asset *)indexable;
3273                         if( asset->format != FILE_PCM ) {
3274                                 asset->format = FILE_UNKNOWN;
3275                                 asset->reset_audio();
3276                         }
3277                         asset->reset_video();
3278 //                      File file; // re-probe the asset
3279 //                      file.open_file(preferences, asset, 1, 0);
3280                 }
3281                 mainindexes->add_next_asset(0, indexable);
3282         }
3283         mainindexes->start_build();
3284 }
3285
3286
3287 void MWindow::save_backup()
3288 {
3289         FileXML file;
3290         edl->optimize();
3291         edl->set_path(session->filename);
3292         char backup_path[BCTEXTLEN];
3293         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3294                 File::get_config_path(), BACKUP_FILE);
3295         edl->save_xml(&file, backup_path, 0, 0);
3296         file.terminate_string();
3297         FileSystem fs;
3298         fs.complete_path(backup_path);
3299
3300         if(file.write_to_file(backup_path))
3301         {
3302                 char string2[256];
3303                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3304                 gui->show_message(string2);
3305         }
3306 }
3307
3308 void MWindow::load_backup()
3309 {
3310         ArrayList<char*> path_list;
3311         path_list.set_array_delete();
3312         char *out_path;
3313         char backup_path[BCTEXTLEN];
3314         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3315                 File::get_config_path(), BACKUP_FILE);
3316         FileSystem fs;
3317         fs.complete_path(backup_path);
3318
3319         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3320         strcpy(out_path, backup_path);
3321
3322         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3323         edl->local_session->clip_title[0] = 0;
3324 // This is unique to backups since the path of the backup is different than the
3325 // path of the project.
3326         set_filename(edl->path);
3327         path_list.remove_all_objects();
3328         save_backup();
3329 }
3330
3331 static inline int gcd(int m, int n)
3332 {
3333         int r;
3334         if( m < n ) { r = m;  m = n;  n = r; }
3335         while( (r = m % n) != 0 ) { m = n;  n = r; }
3336         return n;
3337 }
3338
3339 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3340 {
3341         w = 1;  h = 1;
3342         if(!width || !height) return 1;
3343         if( width == 720 && (height == 480 || height == 576) ) {
3344                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3345         }
3346         double ar = (double)width / height;
3347 // square-ish pixels
3348         if( EQUIV(ar, 1.0000) ) return 0;
3349         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3350         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3351         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3352         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3353         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3354         int ww = width, hh = height;
3355         // numerator, denominator must be under mx
3356         int mx = 255, n = gcd(ww, hh);
3357         if( n > 1 ) { ww /= n; hh /= n; }
3358         // search near height in case extra/missing lines
3359         if( ww >= mx || hh >= mx ) {
3360                 double err = height;  // +/- 2 percent height
3361                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3362                         int iw = width, ih = height+i;
3363                         if( (n=gcd(iw, ih)) > 1 ) {
3364                                 int u = iw/n;  if( u >= mx ) continue;
3365                                 int v = ih/n;  if( v >= mx ) continue;
3366                                 double r = (double) u/v, er = fabs(ar-r);
3367                                 if( er >= err ) continue;
3368                                 err = er;  ww = u;  hh = v;
3369                         }
3370                 }
3371         }
3372
3373         w = ww;  h = hh;
3374         return 0;
3375 }
3376
3377 void MWindow::reset_caches()
3378 {
3379         stop_playback(1);
3380         int locked  = gui->get_window_lock();
3381         if( locked ) gui->unlock_window();
3382         gui->resource_thread->stop_draw(1);
3383         gui->resource_thread->source_lock->lock("MWindow::reset_caches");
3384         frame_cache->remove_all();
3385         wave_cache->remove_all();
3386         audio_cache->remove_all();
3387         video_cache->remove_all();
3388         gui->resource_thread->source_lock->unlock();
3389         if( locked ) gui->lock_window("MWindow::reset_caches");
3390         if( cwindow->playback_engine ) {
3391                 if( cwindow->playback_engine->audio_cache )
3392                         cwindow->playback_engine->audio_cache->remove_all();
3393                 if( cwindow->playback_engine->video_cache )
3394                         cwindow->playback_engine->video_cache->remove_all();
3395         }
3396         for(int i = 0; i < vwindows.size(); i++) {
3397                 VWindow *vwindow = vwindows[i];
3398                 if( !vwindow->is_running() ) continue;
3399                 if( !vwindow->playback_engine ) continue;
3400                 if( vwindow->playback_engine->audio_cache )
3401                         vwindow->playback_engine->audio_cache->remove_all();
3402                 if( vwindow->playback_engine->video_cache )
3403                         vwindow->playback_engine->video_cache->remove_all();
3404         }
3405 }
3406
3407 void MWindow::remove_asset_from_caches(Asset *asset)
3408 {
3409         stop_playback(1);
3410         int locked  = gui->get_window_lock();
3411         if( locked ) gui->unlock_window();
3412         gui->resource_thread->stop_draw(1);
3413         gui->resource_thread->source_lock->lock("MWindow::remove_asset_from_caches");
3414         frame_cache->remove_asset(asset);
3415         wave_cache->remove_asset(asset);
3416         audio_cache->delete_entry(asset);
3417         video_cache->delete_entry(asset);
3418         gui->resource_thread->source_lock->unlock();
3419         if( locked ) gui->lock_window("MWindow::remove_asset_from_caches");
3420         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3421                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3422         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3423                 cwindow->playback_engine->video_cache->delete_entry(asset);
3424         for(int i = 0; i < vwindows.size(); i++) {
3425                 VWindow *vwindow = vwindows[i];
3426                 if( !vwindow->is_running() ) continue;
3427                 if( !vwindow->playback_engine ) continue;
3428                 if( vwindow->playback_engine->audio_cache )
3429                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3430                 if( vwindow->playback_engine->video_cache )
3431                         vwindow->playback_engine->video_cache->delete_entry(asset);
3432         }
3433 }
3434
3435
3436 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3437                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3438 {
3439         for(int i = 0; i < drag_assets->total; i++) {
3440                 Indexable *indexable = drag_assets->get(i);
3441                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3442         }
3443
3444 // Remove from VWindow.
3445         for(int i = 0; i < session->drag_clips->total; i++) {
3446                 for(int j = 0; j < vwindows.size(); j++) {
3447                         VWindow *vwindow = vwindows[j];
3448                         if( !vwindow->is_running() ) continue;
3449                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3450                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3451                                 vwindow->delete_source(1, 1);
3452                                 vwindow->gui->unlock_window();
3453                         }
3454                 }
3455         }
3456
3457         for(int i = 0; i < drag_assets->size(); i++) {
3458                 for(int j = 0; j < vwindows.size(); j++) {
3459                         VWindow *vwindow = vwindows[j];
3460                         if( !vwindow->is_running() ) continue;
3461                         if(drag_assets->get(i) == vwindow->get_source()) {
3462                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3463                                 vwindow->delete_source(1, 1);
3464                                 vwindow->gui->unlock_window();
3465                         }
3466                 }
3467         }
3468
3469         for(int i = 0; i < drag_assets->size(); i++) {
3470                 Indexable *indexable = drag_assets->get(i);
3471                 remove_indexfile(indexable);
3472         }
3473
3474 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3475         if(push_undo) undo->update_undo_before();
3476         if(drag_assets) edl->remove_from_project(drag_assets);
3477         if(drag_clips) edl->remove_from_project(drag_clips);
3478         if(redraw) save_backup();
3479         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3480         if(redraw) {
3481                 restart_brender();
3482
3483                 gui->lock_window("MWindow::remove_assets_from_project 3");
3484                 gui->update(1, 1, 1, 1, 0, 1, 0);
3485                 gui->unlock_window();
3486
3487         // Removes from playback here
3488                 sync_parameters(CHANGE_ALL);
3489         }
3490
3491         awindow->gui->async_update_assets();
3492 }
3493
3494 void MWindow::remove_assets_from_disk()
3495 {
3496 // Remove from disk
3497         for(int i = 0; i < session->drag_assets->total; i++)
3498         {
3499                 remove(session->drag_assets->get(i)->path);
3500         }
3501
3502         remove_assets_from_project(1,
3503                 1,
3504                 session->drag_assets,
3505                 session->drag_clips);
3506 }
3507
3508 void MWindow::dump_plugins(FILE *fp)
3509 {
3510         if( !plugindb ) return;
3511         for(int i = 0; i < plugindb->total; i++)
3512         {
3513                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3514                         " synth=%d transition=%d theme=%d %s\n",
3515                         plugindb->get(i)->plugin_type,
3516                         plugindb->get(i)->audio,
3517                         plugindb->get(i)->video,
3518                         plugindb->get(i)->realtime,
3519                         plugindb->get(i)->multichannel,
3520                         plugindb->get(i)->get_synthesis(),
3521                         plugindb->get(i)->transition,
3522                         plugindb->get(i)->theme,
3523                         plugindb->get(i)->title);
3524         }
3525 }
3526
3527 void MWindow::dump_edl(FILE *fp)
3528 {
3529         if( !edl ) return;
3530         edl->dump(fp);
3531 }
3532
3533 void MWindow::dump_undo(FILE *fp)
3534 {
3535         if( !undo ) return;
3536         undo->dump(fp);
3537 }
3538
3539 void MWindow::dump_exe(FILE *fp)
3540 {
3541         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3542         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3543
3544         int ret = -1, n = 100;
3545         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3546                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3547                 ret = 0;
3548         }
3549         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3550
3551         struct stat st;
3552         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3553         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3554         struct tm *tm = localtime(&st.st_mtime);
3555         char mtime[256];
3556         strftime(mtime, sizeof(mtime), "%F %T", tm);
3557         fprintf(fp,"mtime: %s\n", mtime);
3558 #if 0
3559 // people hit ctl-c waiting for this
3560         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3561         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3562         uint8_t *bfr = 0;
3563         int64_t bfrsz = 0;
3564         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3565         int64_t maxsz = 1024*pagsz;
3566         int64_t size = st.st_size, pos = 0;
3567         SHA1 sha1;
3568         while( (bfrsz = size-pos) > 0 ) {
3569                 if( bfrsz > maxsz ) bfrsz = maxsz;
3570                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3571                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3572                 if( bfr == MAP_FAILED ) break;
3573                 sha1.addBytes(bfr, bfrsz);
3574                 munmap(bfr, bfrsz);
3575                 pos += bfrsz;
3576         }
3577         close(fd);
3578         ret = pos < size ? EIO : 0;
3579         fprintf(fp, "SHA1: ");
3580         uint8_t digest[20];  sha1.computeHash(digest);
3581         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3582         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3583         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3584 #endif
3585         fprintf(fp, "\n");
3586 }
3587
3588 void MWindow::trap_hook(FILE *fp, void *vp)
3589 {
3590         MWindow *mwindow = (MWindow *)vp;
3591 //      fprintf(fp, "\nPLUGINS:\n");
3592 //      mwindow->dump_plugins(fp);
3593         fprintf(fp, "\nEDL:\n");
3594         mwindow->dump_edl(fp);
3595         fprintf(fp, "\nUNDO:\n");
3596         mwindow->dump_undo(fp);
3597         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
3598         mwindow->dump_exe(fp);
3599 }
3600
3601
3602
3603
3604
3605
3606 int MWindow::save_defaults()
3607 {
3608         gui->save_defaults(defaults);
3609         edl->save_defaults(defaults);
3610         session->save_defaults(defaults);
3611         preferences->save_defaults(defaults);
3612
3613         for(int i = 0; i < plugin_guis->total; i++)
3614         {
3615 // Pointer comparison
3616                 plugin_guis->get(i)->save_defaults();
3617         }
3618         awindow->save_defaults(defaults);
3619
3620         defaults->save();
3621         return 0;
3622 }
3623
3624 int MWindow::run_script(FileXML *script)
3625 {
3626         int result = 0, result2 = 0;
3627         while(!result && !result2)
3628         {
3629                 result = script->read_tag();
3630                 if(!result)
3631                 {
3632                         if(script->tag.title_is("new_project"))
3633                         {
3634 // Run new in immediate mode.
3635 //                              gui->mainmenu->new_project->run_script(script);
3636                         }
3637                         else
3638                         if(script->tag.title_is("record"))
3639                         {
3640 // Run record as a thread.  It is a terminal command.
3641                                 ;
3642 // Will read the complete scipt file without letting record read it if not
3643 // terminated.
3644                                 result2 = 1;
3645                         }
3646                         else
3647                         {
3648                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3649                         }
3650                 }
3651         }
3652         return result2;
3653 }
3654
3655 // ================================= synchronization
3656
3657
3658 int MWindow::interrupt_indexes()
3659 {
3660         mainprogress->cancelled = 1;
3661         mainindexes->interrupt_build();
3662         return 0;
3663 }
3664
3665
3666
3667 void MWindow::next_time_format()
3668 {
3669         switch(edl->session->time_format)
3670         {
3671                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3672                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3673                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3674                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3675                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3676                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3677                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3678         }
3679
3680         time_format_common();
3681 }
3682
3683 void MWindow::prev_time_format()
3684 {
3685         switch(edl->session->time_format)
3686         {
3687                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3688                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3689                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3690                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3691                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3692                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3693                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3694         }
3695
3696         time_format_common();
3697 }
3698
3699 void MWindow::time_format_common()
3700 {
3701         gui->lock_window("MWindow::next_time_format");
3702         gui->redraw_time_dependancies();
3703
3704
3705         char string[BCTEXTLEN], string2[BCTEXTLEN];
3706         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3707         gui->show_message(string);
3708         gui->flush();
3709         gui->unlock_window();
3710 }
3711
3712
3713 int MWindow::set_filename(const char *filename)
3714 {
3715         if( filename != session->filename )
3716                 strcpy(session->filename, filename);
3717         if( filename != edl->path )
3718                 strcpy(edl->path, filename);
3719
3720         if(gui)
3721         {
3722                 if(filename[0] == 0)
3723                 {
3724                         gui->set_title(PROGRAM_NAME);
3725                 }
3726                 else
3727                 {
3728                         FileSystem dir;
3729                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3730                         dir.extract_name(string, filename);
3731                         sprintf(string2, PROGRAM_NAME ": %s", string);
3732                         gui->set_title(string2);
3733                 }
3734         }
3735         return 0;
3736 }
3737
3738
3739
3740
3741
3742
3743
3744
3745 int MWindow::set_loop_boundaries()
3746 {
3747         double start = edl->local_session->get_selectionstart();
3748         double end = edl->local_session->get_selectionend();
3749
3750         if(start !=
3751                 end)
3752         {
3753                 ;
3754         }
3755         else
3756         if(edl->tracks->total_length())
3757         {
3758                 start = 0;
3759                 end = edl->tracks->total_length();
3760         }
3761         else
3762         {
3763                 start = end = 0;
3764         }
3765
3766         if(edl->local_session->loop_playback && start != end)
3767         {
3768                 edl->local_session->loop_start = start;
3769                 edl->local_session->loop_end = end;
3770         }
3771         return 0;
3772 }
3773
3774
3775
3776
3777
3778
3779
3780 int MWindow::reset_meters()
3781 {
3782         cwindow->gui->lock_window("MWindow::reset_meters 1");
3783         cwindow->gui->meters->reset_meters();
3784         cwindow->gui->unlock_window();
3785
3786         for(int j = 0; j < vwindows.size(); j++) {
3787                 VWindow *vwindow = vwindows[j];
3788                 if( !vwindow->is_running() ) continue;
3789                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3790                 vwindow->gui->meters->reset_meters();
3791                 vwindow->gui->unlock_window();
3792         }
3793
3794         lwindow->gui->lock_window("MWindow::reset_meters 3");
3795         lwindow->gui->panel->reset_meters();
3796         lwindow->gui->unlock_window();
3797
3798         gui->lock_window("MWindow::reset_meters 4");
3799         gui->reset_meters();
3800         gui->unlock_window();
3801         return 0;
3802 }
3803
3804
3805 void MWindow::resync_guis()
3806 {
3807 // Update GUIs
3808         restart_brender();
3809         gui->lock_window("MWindow::resync_guis");
3810         gui->update(1, 1, 1, 1, 1, 1, 0);
3811         gui->unlock_window();
3812
3813         cwindow->gui->lock_window("MWindow::resync_guis");
3814         cwindow->gui->resize_event(cwindow->gui->get_w(),
3815                 cwindow->gui->get_h());
3816         int channels = edl->session->audio_channels;
3817         cwindow->gui->meters->set_meters(channels, 1);
3818         cwindow->gui->flush();
3819         cwindow->gui->unlock_window();
3820
3821         for(int i = 0; i < vwindows.size(); i++) {
3822                 VWindow *vwindow = vwindows[i];
3823                 if( !vwindow->is_running() ) continue;
3824                 vwindow->gui->lock_window("MWindow::resync_guis");
3825                 vwindow->gui->resize_event(vwindow->gui->get_w(),
3826                         vwindow->gui->get_h());
3827                 vwindow->gui->meters->set_meters(channels, 1);
3828                 vwindow->gui->flush();
3829                 vwindow->gui->unlock_window();
3830         }
3831
3832         lwindow->gui->lock_window("MWindow::resync_guis");
3833         lwindow->gui->panel->set_meters(channels, 1);
3834         lwindow->gui->flush();
3835         lwindow->gui->unlock_window();
3836
3837 // Warn user
3838         if(((edl->session->output_w % 4) ||
3839                 (edl->session->output_h % 4)) &&
3840                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3841         {
3842                 MainError::show_error(
3843                         _("This project's dimensions are not multiples of 4 so\n"
3844                         "it can't be rendered by OpenGL."));
3845         }
3846
3847
3848 // Flash frame
3849         sync_parameters(CHANGE_ALL);
3850 }
3851
3852 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3853 {
3854         File *file = new File;
3855         EDLSession *session = edl->session;
3856         double old_framerate = session->frame_rate;
3857         double old_samplerate = session->sample_rate;
3858         int old_auto_keyframes = session->auto_keyframes;
3859         session->auto_keyframes = 0;
3860         int result = file->open_file(preferences, asset, 1, 0);
3861         if( !result && delete_tracks > 0 )
3862                 undo->update_undo_before();
3863         int video_layers = asset->get_video_layers();
3864         if( !result && asset->video_data && vstream < video_layers ) {
3865                 // try to get asset up to date, may fail
3866                 file->select_video_stream(asset, vstream);
3867                 // either way use what was/is there.
3868                 double framerate = asset->get_frame_rate();
3869                 int width = asset->get_w();
3870                 int height = asset->get_h();
3871                 // must be multiple of 4 for opengl
3872                 width = (width+3) & ~3;  height = (height+3) & ~3;
3873                 int driver = session->playback_config->vconfig->driver;
3874                 int color_model = file->get_best_colormodel(asset, driver);
3875 //              color_model = BC_CModels::is_yuv(color_model) ?
3876 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3877 //                      BC_CModels::is_float(color_model) ?
3878 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3879 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3880 // have alpha for now
3881                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
3882                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
3883                 session->color_model = color_model;
3884                 session->output_w = width;
3885                 session->output_h = height;
3886                 session->frame_rate = framerate;
3887                 // not, asset->actual_width/actual_height
3888                 asset->width = session->output_w;
3889                 asset->height = session->output_h;
3890                 asset->frame_rate = session->frame_rate;
3891                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3892                         session->output_w, session->output_h);
3893                 Track *track = edl->tracks->first;
3894                 for( Track *next_track=0; track; track=next_track ) {
3895                         next_track = track->next;
3896                         if( track->data_type != TRACK_VIDEO ) continue;
3897                         if( delete_tracks ) {
3898                                 Edit *edit = track->edits->first;
3899                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3900                                         next_edit = edit->next;
3901                                         if( edit->channel != vstream ||
3902                                             !edit->asset || !edit->asset->is_asset ||
3903                                             !asset->equivalent(*edit->asset,1,1,edl) )
3904                                                 delete edit;
3905                                 }
3906                         }
3907                         if( track->edits->first ) {
3908                                 track->track_w = edl->session->output_w;
3909                                 track->track_h = edl->session->output_h;
3910                         }
3911                         else if( delete_tracks )
3912                                 edl->tracks->delete_track(track);
3913                 }
3914                 edl->retrack();
3915                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3916         }
3917         if( !result && asset->audio_data && asset->channels > 0 ) {
3918                 session->sample_rate = asset->get_sample_rate();
3919                 int64_t channel_mask = 0;
3920                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
3921                         file->get_audio_for_video(vstream, astream, channel_mask);
3922                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3923                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3924                 int channels = 0;
3925                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3926                 if( channels < 1 ) channels = 1;
3927                 if( channels > 6 ) channels = 6;
3928                 session->audio_tracks = session->audio_channels = channels;
3929                 switch( channels ) {
3930                 case 6:
3931                         session->achannel_positions[0] = 90;
3932                         session->achannel_positions[1] = 150;
3933                         session->achannel_positions[2] = 30;
3934                         session->achannel_positions[3] = 210;
3935                         session->achannel_positions[4] = 330;
3936                         session->achannel_positions[5] = 270;
3937                         break;
3938                 case 2:
3939                         session->achannel_positions[0] = 180;
3940                         session->achannel_positions[1] = 0;
3941                         break;
3942                 case 1:
3943                         session->achannel_positions[1] = 90;
3944                         break;
3945                 default: {
3946                         if( !channels ) break;
3947                         double t = 0, dt = 360./channels;
3948                         for( int i=channels; --i>=0; t+=dt )
3949                                 session->achannel_positions[i] = int(t+0.5);
3950                         break; }
3951                 }
3952                 remap_audio(MWindow::AUDIO_1_TO_1);
3953
3954                 if( delete_tracks ) {
3955                         Track *track = edl->tracks->first;
3956                         for( Track *next_track=0; track; track=next_track ) {
3957                                 next_track = track->next;
3958                                 if( track->data_type != TRACK_AUDIO ) continue;
3959                                 Edit *edit = track->edits->first;
3960                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
3961                                         next_edit = edit->next;
3962                                         if( !((1<<edit->channel) & channel_mask) ||
3963                                             !edit->asset || !edit->asset->is_asset ||
3964                                             !asset->equivalent(*edit->asset,1,1,edl) )
3965                                                 delete edit;
3966                                 }
3967                                 if( !track->edits->first )
3968                                         edl->tracks->delete_track(track);
3969                         }
3970                 }
3971                 edl->rechannel();
3972                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
3973         }
3974         delete file;
3975         session->auto_keyframes = old_auto_keyframes;
3976         if( !result && delete_tracks > 0 ) {
3977                 save_backup();
3978                 undo->update_undo_after(_("select asset"), LOAD_ALL);
3979         }
3980         resync_guis();
3981         return result;
3982 }
3983
3984 int MWindow::select_asset(int vtrack, int delete_tracks)
3985 {
3986         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
3987         if( !track )
3988                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
3989         if( !track ) return 1;
3990         Edit *edit = track->edits->first;
3991         if( !edit ) return 1;
3992         Asset *asset = edit->asset;
3993         if( !asset || !asset->is_asset ) return 1;
3994         return select_asset(asset, edit->channel, 0, delete_tracks);
3995 }
3996
3997 void MWindow::dump_plugindb(FILE *fp)
3998 {
3999         if( !plugindb ) return;
4000         for(int i = 0; i < plugindb->total; i++)
4001                 plugindb->get(i)->dump(fp);
4002 }
4003
4004 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
4005 {
4006         Auto *current = 0;
4007         double unit_position = edl->local_session->get_selectionstart(1);
4008         unit_position = patch->track->to_units(unit_position, 0);
4009
4010         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
4011         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4012 }
4013
4014 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
4015 {
4016         Auto *current = 0;
4017         double unit_position = edl->local_session->get_selectionstart(1);
4018         unit_position = patch->track->to_units(unit_position, 0);
4019
4020         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
4021         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4022 }
4023
4024 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
4025 {
4026         Auto *current = 0;
4027         double unit_position = edl->local_session->get_selectionstart(1);
4028         unit_position = patch->track->to_units(unit_position, 0);
4029
4030         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
4031         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4032 }
4033
4034 PatchGUI *MWindow::get_patchgui(Track *track)
4035 {
4036         PatchGUI *patchgui = 0;
4037         TimelinePane **panes = gui->pane;
4038         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
4039                 if( !panes[i] ) continue;
4040                 PatchBay *patchbay = panes[i]->patchbay;
4041                 if( !patchbay ) continue;
4042                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
4043                         if( patchbay->patches.values[j]->track == track )
4044                                 patchgui = patchbay->patches.values[j];
4045                 }
4046         }
4047         return patchgui;
4048 }
4049