852958b79846a917ef595e19c5e9d3879a85ba49
[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 <sys/time.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <algorithm>
26
27 #include <sndfile.h>
28
29 #include "pbd/pthread_utils.h"
30 #include "pbd/basename.h"
31 #include "pbd/shortpath.h"
32 #include "pbd/stateful_diff_command.h"
33
34 #include <gtkmm2ext/choice.h>
35
36 #include "ardour/session.h"
37 #include "ardour/session_directory.h"
38 #include "ardour/audioplaylist.h"
39 #include "ardour/audioregion.h"
40 #include "ardour/audio_diskstream.h"
41 #include "ardour/midi_track.h"
42 #include "ardour/midi_region.h"
43 #include "ardour/utils.h"
44 #include "ardour/audio_track.h"
45 #include "ardour/audioplaylist.h"
46 #include "ardour/audiofilesource.h"
47 #include "ardour/region_factory.h"
48 #include "ardour/source_factory.h"
49 #include "ardour/session.h"
50 #include "ardour/smf_source.h"
51 #include "pbd/memento_command.h"
52
53 #include "ardour_ui.h"
54 #include "editor.h"
55 #include "sfdb_ui.h"
56 #include "editing.h"
57 #include "audio_time_axis.h"
58 #include "midi_time_axis.h"
59 #include "session_import_dialog.h"
60 #include "utils.h"
61 #include "gui_thread.h"
62 #include "interthread_progress_window.h"
63
64 #include "i18n.h"
65
66 using namespace std;
67 using namespace ARDOUR;
68 using namespace PBD;
69 using namespace Gtk;
70 using namespace Gtkmm2ext;
71 using namespace Editing;
72 using std::string;
73
74 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
75
76 void
77 Editor::add_external_audio_action (ImportMode mode_hint)
78 {
79         if (_session == 0) {
80                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
81                 msg.run ();
82                 return;
83         }
84         
85         if (sfbrowser == 0) {
86                 sfbrowser = new SoundFileOmega (*this, _("Add Existing Media"), _session, 0, true, mode_hint);
87         } else {
88                 sfbrowser->set_mode (mode_hint);
89         }
90
91         external_audio_dialog ();
92 }
93
94 void
95 Editor::external_audio_dialog ()
96 {
97         vector<string> paths;
98         uint32_t track_cnt;
99
100         if (_session == 0) {
101                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
102                 msg.run ();
103                 return;
104         }
105
106         track_cnt = 0;
107
108         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
109                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*x);
110
111                 if (!atv) {
112                         continue;
113                 } else if (atv->is_audio_track()) {
114                         track_cnt++;
115                 }
116         }
117
118         if (sfbrowser == 0) {
119                 sfbrowser = new SoundFileOmega (*this, _("Add Existing Media"), _session, track_cnt, true);
120         } else {
121                 sfbrowser->reset (track_cnt);
122         }
123
124         sfbrowser->show_all ();
125
126
127         bool keepRunning;
128
129         do {
130                 keepRunning = false;
131
132                 int response = sfbrowser->run ();
133
134                 switch (response) {
135                         case RESPONSE_APPLY:
136                                 // leave the dialog open
137                                 break;
138
139                         case RESPONSE_OK:
140                                 sfbrowser->hide ();
141                                 break;
142
143                         default:
144                                 // cancel from the browser - we are done
145                                 sfbrowser->hide ();
146                                 return;
147                 }
148
149                 /* lets do it */
150
151                 vector<string> upaths = sfbrowser->get_paths ();
152                 for (vector<string>::iterator x = upaths.begin(); x != upaths.end(); ++x) {
153                         paths.push_back (*x);
154                 }
155                 
156                 ImportPosition pos = sfbrowser->get_position ();
157                 ImportMode mode = sfbrowser->get_mode ();
158                 ImportDisposition chns = sfbrowser->get_channel_disposition ();
159                 framepos_t where;
160
161                 switch (pos) {
162                         case ImportAtEditPoint:
163                                 where = get_preferred_edit_position ();
164                                 break;
165                         case ImportAtTimestamp:
166                                 where = -1;
167                                 break;
168                         case ImportAtPlayhead:
169                                 where = playhead_cursor->current_frame;
170                                 break;
171                         case ImportAtStart:
172                                 where = _session->current_start_frame();
173                                 break;
174                 }
175
176                 SrcQuality quality = sfbrowser->get_src_quality();
177
178
179                 if (sfbrowser->copy_files_btn.get_active()) {
180                         do_import (paths, chns, mode, quality, where);
181                 } else {
182                         do_embed (paths, chns, mode, where);
183                 }
184
185                 if (response == RESPONSE_APPLY) {
186                         sfbrowser->clear_selection ();
187                         keepRunning = true;
188                 }
189
190         } while (keepRunning);
191 }
192
193 void
194 Editor::session_import_dialog ()
195 {
196         SessionImportDialog dialog (_session);
197         ensure_float (dialog);
198         dialog.run ();
199 }
200
201 typedef std::map<PBD::ID,boost::shared_ptr<ARDOUR::Source> > SourceMap;
202
203 /**
204  * Updating is still disabled, see note in libs/ardour/import.cc Session::import_audiofiles()
205  *
206  * all_or_nothing:
207  *   true  = show "Update", "Import" and "Skip"
208  *   false = show "Import", and "Cancel"
209  *
210  * Returns:
211  *     0  To update an existing source of the same name
212  *     1  To import/embed the file normally (make sure the new name will be unique)
213  *     2  If the user wants to skip this file
214  **/
215 int
216 Editor::check_whether_and_how_to_import(string path, bool all_or_nothing)
217 {
218         string wave_name (Glib::path_get_basename(path));
219
220         SourceMap all_sources = _session->get_sources();
221         bool wave_name_exists = false;
222
223         for (SourceMap::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
224                 string tmp (Glib::path_get_basename (i->second->path()));
225                 if (tmp == wave_name) {
226                         wave_name_exists = true;
227                         break;
228                 }
229         }
230
231         int function = 1;
232
233         if (wave_name_exists) {
234                 string message;
235                 if (all_or_nothing) {
236                         // updating is still disabled
237                         //message = string_compose(_("The session already contains a source file named %1. Do you want to update that file (and thus all regions using the file) or import this file as a new file?"),wave_name);
238                         message = string_compose (_("The session already contains a source file named %1.  Do you want to import %1 as a new file, or skip it?"), wave_name);
239                 } else {
240                         message = string_compose (_("The session already contains a source file named %1.  Do you want to import %2 as a new source, or skip it?"), wave_name, wave_name);
241
242                 }
243                 MessageDialog dialog(message, false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true);
244
245                 if (all_or_nothing) {
246                         // disabled
247                         //dialog.add_button("Update", 0);
248                         dialog.add_button("Import", 1);
249                         dialog.add_button("Skip",   2);
250                 } else {
251                         dialog.add_button("Import", 1);
252                         dialog.add_button("Cancel", 2);
253                 }
254
255                 //dialog.add_button("Skip all", 4); // All or rest?
256
257                 dialog.show();
258
259                 function = dialog.run ();
260
261                 dialog.hide();
262         }
263
264         return function;
265 }
266
267 boost::shared_ptr<AudioTrack>
268 Editor::get_nth_selected_audio_track (int nth) const
269 {
270         AudioTimeAxisView* atv;
271         TrackSelection::iterator x;
272
273         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
274
275                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
276
277                 if (!atv) {
278                         continue;
279                 } else if (atv->is_audio_track()) {
280                         --nth;
281                 }
282         }
283
284         if (x == selection->tracks.end()) {
285                 atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.back());
286         } else {
287                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
288         }
289
290         if (!atv || !atv->is_audio_track()) {
291                 return boost::shared_ptr<AudioTrack>();
292         }
293
294         return atv->audio_track();
295 }
296
297 boost::shared_ptr<MidiTrack>
298 Editor::get_nth_selected_midi_track (int nth) const
299 {
300         MidiTimeAxisView* mtv;
301         TrackSelection::iterator x;
302
303         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
304
305                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
306
307                 if (!mtv) {
308                         continue;
309                 } else if (mtv->is_midi_track()) {
310                         --nth;
311                 }
312         }
313
314         if (x == selection->tracks.end()) {
315                 mtv = dynamic_cast<MidiTimeAxisView*>(selection->tracks.back());
316         } else {
317                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
318         }
319
320         if (!mtv || !mtv->is_midi_track()) {
321                 return boost::shared_ptr<MidiTrack>();
322         }
323
324         return mtv->midi_track();
325 }
326
327 void
328 Editor::do_import (vector<string> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, framepos_t& pos)
329 {
330         boost::shared_ptr<Track> track;
331         vector<string> to_import;
332         int nth = 0;
333         bool use_timestamp = (pos == -1);
334
335         current_interthread_info = &import_status;
336         import_status.current = 1;
337         import_status.total = paths.size ();
338         import_status.all_done = false;
339
340         ImportProgressWindow ipw (&import_status, _("Import"), _("Cancel Import"));
341
342         bool ok = true;
343
344         if (chns == Editing::ImportMergeFiles) {
345
346                 /* create 1 region from all paths, add to 1 track,
347                    ignore "track"
348                 */
349
350                 bool cancel = false;
351                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
352                         int check = check_whether_and_how_to_import(*a, false);
353                         if (check == 2) {
354                                 cancel = true;
355                                 break;
356                         }
357                 }
358
359                 if (cancel) {
360                         ok = false;
361                 } else {
362                         ipw.show ();
363                         ok = (import_sndfiles (paths, mode, quality, pos, 1, 1, track, false) == 0);
364                 }
365
366         } else {
367
368                 bool replace = false;
369
370                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
371
372                         const int check = check_whether_and_how_to_import (*a, true);
373                         
374                         switch (check) {
375                         case 2:
376                                 // user said skip
377                                 continue;
378                         case 0:
379                                 fatal << "Updating existing sources should be disabled!" << endmsg;
380                                 /* NOTREACHED*/
381                                 break;
382                         case 1:
383                                 replace = false;
384                                 break;
385                         default:
386                                 fatal << "Illegal return " << check <<  " from check_whether_and_how_to_import()!" << endmsg;
387                                 /* NOTREACHED*/
388                         }
389
390                         /* have to reset this for every file we handle */
391                         
392                         if (use_timestamp) {
393                                 pos = -1;
394                         }
395
396                         ipw.show ();
397                                 
398                         switch (chns) {
399                         case Editing::ImportDistinctFiles:
400                                 
401                                 to_import.clear ();
402                                 to_import.push_back (*a);
403                                 
404                                 if (mode == Editing::ImportToTrack) {
405                                         track = get_nth_selected_audio_track (nth++);
406                                 }
407                         
408                                 ok = (import_sndfiles (to_import, mode, quality, pos, 1, -1, track, replace) == 0);
409                                 break;
410                                 
411                         case Editing::ImportDistinctChannels:
412                                 
413                                 to_import.clear ();
414                                 to_import.push_back (*a);
415                                 
416                                 ok = (import_sndfiles (to_import, mode, quality, pos, -1, -1, track, replace) == 0);
417                                 break;
418                                 
419                         case Editing::ImportSerializeFiles:
420                                 
421                                 to_import.clear ();
422                                 to_import.push_back (*a);
423
424                                 ok = (import_sndfiles (to_import, mode, quality, pos, 1, 1, track, replace) == 0);
425                                 break;
426
427                         case Editing::ImportMergeFiles:
428                                 // Not entered, handled in earlier if() branch
429                                 break;
430                         }
431                 }
432         }
433
434         if (ok) {
435                 _session->save_state ("");
436         }
437
438         import_status.all_done = true;
439 }
440
441 void
442 Editor::do_embed (vector<string> paths, ImportDisposition chns, ImportMode mode, framepos_t& pos)
443 {
444         boost::shared_ptr<Track> track;
445         bool check_sample_rate = true;
446         bool ok = false;
447         vector<string> to_embed;
448         bool multi = paths.size() > 1;
449         int nth = 0;
450
451         switch (chns) {
452         case Editing::ImportDistinctFiles:
453                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
454
455                         to_embed.clear ();
456                         to_embed.push_back (*a);
457
458                         if (mode == Editing::ImportToTrack) {
459                                 track = get_nth_selected_audio_track (nth++);
460                         }
461
462                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, -1, track) < -1) {
463                                 goto out;
464                         }
465                 }
466                 break;
467
468         case Editing::ImportDistinctChannels:
469                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
470
471                         to_embed.clear ();
472                         to_embed.push_back (*a);
473
474                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, -1, -1, track) < -1) {
475                                 goto out;
476                         }
477                 }
478                 break;
479
480         case Editing::ImportMergeFiles:
481                 if (embed_sndfiles (paths, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
482                         goto out;
483                 }
484                 break;
485
486         case Editing::ImportSerializeFiles:
487                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
488
489                         to_embed.clear ();
490                         to_embed.push_back (*a);
491
492                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
493                                 goto out;
494                         }
495                 }
496                 break;
497         }
498
499         ok = true;
500
501   out:
502         if (ok) {
503                 _session->save_state ("");
504         }
505 }
506
507 int
508 Editor::import_sndfiles (vector<string> paths, ImportMode mode, SrcQuality quality, framepos_t& pos,
509                          int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool replace)
510 {
511         /* check for existing wholefile regions of the same name,
512            which can happen when we import foo.wav but end up with foo-L.wav 
513            and foo-R.wav inside the session. this case doesn't trigger
514            source name collisions, so we have to catch it at the region
515            name level.
516         */
517         
518         string region_name = region_name_from_path (paths.front(), true, false);
519         
520         if (RegionFactory::wholefile_region_by_name (region_name)) {
521                 string message = string_compose ( _("You appear to have already imported this file, since a region called %1 already exists.\nDo you really want to import it again?"),
522                                                   region_name);
523                 MessageDialog dialog (message, false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_OK_CANCEL, true);
524                 int ret;
525                 
526                 dialog.show ();
527                 ret = dialog.run ();
528                 dialog.hide ();
529                 
530                 if (ret != RESPONSE_OK) {
531                         return -1;
532                 }
533                 
534                 int l = 0;
535                 
536                 while (RegionFactory::region_by_name (region_name) && ++l < 999) {
537                         region_name = bump_name_once (region_name, '.');
538                 }
539                 
540                 if (l == 999) {
541                         error << string_compose (_("Too many regions already named something like \"%1\""), paths.front()) << endmsg;
542                         return -1;
543                 }
544         }
545
546         import_status.paths = paths;
547         import_status.done = false;
548         import_status.cancel = false;
549         import_status.freeze = false;
550         import_status.quality = quality;
551         import_status.replace_existing_source = replace;
552
553         import_status.mode = mode;
554         import_status.pos = pos;
555         import_status.target_tracks = target_tracks;
556         import_status.target_regions = target_regions;
557         import_status.track = track;
558         import_status.replace = replace;
559         
560         set_canvas_cursor (wait_cursor);
561         gdk_flush ();
562
563         /* start import thread for this spec. this will ultimately call Session::import_audiofiles()
564            which, if successful, will add the files as regions to the region list. its up to us
565            (the GUI) to direct additional steps after that.
566         */
567
568         pthread_create_and_store ("import", &import_status.thread, _import_thread, this);
569         pthread_detach (import_status.thread);
570
571         while (!import_status.done && !import_status.cancel) {
572                 gtk_main_iteration ();
573         }
574
575         import_status.done = true;
576
577         int result = -1;
578
579         if (!import_status.cancel && !import_status.sources.empty()) {
580                 result = add_sources (
581                         import_status.paths,
582                         import_status.sources,
583                         import_status.pos,
584                         import_status.mode,
585                         import_status.target_regions,
586                         import_status.target_tracks,
587                         track, false
588                         );
589
590                 /* update position from results */
591
592                 pos = import_status.pos;
593         }
594
595         set_canvas_cursor (current_canvas_cursor);
596         return result;
597 }
598
599 int
600 Editor::embed_sndfiles (vector<string> paths, bool multifile,
601                         bool& check_sample_rate, ImportMode mode, framepos_t& pos, int target_regions, int target_tracks,
602                         boost::shared_ptr<Track>& track)
603 {
604         boost::shared_ptr<AudioFileSource> source;
605         SourceList sources;
606         string linked_path;
607         SoundFileInfo finfo;
608         int ret = 0;
609         string path_to_use;
610
611         set_canvas_cursor (wait_cursor);
612         gdk_flush ();
613
614         for (vector<string>::iterator p = paths.begin(); p != paths.end(); ++p) {
615
616                 string path = *p;
617
618                 if (Config->get_try_link_for_embed()) {
619
620                         /* lets see if we can link it into the session */
621                         
622                         sys::path tmp = _session->session_directory().sound_path() / Glib::path_get_basename(path);
623                         linked_path = tmp.to_string();
624                         
625                         path_to_use = linked_path;
626                         
627                         if (link (path.c_str(), linked_path.c_str()) == 0) {
628                                 
629                                 /* there are many reasons why link(2) might have failed.
630                                    but if it succeeds, we now have a link in the
631                                    session sound dir that will protect against
632                                    unlinking of the original path. nice.
633                                 */
634                                 
635                                 path = linked_path;
636                                 path_to_use = Glib::path_get_basename (path);
637                                 
638                         } else {
639
640                                 /* one possible reason is that its already linked */
641                                 
642                                 if (errno == EEXIST) {
643                                         struct stat sb;
644                                         
645                                         if (stat (linked_path.c_str(), &sb) == 0) {
646                                                 if (sb.st_nlink > 1) { // its a hard link, assume its the one we want
647                                                         path = linked_path;
648                                                         path_to_use = Glib::path_get_basename (path);
649                                                 }
650                                         }
651                                 }
652                         }
653                 }
654
655                 /* note that we temporarily truncated _id at the colon */
656
657                 string error_msg;
658
659                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
660                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
661                         goto out;
662                 }
663
664                 if (check_sample_rate  && (finfo.samplerate != (int) _session->frame_rate())) {
665                         vector<string> choices;
666
667                         if (multifile) {
668                                 choices.push_back (_("Cancel entire import"));
669                                 choices.push_back (_("Don't embed it"));
670                                 choices.push_back (_("Embed all without questions"));
671
672                                 Gtkmm2ext::Choice rate_choice (
673                                         _("Sample rate"),
674                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"),
675                                                         short_path (path, 40)),
676                                         choices, false
677                                         );
678
679                                 int resx = rate_choice.run ();
680
681                                 switch (resx) {
682                                 case 0: /* stop a multi-file import */
683                                         ret = -2;
684                                         goto out;
685                                 case 1: /* don't embed this one */
686                                         ret = -1;
687                                         goto out;
688                                 case 2: /* do it, and the rest without asking */
689                                         check_sample_rate = false;
690                                         break;
691                                 case 3: /* do it */
692                                         break;
693                                 default:
694                                         ret = -2;
695                                         goto out;
696                                 }
697                         } else {
698                                 choices.push_back (_("Cancel"));
699                                 choices.push_back (_("Embed it anyway"));
700
701                                 Gtkmm2ext::Choice rate_choice (
702                                         _("Sample rate"),
703                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
704                                         choices, false
705                                         );
706
707                                 int resx = rate_choice.run ();
708
709                                 switch (resx) {
710                                 case 0: /* don't import */
711                                         ret = -1;
712                                         goto out;
713                                 case 1: /* do it */
714                                         break;
715                                 default:
716                                         ret = -2;
717                                         goto out;
718                                 }
719                         }
720                 }
721
722                 set_canvas_cursor (wait_cursor);
723
724                 for (int n = 0; n < finfo.channels; ++n) {
725                         try {
726
727                                 /* check if we have this thing embedded already */
728
729                                 boost::shared_ptr<Source> s;
730
731                                 if ((s = _session->source_by_path_and_channel (path, n)) == 0) {
732
733                                         source = boost::dynamic_pointer_cast<AudioFileSource> (
734                                                 SourceFactory::createReadable (DataType::AUDIO, *_session,
735                                                                                path_to_use, n,
736                                                                                (mode == ImportAsTapeTrack
737                                                                                 ? Source::Destructive
738                                                                                 : Source::Flag (0)),
739                                                                         true, true));
740                                 } else {
741                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
742                                 }
743
744                                 sources.push_back(source);
745                         }
746
747                         catch (failed_constructor& err) {
748                                 error << string_compose(_("could not open %1"), path) << endmsg;
749                                 goto out;
750                         }
751
752                         ARDOUR_UI::instance()->flush_pending ();
753                 }
754         }
755
756         if (sources.empty()) {
757                 goto out;
758         }
759
760         ret = add_sources (paths, sources, pos, mode, target_regions, target_tracks, track, true);
761
762   out:
763         set_canvas_cursor (current_canvas_cursor);
764         return ret;
765 }
766
767 int
768 Editor::add_sources (vector<string> paths, SourceList& sources, framepos_t& pos, ImportMode mode,
769                      int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool /*add_channel_suffix*/)
770 {
771         vector<boost::shared_ptr<Region> > regions;
772         string region_name;
773         uint32_t input_chan = 0;
774         uint32_t output_chan = 0;
775         bool use_timestamp;
776
777         use_timestamp = (pos == -1);
778
779         // kludge (for MIDI we're abusing "channel" for "track" here)
780         if (SMFSource::safe_midi_file_extension (paths.front())) {
781                 target_regions = -1;
782         }
783
784         if (target_regions == 1) {
785
786                 /* take all the sources we have and package them up as a region */
787
788                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
789
790                 /* we checked in import_sndfiles() that there were not too many */
791
792                 while (RegionFactory::region_by_name (region_name)) {
793                         region_name = bump_name_once (region_name, '.');
794                 }
795
796                 PropertyList plist; 
797                 
798                 plist.add (ARDOUR::Properties::start, 0);
799                 plist.add (ARDOUR::Properties::length, sources[0]->length (pos));
800                 plist.add (ARDOUR::Properties::name, region_name);
801                 plist.add (ARDOUR::Properties::layer, 0);
802                 plist.add (ARDOUR::Properties::whole_file, true);
803                 plist.add (ARDOUR::Properties::external, true);
804
805                 boost::shared_ptr<Region> r = RegionFactory::create (sources, plist);
806
807                 if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
808                         boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position(sources[0]->natural_position());
809                 }
810
811                 regions.push_back (r);
812
813
814         } else if (target_regions == -1 || target_regions > 1) {
815
816                 /* take each source and create a region for each one */
817
818                 SourceList just_one;
819                 SourceList::iterator x;
820                 uint32_t n;
821
822                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
823
824                         just_one.clear ();
825                         just_one.push_back (*x);
826
827                         region_name = region_name_from_path ((*x)->path(), false, false, sources.size(), n);
828
829                         PropertyList plist; 
830                         
831                         plist.add (ARDOUR::Properties::start, 0);
832                         plist.add (ARDOUR::Properties::length, (*x)->length (pos));
833                         plist.add (ARDOUR::Properties::name, region_name);
834                         plist.add (ARDOUR::Properties::layer, 0);
835                         plist.add (ARDOUR::Properties::whole_file, true);
836                         plist.add (ARDOUR::Properties::external, true);
837
838                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
839
840                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
841                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
842                         }
843
844                         regions.push_back (r);
845                 }
846         }
847
848         if (target_regions == 1) {
849                 input_chan = regions.front()->n_channels();
850         } else {
851                 if (target_tracks == 1) {
852                         input_chan = regions.size();
853                 } else {
854                         input_chan = 1;
855                 }
856         }
857
858         if (Config->get_output_auto_connect() & AutoConnectMaster) {
859                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
860         } else {
861                 output_chan = input_chan;
862         }
863
864         int n = 0;
865         framepos_t rlen = 0;
866
867         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
868                 
869                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*r);
870                 
871                 if (use_timestamp && ar) {
872                         
873                         /* get timestamp for this region */
874
875                         const boost::shared_ptr<Source> s (ar->sources().front());
876                         const boost::shared_ptr<AudioSource> as = boost::dynamic_pointer_cast<AudioSource> (s);
877                         
878                         assert (as);
879                         
880                         if (as->natural_position() != 0) {
881                                 pos = as->natural_position();
882                         } else if (target_tracks == 1) {
883                                 /* hmm, no timestamp available, put it after the previous region
884                                  */
885                                 if (n == 0) {
886                                         pos = get_preferred_edit_position ();
887                                 } else {
888                                         pos += rlen;
889                                 }
890                         } else {
891                                 pos = get_preferred_edit_position ();
892                         }
893                                 
894                 }
895
896                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track);
897
898                 rlen = (*r)->length();
899                 
900                 if (target_tracks != 1) {
901                         track.reset ();
902                 } else { 
903                         if (!use_timestamp || !ar) {
904                                 /* line each one up right after the other */
905                                 pos += (*r)->length();
906                         }
907                 }
908         }
909
910         /* setup peak file building in another thread */
911
912         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
913                 SourceFactory::setup_peakfile (*x, true);
914         }
915
916         return 0;
917 }
918
919 int
920 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, framepos_t& pos,
921                                   ImportMode mode, boost::shared_ptr<Track>& existing_track)
922 {
923         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
924         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
925
926         switch (mode) {
927         case ImportAsRegion:
928                 /* relax, its been done */
929                 break;
930
931         case ImportToTrack:
932         {
933                 if (!existing_track) {
934
935                         if (ar) {
936                                 existing_track = get_nth_selected_audio_track (0);
937                         } else if (mr) {
938                                 existing_track = get_nth_selected_midi_track (0);
939                         }
940
941                         if (!existing_track) {
942                                 return -1;
943                         }
944                 }
945
946                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
947                 boost::shared_ptr<Region> copy (RegionFactory::create (region, region->properties()));
948                 begin_reversible_command (_("insert file"));
949                 playlist->clear_changes ();
950                 playlist->add_region (copy, pos);
951                 _session->add_command (new StatefulDiffCommand (playlist));
952                 commit_reversible_command ();
953                 break;
954         }
955
956         case ImportAsTrack:
957         {
958                 if (!existing_track) {
959                         if (ar) {
960                                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Normal, 0, 1));
961
962                                 if (at.empty()) {
963                                         return -1;
964                                 }
965
966                                 existing_track = at.front();
967                         } else if (mr) {
968                                 list<boost::shared_ptr<MidiTrack> > mt (_session->new_midi_track (Normal, 0, 1));
969
970                                 if (mt.empty()) {
971                                         return -1;
972                                 }
973
974                                 existing_track = mt.front();
975                         }
976                         
977                         existing_track->set_name (region->name());
978                 }
979
980                 boost::shared_ptr<Region> copy (RegionFactory::create (region));
981                 existing_track->playlist()->add_region (copy, pos);
982                 break;
983         }
984
985
986         case ImportAsTapeTrack:
987         {
988                 if (!ar)
989                         return -1;
990
991                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Destructive));
992                 if (!at.empty()) {
993                         boost::shared_ptr<Region> copy (RegionFactory::create (region));
994                         at.front()->set_name (basename_nosuffix (copy->name()));
995                         at.front()->playlist()->add_region (copy, pos);
996                 }
997                 break;
998         }
999         }
1000
1001         return 0;
1002 }
1003
1004 void *
1005 Editor::_import_thread (void *arg)
1006 {
1007         SessionEvent::create_per_thread_pool ("import events", 64);
1008
1009         Editor *ed = (Editor *) arg;
1010         return ed->import_thread ();
1011 }
1012
1013 void *
1014 Editor::import_thread ()
1015 {
1016         _session->import_audiofiles (import_status);
1017         pthread_exit_pbd (0);
1018         /*NOTREACHED*/
1019         return 0;
1020 }