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