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