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