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