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