Fix split buffer audio glitches with lv2 plugins.
[ardour.git] / libs / ardour / import.cc
1 /*
2     Copyright (C) 2000 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 #include <cstdio>
21 #include <cstdlib>
22 #include <string>
23 #include <climits>
24 #include <cerrno>
25 #include <unistd.h>
26 #include <sys/stat.h>
27 #include <time.h>
28
29 #include <sndfile.h>
30 #include <samplerate.h>
31
32 #include <glibmm.h>
33
34 #include <boost/scoped_array.hpp>
35 #include <boost/shared_array.hpp>
36
37 #include <pbd/basename.h>
38 #include <pbd/convert.h>
39
40 #include <ardour/ardour.h>
41 #include <ardour/session.h>
42 #include <ardour/audio_diskstream.h>
43 #include <ardour/sndfilesource.h>
44 #include <ardour/sndfile_helpers.h>
45 #include <ardour/audioregion.h>
46 #include <ardour/region_factory.h>
47 #include <ardour/source_factory.h>
48 #include <ardour/resampled_source.h>
49 #include <ardour/sndfileimportable.h>
50 #include <ardour/analyser.h>
51
52 #ifdef HAVE_COREAUDIO
53 #include <ardour/caimportable.h>
54 #endif
55
56 #include "i18n.h"
57
58 using namespace ARDOUR;
59 using namespace PBD;
60
61
62 static boost::shared_ptr<ImportableSource>
63 open_importable_source (const string& path, nframes_t samplerate, ARDOUR::SrcQuality quality)
64 {
65 #ifdef HAVE_COREAUDIO
66
67         /* see if we can use CoreAudio to handle the IO */
68         
69         try { 
70                 boost::shared_ptr<CAImportableSource> source(new CAImportableSource(path));
71                 
72                 if (source->samplerate() == samplerate) {
73                         return source;
74                 }
75                 
76                 /* rewrap as a resampled source */
77
78                 return boost::shared_ptr<ImportableSource>(new ResampledImportableSource(source, samplerate, quality));
79         }
80
81         catch (...) {
82
83                 /* fall back to SndFile */
84
85 #endif  
86
87                 try { 
88                         boost::shared_ptr<SndFileImportableSource> source(new SndFileImportableSource(path));
89                         
90                         if (source->samplerate() == samplerate) {
91                                 return source;
92                         }
93
94                         /* rewrap as a resampled source */
95                         
96                         return boost::shared_ptr<ImportableSource>(new ResampledImportableSource(source, samplerate, quality));
97                 }
98                 
99                 catch (...) {
100                         throw; // rethrow
101                 }
102                 
103 #ifdef HAVE_COREAUDIO           
104         }
105 #endif
106 }
107
108 static std::string
109 get_non_existent_filename (const bool allow_replacing, const std::string destdir, const std::string& basename, uint channel, uint channels)
110 {
111         char buf[PATH_MAX+1];
112         bool goodfile = false;
113         string base(basename);
114
115         do {
116                 if (channels == 2) {
117                         if (channel == 0) {
118                                 snprintf (buf, sizeof(buf), "%s-L.wav", base.c_str());
119                         } else {
120                                 snprintf (buf, sizeof(buf), "%s-R.wav", base.c_str());
121                         }
122                 } else if (channels > 1) {
123                         snprintf (buf, sizeof(buf), "%s-c%d.wav", base.c_str(), channel+1);
124                 } else {
125                         snprintf (buf, sizeof(buf), "%s.wav", base.c_str());
126                 }
127                 
128
129                 string tempname = destdir + "/" + buf;
130                 if (!allow_replacing && Glib::file_test (tempname, Glib::FILE_TEST_EXISTS)) {
131
132                         /* if the file already exists, we must come up with
133                          *  a new name for it.  for now we just keep appending
134                          *  _ to basename
135                          */
136
137                         base += "_";
138
139                 } else {
140
141                         goodfile = true;
142                 }
143
144         } while ( !goodfile);
145
146         return buf;
147 }
148
149 static vector<string>
150 get_paths_for_new_sources (const bool allow_replacing, const string& import_file_path, const string& session_dir, uint channels)
151 {
152         vector<string> new_paths;
153         const string basename = basename_nosuffix (import_file_path);
154
155         for (uint n = 0; n < channels; ++n) {
156
157                 std::string filepath;
158
159                 filepath = session_dir;
160                 filepath += '/';
161                 filepath += get_non_existent_filename (allow_replacing, session_dir, basename, n, channels); 
162
163                 new_paths.push_back (filepath);
164         }
165
166         return new_paths;
167 }
168
169 static bool
170 map_existing_mono_sources (const vector<string>& new_paths, Session& sess,
171                            uint samplerate, vector<boost::shared_ptr<AudioFileSource> >& newfiles, Session *session)
172 {
173         for (vector<string>::const_iterator i = new_paths.begin();
174                         i != new_paths.end(); ++i)
175         {
176                 boost::shared_ptr<Source> source = session->source_by_path_and_channel(*i, 0);
177
178                 if (source == 0) {
179                         error << string_compose(_("Could not find a source for %1 even though we are updating this file!"), (*i)) << endl;
180                         return false;
181                 }
182
183                 newfiles.push_back(boost::dynamic_pointer_cast<AudioFileSource>(source));
184         }
185         return true;
186 }
187
188 static bool
189 create_mono_sources_for_writing (const vector<string>& new_paths, Session& sess,
190                 uint samplerate, vector<boost::shared_ptr<AudioFileSource> >& newfiles)
191 {
192         for (vector<string>::const_iterator i = new_paths.begin();
193                         i != new_paths.end(); ++i)
194         {
195                 boost::shared_ptr<Source> source;
196
197                 try
198                 {
199                         source = SourceFactory::createWritable (
200                                 sess,
201                                 i->c_str(),
202                                 false, // destructive
203                                 samplerate
204                                 );
205                 }
206                 catch (const failed_constructor& err)
207                 {
208                         error << string_compose (_("Unable to create file %1 during import"), *i) << endmsg;
209                         return false;
210                 }
211
212                 newfiles.push_back(boost::dynamic_pointer_cast<AudioFileSource>(source));
213         }
214         return true;
215 }
216
217 static Glib::ustring
218 compose_status_message (const string& path,
219                         uint file_samplerate,
220                         uint session_samplerate,
221                         uint current_file,
222                         uint total_files)
223 {
224         if (file_samplerate != session_samplerate) {
225                 return string_compose (_("converting %1\n(resample from %2KHz to %3KHz)\n(%4 of %5)"),
226                                        Glib::path_get_basename (path),
227                                        file_samplerate/1000.0f,
228                                        session_samplerate/1000.0f,
229                                        current_file, total_files);
230         }
231
232         return  string_compose (_("converting %1\n(%2 of %3)"), 
233                                 Glib::path_get_basename (path),
234                                 current_file, total_files);
235 }
236
237 static void
238 write_audio_data_to_new_files (ImportableSource* source, Session::import_status& status,
239                                vector<boost::shared_ptr<AudioFileSource> >& newfiles)
240 {
241         const nframes_t nframes = ResampledImportableSource::blocksize;
242         uint channels = source->channels();
243
244         boost::scoped_array<float> data(new float[nframes * channels]);
245         vector<boost::shared_array<Sample> > channel_data;
246
247         for (uint n = 0; n < channels; ++n) {
248                 channel_data.push_back(boost::shared_array<Sample>(new Sample[nframes]));
249         }
250         
251         uint read_count = 0;
252         status.progress = 0.0f;
253
254         while (!status.cancel) {
255
256                 nframes_t nread, nfread;
257                 uint x;
258                 uint chn;
259
260                 if ((nread = source->read (data.get(), nframes)) == 0) {
261                         break;
262                 }
263                 nfread = nread / channels;
264
265                 /* de-interleave */
266
267                 for (chn = 0; chn < channels; ++chn) {
268
269                         nframes_t n;
270                         for (x = chn, n = 0; n < nfread; x += channels, ++n) {
271                                 channel_data[chn][n] = (Sample) data[x];
272                         }
273                 }
274
275                 /* flush to disk */
276
277                 for (chn = 0; chn < channels; ++chn) {
278                         newfiles[chn]->write (channel_data[chn].get(), nfread);
279                 }
280
281                 read_count += nread;
282                 status.progress = read_count / (source->ratio () * source->length() * channels);
283         }
284 }
285
286 static void
287 remove_file_source (boost::shared_ptr<AudioFileSource> file_source)
288 {
289         ::unlink (file_source->path().c_str());
290 }
291
292 // This function is still unable to cleanly update an existing source, even though
293 // it is possible to set the import_status flag accordingly. The functinality
294 // is disabled at the GUI until the Source implementations are able to provide
295 // the necessary API.
296 void
297 Session::import_audiofiles (import_status& status)
298 {
299         uint32_t cnt = 1;
300         typedef vector<boost::shared_ptr<AudioFileSource> > AudioSources;
301         AudioSources all_new_sources;
302
303         status.sources.clear ();
304         
305         for (vector<Glib::ustring>::iterator p = status.paths.begin();
306                         p != status.paths.end() && !status.cancel;
307                         ++p, ++cnt)
308         {
309                 boost::shared_ptr<ImportableSource> source;
310                 
311                 try
312                 {
313                         source = open_importable_source (*p, frame_rate(), status.quality);
314                 }
315                 
316                 catch (const failed_constructor& err)
317                 {
318                         error << string_compose(_("Import: cannot open input sound file \"%1\""), (*p)) << endmsg;
319                         status.done = status.cancel = true;
320                         return;
321                 }
322
323                 vector<string> new_paths = get_paths_for_new_sources (status.replace_existing_source,
324                                                                       *p,
325                                                                       discover_best_sound_dir (),
326                                                                       source->channels());
327                 
328                 AudioSources newfiles;
329
330                 if (status.replace_existing_source) {
331                         fatal << "THIS IS NOT IMPLEMENTED YET, IT SHOULD NEVER GET CALLED!!! DYING!" << endl;
332                         status.cancel = !map_existing_mono_sources (new_paths, *this, frame_rate(), newfiles, this);
333                 } else {
334                         status.cancel = !create_mono_sources_for_writing (new_paths, *this, frame_rate(), newfiles);
335                 }
336
337                 // copy on cancel/failure so that any files that were created will be removed below
338                 std::copy (newfiles.begin(), newfiles.end(), std::back_inserter(all_new_sources));
339
340                 if (status.cancel) break;
341
342                 for (AudioSources::iterator i = newfiles.begin(); i != newfiles.end(); ++i) {
343                         (*i)->prepare_for_peakfile_writes ();
344                 }
345
346                 status.doing_what = compose_status_message (*p, source->samplerate(),
347                                 frame_rate(), cnt, status.paths.size());
348
349                 write_audio_data_to_new_files (source.get(), status, newfiles);
350         }
351
352         if (!status.cancel) {
353                 struct tm* now;
354                 time_t xnow;
355                 time (&xnow);
356                 now = localtime (&xnow);
357                 status.freeze = true;
358
359                 /* flush the final length(s) to the header(s) */
360
361                 for (AudioSources::iterator x = all_new_sources.begin(); x != all_new_sources.end(); ++x)
362                 {
363                         (*x)->update_header(0, *now, xnow);
364                         (*x)->done_with_peakfile_writes ();
365                         
366                         /* now that there is data there, requeue the file for analysis */
367                         
368                         if (Config->get_auto_analyse_audio()) {
369                                 Analyser::queue_source_for_analysis (boost::static_pointer_cast<Source>(*x), false);
370                         }
371                 }
372
373                 /* save state so that we don't lose these new Sources */
374
375                 save_state (_name);
376
377                 std::copy (all_new_sources.begin(), all_new_sources.end(),
378                                 std::back_inserter(status.sources));
379         } else {
380                 // this can throw...but it seems very unlikely
381                 std::for_each (all_new_sources.begin(), all_new_sources.end(), remove_file_source);
382         }
383
384         status.done = true;
385 }
386
387