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