change the way thread name is managed and accessed; store thread name for JACK thread...
[ardour.git] / libs / ardour / export_file_io.cc
1 /*
2     Copyright (C) 2008 Paul Davis
3     Author: Sakari Bergen
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <string.h>
22
23 #include "ardour/export_file_io.h"
24
25 #include "ardour/export_failed.h"
26 #include "pbd/failed_constructor.h"
27
28 #include "i18n.h"
29
30 using namespace std;
31 using namespace Glib;
32 using namespace PBD;
33
34 namespace ARDOUR
35 {
36
37 /* SndfileWriterBase */
38
39 SndfileWriterBase::SndfileWriterBase (int channels, nframes_t samplerate, int format, string const & path) :
40   ExportFileWriter (path)
41 {
42         char errbuf[256];
43
44         sf_info.channels = channels;
45         sf_info.samplerate = samplerate;
46         sf_info.format = format;
47
48         if (!sf_format_check (&sf_info)) {
49                 throw ExportFailed (X_("Invalid format given for SndfileWriter!"));
50         }
51
52         if (path.length() == 0) {
53                 throw ExportFailed (X_("No output file specified for SndFileWriter"));
54         }
55
56         /* TODO add checks that the directory path exists, and also
57            check if we are overwriting an existing file...
58         */
59
60         // Open file TODO make sure we have enough disk space for the output
61         if (path.compare ("temp")) {
62                 if ((sndfile = sf_open (path.c_str(), SFM_WRITE, &sf_info)) == 0) {
63                         sf_error_str (0, errbuf, sizeof (errbuf) - 1);
64                         throw ExportFailed (string_compose(X_("Cannot open output file \"%1\" for SndFileWriter (%2)"), path, errbuf));
65                 }
66         } else {
67                 FILE * file;
68                 if (!(file = tmpfile ())) {
69                         throw ExportFailed (X_("Cannot open tempfile"));
70                 }
71                 sndfile = sf_open_fd (fileno(file), SFM_RDWR, &sf_info, true);
72         }
73 }
74
75 SndfileWriterBase::~SndfileWriterBase ()
76 {
77         sf_close (sndfile);
78 }
79
80 /* SndfileWriter */
81
82 template <typename T>
83 SndfileWriter<T>::SndfileWriter (int channels, nframes_t samplerate, int format, string const & path) :
84   SndfileWriterBase (channels, samplerate, format, path)
85 {
86         // init write function
87         init ();
88 }
89
90 template <>
91 void
92 SndfileWriter<float>::init ()
93 {
94         write_func = &sf_writef_float;
95 }
96
97 template <>
98 void
99 SndfileWriter<int>::init ()
100 {
101         write_func = &sf_writef_int;
102 }
103
104 template <>
105 void
106 SndfileWriter<short>::init ()
107 {
108         write_func = &sf_writef_short;
109 }
110
111 template <typename T>
112 nframes_t
113 SndfileWriter<T>::write (T * data, nframes_t frames)
114 {
115         char errbuf[256];
116         nframes_t written = (*write_func) (sndfile, data, frames);
117         if (written != frames) {
118                 sf_error_str (sndfile, errbuf, sizeof (errbuf) - 1);
119                 throw ExportFailed (string_compose(_("Could not write data to output file (%1)"), errbuf));
120         }
121
122         if (GraphSink<T>::end_of_input) {
123                 sf_write_sync (sndfile);
124         }
125
126         return frames;
127 }
128
129 template class SndfileWriter<short>;
130 template class SndfileWriter<int>;
131 template class SndfileWriter<float>;
132
133 /* ExportTempFile */
134
135 ExportTempFile::ExportTempFile (uint32_t channels, nframes_t samplerate) :
136   SndfileWriter<float> (channels, samplerate, SF_FORMAT_RAW | SF_FORMAT_FLOAT | SF_ENDIAN_FILE, "temp"),
137   channels (channels),
138   reading (false),
139   start (0),
140   end (0),
141   beginning_processed (false),
142   end_processed (false),
143   silence_beginning (0),
144   silence_end (0),
145   end_set (false)
146 {
147 }
148
149 nframes_t
150 ExportTempFile::read (float * data, nframes_t frames)
151 {
152         nframes_t frames_read = 0;
153         nframes_t to_read = 0;
154         sf_count_t read_status = 0;
155
156         /* Initialize state at first read */
157
158         if (!reading) {
159                 if (!end_set) {
160                         end = get_length();
161                         end_set = true;
162                 }
163                 locate_to (start);
164                 reading = true;
165         }
166
167         /* Add silence to beginning */
168
169         if (silence_beginning > 0) {
170                 if (silence_beginning >= frames) {
171                         memset (data, 0, channels * frames * sizeof (float));
172                         silence_beginning -= frames;
173                         return frames;
174                 }
175
176                 memset (data, 0, channels * silence_beginning * sizeof (float));
177
178                 frames_read += silence_beginning;
179                 data += channels * silence_beginning;
180                 silence_beginning = 0;
181         }
182
183         /* Read file, but don't read past end */
184
185         if (get_read_position() >= end) {
186                 // File already read, do nothing!
187         } else {
188                 if ((get_read_position() + (frames - frames_read)) > end) {
189                         to_read = end - get_read_position();
190                 } else {
191                         to_read = frames - frames_read;
192                 }
193
194                 read_status = sf_readf_float (sndfile, data, to_read);
195
196                 frames_read += to_read;
197                 data += channels * to_read;
198         }
199
200         /* Check for errors */
201
202         if (read_status != to_read) {
203                 throw ExportFailed (X_("Error reading temporary export file, export might not be complete!"));
204         }
205
206         /* Add silence at end */
207
208         if (silence_end > 0) {
209                 to_read = frames - frames_read;
210                 if (silence_end < to_read) {
211                         to_read = silence_end;
212                 }
213
214                 memset (data, 0, channels * to_read * sizeof (float));
215                 silence_end -= to_read;
216                 frames_read += to_read;
217         }
218
219         return frames_read;
220 }
221
222 nframes_t
223 ExportTempFile::trim_beginning (bool yn)
224 {
225         if (!yn) {
226                 start = 0;
227                 return start;
228         }
229
230         if (!beginning_processed) {
231                 process_beginning ();
232         }
233
234         start = silent_frames_beginning;
235         return start;
236
237 }
238
239 nframes_t
240 ExportTempFile::trim_end (bool yn)
241 {
242         end_set = true;
243
244         if (!yn) {
245                 end = get_length();
246                 return end;
247         }
248
249         if (!end_processed) {
250                 process_end ();
251         }
252
253         end = silent_frames_end;
254         return end;
255 }
256
257
258 void
259 ExportTempFile::process_beginning ()
260 {
261         nframes_t frames = 1024;
262         nframes_t frames_read;
263         float * buf = new float[channels * frames];
264
265         nframes_t pos = 0;
266         locate_to (pos);
267
268         while ((frames_read = _read (buf, frames)) > 0) {
269                 for (nframes_t i = 0; i < frames_read; i++) {
270                         for (uint32_t chn = 0; chn < channels; ++chn) {
271                                 if (buf[chn + i * channels] != 0.0f) {
272                                         --pos;
273                                         goto out;
274                                 }
275                         }
276                         ++pos;
277                 }
278         }
279
280         out:
281
282         silent_frames_beginning = pos;
283         beginning_processed = true;
284
285         delete [] buf;
286 }
287
288 void
289 ExportTempFile::process_end ()
290 {
291         nframes_t frames = 1024;
292         nframes_t frames_read;
293         float * buf = new float[channels * frames];
294
295         nframes_t pos = get_length() - 1;
296
297         while (pos > 0) {
298                 if (pos > frames) {
299                         locate_to (pos - frames);
300                         frames_read = _read (buf, frames);
301                 } else {
302                         // Last time reading
303                         locate_to (0);
304                         frames_read = _read (buf, pos);
305                 }
306
307                 for (nframes_t i = frames_read; i > 0; --i) {
308                         for (uint32_t chn = 0; chn < channels; ++chn) {
309                                 if (buf[chn + (i - 1) * channels] != 0.0f) {
310                                         goto out;
311                                 }
312                         }
313                         --pos;
314                 }
315         }
316
317         out:
318
319         silent_frames_end = pos;
320         end_processed = true;
321
322         delete [] buf;
323 }
324
325 void
326 ExportTempFile::set_silence_beginning (nframes_t frames)
327 {
328         silence_beginning = frames;
329 }
330
331 void
332 ExportTempFile::set_silence_end (nframes_t frames)
333 {
334         silence_end = frames;
335 }
336
337 sf_count_t
338 ExportTempFile::get_length ()
339 {
340         sf_count_t pos = get_position();
341         sf_count_t len = sf_seek (sndfile, 0, SEEK_END);
342         locate_to (pos);
343         return len;
344 }
345
346 sf_count_t
347 ExportTempFile::get_position ()
348 {
349         return sf_seek (sndfile, 0, SEEK_CUR);
350 }
351
352 sf_count_t
353 ExportTempFile::get_read_position ()
354 {
355         return sf_seek (sndfile, 0, SEEK_CUR | SFM_READ);
356 }
357
358 sf_count_t
359 ExportTempFile::locate_to (nframes_t frames)
360 {
361         return sf_seek (sndfile, frames, SEEK_SET);
362 }
363
364 sf_count_t
365 ExportTempFile::_read (float * data, nframes_t frames)
366 {
367         return sf_readf_float (sndfile, data, frames);
368 }
369
370 ExportFileFactory::FilePair
371 ExportFileFactory::create (FormatPtr format, uint32_t channels, ustring const & filename)
372 {
373         switch (format->type()) {
374           case ExportFormatBase::T_Sndfile:
375                 return create_sndfile (format, channels, filename);
376
377           default:
378                 throw ExportFailed (X_("Invalid format given for ExportFileFactory::create!"));
379         }
380 }
381
382 bool
383 ExportFileFactory::check (FormatPtr format, uint32_t channels)
384 {
385         switch (format->type()) {
386           case ExportFormatBase::T_Sndfile:
387                 return check_sndfile (format, channels);
388
389           default:
390                 throw ExportFailed (X_("Invalid format given for ExportFileFactory::check!"));
391         }
392 }
393
394 ExportFileFactory::FilePair
395 ExportFileFactory::create_sndfile (FormatPtr format, unsigned int channels, ustring const & filename)
396 {
397         typedef boost::shared_ptr<SampleFormatConverter<short> > ShortConverterPtr;
398         typedef boost::shared_ptr<SampleFormatConverter<int> > IntConverterPtr;
399         typedef boost::shared_ptr<SampleFormatConverter<float> > FloatConverterPtr;
400
401         typedef boost::shared_ptr<SndfileWriter<short> > ShortWriterPtr;
402         typedef boost::shared_ptr<SndfileWriter<int> > IntWriterPtr;
403         typedef boost::shared_ptr<SndfileWriter<float> > FloatWriterPtr;
404
405         int real_format = format->format_id() | format->sample_format() | format->endianness();
406
407         uint32_t data_width = sndfile_data_width (real_format);
408
409         if (data_width == 8 || data_width == 16) {
410
411                 ShortConverterPtr sfc = ShortConverterPtr (new SampleFormatConverter<short> (channels, format->dither_type(), data_width));
412                 ShortWriterPtr sfw = ShortWriterPtr (new SndfileWriter<short> (channels, format->sample_rate(), real_format, filename));
413                 sfc->pipe_to (sfw);
414
415                 return std::make_pair (boost::static_pointer_cast<FloatSink> (sfc), boost::static_pointer_cast<ExportFileWriter> (sfw));
416
417         } else if (data_width == 24 || data_width == 32) {
418
419                 IntConverterPtr sfc = IntConverterPtr (new SampleFormatConverter<int> (channels, format->dither_type(), data_width));
420                 IntWriterPtr sfw = IntWriterPtr (new SndfileWriter<int> (channels, format->sample_rate(), real_format, filename));
421                 sfc->pipe_to (sfw);
422
423                 return std::make_pair (boost::static_pointer_cast<FloatSink> (sfc), boost::static_pointer_cast<ExportFileWriter> (sfw));
424
425         }
426
427         FloatConverterPtr sfc = FloatConverterPtr (new SampleFormatConverter<float> (channels, format->dither_type(), data_width));
428         FloatWriterPtr sfw = FloatWriterPtr (new SndfileWriter<float> (channels, format->sample_rate(), real_format, filename));
429         sfc->pipe_to (sfw);
430
431         return std::make_pair (boost::static_pointer_cast<FloatSink> (sfc), boost::static_pointer_cast<ExportFileWriter> (sfw));
432 }
433
434 bool
435 ExportFileFactory::check_sndfile (FormatPtr format, unsigned int channels)
436 {
437         SF_INFO sf_info;
438         sf_info.channels = channels;
439         sf_info.samplerate = format->sample_rate ();
440         sf_info.format = format->format_id () | format->sample_format ();
441
442         return (sf_format_check (&sf_info) == SF_TRUE ? true : false);
443 }
444
445 } // namespace ARDOUR