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