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