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