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