refactor JACK MIDI port to allow writing from a non-process() thread, and move ARDOUR...
[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/session_directory.h>
43 #include <ardour/audio_diskstream.h>
44 #include <ardour/audioengine.h>
45 #include <ardour/sndfilesource.h>
46 #include <ardour/sndfile_helpers.h>
47 #include <ardour/audioregion.h>
48 #include <ardour/region_factory.h>
49 #include <ardour/source_factory.h>
50 #include <ardour/resampled_source.h>
51 #include <ardour/sndfileimportable.h>
52 #include <ardour/analyser.h>
53 #include <ardour/smf_reader.h>
54 #include <ardour/smf_source.h>
55 #include <ardour/tempo.h>
56
57 #ifdef HAVE_COREAUDIO
58 #include <ardour/caimportable.h>
59 #endif
60
61 #include "i18n.h"
62
63 using namespace ARDOUR;
64 using namespace PBD;
65
66
67 static boost::shared_ptr<ImportableSource>
68 open_importable_source (const string& path, nframes_t samplerate, ARDOUR::SrcQuality quality)
69 {
70 #ifdef HAVE_COREAUDIO
71
72         /* see if we can use CoreAudio to handle the IO */
73         
74         try { 
75                 boost::shared_ptr<CAImportableSource> source(new CAImportableSource(path));
76                 
77                 if (source->samplerate() == samplerate) {
78                         return source;
79                 }
80                 
81                 /* rewrap as a resampled source */
82
83                 return boost::shared_ptr<ImportableSource>(new ResampledImportableSource(source, samplerate, quality));
84         }
85
86         catch (...) {
87
88                 /* fall back to SndFile */
89
90 #endif  
91
92                 try { 
93                         boost::shared_ptr<SndFileImportableSource> source(new SndFileImportableSource(path));
94                         
95                         if (source->samplerate() == samplerate) {
96                                 return source;
97                         }
98
99                         /* rewrap as a resampled source */
100                         
101                         return boost::shared_ptr<ImportableSource>(new ResampledImportableSource(source, samplerate, quality));
102                 }
103                 
104                 catch (...) {
105                         throw; // rethrow
106                 }
107                 
108 #ifdef HAVE_COREAUDIO           
109         }
110 #endif
111 }
112
113 static std::string
114 get_non_existent_filename (DataType type, const bool allow_replacing, const std::string destdir, const std::string& basename, uint channel, uint channels)
115 {
116         char buf[PATH_MAX+1];
117         bool goodfile = false;
118         string base(basename);
119         const char* ext = (type == DataType::AUDIO) ? "wav" : "mid";
120
121         do {
122
123                 if (type == DataType::AUDIO && channels == 2) {
124                         if (channel == 0) {
125                                 snprintf (buf, sizeof(buf), "%s-L.wav", base.c_str());
126                         } else {
127                                 snprintf (buf, sizeof(buf), "%s-R.wav", base.c_str());
128                         }
129                 } else if (channels > 1) {
130                         snprintf (buf, sizeof(buf), "%s-c%d.%s", base.c_str(), channel, ext);
131                 } else {
132                         snprintf (buf, sizeof(buf), "%s.%s", base.c_str(), ext);
133                 }
134                 
135
136                 string tempname = destdir + "/" + buf;
137                 if (!allow_replacing && Glib::file_test (tempname, Glib::FILE_TEST_EXISTS)) {
138
139                         /* if the file already exists, we must come up with
140                          *  a new name for it.  for now we just keep appending
141                          *  _ to basename
142                          */
143
144                         base += "_";
145
146                 } else {
147
148                         goodfile = true;
149                 }
150
151         } while ( !goodfile);
152
153         return buf;
154 }
155
156 static vector<string>
157 get_paths_for_new_sources (const bool allow_replacing, const string& import_file_path, const string& session_dir, uint channels)
158 {
159         vector<string> new_paths;
160         const string basename = basename_nosuffix (import_file_path);
161
162         SessionDirectory sdir(session_dir);
163
164         for (uint n = 0; n < channels; ++n) {
165
166                 const DataType type = (import_file_path.rfind(".mid") != string::npos)
167                                 ? DataType::MIDI : DataType::AUDIO;
168
169                 std::string filepath = (type == DataType::MIDI)
170                                 ? sdir.midi_path().to_string() : sdir.sound_path().to_string();
171
172                 filepath += '/';
173                 filepath += get_non_existent_filename (type, allow_replacing, filepath, basename, n, channels); 
174
175                 cout << "NEW SOURCE PATH: " << filepath << endl;
176
177                 new_paths.push_back (filepath);
178         }
179
180         return new_paths;
181 }
182
183 static bool
184 map_existing_mono_sources (const vector<string>& new_paths, Session& sess,
185                            uint samplerate, vector<boost::shared_ptr<Source> >& newfiles, Session *session)
186 {
187         for (vector<string>::const_iterator i = new_paths.begin();
188                         i != new_paths.end(); ++i)
189         {
190                 boost::shared_ptr<Source> source = session->source_by_path_and_channel(*i, 0);
191
192                 if (source == 0) {
193                         error << string_compose(_("Could not find a source for %1 even though we are updating this file!"), (*i)) << endl;
194                         return false;
195                 }
196
197                 newfiles.push_back(boost::dynamic_pointer_cast<Source>(source));
198         }
199         return true;
200 }
201
202 static bool
203 create_mono_sources_for_writing (const vector<string>& new_paths, Session& sess,
204                 uint samplerate, vector<boost::shared_ptr<Source> >& newfiles)
205 {
206         for (vector<string>::const_iterator i = new_paths.begin();
207                         i != new_paths.end(); ++i)
208         {
209                 boost::shared_ptr<Source> source;
210
211                 try
212                 {
213                         const DataType type = ((*i).rfind(".mid") != string::npos)
214                                 ? DataType::MIDI : DataType::AUDIO;
215                                 
216                         source = SourceFactory::createWritable (
217                                         type,
218                                         sess,
219                                         i->c_str(),
220                                         false, // destructive
221                                         samplerate
222                                         );
223                 }
224                 catch (const failed_constructor& err)
225                 {
226                         error << string_compose (_("Unable to create file %1 during import"), *i) << endmsg;
227                         return false;
228                 }
229
230                 newfiles.push_back(boost::dynamic_pointer_cast<Source>(source));
231         }
232         return true;
233 }
234
235 static Glib::ustring
236 compose_status_message (const string& path,
237                         uint file_samplerate,
238                         uint session_samplerate,
239                         uint current_file,
240                         uint total_files)
241 {
242         if (file_samplerate != session_samplerate) {
243                 return string_compose (_("converting %1\n(resample from %2KHz to %3KHz)\n(%4 of %5)"),
244                                        Glib::path_get_basename (path),
245                                        file_samplerate/1000.0f,
246                                        session_samplerate/1000.0f,
247                                        current_file, total_files);
248         }
249
250         return  string_compose (_("converting %1\n(%2 of %3)"), 
251                                 Glib::path_get_basename (path),
252                                 current_file, total_files);
253 }
254
255 static void
256 write_audio_data_to_new_files (ImportableSource* source, Session::import_status& status,
257                                vector<boost::shared_ptr<Source> >& newfiles)
258 {
259         const nframes_t nframes = ResampledImportableSource::blocksize;
260         boost::shared_ptr<AudioFileSource> afs;
261         uint channels = source->channels();
262
263         boost::scoped_array<float> data(new float[nframes * channels]);
264         vector<boost::shared_array<Sample> > channel_data;
265
266         for (uint n = 0; n < channels; ++n) {
267                 channel_data.push_back(boost::shared_array<Sample>(new Sample[nframes]));
268         }
269         
270         uint read_count = 0;
271         status.progress = 0.0f;
272
273         while (!status.cancel) {
274
275                 nframes_t nread, nfread;
276                 uint x;
277                 uint chn;
278
279                 if ((nread = source->read (data.get(), nframes)) == 0) {
280                         break;
281                 }
282                 nfread = nread / channels;
283
284                 /* de-interleave */
285
286                 for (chn = 0; chn < channels; ++chn) {
287
288                         nframes_t n;
289                         for (x = chn, n = 0; n < nfread; x += channels, ++n) {
290                                 channel_data[chn][n] = (Sample) data[x];
291                         }
292                 }
293
294                 /* flush to disk */
295
296                 for (chn = 0; chn < channels; ++chn) {
297                         if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(newfiles[chn])) != 0) {
298                                 afs->write (channel_data[chn].get(), nfread);
299                         }
300                 }
301
302                 read_count += nread;
303                 status.progress = read_count / (source->ratio () * source->length() * channels);
304         }
305 }
306
307 static void
308 write_midi_data_to_new_files (SMFReader* source, Session::import_status& status,
309                                vector<boost::shared_ptr<Source> >& newfiles)
310 {
311         MIDI::Event ev(0.0, 4, NULL, true);
312
313         status.progress = 0.0f;
314
315         try {
316
317         for (unsigned i = 1; i <= source->num_tracks(); ++i) {
318         
319                 boost::shared_ptr<SMFSource> smfs = boost::dynamic_pointer_cast<SMFSource>(newfiles[i-1]);
320                 
321                 source->seek_to_track(i);
322         
323                 uint64_t t       = 0;
324                 uint32_t delta_t = 0;
325                 uint32_t size    = 0;
326                 
327                 while (!status.cancel) {
328
329                         if (source->read_event(4, ev.buffer(), &size, &delta_t) < 0)
330                                 break;
331
332                         t += delta_t;
333                         ev.time() = (double)t / (double)source->ppqn();
334                         ev.size() = size;
335
336                         smfs->append_event_unlocked(Beats, ev);
337                         if (status.progress < 0.99)
338                                 status.progress += 0.01;
339                 }
340                         
341                 nframes_t timeline_position = 0; // FIXME: ?
342
343                 // FIXME: kluuuuudge: assumes tempo never changes after start
344                 const double frames_per_beat = smfs->session().tempo_map().tempo_at(
345                                 timeline_position).frames_per_beat(
346                                         smfs->session().engine().frame_rate(),
347                                         smfs->session().tempo_map().meter_at(timeline_position));
348
349                 smfs->update_length(0, (nframes_t) floor ((t * source->ppqn()) * frames_per_beat));
350
351                 smfs->flush_header();
352                 smfs->flush_footer();
353
354                 if (status.cancel)
355                         break;
356         }
357
358         } catch (...) {
359                 error << "Corrupt MIDI file " << source->filename() << endl;
360         }
361 }
362
363 static void
364 remove_file_source (boost::shared_ptr<Source> source)
365 {
366         ::unlink (source->path().c_str());
367 }
368
369 // This function is still unable to cleanly update an existing source, even though
370 // it is possible to set the import_status flag accordingly. The functinality
371 // is disabled at the GUI until the Source implementations are able to provide
372 // the necessary API.
373 void
374 Session::import_audiofiles (import_status& status)
375 {
376         uint32_t cnt = 1;
377         typedef vector<boost::shared_ptr<Source> > Sources;
378         Sources all_new_sources;
379         boost::shared_ptr<AudioFileSource> afs;
380         uint channels = 0;
381
382         status.sources.clear ();
383         
384         for (vector<Glib::ustring>::iterator p = status.paths.begin();
385                         p != status.paths.end() && !status.cancel;
386                         ++p, ++cnt)
387         {
388
389                 boost::shared_ptr<ImportableSource> source;
390                 std::auto_ptr<SMFReader>        smf_reader;
391                 const DataType type = ((*p).rfind(".mid") != string::npos) ? 
392                         DataType::MIDI : DataType::AUDIO;
393                 
394                 if (type == DataType::AUDIO) {
395                         try {
396                                 source = open_importable_source (*p, frame_rate(), status.quality);
397                                 channels = source->channels();
398                         } catch (const failed_constructor& err) {
399                                 error << string_compose(_("Import: cannot open input sound file \"%1\""), (*p)) << endmsg;
400                                 status.done = status.cancel = true;
401                                 return;
402                         }
403
404                 } else {
405                         try {
406                                 smf_reader = std::auto_ptr<SMFReader>(new SMFReader(*p));
407                                 channels = smf_reader->num_tracks();
408                         } catch (const SMFReader::UnsupportedTime& err) {
409                                 error << _("Import: unsupported MIDI time stamp format") << endmsg;
410                                 status.done = status.cancel = true;
411                                 return;
412                         } catch (...) {
413                                 error << _("Import: error reading MIDI file") << endmsg;
414                                 status.done = status.cancel = true;
415                                 return;
416                         }
417                 }
418
419                 vector<string> new_paths = get_paths_for_new_sources (status.replace_existing_source, *p,
420                                                                       get_best_session_directory_for_new_source (),
421                                                                       channels);
422                 Sources newfiles;
423
424                 if (status.replace_existing_source) {
425                         fatal << "THIS IS NOT IMPLEMENTED YET, IT SHOULD NEVER GET CALLED!!! DYING!" << endl;
426                         status.cancel = !map_existing_mono_sources (new_paths, *this, frame_rate(), newfiles, this);
427                 } else {
428                         status.cancel = !create_mono_sources_for_writing (new_paths, *this, frame_rate(), newfiles);
429                 }
430
431                 // copy on cancel/failure so that any files that were created will be removed below
432                 std::copy (newfiles.begin(), newfiles.end(), std::back_inserter(all_new_sources));
433
434                 if (status.cancel) break;
435
436                 for (Sources::iterator i = newfiles.begin(); i != newfiles.end(); ++i) {
437                         if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(*i)) != 0) {
438                                 afs->prepare_for_peakfile_writes ();
439                         }
440                 }
441
442                 if (source) { // audio
443                         status.doing_what = compose_status_message (*p, source->samplerate(),
444                                                                     frame_rate(), cnt, status.paths.size());
445                         write_audio_data_to_new_files (source.get(), status, newfiles);
446                 } else if (smf_reader.get()) { // midi
447                         status.doing_what = string_compose(_("loading MIDI file %1"), *p);
448                         write_midi_data_to_new_files (smf_reader.get(), status, newfiles);
449                 }
450         }
451
452         if (!status.cancel) {
453                 struct tm* now;
454                 time_t xnow;
455                 time (&xnow);
456                 now = localtime (&xnow);
457                 status.freeze = true;
458
459                 /* flush the final length(s) to the header(s) */
460
461                 for (Sources::iterator x = all_new_sources.begin(); x != all_new_sources.end(); ++x)
462                 {
463                         cout << "NEW SOURCE: " << (*x)->path() << endl;
464
465                         if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(*x)) != 0) {
466                                 afs->update_header(0, *now, xnow);
467                                 afs->done_with_peakfile_writes ();
468                         }
469                         
470                         /* now that there is data there, requeue the file for analysis */
471                         
472                         Analyser::queue_source_for_analysis (boost::static_pointer_cast<Source>(*x), false);
473                 }
474
475                 /* save state so that we don't lose these new Sources */
476
477                 save_state (_name);
478
479                 std::copy (all_new_sources.begin(), all_new_sources.end(),
480                                 std::back_inserter(status.sources));
481         } else {
482                 // this can throw...but it seems very unlikely
483                 std::for_each (all_new_sources.begin(), all_new_sources.end(), remove_file_source);
484         }
485
486         status.done = true;
487 }
488