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