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