use shared_ptr<> for all region handling
[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     $Id$
19 */
20
21 #include <pbd/pthread_utils.h>
22 #include <pbd/basename.h>
23
24 #include <gtkmm2ext/choice.h>
25
26 #include <ardour/session.h>
27 #include <ardour/audioplaylist.h>
28 #include <ardour/audioregion.h>
29 #include <ardour/audio_diskstream.h>
30 #include <ardour/utils.h>
31 #include <ardour/audio_track.h>
32 #include <ardour/audioplaylist.h>
33 #include <ardour/audiofilesource.h>
34 #include <ardour/region_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
43 #include "i18n.h"
44
45 using namespace std;
46 using namespace ARDOUR;
47 using namespace PBD;
48 using namespace sigc;
49 using namespace Gtk;
50 using namespace Editing;
51
52 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
53
54 void
55 Editor::add_external_audio_action (ImportMode mode)
56 {
57         jack_nframes_t& pos = edit_cursor->current_frame;
58         AudioTrack* track = 0;
59
60         if (!selection->tracks.empty()) {
61                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.front());
62                 if (atv) {
63                         track = atv->audio_track();
64                 }
65         }
66
67         bring_in_external_audio (mode, track, pos, false);
68 }
69
70 void
71 Editor::bring_in_external_audio (ImportMode mode, AudioTrack* track, jack_nframes_t& pos, bool prompt)
72 {
73         if (session == 0) {
74                 MessageDialog msg (0, _("You can't import or embed an audiofile until you have a session loaded."));
75                 msg.run ();
76                 return;
77         }
78
79         SoundFileOmega sfdb (_("Add existing audio to session"), session);
80         sfdb.set_mode (mode);
81
82         switch (sfdb.run()) {
83         case SoundFileOmega::ResponseImport:
84                 do_import (sfdb.get_paths(), sfdb.get_split(), mode, track, pos, prompt);
85                 break;
86                 
87         case SoundFileOmega::ResponseEmbed:
88                 do_embed (sfdb.get_paths(), sfdb.get_split(), mode, track, pos, prompt);
89                 break;
90
91         default:
92                 break;
93         }
94 }
95
96 void
97 Editor::do_import (vector<Glib::ustring> paths, bool split, ImportMode mode, AudioTrack* track, jack_nframes_t& pos, bool prompt)
98 {
99         /* SFDB sets "multichan" to true to indicate "split channels"
100            so reverse the setting to match the way libardour
101            interprets it.
102         */
103         
104         import_status.multichan = !split;
105
106         if (interthread_progress_window == 0) {
107                 build_interthread_progress_window ();
108         }
109         
110         /* for each path that was selected, import it and then potentially create a new track
111            containing the new region as the sole contents.
112         */
113
114         for (vector<Glib::ustring>::iterator i = paths.begin(); i != paths.end(); ++i ) {
115                 import_sndfile (*i, mode, track, pos);
116         }
117
118         interthread_progress_window->hide_all ();
119 }
120
121 void
122 Editor::do_embed (vector<Glib::ustring> paths, bool split, ImportMode mode, AudioTrack* track, jack_nframes_t& pos, bool prompt)
123 {
124         bool multiple_files = paths.size() > 1;
125         bool check_sample_rate = true;
126         vector<Glib::ustring>::iterator i;
127         
128         for (i = paths.begin(); i != paths.end(); ++i) {
129                 int ret = embed_sndfile (*i, split, multiple_files, check_sample_rate, mode, track, pos, prompt);
130
131                 if (ret < -1) {
132                         break;
133                 }
134         }
135
136         if (i == paths.end()) {
137                 session->save_state ("");
138         }
139 }
140
141 int
142 Editor::import_sndfile (Glib::ustring path, ImportMode mode, AudioTrack* track, jack_nframes_t& pos)
143 {
144         interthread_progress_window->set_title (string_compose (_("ardour: importing %1"), path));
145         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
146         interthread_progress_window->show_all ();
147         interthread_progress_bar.set_fraction (0.0f);
148         interthread_cancel_label.set_text (_("Cancel Import"));
149         current_interthread_info = &import_status;
150
151         import_status.pathname = path;
152         import_status.done = false;
153         import_status.cancel = false;
154         import_status.freeze = false;
155         import_status.done = 0.0;
156         
157         interthread_progress_connection = Glib::signal_timeout().connect 
158                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
159         
160         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
161         ARDOUR_UI::instance()->flush_pending ();
162
163         /* start import thread for this path. this will ultimately call Session::import_audiofile()
164            and if successful will add the file as a region to the session region list.
165         */
166         
167         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
168         pthread_detach (import_status.thread);
169         
170         while (!(import_status.done || import_status.cancel)) {
171                 gtk_main_iteration ();
172         }
173         
174         import_status.done = true;
175         interthread_progress_connection.disconnect ();
176         
177         /* import thread finished - see if we should build a new track */
178         
179         if (!import_status.new_regions.empty()) {
180                 boost::shared_ptr<AudioRegion> region (import_status.new_regions.front());
181                 finish_bringing_in_audio (region, region->n_channels(), region->n_channels(), track, pos, mode);
182         }
183
184         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
185         return 0;
186 }
187
188 int
189 Editor::embed_sndfile (Glib::ustring path, bool split, bool multiple_files, bool& check_sample_rate, ImportMode mode, 
190                        AudioTrack* track, jack_nframes_t& pos, bool prompt)
191 {
192         AudioFileSource *source = 0; /* keep g++ quiet */
193         SourceList sources;
194         boost::shared_ptr<AudioRegion> region;
195         string idspec;
196         string linked_path;
197         SoundFileInfo finfo;
198         string region_name;
199         uint32_t input_chan;
200         uint32_t output_chan;
201
202         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
203         ARDOUR_UI::instance()->flush_pending ();
204
205         /* lets see if we can link it into the session */
206         
207         linked_path = session->sound_dir();
208         linked_path += Glib::path_get_basename (path);
209
210         if (link (path.c_str(), linked_path.c_str()) == 0) {
211
212                 /* there are many reasons why link(2) might have failed.
213                    but if it succeeds, we now have a link in the
214                    session sound dir that will protect against
215                    unlinking of the original path. nice.
216                 */
217
218                 path = linked_path;
219         }
220
221         /* note that we temporarily truncated _id at the colon */
222
223         string error_msg;
224
225         if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
226                 error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), selection, error_msg ) << endmsg;
227                 return 0;
228         }
229         
230         if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
231                 vector<string> choices;
232                 
233                 if (multiple_files) {
234                         choices.push_back (_("Cancel entire import"));
235                         choices.push_back (_("Don't embed it"));
236                         choices.push_back (_("Embed all without questions"));
237                 } else {
238                         choices.push_back (_("Cancel"));
239                 }
240
241                 choices.push_back (_("Embed it anyway"));
242                 
243                 Gtkmm2ext::Choice rate_choice (
244                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
245                         choices, false);
246                 
247                 switch (rate_choice.run()) {
248                 case 0: /* stop a multi-file import */
249                 case 1: /* don't import this one */
250                         return -1;
251                 case 2: /* do it, and the rest without asking */
252                         check_sample_rate = false;
253                         break;
254                 case 3: /* do it */
255                         break;
256                 default:
257                         return -2;
258                 }
259         }
260         
261         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
262         ARDOUR_UI::instance()->flush_pending ();
263         
264         /* make the proper number of channels in the region */
265
266         for (int n = 0; n < finfo.channels; ++n)
267         {
268                 idspec = path;
269                 idspec += string_compose(":%1", n);
270                 
271                 try {
272                         source = AudioFileSource::create (idspec.c_str(), (mode == ImportAsTrack ? AudioFileSource::Destructive : AudioFileSource::Flag (0)));
273                         sources.push_back(source);
274                 } 
275                 
276                  catch (failed_constructor& err) {
277                          error << string_compose(_("could not open %1"), path) << endmsg;
278                          goto out;
279                  }
280                 
281                  ARDOUR_UI::instance()->flush_pending ();
282         }
283         
284         if (sources.empty()) {
285                 goto out;
286         }
287         
288         region_name = PBD::basename_nosuffix (path);
289         region_name += "-0";
290         
291         region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
292                                                                                   Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
293         
294         input_chan = finfo.channels;
295         
296         if (session->get_output_auto_connect() & Session::AutoConnectMaster) {
297                 output_chan = (session->master_out() ? session->master_out()->n_inputs() : input_chan);
298         } else {
299                 output_chan = input_chan;
300         }
301         
302         finish_bringing_in_audio (region, input_chan, output_chan, track, pos, mode);
303         
304   out:
305         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
306         return 0;
307 }
308
309 int
310 Editor::finish_bringing_in_audio (boost::shared_ptr<AudioRegion> region, uint32_t in_chans, uint32_t out_chans, AudioTrack* track, jack_nframes_t& pos, ImportMode mode)
311 {
312         switch (mode) {
313         case ImportAsRegion:
314                 /* relax, its been done */
315                 break;
316                 
317         case ImportToTrack:
318                 if (track) {
319                         Playlist* playlist  = track->diskstream()->playlist();
320                         
321                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
322                         begin_reversible_command (_("insert sndfile"));
323                         XMLNode &before = playlist->get_state();
324                         playlist->add_region (copy, pos);
325                         session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
326                         commit_reversible_command ();
327
328                         pos += region->length();
329                 }
330                 break;
331                 
332         case ImportAsTrack:
333         { 
334                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
335                 if (!at.empty()) {
336                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
337                         at.front()->diskstream()->playlist()->add_region (copy, pos);
338                 }
339                 break;
340         }
341
342         case ImportAsTapeTrack:
343         {
344                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
345                 if (!at.empty()) {
346                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
347                         at.front()->diskstream()->playlist()->add_region (copy, pos);
348                 }
349                 break;
350         }
351         }
352
353         return 0;
354 }
355
356 void *
357 Editor::_import_thread (void *arg)
358 {
359         PBD::ThreadCreated (pthread_self(), X_("Import"));
360
361         Editor *ed = (Editor *) arg;
362         return ed->import_thread ();
363 }
364
365 void *
366 Editor::import_thread ()
367 {
368         session->import_audiofile (import_status);
369         pthread_exit_pbd (0);
370         /*NOTREACHED*/
371         return 0;
372 }
373
374 gint
375 Editor::import_progress_timeout (void *arg)
376 {
377         interthread_progress_label.set_text (import_status.doing_what);
378
379         if (import_status.freeze) {
380                 interthread_cancel_button.set_sensitive(false);
381         } else {
382                 interthread_cancel_button.set_sensitive(true);
383         }
384
385         if (import_status.doing_what == "building peak files") {
386                 interthread_progress_bar.pulse ();
387                 return FALSE;
388         } else {
389                 interthread_progress_bar.set_fraction (import_status.progress);
390         }
391
392         return !(import_status.done || import_status.cancel);
393 }
394