support for 16 bit native files
[ardour.git] / gtk2_ardour / editor_audio_import.cc
1 /*
2     Copyright (C) 2000-2006 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 <sys/types.h>
21 #include <sys/stat.h>
22 #include <errno.h>
23 #include <unistd.h>
24
25 #include <pbd/pthread_utils.h>
26 #include <pbd/basename.h>
27 #include <pbd/shortpath.h>
28
29 #include <gtkmm2ext/choice.h>
30 #include <gtkmm2ext/window_title.h>
31
32 #include <ardour/session.h>
33 #include <ardour/session_directory.h>
34 #include <ardour/audioplaylist.h>
35 #include <ardour/audioregion.h>
36 #include <ardour/audio_diskstream.h>
37 #include <ardour/utils.h>
38 #include <ardour/audio_track.h>
39 #include <ardour/audioplaylist.h>
40 #include <ardour/audiofilesource.h>
41 #include <ardour/region_factory.h>
42 #include <ardour/source_factory.h>
43 #include <pbd/memento_command.h>
44
45 #include "ardour_ui.h"
46 #include "editor.h"
47 #include "sfdb_ui.h"
48 #include "editing.h"
49 #include "audio_time_axis.h"
50 #include "utils.h"
51
52 #include "i18n.h"
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57 using namespace sigc;
58 using namespace Gtk;
59 using namespace Gtkmm2ext;
60 using namespace Editing;
61 using Glib::ustring;
62
63 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
64
65 void
66 Editor::add_external_audio_action (ImportMode mode)
67 {
68         nframes_t& pos = edit_cursor->current_frame;
69         boost::shared_ptr<AudioTrack> track;
70
71         if (!selection->tracks.empty()) {
72                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.front());
73                 if (atv) {
74                         track = atv->audio_track();
75                 }
76         }
77
78         bring_in_external_audio (mode, track.get(), pos, false);
79 }
80
81 void
82 Editor::bring_in_external_audio (ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
83 {
84         if (session == 0) {
85                 MessageDialog msg (0, _("You can't import or embed an audiofile until you have a session loaded."));
86                 msg.run ();
87                 return;
88         }
89
90         SoundFileOmega sfdb (_("Add existing audio to session"), session);
91         sfdb.set_mode (mode);
92
93         switch (sfdb.run()) {
94         case SoundFileOmega::ResponseImport:
95                 do_import (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
96                 break;
97                 
98         case SoundFileOmega::ResponseEmbed:
99                 do_embed (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
100                 break;
101
102         default:
103                 break;
104         }
105 }
106
107 void
108 Editor::do_import (vector<ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
109 {
110         /* SFDB sets "multichan" to true to indicate "split channels"
111            so reverse the setting to match the way libardour
112            interprets it.
113         */
114         
115         import_status.multichan = !split;
116
117         if (interthread_progress_window == 0) {
118                 build_interthread_progress_window ();
119         }
120
121         vector<ustring> to_import;
122
123         for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
124
125                 to_import.clear ();
126                 to_import.push_back (*a);
127
128                 import_sndfile (to_import, mode, track, pos);
129         }
130
131         interthread_progress_window->hide_all ();
132 }
133
134 void
135 Editor::do_embed (vector<ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
136 {
137         bool multiple_files = paths.size() > 1;
138         bool check_sample_rate = true;
139         vector<ustring>::iterator a;
140
141         for (a = paths.begin(); a != paths.end(); ) {
142
143                 cerr << "Considering embed of " << (*a) << endl;
144         
145                 Glib::ustring path = *a;
146                 Glib::ustring pair_base;
147                 vector<ustring> to_embed;
148
149                 to_embed.push_back (path);
150                 a = paths.erase (a);
151
152                 if (path_is_paired (path, pair_base)) {
153
154                         ustring::size_type len = pair_base.length();
155
156                         for (vector<Glib::ustring>::iterator b = paths.begin(); b != paths.end(); ) {
157
158                                 if (((*b).substr (0, len) == pair_base) && ((*b).length() == path.length())) {
159
160                                         to_embed.push_back (*b);
161                                                 
162                                         /* don't process this one again */
163
164                                         b = paths.erase (b);
165                                         break;
166
167                                 } else {
168                                         ++b;
169                                 }
170                         }
171                 }
172
173                 if (to_embed.size() > 1) {
174
175                         vector<string> choices;
176
177                         choices.push_back (string_compose (_("Import as a %1 region"),
178                                                            to_embed.size() > 2 ? _("multichannel") : _("stereo")));
179                         choices.push_back (_("Import as multiple regions"));
180                         
181                         Choice chooser (string_compose (_("Paired files detected (%1, %2 ...).\nDo you want to:"),
182                                                                    to_embed[0],
183                                                                    to_embed[1]),
184                                                    choices);
185                         
186                         if (chooser.run () == 0) {
187                                 
188                                 /* keep them paired */
189
190                                 if (embed_sndfile (to_embed, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
191                                         break;
192                                 }
193
194                         } else {
195
196                                 /* one thing per file */
197
198                                 vector<ustring> foo;
199
200                                 for (vector<ustring>::iterator x = to_embed.begin(); x != to_embed.end(); ++x) {
201
202                                         foo.clear ();
203                                         foo.push_back (*x);
204
205                                         if (embed_sndfile (foo, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
206                                                 break;
207                                         }
208                                 }
209                         }
210
211                 } else {
212                         
213                         if (embed_sndfile (to_embed, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
214                                 break;
215                         }
216                 }
217         }
218         
219         if (a == paths.end()) {
220                 session->save_state ("");
221         }
222 }
223
224 int
225 Editor::import_sndfile (vector<ustring> paths, ImportMode mode, AudioTrack* track, nframes_t& pos)
226 {
227         WindowTitle title = string_compose (_("importing %1"), paths.front());
228
229         interthread_progress_window->set_title (title.get_string());
230         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
231         interthread_progress_window->show_all ();
232         interthread_progress_bar.set_fraction (0.0f);
233         interthread_cancel_label.set_text (_("Cancel Import"));
234         current_interthread_info = &import_status;
235
236         import_status.paths = paths;
237         import_status.done = false;
238         import_status.cancel = false;
239         import_status.freeze = false;
240         import_status.done = 0.0;
241         
242         interthread_progress_connection = Glib::signal_timeout().connect 
243                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
244         
245         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
246         ARDOUR_UI::instance()->flush_pending ();
247
248         /* start import thread for this spec. this will ultimately call Session::import_audiofile()
249            and if successful will add the file(s) as a region to the session region list.
250         */
251         
252         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
253         pthread_detach (import_status.thread);
254         
255         while (!(import_status.done || import_status.cancel)) {
256                 gtk_main_iteration ();
257         }
258
259         interthread_progress_window->hide ();
260         
261         import_status.done = true;
262         interthread_progress_connection.disconnect ();
263         
264         /* import thread finished - see if we should build a new track */
265         
266         if (!import_status.new_regions.empty()) {
267                 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion>(import_status.new_regions.front());
268                 finish_bringing_in_audio (region, region->n_channels(), region->n_channels(), track, pos, mode);
269         }
270
271         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
272         return 0;
273 }
274
275 int
276 Editor::embed_sndfile (vector<Glib::ustring> paths, bool split, bool multiple_files, bool& check_sample_rate, ImportMode mode, 
277                        AudioTrack* track, nframes_t& pos, bool prompt)
278 {
279         boost::shared_ptr<AudioFileSource> source;
280         SourceList sources;
281         boost::shared_ptr<AudioRegion> region;
282         string linked_path;
283         SoundFileInfo finfo;
284         ustring region_name;
285         uint32_t input_chan = 0;
286         uint32_t output_chan = 0;
287         int ret = 0;
288
289         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
290         ARDOUR_UI::instance()->flush_pending ();
291
292         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
293
294                 ustring path = *p;
295
296                 /* lets see if we can link it into the session */
297
298                 sys::path tmp = session->session_directory().sound_path();
299
300                 tmp /= Glib::path_get_basename(path);
301                 linked_path = tmp.to_string();
302                 
303                 if (link (path.c_str(), linked_path.c_str()) == 0) {
304
305                         /* there are many reasons why link(2) might have failed.
306                            but if it succeeds, we now have a link in the
307                            session sound dir that will protect against
308                            unlinking of the original path. nice.
309                         */
310                         
311                         path = linked_path;
312
313                 } else {
314
315                         /* one possible reason is that its already linked */
316
317                         if (errno == EEXIST) {
318                                 struct stat sb;
319
320                                 if (stat (linked_path.c_str(), &sb) == 0) {
321                                         if (sb.st_nlink > 1) { // its a hard link, assume its the one we want
322                                                 path = linked_path;
323                                         }
324                                 }
325                         }
326
327                 }
328                 
329                 /* note that we temporarily truncated _id at the colon */
330                 
331                 string error_msg;
332                 
333                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
334                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), selection, error_msg ) << endmsg;
335                         goto out;
336                 }
337                 
338                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
339                         vector<string> choices;
340                         
341                         if (multiple_files) {
342                                 choices.push_back (_("Cancel entire import"));
343                                 choices.push_back (_("Don't embed it"));
344                                 choices.push_back (_("Embed all without questions"));
345                         
346                                 Gtkmm2ext::Choice rate_choice (
347                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), 
348                                                         short_path (path, 40)),
349                                         choices, false);
350                                 
351                                 int resx = rate_choice.run ();
352                                 
353                                 switch (resx) {
354                                 case 0: /* stop a multi-file import */
355                                         ret = -2;
356                                         goto out;
357                                 case 1: /* don't embed this one */
358                                         ret = -1;
359                                         goto out;
360                                 case 2: /* do it, and the rest without asking */
361                                         check_sample_rate = false;
362                                         break;
363                                 case 3: /* do it */
364                                         break;
365                                 default:
366                                         ret = -2;
367                                         goto out;
368                                 }
369                         } else {
370                                 choices.push_back (_("Cancel"));
371                                 choices.push_back (_("Embed it anyway"));
372                         
373                                 Gtkmm2ext::Choice rate_choice (
374                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
375                                         choices, false);
376                                 
377                                 int resx = rate_choice.run ();
378                                 
379                                 switch (resx) {
380                                 case 0: /* don't import */
381                                         ret = -1;
382                                         goto out;
383                                 case 1: /* do it */
384                                         break;
385                                 default:
386                                         ret = -2;
387                                         goto out;
388                                 }
389                         }
390                 }
391                 
392                 track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
393                 ARDOUR_UI::instance()->flush_pending ();
394         
395                 /* make the proper number of channels in the region */
396                 
397                 input_chan += finfo.channels;
398
399                 for (int n = 0; n < finfo.channels; ++n)
400                 {
401                         try {
402
403                                 /* check if we have this thing embedded already */
404
405                                 boost::shared_ptr<Source> s;
406
407                                 if ((s = session->source_by_path_and_channel (path, n)) == 0) {
408                                         source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
409                                                                                                (DataType::AUDIO, *session, path,  n,
410                                                                                                 (mode == ImportAsTapeTrack ? 
411                                                                                                  AudioFileSource::Destructive : 
412                                                                                                  AudioFileSource::Flag (0))));
413                                 } else {
414                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
415                                 }
416
417                                 sources.push_back(source);
418                         } 
419                         
420                         catch (failed_constructor& err) {
421                                 error << string_compose(_("could not open %1"), path) << endmsg;
422                                 goto out;
423                         }
424                         
425                         ARDOUR_UI::instance()->flush_pending ();
426                 }
427         }
428
429         if (sources.empty()) {
430                 goto out;
431         }
432
433         if (sources[0]->natural_position() != 0) {
434                 pos = sources[0]->natural_position();
435         } 
436
437         region_name = region_name_from_path (paths.front(), (sources.size() > 1));
438         
439         region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
440                                                                                   Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
441
442         if (Config->get_output_auto_connect() & AutoConnectMaster) {
443                 output_chan = (session->master_out() ? session->master_out()->n_inputs().n_audio() : input_chan);
444         } else {
445                 output_chan = input_chan;
446         }
447
448         finish_bringing_in_audio (region, input_chan, output_chan, track, pos, mode);
449         
450   out:
451         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
452         return ret;
453 }
454
455 int
456 Editor::finish_bringing_in_audio (boost::shared_ptr<AudioRegion> region, uint32_t in_chans, uint32_t out_chans, AudioTrack* track, nframes_t& pos, ImportMode mode)
457 {
458         switch (mode) {
459         case ImportAsRegion:
460                 /* relax, its been done */
461                 break;
462                 
463         case ImportToTrack:
464                 if (track) {
465                         boost::shared_ptr<Playlist> playlist = track->diskstream()->playlist();
466                         
467                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
468                         begin_reversible_command (_("insert sndfile"));
469                         XMLNode &before = playlist->get_state();
470                         playlist->add_region (copy, pos);
471                         session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
472                         commit_reversible_command ();
473
474                         pos += region->length();
475                 }
476                 break;
477                 
478         case ImportAsTrack:
479         { 
480                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
481                 if (!at.empty()) {
482                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
483                         at.front()->diskstream()->playlist()->add_region (copy, pos);
484                         at.front()->set_name(short_path(copy->name(), 32));
485                 }
486                 break;
487         }
488
489         case ImportAsTapeTrack:
490         {
491                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
492                 if (!at.empty()) {
493                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
494                         at.front()->diskstream()->playlist()->add_region (copy, pos);
495                         at.front()->set_name(short_path(copy->name(), 32));
496                 }
497                 break;
498         }
499         }
500
501         return 0;
502 }
503
504 void *
505 Editor::_import_thread (void *arg)
506 {
507         PBD::ThreadCreated (pthread_self(), X_("Import"));
508
509         Editor *ed = (Editor *) arg;
510         return ed->import_thread ();
511 }
512
513 void *
514 Editor::import_thread ()
515 {
516         session->import_audiofile (import_status);
517         pthread_exit_pbd (0);
518         /*NOTREACHED*/
519         return 0;
520 }
521
522 gint
523 Editor::import_progress_timeout (void *arg)
524 {
525         interthread_progress_label.set_text (import_status.doing_what);
526
527         if (import_status.freeze) {
528                 interthread_cancel_button.set_sensitive(false);
529         } else {
530                 interthread_cancel_button.set_sensitive(true);
531         }
532
533         if (import_status.doing_what == "building peak files") {
534                 interthread_progress_bar.pulse ();
535                 return FALSE;
536         } else {
537                 interthread_progress_bar.set_fraction (import_status.progress);
538         }
539
540         return !(import_status.done || import_status.cancel);
541 }
542