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