2dbb5b3af5d818128b87a1f29aa1e8e33aaaab12
[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                 render_proxy(orig_idxbls);
1849         }
1850
1851 // need to update undo before project, since mwindow is unlocked & a new load
1852 // can begin here.  Should really prevent loading until we're done.
1853 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1854         undo->update_undo_after(_("load"), LOAD_ALL);
1855
1856         for(int i = 0; i < new_edls.size(); i++)
1857         {
1858                 new_edls[i]->remove_user();
1859         }
1860 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1861
1862         new_edls.remove_all();
1863
1864         for(int i = 0; i < new_assets.size(); i++)
1865         {
1866                 new_assets[i]->Garbage::remove_user();
1867         }
1868
1869         new_assets.remove_all();
1870         new_files.remove_all_objects();
1871
1872
1873 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1874         if(load_mode == LOADMODE_REPLACE ||
1875                 load_mode == LOADMODE_REPLACE_CONCATENATE)
1876         {
1877                 session->changes_made = 0;
1878         }
1879         else
1880         {
1881                 session->changes_made = 1;
1882         }
1883
1884         gui->stop_hourglass();
1885
1886
1887 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1888         update_project(load_mode);
1889
1890 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1891
1892         return 0;
1893 }
1894
1895 void MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
1896 {
1897         Asset *format_asset = new Asset;
1898         format_asset->format = FILE_FFMPEG;
1899         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
1900         ProxyRender proxy_render(this, format_asset);
1901         int new_scale = edl->session->proxy_scale;
1902         int use_scaler = edl->session->proxy_use_scaler;
1903
1904         for( int i=0; i<new_idxbls.size(); ++i ) {
1905                 Indexable *orig = new_idxbls.get(i);
1906                 Asset *proxy = proxy_render.add_original(orig, new_scale);
1907                 if( !proxy ) continue;
1908                 FileSystem fs;
1909                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
1910                 int got_it = exists && // if proxy exists, and is newer than orig
1911                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
1912                 if( got_it ) continue;
1913                 proxy_render.add_needed(orig, proxy);
1914         }
1915
1916 // render needed proxies
1917         int result = proxy_render.create_needed_proxies(new_scale);
1918         if( !result ) {
1919                 add_proxy(use_scaler,
1920                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
1921         }
1922         format_asset->remove_user();
1923 }
1924
1925 void MWindow::test_plugins(EDL *new_edl, char *path)
1926 {
1927         char string[BCTEXTLEN];
1928
1929 // Do a check weather plugins exist
1930         for(Track *track = new_edl->tracks->first; track; track = track->next)
1931         {
1932                 for(int k = 0; k < track->plugin_set.total; k++)
1933                 {
1934                         PluginSet *plugin_set = track->plugin_set[k];
1935                         for(Plugin *plugin = (Plugin*)plugin_set->first;
1936                                 plugin;
1937                                 plugin = (Plugin*)plugin->next)
1938                         {
1939                                 if(plugin->plugin_type == PLUGIN_STANDALONE)
1940                                 {
1941 // ok we need to find it in plugindb
1942                                         int plugin_found = 0;
1943
1944                                         for(int j = 0; j < plugindb->size(); j++)
1945                                         {
1946                                                 PluginServer *server = plugindb->get(j);
1947                                                 if(server->title &&
1948                                                         !strcasecmp(server->title, plugin->title) &&
1949                                                         ((track->data_type == TRACK_AUDIO && server->audio) ||
1950                                                         (track->data_type == TRACK_VIDEO && server->video)) &&
1951                                                         (!server->transition))
1952                                                         plugin_found = 1;
1953                                         }
1954
1955                                         if (!plugin_found)
1956                                         {
1957                                                 sprintf(string,
1958         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1959           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1960                                                         "effect", plugin->title,
1961                                                         path);
1962                                                 MainError::show_error(string);
1963                                         }
1964                                 }
1965                         }
1966                 }
1967
1968                 for(Edit *edit = (Edit*)track->edits->first;
1969                         edit;
1970                         edit = (Edit*)edit->next)
1971                 {
1972                         if (edit->transition)
1973                         {
1974 // ok we need to find transition in plugindb
1975
1976                                 int transition_found = 0;
1977                                 for(int j = 0; j < plugindb->size(); j++)
1978                                 {
1979                                         PluginServer *server = plugindb->get(j);
1980                                         if(server->title &&
1981                                                 !strcasecmp(server->title, edit->transition->title) &&
1982                                                 ((track->data_type == TRACK_AUDIO && server->audio) ||
1983                                                 (track->data_type == TRACK_VIDEO && server->video)) &&
1984                                                 (server->transition))
1985                                                 transition_found = 1;
1986                                 }
1987
1988                                 if (!transition_found)
1989                                 {
1990                                         sprintf(string,
1991         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
1992           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
1993                                                 "transition", edit->transition->title,
1994                                                 path);
1995                                         MainError::show_error(string);
1996                                 }
1997                         }
1998                 }
1999         }
2000 }
2001
2002
2003 void MWindow::init_shm()
2004 {
2005 // Fix shared memory
2006         FILE *fd = fopen("/proc/sys/kernel/shmmax", "w");
2007         if(fd) {
2008                 fprintf(fd, "0x7fffffff");
2009                 fclose(fd);
2010         }
2011         fd = 0;
2012
2013         fd = fopen("/proc/sys/kernel/shmmax", "r");
2014         if(!fd) {
2015                 MainError::show_error("MWindow::init_shm: couldn't open /proc/sys/kernel/shmmax for reading.\n");
2016                 return;
2017         }
2018
2019         int64_t result = 0;
2020         fscanf(fd, "%jd", &result);
2021         fclose(fd);
2022         fd = 0;
2023         if(result < 0x7fffffff) {
2024                 eprintf(_("MWindow::init_shm: /proc/sys/kernel/shmmax is %p.\n"
2025                         "you probably need to be root, or:\n"
2026                         "as root, run: echo 0x7fffffff > /proc/sys/kernel/shmmax\n"
2027                         "before trying to start cinelerra.\n"
2028                         "It should be at least 0x7fffffff for Cinelerra.\n"), (void *)result);
2029         }
2030 }
2031
2032 void MWindow::create_objects(int want_gui,
2033         int want_new,
2034         char *config_path)
2035 {
2036         const int debug = 0;
2037         if(debug) PRINT_TRACE
2038
2039 // For some reason, init_signals must come after show_splash or the signals won't
2040 // get trapped.
2041         init_signals();
2042         if(debug) PRINT_TRACE
2043         init_3d();
2044
2045         if(debug) PRINT_TRACE
2046         show_splash();
2047
2048         if(debug) PRINT_TRACE
2049         default_standard = default_std();
2050         init_defaults(defaults, config_path);
2051         check_language();
2052         init_preferences();
2053         if(splash_window)
2054                 splash_window->operation->update(_("Initializing Plugins"));
2055         init_plugins(this, preferences);
2056         if(debug) PRINT_TRACE
2057         init_ladspa_plugins(this, preferences);
2058         if(debug) PRINT_TRACE
2059         init_plugin_tips(*plugindb, cin_lang);
2060         if(splash_window)
2061                 splash_window->operation->update(_("Initializing GUI"));
2062         if(debug) PRINT_TRACE
2063         init_theme();
2064
2065         if(debug) PRINT_TRACE
2066         init_error();
2067
2068         if(splash_window)
2069                 splash_window->operation->update(_("Initializing Fonts"));
2070         char string[BCTEXTLEN];
2071         strcpy(string, preferences->plugin_dir);
2072         strcat(string, "/" FONT_SEARCHPATH);
2073         BC_Resources::init_fontconfig(string);
2074         if(debug) PRINT_TRACE
2075
2076 // Initialize before too much else is running
2077 // Preferences & theme are required for building MPEG table of contents
2078
2079 // Default project created here
2080         init_edl();
2081         if(debug) PRINT_TRACE
2082
2083         init_cache();
2084         if(debug) PRINT_TRACE
2085
2086         Timer timer;
2087
2088         init_awindow();
2089         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2090
2091         init_compositor();
2092         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2093
2094 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2095         if(session->show_vwindow)
2096                 get_viewer(1, DEFAULT_VWINDOW);
2097         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2098
2099         init_gui();
2100         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2101
2102         init_levelwindow();
2103         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2104
2105         init_indexes();
2106         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2107
2108         init_channeldb();
2109         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2110
2111         init_gwindow();
2112         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2113
2114         init_render();
2115         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2116
2117         init_brender();
2118         init_exportedl();
2119         init_commercials();
2120         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2121         mainprogress = new MainProgress(this, gui);
2122         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2123         undo = new MainUndo(this);
2124
2125         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2126
2127         plugin_guis = new ArrayList<PluginServer*>;
2128         dead_plugins = new ArrayList<PluginServer*>;
2129         keyframe_threads = new ArrayList<KeyFrameThread*>;
2130
2131         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2132                 __LINE__,
2133                 vwindows.size(),
2134                 session->show_vwindow);
2135
2136 // Show all vwindows
2137 //      if(session->show_vwindow) {
2138 //              for(int j = 0; j < vwindows.size(); j++) {
2139 //                      VWindow *vwindow = vwindows[j];
2140 //                      if( !vwindow->is_running() ) continue;
2141 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2142 //                              __LINE__,
2143 //                              vwindow);
2144 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2145 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2146 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2147 //                      vwindow->gui->show_window();
2148 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2149 //                      vwindow->gui->unlock_window();
2150 //              }
2151 //      }
2152
2153
2154         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2155
2156         if(session->show_cwindow)
2157         {
2158                 cwindow->gui->lock_window("MWindow::create_objects 1");
2159                 cwindow->gui->show_window();
2160                 cwindow->gui->unlock_window();
2161         }
2162
2163         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2164         if(session->show_awindow)
2165         {
2166                 awindow->gui->lock_window("MWindow::create_objects 1");
2167                 awindow->gui->show_window();
2168                 awindow->gui->unlock_window();
2169         }
2170
2171         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2172         if(session->show_lwindow)
2173         {
2174                 lwindow->gui->lock_window("MWindow::create_objects 1");
2175                 lwindow->gui->show_window();
2176                 lwindow->gui->unlock_window();
2177         }
2178
2179         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2180                 __LINE__,
2181                 (int)timer.get_difference(),
2182                 gwindow->gui);
2183         if(session->show_gwindow)
2184         {
2185                 gwindow->gui->lock_window("MWindow::create_objects 1");
2186                 gwindow->gui->show_window();
2187                 gwindow->gui->unlock_window();
2188         }
2189
2190         if(debug) PRINT_TRACE
2191
2192         gui->lock_window("MWindow::create_objects 1");
2193         gui->mainmenu->load_defaults(defaults);
2194         gui->mainmenu->update_toggles(0);
2195         gui->update_patchbay();
2196         gui->draw_canvas(0, 0);
2197         gui->draw_cursor(1);
2198         gui->show_window();
2199         gui->raise_window();
2200         gui->unlock_window();
2201
2202         if(debug) PRINT_TRACE
2203
2204         if(preferences->use_tipwindow)
2205                 init_tipwindow();
2206         if(debug) PRINT_TRACE
2207
2208         gui->add_keyboard_listener(
2209                 (int (BC_WindowBase::*)(BC_WindowBase *))
2210                 &MWindowGUI::keyboard_listener);
2211
2212         hide_splash();
2213         init_shm();
2214         if(debug) PRINT_TRACE
2215
2216         BC_WindowBase::get_resources()->vframe_shm = 1;
2217 }
2218
2219
2220 void MWindow::show_splash()
2221 {
2222 #include "data/heroine_logo9_png.h"
2223         VFrame *frame = new VFramePng(heroine_logo9_png);
2224         BC_DisplayInfo dpyi;
2225         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2226         int rr = (rw < rh ? rw : rh) / 4;
2227         splash_window = new SplashGUI(frame, rr, rr);
2228         splash_window->create_objects();
2229 }
2230
2231 void MWindow::hide_splash()
2232 {
2233         if(splash_window)
2234                 delete splash_window;
2235         splash_window = 0;
2236 }
2237
2238
2239 void MWindow::start()
2240 {
2241 ENABLE_BUFFER
2242 //PRINT_TRACE
2243 //      vwindows[DEFAULT_VWINDOW]->start();
2244         awindow->start();
2245 //PRINT_TRACE
2246         cwindow->start();
2247 //PRINT_TRACE
2248         lwindow->start();
2249 //PRINT_TRACE
2250         gwindow->start();
2251 //PRINT_TRACE
2252 //      Thread::start();
2253 //PRINT_TRACE
2254         playback_3d->start();
2255 //PRINT_TRACE
2256 }
2257
2258 void MWindow::run()
2259 {
2260         run_lock->lock("MWindow::run");
2261         gui->run_window();
2262         stop_playback(1);
2263
2264         brender_lock->lock("MWindow::run 1");
2265         delete brender;         brender = 0;
2266         brender_lock->unlock();
2267
2268         interrupt_indexes();
2269         clean_indexes();
2270         save_defaults();
2271         run_lock->unlock();
2272 }
2273
2274 void MWindow::show_vwindow()
2275 {
2276         int total_running = 0;
2277         session->show_vwindow = 1;
2278
2279 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2280 // Raise all windows which are visible
2281         for(int j = 0; j < vwindows.size(); j++) {
2282                 VWindow *vwindow = vwindows[j];
2283                 if( !vwindow->is_running() ) continue;
2284                 vwindow->gui->lock_window("MWindow::show_vwindow");
2285                 vwindow->gui->show_window(0);
2286                 vwindow->gui->raise_window();
2287                 vwindow->gui->flush();
2288                 vwindow->gui->unlock_window();
2289                 total_running++;
2290         }
2291
2292 // If no windows visible
2293         if(!total_running)
2294         {
2295                 get_viewer(1, DEFAULT_VWINDOW);
2296         }
2297
2298         gui->mainmenu->show_vwindow->set_checked(1);
2299 }
2300
2301 void MWindow::show_awindow()
2302 {
2303         session->show_awindow = 1;
2304         awindow->gui->lock_window("MWindow::show_awindow");
2305         awindow->gui->show_window();
2306         awindow->gui->raise_window();
2307         awindow->gui->flush();
2308         awindow->gui->unlock_window();
2309         gui->mainmenu->show_awindow->set_checked(1);
2310 }
2311
2312 char *MWindow::get_cwindow_display()
2313 {
2314         char *x11_host = screens < 2 || session->window_config == 0 ?
2315                 session->a_x11_host : session->b_x11_host;
2316         return *x11_host ? x11_host : 0;
2317 }
2318
2319 void MWindow::show_cwindow()
2320 {
2321         session->show_cwindow = 1;
2322         cwindow->show_window();
2323         gui->mainmenu->show_cwindow->set_checked(1);
2324 }
2325
2326 void MWindow::show_gwindow()
2327 {
2328         session->show_gwindow = 1;
2329
2330         gwindow->gui->lock_window("MWindow::show_gwindow");
2331         gwindow->gui->show_window();
2332         gwindow->gui->raise_window();
2333         gwindow->gui->flush();
2334         gwindow->gui->unlock_window();
2335
2336         gui->mainmenu->show_gwindow->set_checked(1);
2337 }
2338 void MWindow::hide_gwindow()
2339 {
2340         session->show_gwindow = 0;
2341
2342         gwindow->gui->lock_window("MWindow::show_gwindow");
2343         gwindow->gui->hide_window();
2344         gwindow->gui->unlock_window();
2345 }
2346
2347 void MWindow::show_lwindow()
2348 {
2349         session->show_lwindow = 1;
2350         lwindow->gui->lock_window("MWindow::show_lwindow");
2351         lwindow->gui->show_window();
2352         lwindow->gui->raise_window();
2353         lwindow->gui->flush();
2354         lwindow->gui->unlock_window();
2355         gui->mainmenu->show_lwindow->set_checked(1);
2356 }
2357
2358 int MWindow::tile_windows(int window_config)
2359 {
2360         int need_reload = 0;
2361         int play_config = window_config==0 ? 0 : 1;
2362         edl->session->playback_config->load_defaults(defaults, play_config);
2363         session->default_window_positions(window_config);
2364         if( screens == 1 ) {
2365                 gui->default_positions();
2366                 sync_parameters(CHANGE_ALL);
2367         }
2368         else
2369                 need_reload = 1;
2370         return need_reload;
2371 }
2372
2373 void MWindow::toggle_loop_playback()
2374 {
2375         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2376         set_loop_boundaries();
2377         save_backup();
2378
2379         gui->draw_overlays(1);
2380         sync_parameters(CHANGE_PARAMS);
2381 }
2382
2383 //void MWindow::set_titles(int value)
2384 //{
2385 //      edl->session->show_titles = value;
2386 //      trackmovement(edl->local_session->track_start);
2387 //}
2388
2389 void MWindow::set_screens(int value)
2390 {
2391         screens = value;
2392 }
2393
2394 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2395 {
2396         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2397         edl->session->auto_keyframes = value;
2398         gui->mbuttons->edit_panel->keyframe->update(value);
2399         gui->flush();
2400         if(lock_mwindow) gui->unlock_window();
2401
2402         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2403         cwindow->gui->edit_panel->keyframe->update(value);
2404         cwindow->gui->flush();
2405         if(lock_cwindow) cwindow->gui->unlock_window();
2406 }
2407
2408 void MWindow::set_auto_visibility(Autos *autos, int value)
2409 {
2410         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2411                 edl->session->auto_conf->plugins = value;
2412         else if( autos->autoidx >= 0 )
2413                 edl->session->auto_conf->autos[autos->autoidx] = value;
2414         else
2415                 return;
2416
2417         gui->update(0, 1, 0, 0, 0, 0, 0);
2418         gui->mainmenu->update_toggles(1);
2419         gui->unlock_window();
2420         gwindow->gui->update_toggles(1);
2421         gui->lock_window("MWindow::set_auto_visibility");
2422 }
2423
2424 void MWindow::set_keyframe_type(int mode)
2425 {
2426         gui->lock_window("MWindow::set_keyframe_type");
2427         edl->local_session->floatauto_type = mode;
2428         gui->mainmenu->update_toggles(0);
2429         gui->unlock_window();
2430 }
2431
2432 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2433 {
2434         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2435         edl->session->editing_mode = new_editing_mode;
2436         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2437         gui->mbuttons->edit_panel->update();
2438         gui->set_editing_mode(1);
2439         if(lock_mwindow) gui->unlock_window();
2440
2441
2442         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2443         cwindow->gui->edit_panel->update();
2444         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2445         if(lock_cwindow) cwindow->gui->unlock_window();
2446         return 0;
2447 }
2448
2449 void MWindow::toggle_editing_mode()
2450 {
2451         int mode = edl->session->editing_mode;
2452         if( mode == EDITING_ARROW )
2453                 set_editing_mode(EDITING_IBEAM, 0, 1);
2454         else
2455                 set_editing_mode(EDITING_ARROW, 0, 1);
2456 }
2457
2458
2459 void MWindow::set_labels_follow_edits(int value)
2460 {
2461         gui->lock_window("MWindow::set_labels_follow_edits");
2462         edl->session->labels_follow_edits = value;
2463         gui->mbuttons->edit_panel->locklabels->update(value);
2464         gui->mainmenu->labels_follow_edits->set_checked(value);
2465         gui->flush();
2466         gui->unlock_window();
2467 }
2468
2469 void MWindow::sync_parameters(int change_type)
2470 {
2471         if( in_destructor ) return;
2472
2473 // Sync engines which are playing back
2474         if(cwindow->playback_engine->is_playing_back)
2475         {
2476                 if(change_type == CHANGE_PARAMS)
2477                 {
2478 // TODO: block keyframes until synchronization is done
2479                         cwindow->playback_engine->sync_parameters(edl);
2480                 }
2481                 else
2482 // Stop and restart
2483                 {
2484                         int command = cwindow->playback_engine->command->command;
2485                         cwindow->playback_engine->que->send_command(STOP,
2486                                 CHANGE_NONE,
2487                                 0,
2488                                 0);
2489 // Waiting for tracking to finish would make the restart position more
2490 // accurate but it can't lock the window to stop tracking for some reason.
2491 // Not waiting for tracking gives a faster response but restart position is
2492 // only as accurate as the last tracking update.
2493                         cwindow->playback_engine->interrupt_playback(0);
2494                         cwindow->playback_engine->que->send_command(command,
2495                                         change_type,
2496                                         edl,
2497                                         1,
2498                                         0);
2499                 }
2500         }
2501         else
2502         {
2503                 cwindow->playback_engine->que->send_command(CURRENT_FRAME,
2504                                                         change_type,
2505                                                         edl,
2506                                                         1);
2507         }
2508 }
2509
2510 void MWindow::age_caches()
2511 {
2512 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
2513 // __LINE__,
2514 // preferences->cache_size,
2515 // audio_cache->get_memory_usage(1),
2516 // video_cache->get_memory_usage(1),
2517 // frame_cache->get_memory_usage(),
2518 // wave_cache->get_memory_usage(),
2519 // memory_usage);
2520         frame_cache->age_cache(512);
2521         wave_cache->age_cache(8192);
2522
2523         int64_t memory_usage;
2524         int64_t prev_memory_usage = 0;
2525         int result = 0;
2526         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
2527         while( !result && prev_memory_usage !=
2528                 (memory_usage=video_cache->get_memory_usage(1)) &&
2529                 memory_usage > video_size ) {
2530                 video_cache->delete_oldest();
2531                 prev_memory_usage = memory_usage;
2532         }
2533
2534         prev_memory_usage = 0;
2535         result = 0;
2536         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
2537         while( !result && prev_memory_usage !=
2538                 (memory_usage=audio_cache->get_memory_usage(1)) &&
2539                 memory_usage > audio_size ) {
2540                 audio_cache->delete_oldest();
2541                 prev_memory_usage = memory_usage;
2542         }
2543 }
2544
2545 void MWindow::reset_android_remote()
2546 {
2547         gui->use_android_remote(preferences->android_remote);
2548 }
2549
2550
2551 void MWindow::show_keyframe_gui(Plugin *plugin)
2552 {
2553         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
2554 // Find existing thread
2555         for(int i = 0; i < keyframe_threads->size(); i++)
2556         {
2557                 if(keyframe_threads->get(i)->plugin == plugin)
2558                 {
2559                         keyframe_threads->get(i)->start_window(plugin, 0);
2560                         keyframe_gui_lock->unlock();
2561                         return;
2562                 }
2563         }
2564
2565 // Find unused thread
2566         for(int i = 0; i < keyframe_threads->size(); i++)
2567         {
2568                 if(!keyframe_threads->get(i)->plugin)
2569                 {
2570                         keyframe_threads->get(i)->start_window(plugin, 0);
2571                         keyframe_gui_lock->unlock();
2572                         return;
2573                 }
2574         }
2575
2576 // Create new thread
2577         KeyFrameThread *thread = new KeyFrameThread(this);
2578         keyframe_threads->append(thread);
2579         thread->start_window(plugin, 0);
2580
2581         keyframe_gui_lock->unlock();
2582 }
2583
2584
2585
2586
2587
2588 void MWindow::show_plugin(Plugin *plugin)
2589 {
2590         int done = 0;
2591
2592 SET_TRACE
2593 // Remove previously deleted plugin GUIs
2594         dead_plugin_lock->lock("MWindow::show_plugin");
2595         dead_plugins->remove_all_objects();
2596         dead_plugin_lock->unlock();
2597
2598 //printf("MWindow::show_plugin %d\n", __LINE__);
2599 SET_TRACE
2600
2601
2602         plugin_gui_lock->lock("MWindow::show_plugin");
2603         for(int i = 0; i < plugin_guis->total; i++)
2604         {
2605 // Pointer comparison
2606                 if(plugin_guis->get(i)->plugin == plugin)
2607                 {
2608                         plugin_guis->get(i)->raise_window();
2609                         done = 1;
2610                         break;
2611                 }
2612         }
2613 SET_TRACE
2614
2615 //printf("MWindow::show_plugin 1\n");
2616         if( !done && !plugin->track ) {
2617                 printf("MWindow::show_plugin track not defined.\n");
2618                 done = 1;
2619         }
2620         if( !done ) {
2621                 PluginServer *server = scan_plugindb(plugin->title,
2622                         plugin->track->data_type);
2623
2624 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
2625                 if(server && server->uses_gui)
2626                 {
2627                         PluginServer *gui = new PluginServer(*server);
2628                         plugin_guis->append(gui);
2629 // Needs mwindow to do GUI
2630                         gui->set_mwindow(this);
2631                         gui->open_plugin(0, preferences, edl, plugin);
2632                         plugin->show = 1;
2633                         gui->show_gui();
2634                 }
2635         }
2636         plugin_gui_lock->unlock();
2637 //printf("MWindow::show_plugin %d\n", __LINE__);
2638 SET_TRACE
2639 //sleep(1);
2640 //printf("MWindow::show_plugin 2\n");
2641 }
2642
2643 void MWindow::hide_plugin(Plugin *plugin, int lock)
2644 {
2645         plugin->show = 0;
2646 // Update the toggle
2647         gui->lock_window("MWindow::hide_plugin");
2648         gui->update(0, 1, 0, 0, 0, 0, 0);
2649         gui->unlock_window();
2650
2651         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
2652         for(int i = 0; i < plugin_guis->total; i++)
2653         {
2654                 if(plugin_guis->get(i)->plugin == plugin)
2655                 {
2656                         PluginServer *ptr = plugin_guis->get(i);
2657                         plugin_guis->remove(ptr);
2658                         if(lock) plugin_gui_lock->unlock();
2659 // Last command executed in client side close
2660 // Schedule for deletion
2661                         ptr->hide_gui();
2662                         delete_plugin(ptr);
2663 //sleep(1);
2664                         return;
2665                 }
2666         }
2667         if(lock) plugin_gui_lock->unlock();
2668 }
2669
2670 void MWindow::delete_plugin(PluginServer *plugin)
2671 {
2672         dead_plugin_lock->lock("MWindow::delete_plugin");
2673         dead_plugins->append(plugin);
2674         dead_plugin_lock->unlock();
2675 }
2676
2677 void MWindow::hide_plugins()
2678 {
2679         plugin_gui_lock->lock("MWindow::hide_plugins 1");
2680         while(plugin_guis->size())
2681         {
2682                 PluginServer *ptr = plugin_guis->get(0);
2683                 plugin_guis->remove(ptr);
2684                 plugin_gui_lock->unlock();
2685 // Last command executed in client side close
2686 // Schedule for deletion
2687                 ptr->hide_gui();
2688                 delete_plugin(ptr);
2689                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
2690         }
2691         plugin_gui_lock->unlock();
2692
2693         hide_keyframe_guis();
2694 }
2695
2696 void MWindow::hide_keyframe_guis()
2697 {
2698         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
2699         for(int i = 0; i < keyframe_threads->size(); i++)
2700         {
2701                 keyframe_threads->get(i)->close_window();
2702         }
2703         keyframe_gui_lock->unlock();
2704 }
2705
2706 void MWindow::hide_keyframe_gui(Plugin *plugin)
2707 {
2708         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
2709         for(int i = 0; i < keyframe_threads->size(); i++)
2710         {
2711                 if(keyframe_threads->get(i)->plugin == plugin)
2712                 {
2713                         keyframe_threads->get(i)->close_window();
2714                         break;
2715                 }
2716         }
2717         keyframe_gui_lock->unlock();
2718 }
2719
2720 void MWindow::update_keyframe_guis()
2721 {
2722 // Send new configuration to keyframe GUI's
2723         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
2724         for(int i = 0; i < keyframe_threads->size(); i++)
2725         {
2726                 KeyFrameThread *ptr = keyframe_threads->get(i);
2727                 if(edl->tracks->plugin_exists(ptr->plugin))
2728                         ptr->update_gui(1);
2729                 else
2730                 {
2731                         ptr->close_window();
2732                 }
2733         }
2734         keyframe_gui_lock->unlock();
2735 }
2736
2737 void MWindow::update_plugin_guis(int do_keyframe_guis)
2738 {
2739 // Send new configuration to plugin GUI's
2740         plugin_gui_lock->lock("MWindow::update_plugin_guis");
2741
2742         for(int i = 0; i < plugin_guis->size(); i++)
2743         {
2744                 PluginServer *ptr = plugin_guis->get(i);
2745                 if(edl->tracks->plugin_exists(ptr->plugin))
2746                         ptr->update_gui();
2747                 else
2748                 {
2749 // Schedule for deletion if no plugin
2750                         plugin_guis->remove_number(i);
2751                         i--;
2752
2753                         ptr->hide_gui();
2754                         delete_plugin(ptr);
2755                 }
2756         }
2757
2758
2759 // Change plugin variable if not visible
2760         Track *track = edl->tracks->first;
2761         while(track)
2762         {
2763                 for(int i = 0; i < track->plugin_set.size(); i++)
2764                 {
2765                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
2766                         while(plugin)
2767                         {
2768                                 int got_it = 0;
2769                                 for(int i = 0; i < plugin_guis->size(); i++)
2770                                 {
2771                                         PluginServer *server = plugin_guis->get(i);
2772                                         if(server->plugin == plugin)
2773                                         {
2774                                                 got_it = 1;
2775                                                 break;
2776                                         }
2777                                 }
2778
2779                                 if(!got_it) plugin->show = 0;
2780
2781                                 plugin = (Plugin*)plugin->next;
2782                         }
2783                 }
2784
2785                 track = track->next;
2786         }
2787
2788         plugin_gui_lock->unlock();
2789
2790
2791         if(do_keyframe_guis) update_keyframe_guis();
2792 }
2793
2794 int MWindow::plugin_gui_open(Plugin *plugin)
2795 {
2796         int result = 0;
2797         plugin_gui_lock->lock("MWindow::plugin_gui_open");
2798         for(int i = 0; i < plugin_guis->total; i++)
2799         {
2800                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2801                 {
2802                         result = 1;
2803                         break;
2804                 }
2805         }
2806         plugin_gui_lock->unlock();
2807         return result;
2808 }
2809
2810 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
2811 {
2812         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2813         for(int i = 0; i < plugin_guis->total; i++)
2814         {
2815                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2816                 {
2817                         plugin_guis->get(i)->render_gui(data);
2818                         break;
2819                 }
2820         }
2821         plugin_gui_lock->unlock();
2822 }
2823
2824 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
2825 {
2826         plugin_gui_lock->lock("MWindow::render_plugin_gui");
2827         for(int i = 0; i < plugin_guis->total; i++)
2828         {
2829                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
2830                 {
2831                         plugin_guis->get(i)->render_gui(data, size);
2832                         break;
2833                 }
2834         }
2835         plugin_gui_lock->unlock();
2836 }
2837
2838
2839 void MWindow::update_plugin_states()
2840 {
2841         plugin_gui_lock->lock("MWindow::update_plugin_states");
2842         for(int i = 0; i < plugin_guis->total; i++)
2843         {
2844                 int result = 0;
2845 // Get a plugin GUI
2846                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
2847                 PluginServer *src_plugingui = plugin_guis->get(i);
2848
2849 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
2850                 for(Track *track = edl->tracks->first;
2851                         track && !result;
2852                         track = track->next)
2853                 {
2854                         for(int j = 0;
2855                                 j < track->plugin_set.total && !result;
2856                                 j++)
2857                         {
2858                                 PluginSet *plugin_set = track->plugin_set[j];
2859                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
2860                                         plugin && !result;
2861                                         plugin = (Plugin*)plugin->next)
2862                                 {
2863                                         if(plugin == src_plugin &&
2864                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
2865                                 }
2866                         }
2867                 }
2868
2869
2870 // Doesn't exist anymore
2871                 if(!result)
2872                 {
2873                         hide_plugin(src_plugin, 0);
2874                         i--;
2875                 }
2876         }
2877         plugin_gui_lock->unlock();
2878 }
2879
2880
2881 void MWindow::update_plugin_titles()
2882 {
2883         for(int i = 0; i < plugin_guis->total; i++)
2884         {
2885                 plugin_guis->get(i)->update_title();
2886         }
2887 }
2888
2889 int MWindow::asset_to_edl(EDL *new_edl,
2890         Asset *new_asset,
2891         RecordLabels *labels)
2892 {
2893 const int debug = 0;
2894 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
2895 __LINE__,
2896 new_asset->layers);
2897 // Keep frame rate, sample rate, and output size unchanged.
2898 // These parameters would revert the project if VWindow displayed an asset
2899 // of different size than the project.
2900         if(new_asset->video_data)
2901         {
2902                 new_edl->session->video_tracks = new_asset->layers;
2903         }
2904         else
2905                 new_edl->session->video_tracks = 0;
2906
2907 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2908
2909
2910
2911
2912
2913         if(new_asset->audio_data)
2914         {
2915                 new_edl->session->audio_tracks = new_asset->channels;
2916         }
2917         else
2918                 new_edl->session->audio_tracks = 0;
2919 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2920
2921 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2922         new_edl->create_default_tracks();
2923 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
2924 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2925
2926
2927
2928 //printf("MWindow::asset_to_edl 3\n");
2929         new_edl->insert_asset(new_asset,
2930                 0,
2931                 0,
2932                 0,
2933                 labels);
2934 //printf("MWindow::asset_to_edl 3\n");
2935 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2936
2937 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
2938         if(edl->session->cursor_on_frames)
2939         {
2940                 double length = new_edl->tracks->total_length();
2941                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
2942                 new_edl->tracks->clear(length, edl_length, 1, 1);
2943         }
2944
2945
2946
2947
2948         char string[BCTEXTLEN];
2949         FileSystem fs;
2950         fs.extract_name(string, new_asset->path);
2951 //printf("MWindow::asset_to_edl 3\n");
2952
2953         strcpy(new_edl->local_session->clip_title, string);
2954 //printf("MWindow::asset_to_edl 4 %s\n", string);
2955 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
2956
2957         return 0;
2958 }
2959
2960 int MWindow::edl_to_nested(EDL *new_edl,
2961         EDL *nested_edl)
2962 {
2963
2964 // Keep frame rate, sample rate, and output size unchanged.
2965 // These parameters would revert the project if VWindow displayed an asset
2966 // of different size than the project.
2967
2968
2969
2970 // Nest all video & audio outputs
2971         new_edl->session->video_tracks = 1;
2972         new_edl->session->audio_tracks = nested_edl->session->audio_channels;
2973         new_edl->create_default_tracks();
2974
2975
2976
2977         new_edl->insert_asset(0,
2978                 nested_edl,
2979                 0,
2980                 0,
2981                 0);
2982
2983         char string[BCTEXTLEN];
2984         FileSystem fs;
2985         fs.extract_name(string, nested_edl->path);
2986 //printf("MWindow::edl_to_nested %p %s\n", nested_edl, nested_edl->path);
2987
2988         strcpy(new_edl->local_session->clip_title, string);
2989
2990         return 0;
2991 }
2992
2993 // Reset everything after a load.
2994 void MWindow::update_project(int load_mode)
2995 {
2996         const int debug = 0;
2997
2998         if(debug) PRINT_TRACE
2999         init_brender();
3000         edl->tracks->update_y_pixels(theme);
3001
3002         if(debug) PRINT_TRACE
3003
3004         if(load_mode == LOADMODE_REPLACE ||
3005                 load_mode == LOADMODE_REPLACE_CONCATENATE)
3006         {
3007                 gui->load_panes();
3008         }
3009
3010         gui->update(1, 1, 1, 1, 1, 1, 1);
3011         if(debug) PRINT_TRACE
3012         gui->unlock_window();
3013
3014         cwindow->gui->lock_window("MWindow::update_project 1");
3015         cwindow->update(0, 0, 1, 1, 1);
3016         cwindow->gui->unlock_window();
3017
3018         if(debug) PRINT_TRACE
3019
3020 // Close all the vwindows
3021         if(load_mode == LOADMODE_REPLACE ||
3022                 load_mode == LOADMODE_REPLACE_CONCATENATE) {
3023                 if(debug) PRINT_TRACE
3024                 int first_vwindow = 0;
3025                 if(session->show_vwindow) first_vwindow = 1;
3026 // Change visible windows to no source
3027                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3028                         VWindow *vwindow = vwindows[i];
3029                         if( !vwindow->is_running() ) continue;
3030                         vwindow->change_source(-1);
3031                 }
3032
3033 // Close remaining windows
3034                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3035                         VWindow *vwindow = vwindows[i];
3036                         if( !vwindow->is_running() ) continue;
3037                         vwindow->close_window();
3038                 }
3039                 if(debug) PRINT_TRACE
3040         }
3041         else if(vwindows.size()) {
3042                 VWindow *vwindow = vwindows[DEFAULT_VWINDOW];
3043                 if( vwindow->is_running() ) {
3044                         vwindow->gui->lock_window("MWindow::update_project");
3045                         vwindow->update(1);
3046                         vwindow->gui->unlock_window();
3047                 }
3048         }
3049
3050         if(debug) PRINT_TRACE
3051         cwindow->gui->lock_window("MWindow::update_project 2");
3052         cwindow->gui->timebar->update(0);
3053         cwindow->gui->unlock_window();
3054
3055         if(debug) PRINT_TRACE
3056         cwindow->playback_engine->que->send_command(CURRENT_FRAME,
3057                 CHANGE_ALL,
3058                 edl,
3059                 1);
3060
3061         awindow->gui->async_update_assets();
3062         if(debug) PRINT_TRACE
3063
3064         gui->lock_window("MWindow::update_project");
3065         gui->flush();
3066         if(debug) PRINT_TRACE
3067 }
3068
3069 void MWindow::remove_indexfile(Indexable *indexable)
3070 {
3071         if( !indexable->is_asset ) return;
3072         Asset *asset = (Asset *)indexable;
3073 // Erase file
3074         IndexFile::delete_index(preferences, asset, ".toc");
3075         IndexFile::delete_index(preferences, asset, ".idx");
3076         IndexFile::delete_index(preferences, asset, ".mkr");
3077 }
3078
3079 void MWindow::rebuild_indices()
3080 {
3081         for(int i = 0; i < session->drag_assets->total; i++)
3082         {
3083                 Indexable *indexable = session->drag_assets->get(i);
3084 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3085                 remove_indexfile(indexable);
3086 // Schedule index build
3087                 IndexState *index_state = indexable->index_state;
3088                 index_state->index_status = INDEX_NOTTESTED;
3089                 if( indexable->is_asset ) {
3090                         Asset *asset = (Asset *)indexable;
3091                         if( asset->format != FILE_PCM ) {
3092                                 asset->format = FILE_UNKNOWN;
3093                                 asset->reset_audio();
3094                         }
3095                         asset->reset_video();
3096 //                      File file; // re-probe the asset
3097 //                      file.open_file(preferences, asset, 1, 0);
3098                 }
3099                 mainindexes->add_next_asset(0, indexable);
3100         }
3101         mainindexes->start_build();
3102 }
3103
3104
3105 void MWindow::save_backup()
3106 {
3107         FileXML file;
3108         edl->optimize();
3109         edl->set_path(session->filename);
3110         char backup_path[BCTEXTLEN];
3111         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3112                 File::get_config_path(), BACKUP_FILE);
3113         edl->save_xml(&file, backup_path, 0, 0);
3114         file.terminate_string();
3115         FileSystem fs;
3116         fs.complete_path(backup_path);
3117
3118         if(file.write_to_file(backup_path))
3119         {
3120                 char string2[256];
3121                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3122                 gui->show_message(string2);
3123         }
3124 }
3125
3126 void MWindow::load_backup()
3127 {
3128         ArrayList<char*> path_list;
3129         path_list.set_array_delete();
3130         char *out_path;
3131         char backup_path[BCTEXTLEN];
3132         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3133                 File::get_config_path(), BACKUP_FILE);
3134         FileSystem fs;
3135         fs.complete_path(backup_path);
3136
3137         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3138         strcpy(out_path, backup_path);
3139
3140         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3141         edl->local_session->clip_title[0] = 0;
3142 // This is unique to backups since the path of the backup is different than the
3143 // path of the project.
3144         set_filename(edl->path);
3145         path_list.remove_all_objects();
3146         save_backup();
3147 }
3148
3149 static inline int gcd(int m, int n)
3150 {
3151         int r;
3152         if( m < n ) { r = m;  m = n;  n = r; }
3153         while( (r = m % n) != 0 ) { m = n;  n = r; }
3154         return n;
3155 }
3156
3157 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3158 {
3159         w = 1;  h = 1;
3160         if(!width || !height) return 1;
3161         if( width == 720 && (height == 480 || height == 576) ) {
3162                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3163         }
3164         double ar = (double)width / height;
3165 // square-ish pixels
3166         if( EQUIV(ar, 1.0000) ) return 0;
3167         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3168         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3169         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3170         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3171         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3172         int ww = width, hh = height;
3173         // numerator, denominator must be under mx
3174         int mx = 255, n = gcd(ww, hh);
3175         if( n > 1 ) { ww /= n; hh /= n; }
3176         // search near height in case extra/missing lines
3177         if( ww >= mx || hh >= mx ) {
3178                 double err = height;  // +/- 2 percent height
3179                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3180                         int iw = width, ih = height+i;
3181                         if( (n=gcd(iw, ih)) > 1 ) {
3182                                 int u = iw/n;  if( u >= mx ) continue;
3183                                 int v = ih/n;  if( v >= mx ) continue;
3184                                 double r = (double) u/v, er = fabs(ar-r);
3185                                 if( er >= err ) continue;
3186                                 err = er;  ww = u;  hh = v;
3187                         }
3188                 }
3189         }
3190
3191         w = ww;  h = hh;
3192         return 0;
3193 }
3194
3195 void MWindow::reset_caches()
3196 {
3197         frame_cache->remove_all();
3198         wave_cache->remove_all();
3199         audio_cache->remove_all();
3200         video_cache->remove_all();
3201         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3202                 cwindow->playback_engine->audio_cache->remove_all();
3203         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3204                 cwindow->playback_engine->video_cache->remove_all();
3205
3206         for(int i = 0; i < vwindows.size(); i++) {
3207                 VWindow *vwindow = vwindows[i];
3208                 if( !vwindow->is_running() ) continue;
3209                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
3210                         vwindow->playback_engine->audio_cache->remove_all();
3211                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
3212                         vwindow->playback_engine->video_cache->remove_all();
3213         }
3214 }
3215
3216 void MWindow::remove_asset_from_caches(Asset *asset)
3217 {
3218         gui->resource_thread->get_video_source(0);
3219         gui->resource_thread->get_audio_source(0);
3220         frame_cache->remove_asset(asset);
3221         wave_cache->remove_asset(asset);
3222         audio_cache->delete_entry(asset);
3223         video_cache->delete_entry(asset);
3224         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3225                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3226         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3227                 cwindow->playback_engine->video_cache->delete_entry(asset);
3228         for(int i = 0; i < vwindows.size(); i++) {
3229                 VWindow *vwindow = vwindows[i];
3230                 if( !vwindow->is_running() ) continue;
3231                 if(vwindow->playback_engine && vwindow->playback_engine->audio_cache)
3232                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3233                 if(vwindow->playback_engine && vwindow->playback_engine->video_cache)
3234                         vwindow->playback_engine->video_cache->delete_entry(asset);
3235         }
3236 }
3237
3238
3239 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3240                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3241 {
3242         for(int i = 0; i < drag_assets->total; i++) {
3243                 Indexable *indexable = drag_assets->get(i);
3244                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3245         }
3246
3247 // Remove from VWindow.
3248         for(int i = 0; i < session->drag_clips->total; i++) {
3249                 for(int j = 0; j < vwindows.size(); j++) {
3250                         VWindow *vwindow = vwindows[j];
3251                         if( !vwindow->is_running() ) continue;
3252                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
3253                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
3254                                 vwindow->delete_source(1, 1);
3255                                 vwindow->gui->unlock_window();
3256                         }
3257                 }
3258         }
3259
3260         for(int i = 0; i < drag_assets->size(); i++) {
3261                 for(int j = 0; j < vwindows.size(); j++) {
3262                         VWindow *vwindow = vwindows[j];
3263                         if( !vwindow->is_running() ) continue;
3264                         if(drag_assets->get(i) == vwindow->get_source()) {
3265                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
3266                                 vwindow->delete_source(1, 1);
3267                                 vwindow->gui->unlock_window();
3268                         }
3269                 }
3270         }
3271
3272         for(int i = 0; i < drag_assets->size(); i++) {
3273                 Indexable *indexable = drag_assets->get(i);
3274                 remove_indexfile(indexable);
3275         }
3276
3277 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3278         if(push_undo) undo->update_undo_before();
3279         if(drag_assets) edl->remove_from_project(drag_assets);
3280         if(drag_clips) edl->remove_from_project(drag_clips);
3281         if(redraw) save_backup();
3282         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
3283         if(redraw) {
3284                 restart_brender();
3285
3286                 gui->lock_window("MWindow::remove_assets_from_project 3");
3287                 gui->update(1, 1, 1, 1, 0, 1, 0);
3288                 gui->unlock_window();
3289
3290         // Removes from playback here
3291                 sync_parameters(CHANGE_ALL);
3292         }
3293
3294         awindow->gui->async_update_assets();
3295 }
3296
3297 void MWindow::remove_assets_from_disk()
3298 {
3299 // Remove from disk
3300         for(int i = 0; i < session->drag_assets->total; i++)
3301         {
3302                 remove(session->drag_assets->get(i)->path);
3303         }
3304
3305         remove_assets_from_project(1,
3306                 1,
3307                 session->drag_assets,
3308                 session->drag_clips);
3309 }
3310
3311 void MWindow::dump_plugins(FILE *fp)
3312 {
3313         if( !plugindb ) return;
3314         for(int i = 0; i < plugindb->total; i++)
3315         {
3316                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
3317                         " synth=%d transition=%d theme=%d %s\n",
3318                         plugindb->get(i)->plugin_type,
3319                         plugindb->get(i)->audio,
3320                         plugindb->get(i)->video,
3321                         plugindb->get(i)->realtime,
3322                         plugindb->get(i)->multichannel,
3323                         plugindb->get(i)->get_synthesis(),
3324                         plugindb->get(i)->transition,
3325                         plugindb->get(i)->theme,
3326                         plugindb->get(i)->title);
3327         }
3328 }
3329
3330 void MWindow::dump_edl(FILE *fp)
3331 {
3332         if( !edl ) return;
3333         edl->dump(fp);
3334 }
3335
3336 void MWindow::dump_undo(FILE *fp)
3337 {
3338         if( !undo ) return;
3339         undo->dump(fp);
3340 }
3341
3342 void MWindow::dump_exe(FILE *fp)
3343 {
3344         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
3345         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
3346
3347         int ret = -1, n = 100;
3348         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
3349                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
3350                 ret = 0;
3351         }
3352         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
3353
3354         struct stat st;
3355         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
3356         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
3357         struct tm *tm = localtime(&st.st_mtime);
3358         char mtime[256];
3359         strftime(mtime, sizeof(mtime), "%F %T", tm);
3360         fprintf(fp,"mtime: %s\n", mtime);
3361 #if 0
3362 // people hit ctl-c waiting for this
3363         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
3364         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
3365         uint8_t *bfr = 0;
3366         int64_t bfrsz = 0;
3367         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
3368         int64_t maxsz = 1024*pagsz;
3369         int64_t size = st.st_size, pos = 0;
3370         SHA1 sha1;
3371         while( (bfrsz = size-pos) > 0 ) {
3372                 if( bfrsz > maxsz ) bfrsz = maxsz;
3373                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
3374                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
3375                 if( bfr == MAP_FAILED ) break;
3376                 sha1.addBytes(bfr, bfrsz);
3377                 munmap(bfr, bfrsz);
3378                 pos += bfrsz;
3379         }
3380         close(fd);
3381         ret = pos < size ? EIO : 0;
3382         fprintf(fp, "SHA1: ");
3383         uint8_t digest[20];  sha1.computeHash(digest);
3384         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
3385         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
3386         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
3387 #endif
3388         fprintf(fp, "\n");
3389 }
3390
3391 void MWindow::trap_hook(FILE *fp, void *vp)
3392 {
3393         MWindow *mwindow = (MWindow *)vp;
3394 //      fprintf(fp, "\nPLUGINS:\n");
3395 //      mwindow->dump_plugins(fp);
3396         fprintf(fp, "\nEDL:\n");
3397         mwindow->dump_edl(fp);
3398         fprintf(fp, "\nUNDO:\n");
3399         mwindow->dump_undo(fp);
3400         fprintf(fp, "\nEXE:\n");
3401         mwindow->dump_exe(fp);
3402 }
3403
3404
3405
3406
3407
3408
3409 int MWindow::save_defaults()
3410 {
3411         gui->save_defaults(defaults);
3412         edl->save_defaults(defaults);
3413         session->save_defaults(defaults);
3414         preferences->save_defaults(defaults);
3415
3416         for(int i = 0; i < plugin_guis->total; i++)
3417         {
3418 // Pointer comparison
3419                 plugin_guis->get(i)->save_defaults();
3420         }
3421         awindow->save_defaults(defaults);
3422
3423         defaults->save();
3424         return 0;
3425 }
3426
3427 int MWindow::run_script(FileXML *script)
3428 {
3429         int result = 0, result2 = 0;
3430         while(!result && !result2)
3431         {
3432                 result = script->read_tag();
3433                 if(!result)
3434                 {
3435                         if(script->tag.title_is("new_project"))
3436                         {
3437 // Run new in immediate mode.
3438 //                              gui->mainmenu->new_project->run_script(script);
3439                         }
3440                         else
3441                         if(script->tag.title_is("record"))
3442                         {
3443 // Run record as a thread.  It is a terminal command.
3444                                 ;
3445 // Will read the complete scipt file without letting record read it if not
3446 // terminated.
3447                                 result2 = 1;
3448                         }
3449                         else
3450                         {
3451                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
3452                         }
3453                 }
3454         }
3455         return result2;
3456 }
3457
3458 // ================================= synchronization
3459
3460
3461 int MWindow::interrupt_indexes()
3462 {
3463         mainprogress->cancelled = 1;
3464         mainindexes->interrupt_build();
3465         return 0;
3466 }
3467
3468
3469
3470 void MWindow::next_time_format()
3471 {
3472         switch(edl->session->time_format)
3473         {
3474                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
3475                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
3476                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3477                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
3478                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
3479                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
3480                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
3481         }
3482
3483         time_format_common();
3484 }
3485
3486 void MWindow::prev_time_format()
3487 {
3488         switch(edl->session->time_format)
3489         {
3490                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
3491                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
3492                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
3493                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
3494                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
3495                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
3496                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
3497         }
3498
3499         time_format_common();
3500 }
3501
3502 void MWindow::time_format_common()
3503 {
3504         gui->lock_window("MWindow::next_time_format");
3505         gui->redraw_time_dependancies();
3506
3507
3508         char string[BCTEXTLEN], string2[BCTEXTLEN];
3509         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
3510         gui->show_message(string);
3511         gui->flush();
3512         gui->unlock_window();
3513 }
3514
3515
3516 int MWindow::set_filename(const char *filename)
3517 {
3518         if( filename != session->filename )
3519                 strcpy(session->filename, filename);
3520         if( filename != edl->path )
3521                 strcpy(edl->path, filename);
3522
3523         if(gui)
3524         {
3525                 if(filename[0] == 0)
3526                 {
3527                         gui->set_title(PROGRAM_NAME);
3528                 }
3529                 else
3530                 {
3531                         FileSystem dir;
3532                         char string[BCTEXTLEN], string2[BCTEXTLEN];
3533                         dir.extract_name(string, filename);
3534                         sprintf(string2, PROGRAM_NAME ": %s", string);
3535                         gui->set_title(string2);
3536                 }
3537         }
3538         return 0;
3539 }
3540
3541
3542
3543
3544
3545
3546
3547
3548 int MWindow::set_loop_boundaries()
3549 {
3550         double start = edl->local_session->get_selectionstart();
3551         double end = edl->local_session->get_selectionend();
3552
3553         if(start !=
3554                 end)
3555         {
3556                 ;
3557         }
3558         else
3559         if(edl->tracks->total_length())
3560         {
3561                 start = 0;
3562                 end = edl->tracks->total_length();
3563         }
3564         else
3565         {
3566                 start = end = 0;
3567         }
3568
3569         if(edl->local_session->loop_playback && start != end)
3570         {
3571                 edl->local_session->loop_start = start;
3572                 edl->local_session->loop_end = end;
3573         }
3574         return 0;
3575 }
3576
3577
3578
3579
3580
3581
3582
3583 int MWindow::reset_meters()
3584 {
3585         cwindow->gui->lock_window("MWindow::reset_meters 1");
3586         cwindow->gui->meters->reset_meters();
3587         cwindow->gui->unlock_window();
3588
3589         for(int j = 0; j < vwindows.size(); j++) {
3590                 VWindow *vwindow = vwindows[j];
3591                 if( !vwindow->is_running() ) continue;
3592                 vwindow->gui->lock_window("MWindow::reset_meters 2");
3593                 vwindow->gui->meters->reset_meters();
3594                 vwindow->gui->unlock_window();
3595         }
3596
3597         lwindow->gui->lock_window("MWindow::reset_meters 3");
3598         lwindow->gui->panel->reset_meters();
3599         lwindow->gui->unlock_window();
3600
3601         gui->lock_window("MWindow::reset_meters 4");
3602         gui->reset_meters();
3603         gui->unlock_window();
3604         return 0;
3605 }
3606
3607
3608 void MWindow::resync_guis()
3609 {
3610 // Update GUIs
3611         restart_brender();
3612         gui->lock_window("MWindow::resync_guis");
3613         gui->update(1, 1, 1, 1, 1, 1, 0);
3614         gui->unlock_window();
3615
3616         cwindow->gui->lock_window("MWindow::resync_guis");
3617         cwindow->gui->resize_event(cwindow->gui->get_w(),
3618                 cwindow->gui->get_h());
3619         int channels = edl->session->audio_channels;
3620         cwindow->gui->meters->set_meters(channels, 1);
3621         cwindow->gui->flush();
3622         cwindow->gui->unlock_window();
3623
3624         for(int i = 0; i < vwindows.size(); i++) {
3625                 VWindow *vwindow = vwindows[i];
3626                 if( !vwindow->is_running() ) continue;
3627                 vwindow->gui->lock_window("MWindow::resync_guis");
3628                 vwindow->gui->resize_event(vwindow->gui->get_w(),
3629                         vwindow->gui->get_h());
3630                 vwindow->gui->meters->set_meters(channels, 1);
3631                 vwindow->gui->flush();
3632                 vwindow->gui->unlock_window();
3633         }
3634
3635         lwindow->gui->lock_window("MWindow::resync_guis");
3636         lwindow->gui->panel->set_meters(channels, 1);
3637         lwindow->gui->flush();
3638         lwindow->gui->unlock_window();
3639
3640 // Warn user
3641         if(((edl->session->output_w % 4) ||
3642                 (edl->session->output_h % 4)) &&
3643                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
3644         {
3645                 MainError::show_error(
3646                         _("This project's dimensions are not multiples of 4 so\n"
3647                         "it can't be rendered by OpenGL."));
3648         }
3649
3650
3651 // Flash frame
3652         sync_parameters(CHANGE_ALL);
3653 }
3654
3655 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
3656 {
3657         File *file = new File;
3658         EDLSession *session = edl->session;
3659         double old_framerate = session->frame_rate;
3660         double old_samplerate = session->sample_rate;
3661         int old_auto_keyframes = session->auto_keyframes;
3662         session->auto_keyframes = 0;
3663         int result = file->open_file(preferences, asset, 1, 0);
3664         if( !result && delete_tracks > 0 )
3665                 undo->update_undo_before();
3666         int video_layers = asset->get_video_layers();
3667         if( !result && asset->video_data && vstream < video_layers ) {
3668                 // try to get asset up to date, may fail
3669                 file->select_video_stream(asset, vstream);
3670                 // either way use what was/is there.
3671                 double framerate = asset->get_frame_rate();
3672                 int width = asset->get_w();
3673                 int height = asset->get_h();
3674                 // must be multiple of 4 for opengl
3675                 width = (width+3) & ~3;  height = (height+3) & ~3;
3676                 int driver = session->playback_config->vconfig->driver;
3677                 int color_model = file->get_best_colormodel(asset, driver);
3678 //              color_model = BC_CModels::is_yuv(color_model) ?
3679 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
3680 //                      BC_CModels::is_float(color_model) ?
3681 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
3682 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
3683 // have alpha for now
3684                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
3685                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
3686                 session->color_model = color_model;
3687                 session->output_w = width;
3688                 session->output_h = height;
3689                 session->frame_rate = framerate;
3690                 // not, asset->actual_width/actual_height
3691                 asset->width = session->output_w;
3692                 asset->height = session->output_h;
3693                 asset->frame_rate = session->frame_rate;
3694                 create_aspect_ratio(session->aspect_w, session->aspect_h,
3695                         session->output_w, session->output_h);
3696                 Track *track = edl->tracks->first;
3697                 for( Track *next_track=0; track; track=next_track ) {
3698                         next_track = track->next;
3699                         if( track->data_type != TRACK_VIDEO ) continue;
3700                         if( delete_tracks ) {
3701                                 Edit *edit = track->edits->first;
3702                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
3703                                         next_edit = edit->next;
3704                                         if( edit->channel != vstream ||
3705                                             !edit->asset || !edit->asset->is_asset ||
3706                                             !asset->equivalent(*edit->asset,1,1,edl) )
3707                                                 delete edit;
3708                                 }
3709                         }
3710                         if( track->edits->first ) {
3711                                 track->track_w = edl->session->output_w;
3712                                 track->track_h = edl->session->output_h;
3713                         }
3714                         else if( delete_tracks )
3715                                 edl->tracks->delete_track(track);
3716                 }
3717                 edl->retrack();
3718                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
3719         }
3720         if( !result && asset->audio_data && asset->channels > 0 ) {
3721                 session->sample_rate = asset->get_sample_rate();
3722                 int64_t channel_mask = 0;
3723                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
3724                         file->get_audio_for_video(vstream, astream, channel_mask);
3725                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
3726                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
3727                 int channels = 0;
3728                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
3729                 if( channels < 1 ) channels = 1;
3730                 if( channels > 6 ) channels = 6;
3731                 session->audio_tracks = session->audio_channels = channels;
3732                 switch( channels ) {
3733                 case 6:
3734                         session->achannel_positions[0] = 90;
3735                         session->achannel_positions[1] = 150;
3736                         session->achannel_positions[2] = 30;
3737                         session->achannel_positions[3] = 210;
3738                         session->achannel_positions[4] = 330;
3739                         session->achannel_positions[5] = 270;
3740                         break;
3741                 case 2:
3742                         session->achannel_positions[0] = 180;
3743                         session->achannel_positions[1] = 0;
3744                         break;
3745                 case 1:
3746                         session->achannel_positions[1] = 90;
3747                         break;
3748                 default: {
3749                         if( !channels ) break;
3750                         double t = 0, dt = 360./channels;
3751                         for( int i=channels; --i>=0; t+=dt )
3752                                 session->achannel_positions[i] = int(t+0.5);
3753                         break; }
3754                 }
3755                 remap_audio(MWindow::AUDIO_1_TO_1);
3756
3757                 if( delete_tracks ) {
3758                         Track *track = edl->tracks->first;
3759                         for( Track *next_track=0; track; track=next_track ) {
3760                                 next_track = track->next;
3761                                 if( track->data_type != TRACK_AUDIO ) continue;
3762                                 Edit *edit = track->edits->first;
3763                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
3764                                         next_edit = edit->next;
3765                                         if( !((1<<edit->channel) & channel_mask) ||
3766                                             !edit->asset || !edit->asset->is_asset ||
3767                                             !asset->equivalent(*edit->asset,1,1,edl) )
3768                                                 delete edit;
3769                                 }
3770                                 if( !track->edits->first )
3771                                         edl->tracks->delete_track(track);
3772                         }
3773                 }
3774                 edl->rechannel();
3775                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
3776         }
3777         delete file;
3778         session->auto_keyframes = old_auto_keyframes;
3779         if( !result && delete_tracks > 0 ) {
3780                 save_backup();
3781                 undo->update_undo_after(_("select asset"), LOAD_ALL);
3782         }
3783         resync_guis();
3784         return result;
3785 }
3786
3787 int MWindow::select_asset(int vtrack, int delete_tracks)
3788 {
3789         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
3790         if( !track )
3791                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
3792         if( !track ) return 1;
3793         Edit *edit = track->edits->first;
3794         if( !edit ) return 1;
3795         Asset *asset = edit->asset;
3796         if( !asset || !asset->is_asset ) return 1;
3797         return select_asset(asset, edit->channel, 0, delete_tracks);
3798 }
3799
3800 void MWindow::dump_plugindb(FILE *fp)
3801 {
3802         if( !plugindb ) return;
3803         for(int i = 0; i < plugindb->total; i++)
3804                 plugindb->get(i)->dump(fp);
3805 }
3806
3807 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
3808 {
3809         Auto *current = 0;
3810         double unit_position = edl->local_session->get_selectionstart(1);
3811         unit_position = patch->track->to_units(unit_position, 0);
3812
3813         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
3814         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3815 }
3816
3817 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
3818 {
3819         Auto *current = 0;
3820         double unit_position = edl->local_session->get_selectionstart(1);
3821         unit_position = patch->track->to_units(unit_position, 0);
3822
3823         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
3824         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3825 }
3826
3827 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
3828 {
3829         Auto *current = 0;
3830         double unit_position = edl->local_session->get_selectionstart(1);
3831         unit_position = patch->track->to_units(unit_position, 0);
3832
3833         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
3834         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
3835 }
3836
3837