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