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