merge from 2.0-ongoing @ 3581
[ardour.git] / libs / ardour / session_export.cc
1 /*
2     Copyright (C) 1999-2002 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /* see gdither.cc for why we have to do this */
21
22 #define _ISOC9X_SOURCE  1
23 #define _ISOC99_SOURCE  1
24 #include <cmath>
25 #undef  _ISOC99_SOURCE
26 #undef  _ISOC9X_SOURCE
27 #undef  __USE_SVID 
28 #define __USE_SVID 1
29 #include <cstdlib>
30 #undef  __USE_SVID
31
32 #include <unistd.h>
33 #include <inttypes.h>
34 #include <float.h>
35
36 #include <sigc++/bind.h>
37
38 #include <pbd/error.h>
39 #include <glibmm/thread.h>
40
41 #include <ardour/gdither.h>
42 #include <ardour/timestamps.h>
43 #include <ardour/ardour.h>
44 #include <ardour/session.h>
45 #include <ardour/export.h>
46 #include <ardour/sndfile_helpers.h>
47 #include <ardour/port.h>
48 #include <ardour/audio_port.h>
49 #include <ardour/audioengine.h>
50 #include <ardour/audio_diskstream.h>
51 #include <ardour/panner.h>
52
53 #include "i18n.h"
54
55 using namespace std;
56 using namespace ARDOUR;
57 using namespace PBD;
58
59 static int
60 convert_spec_to_info (ExportSpecification& spec, SF_INFO& sfinfo)
61 {
62         if (spec.path.length() == 0) {
63                 error << _("Export: no output file specified") << endmsg;
64                 return -1;
65         }
66
67         /* XXX add checks that the directory path exists, and also 
68            check if we are overwriting an existing file...
69         */
70
71         sfinfo.format = spec.format;
72         sfinfo.samplerate = spec.sample_rate;
73         sfinfo.frames = spec.end_frame - spec.start_frame + 1;
74         sfinfo.channels = min (spec.channels, 2U);
75
76         return 0;
77 }
78
79 ExportSpecification::ExportSpecification ()
80 {
81         init ();
82 }
83
84 ExportSpecification::~ExportSpecification ()
85 {
86         clear ();
87 }
88
89 void
90 ExportSpecification::init ()
91 {
92         src_state = 0;
93         pos = 0;
94         total_frames = 0;
95         out = 0;
96         channels = 0;
97         running = false;
98         stop = false;
99         progress = 0.0;
100         status = 0;
101         dither = 0;
102         start_frame = 0;
103         end_frame = 0;
104         dataF = 0;
105         dataF2 = 0;
106         leftoverF = 0;
107         max_leftover_frames = 0;
108         leftover_frames = 0;
109         output_data = 0;
110         out_samples_max = 0;
111         data_width = 0;
112         do_freewheel = false;
113 }
114
115 void
116 ExportSpecification::clear ()
117 {
118         if (out) {
119                 sf_close (out);
120                 out = 0;
121         }
122
123         if (src_state) {
124                 src_delete (src_state);
125                 src_state = 0;
126         }
127
128         if (dither) {
129                 gdither_free (dither);
130                 dither = 0;
131         }
132
133         if (output_data) {
134                 free (output_data);
135                 output_data = 0;
136         }
137         if (dataF) {
138                 delete [] dataF;
139                 dataF = 0;
140         }
141         if (dataF2) {
142                 delete [] dataF2;
143                 dataF2 = 0;
144         }
145         if (leftoverF) {
146                 delete [] leftoverF;
147                 leftoverF = 0;
148         }
149
150         freewheel_connection.disconnect ();
151
152         init ();
153 }
154
155 int
156 ExportSpecification::prepare (nframes_t blocksize, nframes_t frate)
157 {
158         char errbuf[256];
159         GDitherSize dither_size;
160
161         frame_rate = frate;
162
163         if (channels == 0) {
164                 error << _("illegal channel count in export specification") << endmsg;
165                 return -1;
166         }
167
168         if (start_frame >= end_frame) {
169                 error << _("illegal frame range in export specification") << endmsg;
170                 return -1;
171         }
172
173         if ((data_width = sndfile_data_width(format)) == 0) {
174                 error << _("Bad data width size.  Report me!") << endmsg;
175                 return -1;
176         }
177
178         switch (data_width) {
179         case 8:
180                 dither_size = GDither8bit;
181                 break;
182
183         case 16:
184                 dither_size = GDither16bit;
185                 break;
186
187         case 24:
188                 dither_size = GDither32bit;
189                 break;
190
191         default:
192                 dither_size = GDitherFloat;
193                 break;
194         }
195
196         if (convert_spec_to_info (*this, sfinfo)) {
197                 return -1;
198         }
199
200         /* XXX make sure we have enough disk space for the output */
201         
202         if ((out = sf_open (path.c_str(), SFM_WRITE, &sfinfo)) == 0) {
203                 sf_error_str (0, errbuf, sizeof (errbuf) - 1);
204                 error << string_compose(_("Export: cannot open output file \"%1\" (%2)"), path, errbuf) << endmsg;
205                 return -1;
206         }
207
208         dataF = new float[blocksize * channels];
209
210         if (sample_rate != frame_rate) {
211                 int err;
212
213                 if ((src_state = src_new (src_quality, channels, &err)) == 0) {
214                         error << string_compose (_("cannot initialize sample rate conversion: %1"), src_strerror (err)) << endmsg;
215                         return -1;
216                 }
217                 
218                 src_data.src_ratio = sample_rate / (double) frame_rate;
219                 out_samples_max = (nframes_t) ceil (blocksize * src_data.src_ratio * channels);
220                 dataF2 = new float[out_samples_max];
221
222                 max_leftover_frames = 4 * blocksize;
223                 leftoverF = new float[max_leftover_frames * channels];
224                 leftover_frames = 0;
225
226         } else {
227                 out_samples_max = blocksize * channels;
228         }
229
230         dither = gdither_new (dither_type, channels, dither_size, data_width);
231
232         /* allocate buffers where dithering and output will occur */
233
234         switch (data_width) {
235         case 8:
236                 sample_bytes = 1;
237                 break;
238
239         case 16:
240                 sample_bytes = 2;
241                 break;
242
243         case 24:
244         case 32:
245                 sample_bytes = 4;
246                 break;
247
248         default:
249                 sample_bytes = 0; // float format
250                 break;
251         }
252
253         if (sample_bytes) {
254                 output_data = (void*) malloc (sample_bytes * out_samples_max);
255         }
256
257         pos = start_frame;
258         end_frame = end_frame;
259         total_frames = end_frame - start_frame;
260         running = true; 
261         do_freewheel = false; /* force a call to ::prepare_to_export() before proceeding to normal operation */
262
263         return 0;
264 }
265
266 int
267 ExportSpecification::process (nframes_t nframes)
268 {
269         float* float_buffer = 0;
270         uint32_t chn;
271         uint32_t x;
272         uint32_t i;
273         sf_count_t written;
274         char errbuf[256];
275         nframes_t to_write = 0;
276         int cnt = 0;
277         
278         do {
279
280                 /* now do sample rate conversion */
281         
282                 if (sample_rate != frame_rate) {
283                 
284                         int err;
285                 
286                         src_data.output_frames = out_samples_max / channels;
287                         src_data.end_of_input = ((pos + nframes) >= end_frame);
288                         src_data.data_out = dataF2;
289
290                         if (leftover_frames > 0) {
291
292                                 /* input data will be in leftoverF rather than dataF */
293
294                                 src_data.data_in = leftoverF;
295
296                                 if (cnt == 0) {
297                                         
298                                         /* first time, append new data from dataF into the leftoverF buffer */
299
300                                         memcpy (leftoverF + (leftover_frames * channels), dataF, nframes * channels * sizeof(float));
301                                         src_data.input_frames = nframes + leftover_frames;
302                                 } else {
303                                         
304                                         /* otherwise, just use whatever is still left in leftoverF; the contents
305                                            were adjusted using memmove() right after the last SRC call (see
306                                            below)
307                                         */
308
309                                         src_data.input_frames = leftover_frames;
310                                 }
311                                         
312                         } else {
313
314                                 src_data.data_in = dataF;
315                                 src_data.input_frames = nframes;
316
317                         }
318
319                         ++cnt;
320
321                         if ((err = src_process (src_state, &src_data)) != 0) {
322                                 error << string_compose (_("an error occured during sample rate conversion: %1"),
323                                                   src_strerror (err))
324                                       << endmsg;
325                                 return -1;
326                         }
327                 
328                         to_write = src_data.output_frames_gen;
329                         leftover_frames = src_data.input_frames - src_data.input_frames_used;
330
331                         if (leftover_frames > 0) {
332                                 if (leftover_frames > max_leftover_frames) {
333                                         error << _("warning, leftover frames overflowed, glitches might occur in output") << endmsg;
334                                         leftover_frames = max_leftover_frames;
335                                 }
336                                 memmove (leftoverF, (char *) (src_data.data_in + (src_data.input_frames_used * channels)),
337                                          leftover_frames * channels * sizeof(float));
338                         }
339
340                         float_buffer = dataF2;
341                 
342                 } else {
343
344                         /* no SRC, keep it simple */
345                 
346                         to_write = nframes;
347                         leftover_frames = 0;
348                         float_buffer = dataF;
349                 }
350         
351                 if (output_data) {
352                         memset (output_data, 0, sample_bytes * to_write * channels);
353                 }
354         
355                 switch (data_width) {
356                 case 8:
357                 case 16:
358                 case 24:
359                         for (chn = 0; chn < channels; ++chn) { 
360                                 gdither_runf (dither, chn, to_write, float_buffer, output_data);
361                         }
362                         break;
363                 
364                 case 32:
365                         for (chn = 0; chn < channels; ++chn) {
366                         
367                                 int *ob = (int *) output_data;
368                                 const double int_max = (float) INT_MAX;
369                                 const double int_min = (float) INT_MIN;
370                         
371                                 for (x = 0; x < to_write; ++x) {
372                                         i = chn + (x * channels);
373                                 
374                                         if (float_buffer[i] > 1.0f) {
375                                                 ob[i] = INT_MAX;
376                                         } else if (float_buffer[i] < -1.0f) {
377                                                 ob[i] = INT_MIN;
378                                         } else {
379                                                 if (float_buffer[i] >= 0.0f) {
380                                                         ob[i] = lrintf (int_max * float_buffer[i]);
381                                                 } else {
382                                                         ob[i] = - lrintf (int_min * float_buffer[i]);
383                                                 }
384                                         }
385                                 }
386                         }
387                         break;
388                 
389                 default:
390                         for (x = 0; x < to_write * channels; ++x) {
391                                 if (float_buffer[x] > 1.0f) {
392                                         float_buffer[x] = 1.0f;
393                                 } else if (float_buffer[x] < -1.0f) {
394                                         float_buffer[x] = -1.0f;
395                                 } 
396                         }
397                         break;
398                 }
399         
400                 /* and export to disk */
401         
402                 switch (data_width) {
403                 case 8:
404                         /* XXXX no way to deliver 8 bit audio to libsndfile */
405                         written = to_write;
406                         break;
407                 
408                 case 16:
409                         written = sf_writef_short (out, (short*) output_data, to_write);
410                         break;
411                 
412                 case 24:
413                 case 32:
414                         written = sf_writef_int (out, (int*) output_data, to_write);
415                         break;
416                 
417                 default:
418                         written = sf_writef_float (out, float_buffer, to_write);
419                         break;
420                 }
421         
422                 if ((nframes_t) written != to_write) {
423                         sf_error_str (out, errbuf, sizeof (errbuf) - 1);
424                         error << string_compose(_("Export: could not write data to output file (%1)"), errbuf) << endmsg;
425                         return -1;
426                 }
427
428
429         } while (leftover_frames >= nframes);
430
431         return 0;
432 }
433
434 int
435 Session::start_export (ExportSpecification& spec)
436 {
437         if (!_engine.connected()) {
438                 return -1;
439         }
440
441         if (spec.prepare (current_block_size, frame_rate())) {
442                 return -1;
443         }
444
445         spec.freewheel_connection = _engine.Freewheel.connect (sigc::bind (mem_fun (*this, &Session::process_export), &spec));
446
447         cerr << "Start export at pos = " << spec.pos << endl;
448
449         return _engine.freewheel (true);
450 }
451
452 int
453 Session::stop_export (ExportSpecification& spec)
454 {
455         /* don't stop freewheeling but do stop paying attention to it for now */
456
457         spec.freewheel_connection.disconnect ();
458         spec.clear (); /* resets running/stop etc */
459
460         Exported (spec.path, name());
461
462         return 0;
463 }
464
465 int
466 Session::pre_export ()
467 {
468         wait_till_butler_finished ();
469
470         /* take everyone out of awrite to avoid disasters */
471
472         {
473                 boost::shared_ptr<RouteList> r = routes.reader ();
474
475                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
476                         (*i)->protect_automation ();
477                 }
478         }
479
480         /* make sure we are actually rolling */
481
482         if (get_record_enabled()) {
483                 disable_record (false);
484         }
485
486         /* no slaving */
487
488         post_export_slave = Config->get_slave_source ();
489         post_export_position = _transport_frame;
490
491         Config->set_slave_source (None);
492
493         return 0;
494 }
495
496 int 
497 Session::prepare_to_export (ExportSpecification& spec)
498 {
499         int ret = -1;
500
501         /* get everyone to the right position */
502
503         {
504                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
505
506                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
507                         if ((*i)-> seek (spec.start_frame, true)) {
508                                 error << string_compose (_("%1: cannot seek to %2 for export"),
509                                                   (*i)->name(), spec.start_frame)
510                                       << endmsg;
511                                 goto out;
512                         }
513                 }
514         }
515
516         cerr << "Everybdy is at " << spec.start_frame << endl;
517
518         /* we just did the core part of a locate() call above, but
519            for the sake of any GUI, put the _transport_frame in
520            the right place too.
521         */
522
523         _transport_frame = spec.start_frame;
524         _exporting = true;
525
526         /* get transport ready. note how this is calling butler functions
527            from a non-butler thread. we waited for the butler to stop
528            what it was doing earlier in Session::pre_export() and nothing
529            since then has re-awakened it.
530          */
531
532         set_transport_speed (1.0, false);
533         butler_transport_work ();
534         g_atomic_int_set (&butler_should_do_transport_work, 0);
535         post_transport ();
536
537         /* we are ready to go ... */
538
539         ret = 0;
540
541   out:
542         return ret;
543 }
544
545 int
546 Session::process_export (nframes_t nframes, ExportSpecification* spec)
547 {
548         uint32_t chn;
549         uint32_t x;
550         int ret = -1;
551         nframes_t this_nframes;
552
553         cerr << "Export process at pos = " << spec->pos << " _exporting = "
554              << _exporting << " running = " << spec->running << " stop = "
555              << spec->stop << endl;
556
557         /* This is not required to be RT-safe because we are running while freewheeling */
558
559         if (spec->do_freewheel == false) {
560                 
561                 /* first time in export function: get set up */
562
563                 if (prepare_to_export (*spec)) {
564                         spec->running = false;
565                         spec->status = -1;
566                         return -1;
567                 }
568                 
569                 spec->do_freewheel = true;
570         }
571
572         if (!_exporting) {
573                 /* finished, but still freewheeling */
574                 cerr << "\tExport ... not exporting yet, no_roll() for " << nframes <<endl;
575                 no_roll (nframes, 0);
576                 return 0;
577         }
578         
579         if (!spec->running || spec->stop || (this_nframes = min ((spec->end_frame - spec->pos), nframes)) == 0) {
580                 cerr << "\tExport ... not running or at end, no_roll() for " << nframes <<endl;
581                 no_roll (nframes, 0);
582                 return stop_export (*spec);
583         }
584
585         /* make sure we've caught up with disk i/o, since
586            we're running faster than realtime c/o JACK.
587         */
588
589         wait_till_butler_finished ();
590         
591         /* do the usual stuff */
592         
593         process_without_events (nframes);
594
595         /* and now export the results */
596
597         nframes = this_nframes;
598
599         memset (spec->dataF, 0, sizeof (spec->dataF[0]) * nframes * spec->channels);
600
601         /* foreach output channel ... */
602         
603         for (chn = 0; chn < spec->channels; ++chn) {
604                 
605                 ExportPortMap::iterator mi = spec->port_map.find (chn);
606                 
607                 if (mi == spec->port_map.end()) {
608                         /* no ports exported to this channel */
609                         continue;
610                 }
611                 
612                 vector<PortChannelPair>& mapped_ports ((*mi).second);
613                 
614                 for (vector<PortChannelPair>::iterator t = mapped_ports.begin(); t != mapped_ports.end(); ++t) {
615                         
616                         /* OK, this port's output is supposed to appear on this channel 
617                          */
618
619                         AudioPort* const aport = dynamic_cast<AudioPort*>((*t).first);
620                         MidiPort* const mport = dynamic_cast<MidiPort*>((*t).first);
621                         if (aport != 0) {
622                                 Sample* port_buffer = aport->get_audio_buffer().data();
623
624                                 /* now interleave the data from the channel into the float buffer */
625
626                                 for (x = 0; x < nframes; ++x) {
627                                         spec->dataF[chn+(x*spec->channels)] += (float) port_buffer[x];
628                                 }
629                         } else if (mport != 0) {
630                                 cerr << "EXPORT MIDI PORT" << endl;
631                         }
632                 }
633         }
634
635         cerr << "\tprocess " << nframes << endl;
636
637         if (spec->process (nframes)) {
638                 goto out;
639         }
640         
641         spec->pos += nframes;
642         spec->progress = 1.0 - (((float) spec->end_frame - spec->pos) / spec->total_frames);
643
644         cerr << "\t@ " << spec->pos << " prog = " << spec->progress << endl;
645
646         /* and we're good to go */
647
648         ret = 0;
649
650   out: 
651         if (ret) {
652                 sf_close (spec->out);
653                 spec->out = 0;
654                 unlink (spec->path.c_str());
655                 spec->running = false;
656                 spec->status = ret;
657                 _exporting = false;
658         }
659
660         return ret;
661 }
662
663 void
664 Session::finalize_export ()
665 {
666         _engine.freewheel (false);
667         _exporting = false;
668
669         /* can't use stop_transport() here because we need
670            an immediate halt and don't require all the declick
671            stuff that stop_transport() implements.
672         */
673
674         realtime_stop (true);
675         schedule_butler_transport_work ();
676
677         /* restart slaving */
678
679         if (post_export_slave != None) {
680                 Config->set_slave_source (post_export_slave);
681         } else {
682                 locate (post_export_position, false, false, false);
683         }
684 }