use drobilla's latest, not his penultimate, version of string_is_affirmitive()
[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/audioengine.h>
49 #include <ardour/audio_diskstream.h>
50 #include <ardour/panner.h>
51
52 #include "i18n.h"
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57
58 static int
59 convert_spec_to_info (AudioExportSpecification& spec, SF_INFO& sfinfo)
60 {
61         if (spec.path.length() == 0) {
62                 error << _("Export: no output file specified") << endmsg;
63                 return -1;
64         }
65
66         /* XXX add checks that the directory path exists, and also 
67            check if we are overwriting an existing file...
68         */
69
70         sfinfo.format = spec.format;
71         sfinfo.samplerate = spec.sample_rate;
72         sfinfo.frames = spec.end_frame - spec.start_frame + 1;
73         sfinfo.channels = min (spec.channels, 2U);
74
75         return 0;
76 }
77
78 AudioExportSpecification::AudioExportSpecification ()
79 {
80         init ();
81 }
82
83 AudioExportSpecification::~AudioExportSpecification ()
84 {
85         clear ();
86 }
87
88 void
89 AudioExportSpecification::init ()
90 {
91         memset (&sfinfo, 0, sizeof (sfinfo));
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 AudioExportSpecification::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 AudioExportSpecification::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 frame range 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 (((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_OGG) && (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 AudioExportSpecification::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_audio_export (AudioExportSpecification& 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_audio_export (AudioExportSpecification& spec)
454 {
455         /* don't stop freewheeling but do stop paying attention to it for now */
456
457
458         /* save the value of stop so that the UI
459            can see if it requested a stop.
460         */
461
462         bool old_stop = spec.stop;
463
464         spec.freewheel_connection.disconnect ();
465         spec.clear (); /* resets running/stop etc */
466
467         spec.stop = old_stop;
468
469         if (!spec.stop) {
470                 Exported (spec.path, name());
471         }
472
473         return 0;
474 }
475
476 int
477 Session::pre_export ()
478 {
479         wait_till_butler_finished ();
480
481         /* take everyone out of awrite to avoid disasters */
482
483         {
484                 boost::shared_ptr<RouteList> r = routes.reader ();
485
486                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
487                         (*i)->protect_automation ();
488                 }
489         }
490
491         /* make sure we are actually rolling */
492
493         if (get_record_enabled()) {
494                 disable_record (false);
495         }
496
497         /* no slaving */
498
499         post_export_slave = Config->get_slave_source ();
500         post_export_position = _transport_frame;
501
502         Config->set_slave_source (None);
503
504         return 0;
505 }
506
507 int 
508 Session::prepare_to_export (AudioExportSpecification& spec)
509 {
510         int ret = -1;
511
512         /* get everyone to the right position */
513
514         {
515                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
516
517                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
518                         if ((*i)-> seek (spec.start_frame, true)) {
519                                 error << string_compose (_("%1: cannot seek to %2 for export"),
520                                                   (*i)->name(), spec.start_frame)
521                                       << endmsg;
522                                 goto out;
523                         }
524                 }
525         }
526
527         cerr << "Everybdy is at " << spec.start_frame << endl;
528
529         /* we just did the core part of a locate() call above, but
530            for the sake of any GUI, put the _transport_frame in
531            the right place too.
532         */
533
534         _transport_frame = spec.start_frame;
535         _exporting = true;
536
537         /* get transport ready. note how this is calling butler functions
538            from a non-butler thread. we waited for the butler to stop
539            what it was doing earlier in Session::pre_export() and nothing
540            since then has re-awakened it.
541          */
542
543         set_transport_speed (1.0, false);
544         butler_transport_work ();
545         g_atomic_int_set (&butler_should_do_transport_work, 0);
546         post_transport ();
547
548         /* we are ready to go ... */
549
550         ret = 0;
551
552   out:
553         return ret;
554 }
555
556 int
557 Session::process_export (nframes_t nframes, AudioExportSpecification* spec)
558 {
559         uint32_t chn;
560         uint32_t x;
561         int ret = -1;
562         nframes_t this_nframes;
563
564         /*cerr << "Export process at pos = " << spec->pos << " _exporting = "
565              << _exporting << " running = " << spec->running << " stop = "
566              << spec->stop << endl;
567         */
568         /* This is not required to be RT-safe because we are running while freewheeling */
569
570         if (spec->do_freewheel == false) {
571                 
572                 /* first time in export function: get set up */
573
574                 if (prepare_to_export (*spec)) {
575                         spec->running = false;
576                         spec->status = -1;
577                         return -1;
578                 }
579                 
580                 spec->do_freewheel = true;
581         }
582
583         if (!_exporting) {
584                 /* finished, but still freewheeling */
585                 cerr << "\tExport ... not exporting yet, no_roll() for " << nframes <<endl;
586                 no_roll (nframes);
587                 return 0;
588         }
589         
590         if (!spec->running || spec->stop || (this_nframes = min ((spec->end_frame - spec->pos), nframes)) == 0) {
591                 cerr << "\tExport ... not running or at end, no_roll() for " << nframes <<endl;
592                 no_roll (nframes);
593                 return stop_audio_export (*spec);
594         }
595
596         /* make sure we've caught up with disk i/o, since
597            we're running faster than realtime c/o JACK.
598         */
599
600         wait_till_butler_finished ();
601         
602         /* do the usual stuff */
603         
604         process_without_events (nframes);
605
606         /* and now export the results */
607
608         nframes = this_nframes;
609
610         memset (spec->dataF, 0, sizeof (spec->dataF[0]) * nframes * spec->channels);
611
612         /* foreach output channel ... */
613         
614         for (chn = 0; chn < spec->channels; ++chn) {
615                 
616                 AudioExportPortMap::iterator mi = spec->port_map.find (chn);
617                 
618                 if (mi == spec->port_map.end()) {
619                         /* no ports exported to this channel */
620                         continue;
621                 }
622                 
623                 vector<PortChannelPair>& mapped_ports ((*mi).second);
624                 
625                 for (vector<PortChannelPair>::iterator t = mapped_ports.begin(); t != mapped_ports.end(); ++t) {
626                         
627                         /* OK, this port's output is supposed to appear on this channel 
628                          */
629
630                         Port* port = (*t).first;
631                         Sample* port_buffer = port->get_buffer (nframes);
632
633                         /* now interleave the data from the channel into the float buffer */
634                                 
635                         for (x = 0; x < nframes; ++x) {
636                                 spec->dataF[chn+(x*spec->channels)] += (float) port_buffer[x];
637                         }
638                 }
639         }
640
641         //cerr << "\tprocess " << nframes << endl;
642
643         if (spec->process (nframes)) {
644                 goto out;
645         }
646         
647         spec->pos += nframes;
648         spec->progress = 1.0 - (((float) spec->end_frame - spec->pos) / spec->total_frames);
649
650         //cerr << "\t@ " << spec->pos << " prog = " << spec->progress << endl;
651
652         /* and we're good to go */
653
654         ret = 0;
655
656   out: 
657         if (ret) {
658                 sf_close (spec->out);
659                 spec->out = 0;
660                 unlink (spec->path.c_str());
661                 spec->running = false;
662                 spec->status = ret;
663                 _exporting = false;
664         }
665
666         return ret;
667 }
668
669 void
670 Session::finalize_audio_export ()
671 {
672         _engine.freewheel (false);
673         _exporting = false;
674
675         /* can't use stop_transport() here because we need
676            an immediate halt and don't require all the declick
677            stuff that stop_transport() implements.
678         */
679
680         realtime_stop (true);
681         schedule_butler_transport_work ();
682
683         /* restart slaving */
684
685         if (post_export_slave != None) {
686                 Config->set_slave_source (post_export_slave);
687         } else {
688                 locate (post_export_position, false, false, false);
689         }
690 }