add an example script to show/hide TAVs
[ardour.git] / gtk2_ardour / editor_pt_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 "pbd/pthread_utils.h"
28 #include "pbd/basename.h"
29 #include "pbd/shortpath.h"
30 #include "pbd/stateful_diff_command.h"
31
32 #include <gtkmm2ext/choice.h>
33
34 #include "ardour/audio_track.h"
35 #include "ardour/audiofilesource.h"
36 #include "ardour/audioregion.h"
37 #include "ardour/midi_region.h"
38 #include "ardour/midi_track.h"
39 #include "ardour/midi_model.h"
40 #include "ardour/operations.h"
41 #include "ardour/region_factory.h"
42 #include "ardour/smf_source.h"
43 #include "ardour/source_factory.h"
44 #include "ardour/utils.h"
45 #include "ardour/playlist.h"
46 #include "ardour/session.h"
47 #include "pbd/memento_command.h"
48
49 #include "ptformat/ptfformat.h"
50
51 #include "ardour_ui.h"
52 #include "cursor_context.h"
53 #include "editor.h"
54 #include "sfdb_ui.h"
55 #include "editing.h"
56 #include "audio_time_axis.h"
57 #include "midi_time_axis.h"
58 #include "session_import_dialog.h"
59 #include "gui_thread.h"
60 #include "interthread_progress_window.h"
61 #include "mouse_cursors.h"
62 #include "editor_cursors.h"
63
64 #include "pbd/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 PT sessions into ardour */
75
76 void
77 Editor::external_pt_dialog ()
78 {
79         std::string ptpath;
80
81         if (_session == 0) {
82                 MessageDialog msg (_("You can't import a PT session until you have a session loaded."));
83                 msg.run ();
84                 return;
85         }
86
87         Gtk::FileChooserDialog dialog(_("Import PT Session"), FILE_CHOOSER_ACTION_OPEN);
88         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
89         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
90
91         while (true) {
92                 int result = dialog.run();
93
94                 if (result == Gtk::RESPONSE_OK) {
95                         ptpath = dialog.get_filename ();
96
97                         if (!Glib::file_test (ptpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
98                                 Gtk::MessageDialog msg (string_compose (_("%1: this is only the directory/folder name, not the filename.\n"), ptpath));
99                                 msg.run ();
100                                 continue;
101                         }
102                 }
103
104                 if (ptpath.length()) {
105                         do_ptimport(ptpath, SrcBest);
106                         break;
107                 }
108
109                 if (result == Gtk::RESPONSE_CANCEL) {
110                         break;
111                 }
112         }
113 }
114
115 void
116 Editor::do_ptimport (std::string ptpath,
117                       SrcQuality  quality)
118 {
119         vector<boost::shared_ptr<Region> > regions;
120         boost::shared_ptr<ARDOUR::Track> track;
121         ARDOUR::PluginInfoPtr instrument;
122         vector<string> to_import;
123         string fullpath;
124         bool ok = false;
125         bool onefailed = false;
126         PTFFormat ptf;
127         framepos_t pos = -1;
128
129         vector<ptflookup_t> ptfwavpair;
130         vector<ptflookup_t> ptfregpair;
131
132         if (ptf.load(ptpath, _session->frame_rate()) == -1) {
133                 MessageDialog msg (_("Doesn't seem to be a valid PT session file"));
134                 msg.run ();
135                 return;
136         } else {
137                 MessageDialog msg (string_compose (_("PT v%1 Session @ %2Hz\n\n%3 audio files\n%4 regions\n%5 active regions\n\nContinue..."), (int)ptf.version, ptf.sessionrate, ptf.audiofiles.size(), ptf.regions.size(), ptf.tracks.size()));
138                 msg.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
139
140                 int result = msg.run ();
141                 if (result != Gtk::RESPONSE_OK) {
142                         return;
143                 }
144         }
145         current_interthread_info = &import_status;
146         import_status.current = 1;
147         import_status.total = ptf.audiofiles.size ();
148         import_status.all_done = false;
149
150         ImportProgressWindow ipw (&import_status, _("Import"), _("Cancel Import"));
151
152         SourceList just_one;
153         SourceList imported;
154
155         for (vector<PTFFormat::wav_t>::iterator a = ptf.audiofiles.begin(); a != ptf.audiofiles.end(); ++a) {
156                 ptflookup_t p;
157
158                 fullpath = Glib::build_filename (Glib::path_get_dirname(ptpath), "Audio Files");
159                 fullpath = Glib::build_filename (fullpath, a->filename);
160                 to_import.clear ();
161                 to_import.push_back (fullpath);
162                 ipw.show ();
163                 ok = import_sndfiles (to_import, Editing::ImportDistinctFiles, Editing::ImportAsRegion, quality, pos, 1, -1, track, false, instrument);
164                 if (!import_status.sources.empty()) {
165                         p.index1 = a->index;
166                         p.id = import_status.sources.back()->id();
167
168                         ptfwavpair.push_back(p);
169                         imported.push_back(import_status.sources.back());
170                 } else {
171                         onefailed = true;
172                 }
173         }
174
175         if (onefailed) {
176                 MessageDialog msg (_("Failed to load one or more of the audio files, but continuing to attempt import."));
177                 msg.run ();
178         } else {
179                 MessageDialog msg (_("Success! Import should complete soon."));
180                 msg.run ();
181         }
182
183         // Create a dummy midi track first to get a midi Source
184         list<boost::shared_ptr<MidiTrack> > mt (
185                 _session->new_midi_track (ChanCount (DataType::MIDI, 1),
186                                           ChanCount (DataType::MIDI, 1),
187                                           true,
188                                           instrument, (Plugin::PresetRecord*) 0,
189                                           (RouteGroup*) 0,
190                                           1,
191                                           string(),
192                                           PresentationInfo::max_order));
193         if (mt.empty()) {
194                 return;
195         }
196
197         for (vector<PTFFormat::region_t>::iterator a = ptf.regions.begin();
198                         a != ptf.regions.end(); ++a) {
199                 for (vector<ptflookup_t>::iterator p = ptfwavpair.begin();
200                                 p != ptfwavpair.end(); ++p) {
201                         if ((p->index1 == a->wave.index) && (strcmp(a->wave.filename.c_str(), "") != 0)) {
202                                 for (SourceList::iterator x = imported.begin();
203                                                 x != imported.end(); ++x) {
204                                         if ((*x)->id() == p->id) {
205                                                 // Matched an uncreated ptf region to ardour region
206                                                 ptflookup_t rp;
207                                                 PropertyList plist;
208
209                                                 plist.add (ARDOUR::Properties::start, a->sampleoffset);
210                                                 plist.add (ARDOUR::Properties::position, 0);
211                                                 plist.add (ARDOUR::Properties::length, a->length);
212                                                 plist.add (ARDOUR::Properties::name, a->name);
213                                                 plist.add (ARDOUR::Properties::layer, 0);
214                                                 plist.add (ARDOUR::Properties::whole_file, false);
215                                                 plist.add (ARDOUR::Properties::external, true);
216
217                                                 just_one.clear();
218                                                 just_one.push_back(*x);
219
220                                                 boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
221                                                 regions.push_back(r);
222
223                                                 rp.id = regions.back()->id();
224                                                 rp.index1 = a->index;
225                                                 ptfregpair.push_back(rp);
226                                         }
227                                 }
228                         }
229                 }
230                 if (strcmp(a->wave.filename.c_str(), "") == 0) {
231                         /* Empty wave - assume MIDI region */
232                         boost::shared_ptr<MidiTrack> midi_track = mt.back();
233                         boost::shared_ptr<Playlist> playlist = midi_track->playlist();
234                         framepos_t f = (framepos_t)a->startpos;
235                         framecnt_t length = (framecnt_t)a->length;
236                         MusicFrame pos (f, 0);
237                         boost::shared_ptr<Source> src = _session->create_midi_source_by_stealing_name (midi_track);
238                         PropertyList plist;
239                         plist.add (ARDOUR::Properties::start, 0);
240                         plist.add (ARDOUR::Properties::length, length);
241                         plist.add (ARDOUR::Properties::name, PBD::basename_nosuffix(src->name()));
242                         boost::shared_ptr<Region> region = (RegionFactory::create (src, plist));
243                         /* sets beat position */
244                         region->set_position (pos.frame, pos.division);
245                         midi_track->playlist()->add_region (region, pos.frame, 1.0, false, pos.division);
246
247                         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
248                         boost::shared_ptr<MidiModel> mm = mr->midi_source(0)->model();
249                         MidiModel::NoteDiffCommand *midicmd;
250                         midicmd = mm->new_note_diff_command ("Import ProTools MIDI");
251
252                         for (vector<PTFFormat::midi_ev_t>::iterator
253                                         j = a->midi.begin();
254                                         j != a->midi.end(); ++j) {
255                                 Evoral::Beats start = (Evoral::Beats)(j->pos/960000.);
256                                 Evoral::Beats len = (Evoral::Beats)(j->length/960000.);
257                                 // PT C-2 = 0, Ardour C-1 = 0, subtract twelve to convert...
258                                 midicmd->add(boost::shared_ptr<Evoral::Note<Evoral::Beats> >
259                                         (new Evoral::Note<Evoral::Beats>( (uint8_t)1, start, len, j->note - 12, j->velocity )));
260                         }
261                         mm->apply_command (_session, midicmd);
262                         boost::shared_ptr<Region> copy (RegionFactory::create (mr, true));
263                         playlist->clear_changes ();
264                         playlist->add_region (copy, a->startpos);
265                 }
266         }
267
268         boost::shared_ptr<AudioTrack> existing_track;
269         uint16_t nth = 0;
270         vector<ptflookup_t> usedtracks;
271         ptflookup_t utr;
272
273         for (vector<PTFFormat::track_t>::iterator a = ptf.tracks.begin();
274                         a != ptf.tracks.end(); ++a) {
275                 for (vector<ptflookup_t>::iterator p = ptfregpair.begin();
276                                 p != ptfregpair.end(); ++p) {
277
278                         if (p->index1 == a->reg.index)  {
279                                 // Matched a ptf active region to an ardour region
280                                 utr.index1 = a->index;
281                                 utr.index2 = nth;
282                                 utr.id = p->id;
283                                 boost::shared_ptr<Region> r = RegionFactory::region_by_id (p->id);
284                                 vector<ptflookup_t>::iterator lookuptr = usedtracks.begin();
285                                 vector<ptflookup_t>::iterator found;
286                                 if ((found = std::find(lookuptr, usedtracks.end(), utr)) != usedtracks.end()) {
287                                         DEBUG_TRACE (DEBUG::FileUtils, string_compose ("\twav(%1) reg(%2) ptf_tr(%3) ard_tr(%4)\n", a->reg.wave.filename.c_str(), a->reg.index, found->index1, found->index2));
288                                         existing_track =  get_nth_selected_audio_track(found->index2);
289                                         // Put on existing track
290                                         boost::shared_ptr<Playlist> playlist = existing_track->playlist();
291                                         boost::shared_ptr<Region> copy (RegionFactory::create (r, true));
292                                         playlist->clear_changes ();
293                                         playlist->add_region (copy, a->reg.startpos);
294                                         //_session->add_command (new StatefulDiffCommand (playlist));
295                                 } else {
296                                         // Put on a new track
297                                         DEBUG_TRACE (DEBUG::FileUtils, string_compose ("\twav(%1) reg(%2) new_tr(%3)\n", a->reg.wave.filename.c_str(), a->reg.index, nth));
298                                         list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (1, 2, 0, 1, string(), PresentationInfo::max_order, Normal));
299                                         if (at.empty()) {
300                                                 return;
301                                         }
302                                         existing_track = at.back();
303                                         std::string trackname;
304                                         try {
305                                                 trackname = Glib::convert_with_fallback (a->name, "UTF-8", "UTF-8", "_");
306                                         } catch (Glib::ConvertError& err) {
307                                                 trackname = string_compose ("Invalid %1", a->index);
308                                         }
309                                         // TODO legalize track name (no slashes, no colons)
310 #if 0 // TODO --  "find_route_name" is currently private
311                                         /* generate a unique name by adding a number if needed */
312                                         uint32_t id = 0;
313                                         if (!_session->find_route_name (trackname.c_str (), id, trackname, false)) {
314                                                 fatal << _("PTImport: UINT_MAX routes? impossible!") << endmsg;
315                                                 abort(); /*NOTREACHED*/
316                                         }
317 #endif
318                                         existing_track->set_name (trackname);
319                                         boost::shared_ptr<Playlist> playlist = existing_track->playlist();
320                                         boost::shared_ptr<Region> copy (RegionFactory::create (r, true));
321                                         playlist->clear_changes ();
322                                         playlist->add_region (copy, a->reg.startpos);
323                                         //_session->add_command (new StatefulDiffCommand (playlist));
324                                         nth++;
325                                 }
326                                 usedtracks.push_back(utr);
327                         }
328                 }
329         }
330
331         import_status.sources.clear();
332
333         if (ok) {
334                 _session->save_state ("");
335         }
336         import_status.all_done = true;
337 }