ins mixers, match all and move for mixer align, cr in xml string kludge, save_as...
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / render.C
1 /*
2  * CINELERRA
3  * Copyright (C) 1997-2011 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 "arender.h"
22 #include "asset.h"
23 #include "auto.h"
24 #include "awindow.h"
25 #include "awindowgui.h"
26 #include "batchrender.h"
27 #include "bcprogressbox.h"
28 #include "bcsignals.h"
29 #include "cache.h"
30 #include "clip.h"
31 #include "compresspopup.h"
32 #include "condition.h"
33 #include "confirmsave.h"
34 #include "cwindowgui.h"
35 #include "cwindow.h"
36 #include "bchash.h"
37 #include "edits.h"
38 #include "edl.h"
39 #include "edlsession.h"
40 #include "errorbox.h"
41 #include "file.h"
42 #include "filesystem.h"
43 #include "filexml.h"
44 #include "formatcheck.h"
45 #include "formatpopup.h"
46 #include "formattools.h"
47 #include "indexable.h"
48 #include "labels.h"
49 #include "language.h"
50 #include "loadmode.h"
51 #include "localsession.h"
52 #include "mainprogress.h"
53 #include "mainsession.h"
54 #include "mainundo.h"
55 #include "module.h"
56 #include "mutex.h"
57 #include "mwindowgui.h"
58 #include "mwindow.h"
59 #include "packagedispatcher.h"
60 #include "packagerenderer.h"
61 #include "patchbay.h"
62 #include "playabletracks.h"
63 #include "preferences.h"
64 #include "preferencesthread.h"
65 #include "renderfarm.h"
66 #include "render.h"
67 #include "renderprofiles.h"
68 #include "statusbar.h"
69 #include "theme.h"
70 #include "timebar.h"
71 #include "tracks.h"
72 #include "transportque.h"
73 #include "vedit.h"
74 #include "vframe.h"
75 #include "videoconfig.h"
76 #include "vrender.h"
77
78 #include <ctype.h>
79 #include <string.h>
80
81
82
83 RenderItem::RenderItem(MWindow *mwindow)
84  : BC_MenuItem(_("Render..."), _("Shift-R"), 'R')
85 {
86         this->mwindow = mwindow;
87         set_shift(1);
88 }
89
90 int RenderItem::handle_event()
91 {
92         mwindow->gui->unlock_window();
93         mwindow->render->start_interactive();
94         mwindow->gui->lock_window("RenderItem::handle_event");
95         return 1;
96 }
97
98 RenderProgress::RenderProgress(MWindow *mwindow, Render *render)
99  : Thread(1, 0, 0)
100 {
101         this->mwindow = mwindow;
102         this->render = render;
103         last_value = 0;
104         Thread::set_synchronous(1);
105 }
106
107 RenderProgress::~RenderProgress()
108 {
109         Thread::cancel();
110         Thread::join();
111 }
112
113
114 void RenderProgress::run()
115 {
116         Thread::disable_cancel();
117         for( ;; ) {
118                 if( render->total_rendered != last_value ) {
119                         render->progress->update(render->total_rendered);
120                         last_value = render->total_rendered;
121
122                         if( mwindow ) mwindow->preferences_thread->update_rates();
123                 }
124
125                 Thread::enable_cancel();
126                 sleep(1);
127                 Thread::disable_cancel();
128         }
129 }
130
131
132
133 MainPackageRenderer::MainPackageRenderer(Render *render)
134  : PackageRenderer()
135 {
136         this->render = render;
137 }
138
139
140
141 MainPackageRenderer::~MainPackageRenderer()
142 {
143 }
144
145
146 int MainPackageRenderer::get_master()
147 {
148         return 1;
149 }
150
151 int MainPackageRenderer::get_result()
152 {
153         return render->result;
154 }
155
156 void MainPackageRenderer::set_result(int value)
157 {
158         if( value )
159                 render->result = value;
160 }
161
162 void MainPackageRenderer::set_progress(int64_t value)
163 {
164         render->counter_lock->lock("MainPackageRenderer::set_progress");
165 // Increase total rendered for all nodes
166         render->total_rendered += value;
167
168 // Update frames per second for master node
169         render->preferences->set_rate(frames_per_second, -1);
170
171 //printf("MainPackageRenderer::set_progress %d %ld %f\n", __LINE__, (long)value, frames_per_second);
172
173 // If non interactive, print progress out
174         if( !render->progress )
175                 render->show_progress();
176
177         render->counter_lock->unlock();
178
179         if( mwindow )
180                 mwindow->preferences->copy_rates_from(preferences);
181 }
182
183 int MainPackageRenderer::progress_cancelled()
184 {
185         return (render->progress && render->progress->is_cancelled()) ||
186                 render->batch_cancelled;
187 }
188
189 void RenderAssets::clear()
190 {
191         for( int i=size(); --i>=0; get(i)->remove_user() );
192         remove_all();
193 }
194 RenderAssets::RenderAssets()
195 {
196 }
197 RenderAssets::~RenderAssets()
198 {
199          clear();
200 }
201
202 Render::Render(MWindow *mwindow)
203  : BC_DialogThread()
204 {
205         this->mwindow = mwindow;
206         in_progress = 0;
207         progress = 0;
208         elapsed_time = 0.0;
209         package_lock = new Mutex("Render::package_lock");
210         counter_lock = new Mutex("Render::counter_lock");
211         completion = new Condition(0, "Render::completion");
212         progress_timer = new Timer;
213         range_type = RANGE_BACKCOMPAT;
214         preferences = new Preferences();
215         thread = new RenderThread(mwindow, this);
216         render_window = 0;
217         asset = 0;
218         result = 0;
219         beep = 0;
220 }
221
222 Render::~Render()
223 {
224         close_window();
225         delete package_lock;
226         delete counter_lock;
227         delete completion;
228         delete preferences;
229         delete progress_timer;
230         if( asset ) asset->Garbage::remove_user();
231         delete thread;
232 }
233
234 void Render::start_interactive()
235 {
236         if( !thread->running() ) {
237                 mode = Render::INTERACTIVE;
238                 BC_DialogThread::start();
239         }
240         else if( in_progress ) {
241                 int cx, cy;
242                 mwindow->gui->get_abs_cursor(cx, cy, 1);
243                 ErrorBox error_box(_(PROGRAM_NAME ": Error"), cx, cy);
244                 error_box.create_objects(_("Already rendering"));
245                 error_box.raise_window();
246                 error_box.run_window();
247         }
248         else if( render_window ) {
249                 render_window->raise_window();
250         }
251 }
252
253
254 void Render::start_batches(ArrayList<BatchRenderJob*> *jobs)
255 {
256         if( !thread->running() ) {
257                 mode = Render::BATCH;
258                 batch_cancelled = 0;
259                 this->jobs = jobs;
260                 completion->reset();
261                 start_render();
262         }
263         else if( in_progress ) {
264                 int cx, cy;
265                 mwindow->gui->get_abs_cursor(cx, cy, 1);
266                 ErrorBox error_box(_(PROGRAM_NAME ": Error"), cx, cy);
267                 error_box.create_objects("Already rendering");
268                 error_box.raise_window();
269                 error_box.run_window();
270         }
271         // raise the window if rendering hasn't started yet
272         else if( render_window ) {
273                 render_window->raise_window();
274         }
275 }
276
277 void Render::start_batches(ArrayList<BatchRenderJob*> *jobs,
278         BC_Hash *boot_defaults, Preferences *batch_prefs)
279 {
280         mode = Render::BATCH;
281         batch_cancelled = 0;
282         preferences->copy_from(batch_prefs);
283         this->jobs = jobs;
284
285         completion->reset();
286         thread->run();
287 }
288
289
290 BC_Window* Render::new_gui()
291 {
292         this->jobs = 0;
293         batch_cancelled = 0;
294         result = 0;
295
296         if( mode == Render::INTERACTIVE ) {
297 // Fix the asset for rendering
298                 if( !asset ) asset = new Asset;
299                 load_defaults(asset);
300                 check_asset(mwindow->edl, *asset);
301                 int px = mwindow->gui->get_pop_cursor_x(1);
302                 int py = mwindow->gui->get_pop_cursor_y(1);
303 // Get format from user
304                 render_window = new RenderWindow(mwindow, this, asset, px, py);
305                 render_window->create_objects();
306         }
307
308         return render_window;
309 }
310
311 void Render::handle_done_event(int result)
312 {
313         if( !result ) {
314                 mwindow->edl->session->render_beep = beep;
315                 // add to recentlist only on OK
316                 render_window->render_format->path_recent->
317                         add_item(File::formattostr(asset->format), asset->path);
318                 setenv("CIN_RENDER", asset->path, 1);
319         }
320         render_window = 0;
321 }
322
323 void Render::handle_close_event(int result)
324 {
325         const int debug = 0;
326         double render_range = get_render_range();
327         const char *err_msg = 0;
328
329         if( !result && !render_range ) {
330                 err_msg = _("zero render range");
331                 result = 1;
332         }
333         if( !result && asset->video_data ) {
334                 double frame_rate = mwindow->edl->session->frame_rate;
335                 if( frame_rate > 0 && render_range+1e-3 < 1./frame_rate ) {
336                         err_msg = _("Video data and range less than 1 frame");
337                         result = 1;
338                 }
339         }
340         if( !result && asset->audio_data ) {
341                 double sample_rate = mwindow->edl->session->sample_rate;
342                 if( sample_rate > 0 && render_range+1e-6 < 1./sample_rate ) {
343                         err_msg = _("Audio data and range less than 1 sample");
344                         result = 1;
345                 }
346         }
347         if( !result && File::is_image_render(asset->format) ) {
348                 if( asset->video_data ) {
349                         double frames = render_range * mwindow->edl->session->frame_rate;
350                         if( !EQUIV(frames, 1.) ) {
351                                 err_msg = _("Image format and not 1 frame");
352                                 result = 1;
353                         }
354                 }
355                 else {
356                         err_msg = _("Image format and no video data");
357                         result = 1;
358                 }
359         }
360         if( err_msg ) {
361                 int cx, cy;
362                 mwindow->gui->get_abs_cursor(cx, cy, 1);
363                 ErrorBox error_box(_(PROGRAM_NAME ": Error"),cx, cy);
364                 error_box.create_objects(err_msg);
365                 error_box.raise_window();
366                 error_box.run_window();
367         }
368
369         if( !result ) {
370 // Check the asset format for errors.
371                 FormatCheck format_check(asset);
372                 if( format_check.check_format() )
373                         result = 1;
374         }
375
376 //PRINT_TRACE
377
378         save_defaults(asset);
379 //PRINT_TRACE
380         mwindow->save_defaults();
381 //PRINT_TRACE
382
383         if( !result ) {
384                 if( debug ) printf("Render::handle_close_event %d\n", __LINE__);
385                 if( !result ) start_render();
386                 if( debug ) printf("Render::handle_close_event %d\n", __LINE__);
387         }
388 //PRINT_TRACE
389 }
390
391
392
393 void Render::stop_operation()
394 {
395         if( thread->Thread::running() ) {
396                 batch_cancelled = 1;
397 // Wait for completion
398                 completion->lock("Render::stop_operation");
399                 completion->reset();
400         }
401 }
402
403 int Render::check_asset(EDL *edl, Asset &asset)
404 {
405         if( asset.video_data &&
406                 edl->tracks->playable_video_tracks() &&
407                 File::renders_video(&asset) ) {
408                 asset.video_data = 1;
409                 asset.layers = 1;
410                 asset.width = edl->session->output_w;
411                 asset.height = edl->session->output_h;
412                 asset.interlace_mode = edl->session->interlace_mode;
413         }
414         else {
415                 asset.video_data = 0;
416                 asset.layers = 0;
417         }
418
419         if( asset.audio_data &&
420                 edl->tracks->playable_audio_tracks() &&
421                 File::renders_audio(&asset) ) {
422                 asset.audio_data = 1;
423                 asset.channels = edl->session->audio_channels;
424         }
425         else {
426                 asset.audio_data = 0;
427                 asset.channels = 0;
428         }
429
430         if( !asset.audio_data &&
431                 !asset.video_data ) {
432                 return 1;
433         }
434         return 0;
435 }
436
437 int Render::get_strategy(int use_renderfarm, int use_labels)
438 {
439         return use_renderfarm ?
440                 (use_labels ? FILE_PER_LABEL_FARM : SINGLE_PASS_FARM) :
441                 (use_labels ? FILE_PER_LABEL      : SINGLE_PASS     ) ;
442 }
443 int Render::get_strategy()
444 {
445         return get_strategy(preferences->use_renderfarm, use_labels);
446 }
447
448 void Render::start_progress()
449 {
450         char filename[BCTEXTLEN];
451         char string[BCTEXTLEN];
452         progress_max = packages->get_progress_max();
453
454         progress_timer->update();
455         last_eta = 0;
456         if( mwindow ) {
457 // Generate the progress box
458                 FileSystem fs;
459                 fs.extract_name(filename, default_asset->path);
460                 sprintf(string, _("Rendering %s..."), filename);
461
462 // Don't bother with the filename since renderfarm defeats the meaning
463                 progress = mwindow->mainprogress->start_progress(_("Rendering..."),
464                         progress_max);
465                 render_progress = new RenderProgress(mwindow, this);
466                 render_progress->start();
467         }
468 }
469
470 void Render::stop_progress()
471 {
472         if( progress ) {
473                 char string[BCTEXTLEN], string2[BCTEXTLEN];
474                 delete render_progress;
475                 progress->get_time(string);
476                 elapsed_time = progress->get_time();
477                 progress->stop_progress();
478                 delete progress;
479
480                 sprintf(string2, _("Rendering took %s"), string);
481                 mwindow->gui->lock_window("");
482                 mwindow->gui->show_message(string2);
483                 mwindow->gui->update_default_message();
484                 mwindow->gui->stop_hourglass();
485                 mwindow->gui->unlock_window();
486         }
487         progress = 0;
488 }
489
490 void Render::show_progress()
491 {
492         int64_t current_eta = progress_timer->get_scaled_difference(1000);
493         if( current_eta - last_eta < 1000  ) return;
494         double eta = !total_rendered ? 0 :
495                 current_eta / 1000. * (progress_max / (double)total_rendered - 1.);
496         char string[BCTEXTLEN];  Units::totext(string, eta, TIME_HMS2);
497         printf("\r%d%% %s: %s      ",
498                 (int)(100 * (float)total_rendered / progress_max), _("ETA"), string);
499         fflush(stdout);
500         last_eta = current_eta;
501 }
502
503
504
505 void Render::start_render()
506 {
507         in_progress = 0;
508         elapsed_time = 0.0;
509         result = 0;
510         completion->reset();
511         thread->start();
512 }
513
514
515 void Render::create_filename(char *path,
516         char *default_path,
517         int current_number,
518         int total_digits,
519         int number_start)
520 {
521         int i, j;
522         int len = strlen(default_path);
523         char printf_string[BCTEXTLEN];
524
525         for( i=0, j=0; i<number_start; ++i, ++j ) {
526                 printf_string[j] = default_path[i];
527         }
528
529 // Found the number
530         sprintf(&printf_string[j], "%%0%dd", total_digits);
531         j = strlen(printf_string);
532         i += total_digits;
533
534 // Copy remainder of string
535         for( ; i<len; ++i, ++j ) {
536                 printf_string[j] = default_path[i];
537         }
538         printf_string[j] = 0;
539 // Print the printf argument to the path
540         sprintf(path, printf_string, current_number);
541 }
542
543 void Render::get_starting_number(char *path,
544         int &current_number,
545         int &number_start,
546         int &total_digits,
547         int min_digits)
548 {
549         int len = strlen(path);
550         char number_text[BCTEXTLEN];
551         char *ptr = 0;
552         char *ptr2 = 0;
553
554         total_digits = 0;
555         number_start = 0;
556
557 // Search for last /
558         ptr2 = strrchr(path, '/');
559
560 // Search for first 0 after last /.
561         if( ptr2 )
562                 ptr = strchr(ptr2, '0');
563
564         if( ptr && isdigit(*ptr) ) {
565                 number_start = ptr - path;
566
567 // Store the first number
568                 char *ptr2 = number_text;
569                 while( isdigit(*ptr) ) *ptr2++ = *ptr++;
570                 *ptr2++ = 0;
571                 current_number = atol(number_text);
572                 total_digits = strlen(number_text);
573         }
574
575
576 // No number found or number not long enough
577         if( total_digits < min_digits ) {
578                 current_number = 1;
579                 number_start = len;
580                 total_digits = min_digits;
581         }
582 }
583
584
585 int Render::load_defaults(Asset *asset)
586 {
587         use_labels = mwindow->defaults->get("RENDER_FILE_PER_LABEL", 0);
588         load_mode = mwindow->defaults->get("RENDER_LOADMODE", LOADMODE_NEW_TRACKS);
589         range_type = mwindow->defaults->get("RENDER_RANGE_TYPE", RANGE_PROJECT);
590
591 // some defaults which work
592         asset->video_data = 1;
593         asset->audio_data = 1;
594         asset->format = FILE_FFMPEG;
595         strcpy(asset->acodec, "mp4.qt");
596         strcpy(asset->vcodec, "mp4.qt");
597
598         asset->load_defaults(mwindow->defaults,
599                 "RENDER_", 1, 1, 1, 1, 1);
600         return 0;
601 }
602
603 int Render::load_profile(int profile_slot, Asset *asset)
604 {
605         char string_name[100];
606         sprintf(string_name, "RENDER_%i_FILE_PER_LABEL", profile_slot);
607         use_labels = mwindow->defaults->get(string_name, 0);
608 // Load mode is not part of the profile
609 //      printf(string_name, "RENDER_%i_LOADMODE", profile_slot);
610 //      load_mode = mwindow->defaults->get(string_name, LOADMODE_NEW_TRACKS);
611         sprintf(string_name, "RENDER_%i_RANGE_TYPE", profile_slot);
612         range_type = mwindow->defaults->get(string_name, RANGE_PROJECT);
613
614         sprintf(string_name, "RENDER_%i_", profile_slot);
615         asset->load_defaults(mwindow->defaults,
616                 string_name, 1, 1, 1, 1, 1);
617         return 0;
618 }
619
620
621 int Render::save_defaults(Asset *asset)
622 {
623         mwindow->defaults->update("RENDER_FILE_PER_LABEL", use_labels);
624         mwindow->defaults->update("RENDER_LOADMODE", load_mode);
625         mwindow->defaults->update("RENDER_RANGE_TYPE", range_type);
626
627         asset->save_defaults(mwindow->defaults,
628                 "RENDER_", 1, 1, 1, 1, 1);
629         return 0;
630 }
631
632 void Render::update_assets()
633 {
634         if( packages )
635                 packages->get_asset_list(assets);
636 }
637
638 static void run_script(const char *script, const char *arg)
639 {
640         char *const argv[] = { (char*)script, (char*)arg, 0 };
641         execvp(script ,&argv[0]);
642         perror("execvp script failed");
643         exit(1);
644 }
645
646 RenderThread::RenderThread(MWindow *mwindow, Render *render)
647  : Thread(0, 0, 0)
648 {
649         this->mwindow = mwindow;
650         this->render = render;
651         render_frames = 0;
652 }
653
654 RenderThread::~RenderThread()
655 {
656 }
657
658
659 void RenderThread::render_single(int test_overwrite, Asset *asset, EDL *edl,
660         int strategy, int range_type)
661 {
662 // Total length in seconds
663         double total_length = 0;
664         RenderFarmServer *farm_server = 0;
665
666         render->in_progress = 1;
667         render->default_asset = asset;
668         render->progress = 0;
669         render->result = 0;
670
671 // Create rendering command
672         TransportCommand *command = new TransportCommand;
673         command->command = NORMAL_FWD;
674         command->get_edl()->copy_all(edl);
675         command->change_type = CHANGE_ALL;
676
677         switch( range_type ) {
678         case RANGE_BACKCOMPAT:
679 // Get highlighted playback range
680                 command->set_playback_range();
681 // Adjust playback range with in/out points
682                 command->playback_range_adjust_inout();
683                 break;
684         case RANGE_PROJECT:
685                 command->playback_range_project();
686                 break;
687         case RANGE_SELECTION:
688                 command->set_playback_range();
689                 break;
690         case RANGE_INOUT:
691                 command->playback_range_inout();
692                 break;
693         case RANGE_1FRAME:
694                 command->playback_range_1frame();
695                 break;
696         }
697
698         render->packages = new PackageDispatcher;
699
700 // Create caches
701         CICache *audio_cache = new CICache(render->preferences);
702         CICache *video_cache = new CICache(render->preferences);
703
704         render->default_asset->frame_rate = command->get_edl()->session->frame_rate;
705         render->default_asset->sample_rate = command->get_edl()->session->sample_rate;
706
707 // Conform asset to EDL.  Find out if any tracks are playable.
708         render->result = render->check_asset(command->get_edl(),
709                 *render->default_asset);
710
711         if( !render->result ) {
712 // Get total range to render
713                 render->total_start = command->start_position;
714                 render->total_end = command->end_position;
715                 total_length = render->total_end - render->total_start;
716
717 // Nothing to render
718                 if( EQUIV(total_length, 0) ) {
719                         render->result = 1;
720                 }
721         }
722         render_frames = render->default_asset->frame_rate * total_length;
723
724 // Generate packages
725         if( !render->result ) {
726 // Stop background rendering
727                 if( mwindow ) mwindow->stop_brender();
728
729                 FileSystem fs;
730                 fs.complete_path(render->default_asset->path);
731
732                 render->result = render->packages->create_packages(mwindow, command->get_edl(),
733                         render->preferences, strategy, render->default_asset,
734                         render->total_start, render->total_end, test_overwrite);
735         }
736
737         render->total_rendered = 0;
738
739         if( !render->result &&
740             ( strategy == SINGLE_PASS_FARM || strategy == FILE_PER_LABEL_FARM ) ) {
741 // Start dispatching external jobs
742                 if( mwindow ) {
743                         mwindow->gui->lock_window("Render::render 1");
744                         mwindow->gui->show_message(_("Starting render farm"));
745                         mwindow->gui->start_hourglass();
746                         mwindow->gui->unlock_window();
747                 }
748                 else {
749                         printf("Render::render: starting render farm\n");
750                 }
751
752                 farm_server = new RenderFarmServer(mwindow, render->packages,
753                         render->preferences, 1, &render->result,
754                         &render->total_rendered, render->counter_lock,
755                         render->default_asset, command->get_edl(), 0);
756                 render->result = farm_server->start_clients();
757
758                 if( render->result ) {
759                         if( mwindow ) {
760                                 mwindow->gui->lock_window("Render::render 2");
761                                 mwindow->gui->show_message(_("Failed to start render farm"),
762                                         mwindow->theme->message_error);
763                                 mwindow->gui->stop_hourglass();
764                                 mwindow->gui->unlock_window();
765                         }
766                         else {
767                                 printf("Render::render: Failed to start render farm\n");
768                         }
769                 }
770         }
771
772 // Perform local rendering
773
774         render->assets.clear();
775         if( !render->result ) {
776                 render->start_progress();
777
778                 MainPackageRenderer package_renderer(render);
779                 render->result = package_renderer.initialize(mwindow,
780                                 command->get_edl(),   // Copy of master EDL
781                                 render->preferences,
782                                 render->default_asset);
783
784                 while( !render->result ) {
785                         int fps = strategy == SINGLE_PASS_FARM ?
786                                 package_renderer.frames_per_second : 0;
787 // Get unfinished job
788                         RenderPackage *package = render->packages->get_package(fps, -1, 1);
789 // Exit point
790                         if( !package ) break;
791
792                         if( package_renderer.render_package(package) )
793                                 render->result = 1;
794                 } // file_number
795
796 printf("Render::render_single: Session finished.\n");
797
798                 if( strategy == SINGLE_PASS_FARM ||
799                     strategy == FILE_PER_LABEL_FARM ) {
800                         if( !render->progress ) {
801                                 while( farm_server->active_clients() > 0 ) {
802                                         sleep(1);
803                                         render->show_progress();
804                                 }
805                         }
806                         farm_server->wait_clients();
807                         render->result |= render->packages->packages_are_done();
808                 }
809
810 // Notify of error
811                 if( render->result && !render->batch_cancelled &&
812                     (!render->progress || !render->progress->is_cancelled()) ) {
813                         if( mwindow ) {
814                                 int cx, cy;
815                                 mwindow->gui->get_abs_cursor(cx, cy, 1);
816                                 ErrorBox error_box(_(PROGRAM_NAME ": Error"), cx, cy);
817                                 error_box.create_objects(_("Error rendering data."));
818                                 error_box.raise_window();
819                                 error_box.run_window();
820                         }
821                         else {
822                                 printf("Render::render: Error rendering data\n");
823                         }
824                 }
825
826 // Delete the progress box
827                 render->stop_progress();
828                 render->update_assets();
829         }
830
831 // Paste all packages into timeline if desired
832
833         if( !render->result && mwindow &&
834             render->load_mode != LOADMODE_NOTHING &&
835             render->mode != Render::BATCH ) {
836                 mwindow->gui->lock_window("Render::render 3");
837
838                 mwindow->undo->update_undo_before();
839                 if( render->load_mode == LOADMODE_PASTE )
840                         mwindow->clear(0);
841                 mwindow->load_assets(&render->assets,
842                         -1, render->load_mode, 0, 0,
843                         mwindow->edl->session->labels_follow_edits,
844                         mwindow->edl->session->plugins_follow_edits,
845                         mwindow->edl->session->autos_follow_edits,
846                         0); // overwrite
847                 mwindow->save_backup();
848                 mwindow->undo->update_undo_after(_("render"), LOAD_ALL);
849                 mwindow->update_plugin_guis();
850                 mwindow->gui->update(1, FORCE_REDRAW, 1, 1, 1, 1, 0);
851                 mwindow->sync_parameters(CHANGE_ALL);
852                 mwindow->gui->unlock_window();
853
854                 mwindow->awindow->gui->async_update_assets();
855         }
856
857 // Disable hourglass
858         if( mwindow ) {
859                 mwindow->gui->lock_window("Render::render 3");
860                 mwindow->gui->stop_hourglass();
861                 mwindow->gui->unlock_window();
862         }
863
864 //printf("Render::render 110\n");
865 // Need to restart because brender always stops before render.
866         if( mwindow )
867                 mwindow->restart_brender();
868         if( farm_server ) delete farm_server;
869         delete command;
870         delete audio_cache;
871         delete video_cache;
872 // Must delete packages after server
873         delete render->packages;
874
875         render->packages = 0;
876         render->in_progress = 0;
877 }
878
879 void RenderThread::run()
880 {
881         char *script = 0;
882         Timer render_timer;
883
884         if( mwindow )
885                 render->preferences->copy_from(mwindow->preferences);
886
887         if( render->mode == Render::INTERACTIVE ) {
888                 render_single(1, render->asset, mwindow->edl,
889                         render->get_strategy(), render->range_type);
890         }
891         else
892         if( render->mode == Render::BATCH ) {
893                 for( int i=0; i<render->jobs->total && !render->result; ++i ) {
894                         BatchRenderJob *job = render->jobs->values[i];
895                         if( !job->enabled ) continue;
896                         if( mwindow )
897                                 mwindow->batch_render->update_active(i);
898                         else
899                                 printf("Render::run: %s\n", job->edl_path);
900
901                         FileXML *file = new FileXML;
902                         EDL *edl = new EDL;
903                         edl->create_objects();
904                         file->read_from_file(job->edl_path);
905                         edl->load_xml(file, LOAD_ALL);
906                         delete file;
907
908                         render_single(0, job->asset, edl, job->get_strategy(), RANGE_BACKCOMPAT);
909                         if( !render->result ) {
910                                 if( !i )
911                                         script = job->create_script(edl, &render->assets);
912                                 if( mwindow )
913                                         mwindow->batch_render->update_done(i, 1, render->elapsed_time);
914                                 else {
915                                         char string[BCTEXTLEN];
916                                         render->elapsed_time =
917                                                 (double)render->progress_timer->get_scaled_difference(1);
918                                         Units::totext(string, render->elapsed_time, TIME_HMS2);
919                                         printf("Render::run: done in %s\n", string);
920                                 }
921                         }
922                         else {
923                                 if( mwindow )
924                                         mwindow->batch_render->update_active(-1);
925                                 else
926                                         printf("Render::run: failed\n");
927                         }
928                 }
929                 if( mwindow ) {
930                         mwindow->batch_render->update_active(-1);
931                         mwindow->batch_render->update_done(-1, 0, 0);
932                 }
933         }
934         render->completion->unlock();
935
936         if( !render->result ) {
937                 double render_time = render_timer.get_difference() / 1000.0;
938                 double render_rate = render_time > 0 ? render_frames / render_time : 0;
939                 printf("** rendered %jd frames in %0.3f secs, %0.3f fps\n",
940                         render_frames, render_time, render_rate);
941         }
942
943         if( render->mode == Render::INTERACTIVE && render->beep )
944                 mwindow->beep(3000., 1.5, 0.5);
945
946         if( script ) {
947                 if( !render->result )
948                         run_script(script, 0);
949                 delete [] script;
950         }
951 }
952
953
954 #define WIDTH 480
955 #define HEIGHT 480
956
957
958 RenderWindow::RenderWindow(MWindow *mwindow,
959         Render *render,
960         Asset *asset,
961         int x,
962         int y)
963  : BC_Window(_(PROGRAM_NAME ": Render"), x, y,
964         WIDTH, HEIGHT, WIDTH, HEIGHT, 0, 0, 1)
965 {
966         this->mwindow = mwindow;
967         this->render = render;
968         this->asset = asset;
969         render_format = 0;
970         loadmode = 0;
971         renderprofile = 0;
972         rangeproject = 0;
973         rangeselection = 0;
974         rangeinout = 0;
975         range1frame = 0;
976 }
977
978 RenderWindow::~RenderWindow()
979 {
980         lock_window("RenderWindow::~RenderWindow");
981         delete render_format;
982         delete loadmode;
983         delete renderprofile;
984         unlock_window();
985 }
986
987
988 void RenderWindow::load_profile(int profile_slot)
989 {
990         render->load_profile(profile_slot, asset);
991         update_range_type(render->range_type);
992         render_format->update(asset, &render->use_labels);
993 }
994
995
996 void RenderWindow::create_objects()
997 {
998         int x = 10, y = 10;
999         lock_window("RenderWindow::create_objects");
1000         add_subwindow(new BC_Title(x, y,
1001                 (char*)(render->use_labels ?
1002                         _("Select the first file to render to:") :
1003                         _("Select a file to render to:"))));
1004         y += 25;
1005
1006         render_format = new RenderFormat(mwindow, this, asset);
1007         render_format->create_objects(x, y,
1008                 1, 1, 1, 1, 0, 1, 0, 0, &render->use_labels, 0);
1009
1010         BC_Title *title;
1011         add_subwindow(title = new BC_Title(x, y, _("Render range:")));
1012
1013         int is_image = File::is_image_render(asset->format);
1014         if( is_image )
1015                 render->range_type = RANGE_1FRAME;
1016
1017         int x1 = x + title->get_w() + 20, y1 = y;
1018         add_subwindow(rangeproject = new RenderRangeProject(this,
1019                 render->range_type == RANGE_PROJECT, x1, y));
1020         int x2 = x1 + rangeproject->get_w();
1021         y += 20;
1022         add_subwindow(rangeselection = new RenderRangeSelection(this,
1023                 render->range_type == RANGE_SELECTION, x1, y));
1024         int x3 = x1 + rangeselection->get_w();
1025         if( x2 < x3 ) x2 = x3;
1026         y += 20;
1027         add_subwindow(rangeinout = new RenderRangeInOut(this,
1028                 render->range_type == RANGE_INOUT, x1, y));
1029         x3 = x1 + rangeinout->get_w();
1030         if( x2 < x3 ) x2 = x3;
1031         y += 20;
1032         add_subwindow(range1frame = new RenderRange1Frame(this,
1033                 render->range_type == RANGE_1FRAME, x1, y));
1034         x3 = x1 + range1frame->get_w();
1035         if( x2 < x3 ) x2 = x3;
1036         y += 30;
1037         if( is_image )
1038                 enable_render_range(0);
1039
1040         x1 = x2 + 20;
1041         render->beep = mwindow->edl->session->render_beep;
1042         add_subwindow(beep_on_done = new RenderBeepOnDone(this, x1, y1));
1043
1044         renderprofile = new RenderProfile(mwindow, this, x, y, 1);
1045         renderprofile->create_objects();
1046         y += 70;
1047
1048         loadmode = new LoadMode(mwindow, this, x, y, &render->load_mode, 1);
1049         loadmode->create_objects();
1050
1051         add_subwindow(new BC_OKButton(this));
1052         add_subwindow(new BC_CancelButton(this));
1053
1054         show_window();
1055         unlock_window();
1056 }
1057
1058 void RenderWindow::update_range_type(int range_type)
1059 {
1060         if( render->range_type == range_type ) return;
1061         render->range_type = range_type;
1062         rangeproject->update(range_type == RANGE_PROJECT);
1063         rangeselection->update(range_type == RANGE_SELECTION);
1064         rangeinout->update(range_type == RANGE_INOUT);
1065         range1frame->update(range_type == RANGE_1FRAME);
1066 }
1067
1068 void RenderWindow::enable_render_range(int v)
1069 {
1070         if( v ) {
1071                 rangeproject->enable();
1072                 rangeselection->enable();
1073                 rangeinout->enable();
1074                 range1frame->enable();
1075         }
1076         else {
1077                 rangeproject->disable();
1078                 rangeselection->disable();
1079                 rangeinout->disable();
1080                 range1frame->disable();
1081         }
1082 }
1083
1084
1085 RenderRangeProject::RenderRangeProject(RenderWindow *rwindow, int value, int x, int y)
1086  : BC_Radial(x, y, value, _("Project"))
1087 {
1088         this->rwindow = rwindow;
1089 }
1090 int RenderRangeProject::handle_event()
1091 {
1092         rwindow->update_range_type(RANGE_PROJECT);
1093         return 1;
1094 }
1095
1096 RenderRangeSelection::RenderRangeSelection(RenderWindow *rwindow, int value, int x, int y)
1097  : BC_Radial(x, y, value, _("Selection"))
1098 {
1099         this->rwindow = rwindow;
1100 }
1101 int RenderRangeSelection::handle_event()
1102 {
1103         rwindow->update_range_type(RANGE_SELECTION);
1104         return 1;
1105 }
1106
1107
1108 RenderRangeInOut::RenderRangeInOut(RenderWindow *rwindow, int value, int x, int y)
1109  : BC_Radial(x, y, value, _("In/Out Points"))
1110 {
1111         this->rwindow = rwindow;
1112 }
1113 int RenderRangeInOut::handle_event()
1114 {
1115         rwindow->update_range_type(RANGE_INOUT);
1116         return 1;
1117 }
1118
1119 RenderRange1Frame::RenderRange1Frame(RenderWindow *rwindow, int value, int x, int y)
1120  : BC_Radial(x, y, value, _("One Frame"))
1121 {
1122         this->rwindow = rwindow;
1123 }
1124 int RenderRange1Frame::handle_event()
1125 {
1126         rwindow->update_range_type(RANGE_1FRAME);
1127         return 1;
1128 }
1129
1130 double Render::get_render_range()
1131 {
1132         EDL *edl = mwindow->edl;
1133         double last = edl->tracks->total_playable_length();
1134         double framerate = edl->session->frame_rate;
1135         if( framerate <= 0 ) framerate = 1;
1136         double start = 0, end = last;
1137         switch( range_type ) {
1138         default:
1139         case RANGE_BACKCOMPAT:
1140                 start = edl->local_session->get_selectionstart(1);
1141                 end   = edl->local_session->get_selectionend(1);
1142                 if( EQUIV(start, end) ) end = last;
1143                 break;
1144         case RANGE_PROJECT:
1145                 break;
1146         case RANGE_SELECTION:
1147                 start = edl->local_session->get_selectionstart(1);
1148                 end   = edl->local_session->get_selectionend(1);
1149                 break;
1150         case RANGE_INOUT:
1151                 start = edl->local_session->inpoint_valid() ?
1152                         edl->local_session->get_inpoint() : 0;
1153                 end   = edl->local_session->outpoint_valid() ?
1154                         edl->local_session->get_outpoint() : last;
1155                 break;
1156         case RANGE_1FRAME:
1157                 start = end = edl->local_session->get_selectionstart(1);
1158                 if( edl->session->frame_rate > 0 ) end += 1./edl->session->frame_rate;
1159                 break;
1160         }
1161         if( start < 0 ) start = 0;
1162         if( end > last ) end = last;
1163         return end - start;
1164 }
1165
1166 RenderFormat::RenderFormat(MWindow *mwindow, BC_WindowBase *window, Asset *asset)
1167  : FormatTools(mwindow, window, asset)
1168 {
1169 }
1170 RenderFormat::~RenderFormat()
1171 {
1172 }
1173
1174 void RenderFormat::update_format()
1175 {
1176         FormatTools::update_format();
1177         RenderWindow *render_window = (RenderWindow *)window;
1178         if( render_window->is_hidden() ) return;
1179
1180         int is_image = File::is_image_render(asset->format);
1181         if( is_image ) {
1182                 render_window->update_range_type(RANGE_1FRAME);
1183                 render_window->enable_render_range(0);
1184         }
1185         else
1186                 render_window->enable_render_range(1);
1187 }
1188
1189 RenderBeepOnDone::RenderBeepOnDone(RenderWindow *rwindow, int x, int y)
1190  : BC_CheckBox(x, y, rwindow->render->beep, _("Beep on done"))
1191 {
1192         this->rwindow = rwindow;
1193 }
1194
1195 int RenderBeepOnDone::handle_event()
1196 {
1197         rwindow->render->beep = get_value();
1198         return 1;
1199 }
1200
1201