r269@gandalf: fugalh | 2006-08-03 20:18:05 -0600
[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     $Id$
19 */
20
21 /* see gdither.cc for why we have to do this */
22
23 #define _ISOC9X_SOURCE  1
24 #define _ISOC99_SOURCE  1
25 #include <cmath>
26 #undef  _ISOC99_SOURCE
27 #undef  _ISOC9X_SOURCE
28 #undef  __USE_SVID 
29 #define __USE_SVID 1
30 #include <cstdlib>
31 #undef  __USE_SVID
32
33 #include <unistd.h>
34 #include <inttypes.h>
35 #include <float.h>
36
37 #include <sigc++/bind.h>
38
39 #include <pbd/error.h>
40 #include <glibmm/thread.h>
41
42 #include <ardour/gdither.h>
43 #include <ardour/timestamps.h>
44 #include <ardour/ardour.h>
45 #include <ardour/session.h>
46 #include <ardour/export.h>
47 #include <ardour/sndfile_helpers.h>
48 #include <ardour/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 (AudioExportSpecification& 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 AudioExportSpecification::AudioExportSpecification ()
80 {
81         init ();
82 }
83
84 AudioExportSpecification::~AudioExportSpecification ()
85 {
86         clear ();
87 }
88
89 void
90 AudioExportSpecification::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 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 (jack_nframes_t blocksize, jack_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 ((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 = (jack_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         return 0;
258 }
259
260 int
261 AudioExportSpecification::process (jack_nframes_t nframes)
262 {
263         float* float_buffer = 0;
264         uint32_t chn;
265         uint32_t x;
266         uint32_t i;
267         sf_count_t written;
268         char errbuf[256];
269         jack_nframes_t to_write = 0;
270         int cnt = 0;
271
272         do {
273
274                 /* now do sample rate conversion */
275         
276                 if (sample_rate != frame_rate) {
277                 
278                         int err;
279                 
280                         src_data.output_frames = out_samples_max / channels;
281                         src_data.end_of_input = ((pos + nframes) >= end_frame);
282                         src_data.data_out = dataF2;
283
284                         if (leftover_frames > 0) {
285
286                                 /* input data will be in leftoverF rather than dataF */
287
288                                 src_data.data_in = leftoverF;
289
290                                 if (cnt == 0) {
291                                         
292                                         /* first time, append new data from dataF into the leftoverF buffer */
293
294                                         memcpy (leftoverF + (leftover_frames * channels), dataF, nframes * channels * sizeof(float));
295                                         src_data.input_frames = nframes + leftover_frames;
296                                 } else {
297                                         
298                                         /* otherwise, just use whatever is still left in leftoverF; the contents
299                                            were adjusted using memmove() right after the last SRC call (see
300                                            below)
301                                         */
302
303                                         src_data.input_frames = leftover_frames;
304                                 }
305                                         
306                         } else {
307
308                                 src_data.data_in = dataF;
309                                 src_data.input_frames = nframes;
310
311                         }
312
313                         ++cnt;
314
315                         if ((err = src_process (src_state, &src_data)) != 0) {
316                                 error << string_compose (_("an error occured during sample rate conversion: %1"),
317                                                   src_strerror (err))
318                                       << endmsg;
319                                 return -1;
320                         }
321                 
322                         to_write = src_data.output_frames_gen;
323                         leftover_frames = src_data.input_frames - src_data.input_frames_used;
324
325                         if (leftover_frames > 0) {
326                                 if (leftover_frames > max_leftover_frames) {
327                                         error << _("warning, leftover frames overflowed, glitches might occur in output") << endmsg;
328                                         leftover_frames = max_leftover_frames;
329                                 }
330                                 memmove (leftoverF, (char *) (src_data.data_in + (src_data.input_frames_used * channels)),
331                                          leftover_frames * channels * sizeof(float));
332                         }
333
334                         float_buffer = dataF2;
335                 
336                 } else {
337
338                         /* no SRC, keep it simple */
339                 
340                         to_write = nframes;
341                         leftover_frames = 0;
342                         float_buffer = dataF;
343                 }
344         
345                 if (output_data) {
346                         memset (output_data, 0, sample_bytes * to_write * channels);
347                 }
348         
349                 switch (data_width) {
350                 case 8:
351                 case 16:
352                 case 24:
353                         for (chn = 0; chn < channels; ++chn) { 
354                                 gdither_runf (dither, chn, to_write, float_buffer, output_data);
355                         }
356                         break;
357                 
358                 case 32:
359                         for (chn = 0; chn < channels; ++chn) {
360                         
361                                 int *ob = (int *) output_data;
362                                 const double int_max = (float) INT_MAX;
363                                 const double int_min = (float) INT_MIN;
364                         
365                                 for (x = 0; x < to_write; ++x) {
366                                         i = chn + (x * channels);
367                                 
368                                         if (float_buffer[i] > 1.0f) {
369                                                 ob[i] = INT_MAX;
370                                         } else if (float_buffer[i] < -1.0f) {
371                                                 ob[i] = INT_MIN;
372                                         } else {
373                                                 if (float_buffer[i] >= 0.0f) {
374                                                         ob[i] = lrintf (int_max * float_buffer[i]);
375                                                 } else {
376                                                         ob[i] = - lrintf (int_min * float_buffer[i]);
377                                                 }
378                                         }
379                                 }
380                         }
381                         break;
382                 
383                 default:
384                         for (x = 0; x < to_write * channels; ++x) {
385                                 if (float_buffer[x] > 1.0f) {
386                                         float_buffer[x] = 1.0f;
387                                 } else if (float_buffer[x] < -1.0f) {
388                                         float_buffer[x] = -1.0f;
389                                 } 
390                         }
391                         break;
392                 }
393         
394                 /* and export to disk */
395         
396                 switch (data_width) {
397                 case 8:
398                         /* XXXX no way to deliver 8 bit audio to libsndfile */
399                         written = to_write;
400                         break;
401                 
402                 case 16:
403                         written = sf_writef_short (out, (short*) output_data, to_write);
404                         break;
405                 
406                 case 24:
407                 case 32:
408                         written = sf_writef_int (out, (int*) output_data, to_write);
409                         break;
410                 
411                 default:
412                         written = sf_writef_float (out, float_buffer, to_write);
413                         break;
414                 }
415         
416                 if ((jack_nframes_t) written != to_write) {
417                         sf_error_str (out, errbuf, sizeof (errbuf) - 1);
418                         error << string_compose(_("Export: could not write data to output file (%1)"), errbuf) << endmsg;
419                         return -1;
420                 }
421
422
423         } while (leftover_frames >= nframes);
424
425         return 0;
426 }
427
428 int
429 Session::start_audio_export (AudioExportSpecification& spec)
430 {
431         int ret;
432
433         if (spec.prepare (current_block_size, frame_rate())) {
434                 return -1;
435         }
436
437         spec.pos = spec.start_frame;
438         spec.end_frame = spec.end_frame;
439         spec.total_frames = spec.end_frame - spec.start_frame;
440
441         spec.freewheel_connection = _engine.Freewheel.connect (sigc::bind (mem_fun (*this, &Session::process_export), &spec));
442
443         if ((ret = _engine.freewheel (true)) == 0) {
444                 spec.running = true; 
445                 spec.do_freewheel = false;
446         }
447
448         return ret;
449 }
450
451 int
452 Session::stop_audio_export (AudioExportSpecification& spec)
453 {
454         /* can't use stop_transport() here because we need
455            an immediate halt and don't require all the declick
456            stuff that stop_transport() implements.
457         */
458
459         realtime_stop (true);
460         schedule_butler_transport_work ();
461
462         /* restart slaving */
463
464         if (post_export_slave != None) {
465                 set_slave_source (post_export_slave, post_export_position);
466         } else {
467                 locate (post_export_position, false, false, false);
468         }
469
470         spec.clear ();
471         _exporting = false;
472
473         spec.running = false;
474
475         return 0;
476 }
477
478 int 
479 Session::prepare_to_export (AudioExportSpecification& spec)
480 {
481         int ret = -1;
482
483         wait_till_butler_finished ();
484
485         /* take everyone out of awrite to avoid disasters */
486
487         {
488                 boost::shared_ptr<RouteList> r = routes.reader ();
489
490                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
491                         (*i)->protect_automation ();
492                 }
493         }
494
495         /* get everyone to the right position */
496
497         {
498                 Glib::RWLock::ReaderLock lm (diskstream_lock);
499                 for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
500                         if ((*i)-> seek (spec.start_frame, true)) {
501                                 error << string_compose (_("%1: cannot seek to %2 for export"),
502                                                   (*i)->name(), spec.start_frame)
503                                       << endmsg;
504                                 goto out;
505                         }
506                 }
507         }
508
509         /* make sure we are actually rolling */
510
511         if (get_record_enabled()) {
512                 disable_record (false);
513         }
514
515         _exporting = true;
516         
517         /* no slaving */
518
519         post_export_slave = _slave_type;
520         post_export_position = _transport_frame;
521
522         set_slave_source (None, 0);
523
524         /* get transport ready */
525
526         set_transport_speed (1.0, false);
527         butler_transport_work ();
528         g_atomic_int_set (&butler_should_do_transport_work, 0);
529         post_transport ();
530
531         /* we are ready to go ... */
532
533         ret = 0;
534
535   out:
536         return ret;
537 }
538
539 int
540 Session::process_export (jack_nframes_t nframes, AudioExportSpecification* spec)
541 {
542         uint32_t chn;
543         uint32_t x;
544         int ret = -1;
545         jack_nframes_t this_nframes;
546
547         /* This is not required to be RT-safe because we are running while freewheeling */
548
549         if (spec->do_freewheel == false) {
550                 
551                 /* first time in export function: get set up */
552
553                 if (prepare_to_export (*spec)) {
554                         spec->running = false;
555                         spec->status = -1;
556                         return -1;
557                 }
558                 
559                 spec->do_freewheel = true;
560         }
561
562         if (!_exporting) {
563                 /* finished, but still freewheeling */
564                 process_without_events (nframes);
565                 return 0;
566         }
567                 
568         if (!spec->running || spec->stop || (this_nframes = min ((spec->end_frame - spec->pos), nframes)) == 0) {
569                 process_without_events (nframes);
570                 return stop_audio_export (*spec);
571         }
572
573         /* make sure we've caught up with disk i/o, since
574            we're running faster than realtime c/o JACK.
575         */
576
577         wait_till_butler_finished ();
578         
579         /* do the usual stuff */
580         
581         process_without_events (nframes);
582
583         /* and now export the results */
584
585         nframes = this_nframes;
586
587         memset (spec->dataF, 0, sizeof (spec->dataF[0]) * nframes * spec->channels);
588
589         /* foreach output channel ... */
590         
591         for (chn = 0; chn < spec->channels; ++chn) {
592                 
593                 AudioExportPortMap::iterator mi = spec->port_map.find (chn);
594                 
595                 if (mi == spec->port_map.end()) {
596                         /* no ports exported to this channel */
597                         continue;
598                 }
599                 
600                 vector<PortChannelPair>& mapped_ports ((*mi).second);
601                 
602                 for (vector<PortChannelPair>::iterator t = mapped_ports.begin(); t != mapped_ports.end(); ++t) {
603                         
604                         /* OK, this port's output is supposed to appear on this channel 
605                          */
606
607                         Port* port = (*t).first;
608                         Sample* port_buffer = port->get_buffer (nframes);
609
610                         /* now interleave the data from the channel into the float buffer */
611                                 
612                         for (x = 0; x < nframes; ++x) {
613                                 spec->dataF[chn+(x*spec->channels)] += (float) port_buffer[x];
614                         }
615                 }
616         }
617
618         if (spec->process (nframes)) {
619                 goto out;
620         }
621         
622         spec->pos += nframes;
623         spec->progress = 1.0 - (((float) spec->end_frame - spec->pos) / spec->total_frames);
624
625         /* and we're good to go */
626
627         ret = 0;
628
629   out: 
630         if (ret) {
631                 sf_close (spec->out);
632                 spec->out = 0;
633                 unlink (spec->path.c_str());
634                 spec->running = false;
635                 spec->status = ret;
636                 _exporting = false;
637         }
638
639         return ret;
640 }
641