fixes for destructive track offsets of various kinds; move from jack_nframes_t -...
[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     $Id$
19 */
20
21 #include <cstdio>
22 #include <cstdlib>
23 #include <string>
24 #include <climits>
25 #include <cerrno>
26 #include <unistd.h>
27 #include <sys/stat.h>
28 #include <time.h>
29
30 #include <sndfile.h>
31 #include <samplerate.h>
32
33 #include <glibmm.h>
34
35 #include <pbd/basename.h>
36
37 #include <ardour/ardour.h>
38 #include <ardour/session.h>
39 #include <ardour/audio_diskstream.h>
40 #include <ardour/sndfilesource.h>
41 #include <ardour/sndfile_helpers.h>
42 #include <ardour/audioregion.h>
43 #include <ardour/region_factory.h>
44 #include <ardour/source_factory.h>
45
46
47 #include "i18n.h"
48
49 using namespace ARDOUR;
50 using namespace PBD;
51
52 #define BLOCKSIZE 4096U
53
54 int
55 Session::import_audiofile (import_status& status)
56 {
57         SNDFILE *in;
58         vector<boost::shared_ptr<AudioFileSource> > newfiles;
59         SourceList sources;
60         SF_INFO info;
61         float *data = 0;
62         Sample **channel_data = 0;
63         long nfiles = 0;
64         long n;
65         string basepath;
66         string sounds_dir;
67         nframes_t so_far;
68         char buf[PATH_MAX+1];
69         int ret = -1;
70         vector<string> new_paths;
71         struct tm* now;
72         string tmp_convert_file;
73         
74         status.new_regions.clear ();
75
76         if ((in = sf_open (status.pathname.c_str(), SFM_READ, &info)) == 0) {
77                 error << string_compose(_("Import: cannot open input sound file \"%1\""), status.pathname) << endmsg;
78                 return -1;
79         } else {
80                 if ((uint32_t) info.samplerate != frame_rate()) {
81                         sf_close(in);
82                         status.doing_what = _("resampling audio");
83                         // resample to session frame_rate
84                         if (sample_rate_convert(status, status.pathname, tmp_convert_file)) {
85                                 if ((in = sf_open (tmp_convert_file.c_str(), SFM_READ, &info)) == 0) {
86                                         error << string_compose(_("Import: cannot open converted sound file \"%1\""), tmp_convert_file) << endmsg;
87                                         return -1;
88                                 }
89                         } else if (!status.cancel){
90                                 // error
91                                 error << string_compose(_("Import: error while resampling sound file \"%1\""), status.pathname) << endmsg;
92                                 return -1;
93                         } else {
94                                 // canceled
95                                 goto out;
96                         }
97                 }
98         }
99
100         for (n = 0; n < info.channels; ++n) {
101                 newfiles.push_back (boost::shared_ptr<AudioFileSource>());
102         }
103
104         sounds_dir = discover_best_sound_dir ();
105         basepath = PBD::basename_nosuffix (status.pathname);
106
107         for (n = 0; n < info.channels; ++n) {
108
109                 bool goodfile = false;
110
111                 do {
112                         if (info.channels == 2) {
113                                 if (n == 0) {
114                                         snprintf (buf, sizeof(buf), "%s%s-L.wav", sounds_dir.c_str(), basepath.c_str());
115                                 } else {
116                                         snprintf (buf, sizeof(buf), "%s%s-R.wav", sounds_dir.c_str(), basepath.c_str());
117                                 }
118                         } else if (info.channels > 1) {
119                                 snprintf (buf, sizeof(buf), "%s%s-c%lu.wav", sounds_dir.c_str(), basepath.c_str(), n+1);
120                         } else {
121                                 snprintf (buf, sizeof(buf), "%s%s.wav", sounds_dir.c_str(), basepath.c_str());
122                         }
123
124                         if (::access (buf, F_OK) == 0) {
125
126                                 /* if the file already exists, we must come up with
127                                  *  a new name for it.  for now we just keep appending
128                                  *  _ to basepath
129                                  */
130                                 
131                                 basepath += "_";
132
133                         } else {
134
135                                 goodfile = true;
136                         }
137
138                 } while ( !goodfile);
139
140                 try { 
141                         newfiles[n] = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, buf, false, frame_rate()));
142                 }
143
144                 catch (failed_constructor& err) {
145                         error << string_compose(_("Session::import_audiofile: cannot open new file source for channel %1"), n+1) << endmsg;
146                         goto out;
147                 }
148
149                 new_paths.push_back (buf);
150                 nfiles++;
151         }
152         
153         
154         data = new float[BLOCKSIZE * info.channels];
155         channel_data = new Sample * [ info.channels ];
156         
157         for (n = 0; n < info.channels; ++n) {
158                 channel_data[n] = new Sample[BLOCKSIZE];
159         }
160
161         so_far = 0;
162
163         status.doing_what = _("converting audio");
164         status.progress = 0.0;
165
166         while (!status.cancel) {
167
168                 long nread;
169                 long x;
170                 long chn;
171
172                 if ((nread = sf_readf_float (in, data, BLOCKSIZE)) == 0) {
173                         break;
174                 }
175
176                 /* de-interleave */
177                                 
178                 for (chn = 0; chn < info.channels; ++chn) {
179                         for (x = chn, n = 0; n < nread; x += info.channels, ++n) {
180                                 channel_data[chn][n] = (Sample) data[x];
181                         }
182                 }
183
184                 /* flush to disk */
185
186                 for (chn = 0; chn < info.channels; ++chn) {
187                         newfiles[chn]->write (channel_data[chn], nread);
188                 }
189
190                 so_far += nread;
191                 status.progress = so_far / (float) (info.frames * info.channels);
192         }
193
194         if (status.multichan) {
195                 status.doing_what = _("building region");
196         } else {
197                 status.doing_what = _("building regions");
198         }
199
200         status.freeze = true;
201
202         time_t xnow;
203         time (&xnow);
204         now = localtime (&xnow);
205
206         if (status.cancel) {
207                 goto out;
208         }
209
210         if (status.multichan) {
211                 /* all sources are used in a single multichannel region */
212                 for (n = 0; n < nfiles && !status.cancel; ++n) {
213                         /* flush the final length to the header */
214                         newfiles[n]->update_header(0, *now, xnow);
215                         sources.push_back(newfiles[n]);
216                 }
217
218                 boost::shared_ptr<AudioRegion> r (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, newfiles[0]->length(), region_name_from_path (Glib::path_get_basename (basepath)),
219                                                                                                                    0, AudioRegion::Flag (AudioRegion::DefaultFlags | AudioRegion::WholeFile))));
220                 
221                 status.new_regions.push_back (r);
222
223         } else {
224                 for (n = 0; n < nfiles && !status.cancel; ++n) {
225
226                         /* flush the final length to the header */
227
228                         newfiles[n]->update_header(0, *now, xnow);
229
230                         /* The sources had zero-length when created, which means that the Session
231                            did not bother to create whole-file AudioRegions for them. Do it now.
232                         */
233                 
234                         status.new_regions.push_back (boost::dynamic_pointer_cast<AudioRegion> 
235                                                       (RegionFactory::create (boost::static_pointer_cast<Source> (newfiles[n]), 0, newfiles[n]->length(), 
236                                                                               region_name_from_path (Glib::path_get_basename (newfiles[n]->name())),
237                                                                               0, AudioRegion::Flag (AudioRegion::DefaultFlags | AudioRegion::WholeFile | AudioRegion::Import))));
238                 }
239         }
240         
241         /* save state so that we don't lose these new Sources */
242
243         if (!status.cancel) {
244                 save_state (_name);
245         }
246
247         ret = 0;
248
249   out:
250
251         if (data) {
252                 delete [] data;
253         }
254         
255         if (channel_data) {
256                 for (n = 0; n < info.channels; ++n) {
257                         delete [] channel_data[n];
258                 }
259                 delete [] channel_data;
260         }
261
262         if (status.cancel) {
263
264                 status.new_regions.clear ();
265
266                 for (vector<string>::iterator i = new_paths.begin(); i != new_paths.end(); ++i) {
267                         unlink ((*i).c_str());
268                 }
269         }
270
271         if (tmp_convert_file.length()) {
272                 unlink(tmp_convert_file.c_str());
273         }
274         
275         sf_close (in);
276         status.done = true;
277         return ret;
278 }
279
280 string
281 Session::build_tmp_convert_name(string infile)
282 {
283         string tmp_name(_path + "/." + Glib::path_get_basename (infile.c_str()) + "XXXXXX");
284         char* tmp = new char[tmp_name.length() + 1];
285         tmp_name.copy(tmp, string::npos);
286         tmp[tmp_name.length()] = 0;
287         mkstemp(tmp);
288         string outfile = tmp;
289         delete [] tmp;
290         
291         return outfile;
292 }
293
294 bool
295 Session::sample_rate_convert (import_status& status, string infile, string& outfile)
296 {       
297         float input [BLOCKSIZE] ;
298         float output [BLOCKSIZE] ;
299
300         SF_INFO         sf_info;
301         SRC_STATE*      src_state ;
302         SRC_DATA        src_data ;
303         int                     err ;
304         sf_count_t      output_count = 0 ;
305         sf_count_t  input_count = 0;
306
307         SNDFILE* in = sf_open(infile.c_str(), SFM_READ, &sf_info);
308         if (!in) {
309                 error << string_compose(_("Import/SRC: could not open input file: %1"), outfile) << endmsg;
310                 return false;
311         }
312         sf_count_t total_input_frames = sf_info.frames;
313         
314         outfile = build_tmp_convert_name(infile);
315         SNDFILE* out = sf_open(outfile.c_str(), SFM_RDWR, &sf_info);
316         if (!out) {
317                 error << string_compose(_("Import/SRC: could not open output file: %1"), outfile) << endmsg;
318                 return false;
319         }
320         
321         sf_seek (in, 0, SEEK_SET) ;
322         sf_seek (out, 0, SEEK_SET) ;
323
324         /* Initialize the sample rate converter. */
325         if ((src_state = src_new (SRC_SINC_BEST_QUALITY, sf_info.channels, &err)) == 0) {       
326                 error << string_compose(_("Import: src_new() failed : %1"), src_strerror (err)) << endmsg ;
327                 return false ;
328         }
329
330         src_data.end_of_input = 0 ; /* Set this later. */
331
332         /* Start with zero to force load in while loop. */
333         src_data.input_frames = 0 ;
334         src_data.data_in = input ;
335
336         src_data.src_ratio = (1.0 * frame_rate()) / sf_info.samplerate ;
337
338         src_data.data_out = output ;
339         src_data.output_frames = BLOCKSIZE / sf_info.channels ;
340
341         while (!status.cancel) {
342                 /* If the input buffer is empty, refill it. */
343                 if (src_data.input_frames == 0) {       
344                         src_data.input_frames = sf_readf_float (in, input, BLOCKSIZE / sf_info.channels) ;
345                         src_data.data_in = input ;
346
347                         /* The last read will not be a full buffer, so snd_of_input. */
348                         if (src_data.input_frames < (int)BLOCKSIZE / sf_info.channels) {
349                                 src_data.end_of_input = SF_TRUE ;
350                         }
351                 } 
352
353                 if ((err = src_process (src_state, &src_data))) {
354                         error << string_compose(_("Import: %1"), src_strerror (err)) << endmsg ;
355                         return false ;
356                 } 
357
358                 /* Terminate if at end */
359                 if (src_data.end_of_input && src_data.output_frames_gen == 0) {
360                         break ;
361                 }
362
363                 /* Write output. */
364                 sf_writef_float (out, output, src_data.output_frames_gen) ;
365                 output_count += src_data.output_frames_gen ;
366                 input_count += src_data.input_frames_used;
367
368                 src_data.data_in += src_data.input_frames_used * sf_info.channels ;
369                 src_data.input_frames -= src_data.input_frames_used ;
370                 
371                 status.progress = (float) input_count / total_input_frames;
372         }
373
374         src_state = src_delete (src_state) ;
375         sf_close(in);
376         sf_close(out);
377
378         if (status.cancel) {
379                 return false;
380         } else {
381                 return true ;
382         }
383 }