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