Optimize automation-event process splitting
[ardour.git] / libs / ardour / region_factory.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 <inttypes.h>
21
22 #include "pbd/basename.h"
23 #include "pbd/error.h"
24
25 #include "ardour/audioregion.h"
26 #include "ardour/audiosource.h"
27 #include "ardour/midi_region.h"
28 #include "ardour/midi_source.h"
29 #include "ardour/region.h"
30 #include "ardour/region_factory.h"
31 #include "ardour/session.h"
32
33 #include "pbd/i18n.h"
34
35 using namespace ARDOUR;
36 using namespace PBD;
37 using namespace std;
38
39 PBD::Signal1<void,boost::shared_ptr<Region> > RegionFactory::CheckNewRegion;
40 Glib::Threads::Mutex                          RegionFactory::region_map_lock;
41 RegionFactory::RegionMap                      RegionFactory::region_map;
42 PBD::ScopedConnectionList*                    RegionFactory::region_list_connections = 0;
43 Glib::Threads::Mutex                          RegionFactory::region_name_maps_mutex;
44 std::map<std::string, uint32_t>               RegionFactory::region_name_number_map;
45 std::map<std::string, PBD::ID>                RegionFactory::region_name_map;
46 RegionFactory::CompoundAssociations           RegionFactory::_compound_associations;
47
48 boost::shared_ptr<Region>
49 RegionFactory::create (boost::shared_ptr<const Region> region, bool announce, bool fork)
50 {
51         boost::shared_ptr<Region> ret;
52         boost::shared_ptr<const AudioRegion> ar;
53         boost::shared_ptr<const MidiRegion> mr;
54
55         if ((ar = boost::dynamic_pointer_cast<const AudioRegion>(region)) != 0) {
56
57                 ret = boost::shared_ptr<Region> (new AudioRegion (ar, MusicSample (0, 0)));
58
59         } else if ((mr = boost::dynamic_pointer_cast<const MidiRegion>(region)) != 0) {
60
61                 if (mr->session().config.get_midi_copy_is_fork() || fork) {
62                         /* What we really want to do here is what Editor::fork_region()
63                            does via Session::create_midi_source_by_stealing_name(), but we
64                            don't have a Track.  We'll just live with the skipped number,
65                            and store the ancestral name of sources so multiple clones
66                            generates reasonable names that don't have too many suffixes. */
67                         const std::string ancestor_name = mr->sources().front()->ancestor_name();
68                         const std::string base          = PBD::basename_nosuffix(ancestor_name);
69
70                         boost::shared_ptr<MidiSource> source = mr->session().create_midi_source_for_session(base);
71                         source->set_ancestor_name(mr->sources().front()->name());
72                         ret = mr->clone(source);
73                 } else {
74                         ret = boost::shared_ptr<Region> (new MidiRegion (mr, MusicSample (0, 0)));
75                 }
76
77         } else {
78                 fatal << _("programming error: RegionFactory::create() called with unknown Region type")
79                       << endmsg;
80                 abort(); /*NOTREACHED*/
81         }
82
83         if (ret) {
84                 ret->set_name (new_region_name(ret->name()));
85
86                 if (ret->session().config.get_glue_new_regions_to_bars_and_beats() && ret->position_lock_style() != MusicTime) {
87                         ret->set_position_lock_style (MusicTime);
88                 }
89
90                 /* pure copy constructor - no property list */
91                 if (announce) {
92                         map_add (ret);
93                         CheckNewRegion (ret);
94                 }
95         }
96
97 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
98         // boost_debug_shared_ptr_mark_interesting (ret.get(), "Region");
99 #endif
100         return ret;
101 }
102
103 boost::shared_ptr<Region>
104 RegionFactory::create (boost::shared_ptr<Region> region, const PropertyList& plist, bool announce)
105 {
106         boost::shared_ptr<Region> ret;
107         boost::shared_ptr<const AudioRegion> other_a;
108         boost::shared_ptr<const MidiRegion> other_m;
109
110         if ((other_a = boost::dynamic_pointer_cast<AudioRegion>(region)) != 0) {
111
112                 ret = boost::shared_ptr<Region> (new AudioRegion (other_a));
113
114         } else if ((other_m = boost::dynamic_pointer_cast<MidiRegion>(region)) != 0) {
115
116                 ret = boost::shared_ptr<Region> (new MidiRegion (other_m));
117
118         } else {
119                 fatal << _("programming error: RegionFactory::create() called with unknown Region type")
120                       << endmsg;
121                 abort(); /*NOTREACHED*/
122                 return boost::shared_ptr<Region>();
123         }
124
125         if (ret) {
126                 ret->apply_changes (plist);
127
128                 if (ret->session().config.get_glue_new_regions_to_bars_and_beats() && ret->position_lock_style() != MusicTime) {
129                         ret->set_position_lock_style (MusicTime);
130                 }
131
132                 if (announce) {
133                         map_add (ret);
134                         CheckNewRegion (ret);
135                 }
136         }
137
138 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
139         // boost_debug_shared_ptr_mark_interesting (ret.get(), "Region");
140 #endif
141         return ret;
142 }
143
144 boost::shared_ptr<Region>
145 RegionFactory::create (boost::shared_ptr<Region> region, MusicSample offset, const PropertyList& plist, bool announce)
146 {
147         boost::shared_ptr<Region> ret;
148         boost::shared_ptr<const AudioRegion> other_a;
149         boost::shared_ptr<const MidiRegion> other_m;
150
151         if ((other_a = boost::dynamic_pointer_cast<AudioRegion>(region)) != 0) {
152
153                 ret = boost::shared_ptr<Region> (new AudioRegion (other_a, offset));
154
155         } else if ((other_m = boost::dynamic_pointer_cast<MidiRegion>(region)) != 0) {
156
157                 ret = boost::shared_ptr<Region> (new MidiRegion (other_m, offset));
158
159         } else {
160                 fatal << _("programming error: RegionFactory::create() called with unknown Region type")
161                       << endmsg;
162                 abort(); /*NOTREACHED*/
163                 return boost::shared_ptr<Region>();
164         }
165
166         if (ret) {
167                 ret->apply_changes (plist);
168
169                 if (ret->session().config.get_glue_new_regions_to_bars_and_beats() && ret->position_lock_style() != MusicTime) {
170                         ret->set_position_lock_style (MusicTime);
171                 }
172
173                 if (announce) {
174                         map_add (ret);
175                         CheckNewRegion (ret);
176                 }
177         }
178
179 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
180         // boost_debug_shared_ptr_mark_interesting (ret.get(), "Region");
181 #endif
182         return ret;
183 }
184
185 boost::shared_ptr<Region>
186 RegionFactory::create (boost::shared_ptr<Region> region, const SourceList& srcs, const PropertyList& plist, bool announce)
187 {
188         boost::shared_ptr<Region> ret;
189         boost::shared_ptr<const AudioRegion> other;
190
191         /* used by AudioFilter when constructing a new region that is intended to have nearly
192            identical settings to an original, but using different sources.
193         */
194
195         if ((other = boost::dynamic_pointer_cast<AudioRegion>(region)) != 0) {
196
197                 // XXX use me in caller where plist is setup, this is start i think srcs.front()->length (srcs.front()->timeline_position())
198
199                 ret = boost::shared_ptr<Region> (new AudioRegion (other, srcs));
200
201         } else {
202                 fatal << _("programming error: RegionFactory::create() called with unknown Region type")
203                       << endmsg;
204                 abort(); /*NOTREACHED*/
205         }
206
207         if (ret) {
208                 ret->apply_changes (plist);
209
210                 if (ret->session().config.get_glue_new_regions_to_bars_and_beats() && ret->position_lock_style() != MusicTime) {
211                         ret->set_position_lock_style (MusicTime);
212                 }
213
214                 if (announce) {
215                         map_add (ret);
216                         CheckNewRegion (ret);
217                 }
218         }
219
220 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
221         // boost_debug_shared_ptr_mark_interesting (ret.get(), "Region");
222 #endif
223         return ret;
224 }
225
226 boost::shared_ptr<Region>
227 RegionFactory::create (boost::shared_ptr<Source> src, const PropertyList& plist, bool announce)
228 {
229         SourceList srcs;
230         srcs.push_back (src);
231         return create (srcs, plist, announce);
232 }
233
234 boost::shared_ptr<Region>
235 RegionFactory::create (const SourceList& srcs, const PropertyList& plist, bool announce)
236 {
237         boost::shared_ptr<Region> ret;
238         boost::shared_ptr<AudioSource> as;
239         boost::shared_ptr<MidiSource> ms;
240
241         if ((as = boost::dynamic_pointer_cast<AudioSource>(srcs[0])) != 0) {
242
243                 ret = boost::shared_ptr<Region> (new AudioRegion (srcs));
244
245         } else if ((ms = boost::dynamic_pointer_cast<MidiSource>(srcs[0])) != 0) {
246
247                 ret = boost::shared_ptr<Region> (new MidiRegion (srcs));
248
249         }
250
251         if (ret) {
252                 ret->apply_changes (plist);
253
254                 if (ret->session().config.get_glue_new_regions_to_bars_and_beats() && ret->position_lock_style() != MusicTime) {
255                         ret->set_position_lock_style (MusicTime);
256                 }
257
258                 if (announce) {
259                         map_add (ret);
260                         CheckNewRegion (ret);
261                 }
262         }
263
264 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
265         // boost_debug_shared_ptr_mark_interesting (ret.get(), "Region");
266 #endif
267         return ret;
268 }
269
270 boost::shared_ptr<Region>
271 RegionFactory::create (Session& session, XMLNode& node, bool yn)
272 {
273         return session.XMLRegionFactory (node, yn);
274 }
275
276 boost::shared_ptr<Region>
277 RegionFactory::create (SourceList& srcs, const XMLNode& node)
278 {
279         boost::shared_ptr<Region> ret;
280
281         if (srcs.empty()) {
282                 return ret;
283         }
284
285         if (srcs[0]->type() == DataType::AUDIO) {
286
287                 ret = boost::shared_ptr<Region> (new AudioRegion (srcs));
288
289         } else if (srcs[0]->type() == DataType::MIDI) {
290
291                 ret = boost::shared_ptr<Region> (new MidiRegion (srcs));
292
293         }
294
295         if (ret) {
296                 if (ret->set_state (node, Stateful::loading_state_version)) {
297                         ret.reset ();
298                 } else {
299                         map_add (ret);
300
301                         /* Don't fiddle with position_lock_style here as the region
302                            description is coming from XML.
303                         */
304
305                         CheckNewRegion (ret);
306                 }
307         }
308
309 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
310         // boost_debug_shared_ptr_mark_interesting (ret.get(), "Region");
311 #endif
312         return ret;
313 }
314
315 void
316 RegionFactory::map_add (boost::shared_ptr<Region> r)
317 {
318         pair<ID,boost::shared_ptr<Region> > p;
319         p.first = r->id();
320         p.second = r;
321
322         {
323                 Glib::Threads::Mutex::Lock lm (region_map_lock);
324                 region_map.insert (p);
325         }
326
327         if (!region_list_connections) {
328                 region_list_connections = new ScopedConnectionList;
329         }
330
331         r->DropReferences.connect_same_thread (*region_list_connections, boost::bind (&RegionFactory::map_remove, boost::weak_ptr<Region> (r)));
332         r->PropertyChanged.connect_same_thread (*region_list_connections, boost::bind (&RegionFactory::region_changed, _1, boost::weak_ptr<Region> (r)));
333
334         add_to_region_name_maps (r);
335 }
336
337 void
338 RegionFactory::map_remove (boost::weak_ptr<Region> w)
339 {
340         boost::shared_ptr<Region> r = w.lock ();
341         if (!r) {
342                 return;
343         }
344
345         Glib::Threads::Mutex::Lock lm (region_map_lock);
346         RegionMap::iterator i = region_map.find (r->id());
347
348         if (i != region_map.end()) {
349                 remove_from_region_name_map (i->second->name ());
350                 region_map.erase (i);
351         }
352 }
353
354 boost::shared_ptr<Region>
355 RegionFactory::region_by_id (const PBD::ID& id)
356 {
357         RegionMap::iterator i = region_map.find (id);
358
359         if (i == region_map.end()) {
360                 return boost::shared_ptr<Region>();
361         }
362
363         return i->second;
364 }
365
366 boost::shared_ptr<Region>
367 RegionFactory::wholefile_region_by_name (const std::string& name)
368 {
369         for (RegionMap::iterator i = region_map.begin(); i != region_map.end(); ++i) {
370                 if (i->second->whole_file() && i->second->name() == name) {
371                         return i->second;
372                 }
373         }
374         return boost::shared_ptr<Region>();
375 }
376
377 boost::shared_ptr<Region>
378 RegionFactory::region_by_name (const std::string& name)
379 {
380         for (RegionMap::iterator i = region_map.begin(); i != region_map.end(); ++i) {
381                 if (i->second->name() == name) {
382                         return i->second;
383                 }
384         }
385         return boost::shared_ptr<Region>();
386 }
387
388 void
389 RegionFactory::clear_map ()
390 {
391         if (region_list_connections) {
392                 region_list_connections->drop_connections ();
393         }
394
395         {
396                 Glib::Threads::Mutex::Lock lm (region_map_lock);
397                 region_map.clear ();
398                 _compound_associations.clear ();
399                 region_name_map.clear ();
400         }
401 }
402
403 void
404 RegionFactory::delete_all_regions ()
405 {
406         RegionMap copy;
407
408         /* copy region list */
409         {
410                 Glib::Threads::Mutex::Lock lm (region_map_lock);
411                 copy = region_map;
412         }
413
414         /* clear existing map */
415         clear_map ();
416
417         /* tell everyone to drop references */
418         for (RegionMap::iterator i = copy.begin(); i != copy.end(); ++i) {
419                 i->second->drop_references ();
420         }
421
422         /* the copy should now hold the only references, which will
423            vanish as we leave this scope, thus calling all destructors.
424         */
425 }
426
427 uint32_t
428 RegionFactory::nregions ()
429 {
430         Glib::Threads::Mutex::Lock lm (region_map_lock);
431         return region_map.size ();
432 }
433
434 /** Add a region to the two region name maps */
435 void
436 RegionFactory::add_to_region_name_maps (boost::shared_ptr<Region> region)
437 {
438         update_region_name_number_map (region);
439
440         Glib::Threads::Mutex::Lock lm (region_name_maps_mutex);
441         region_name_map[region->name()] = region->id ();
442 }
443
444 /** Account for a region rename in the two region name maps */
445 void
446 RegionFactory::rename_in_region_name_maps (boost::shared_ptr<Region> region)
447 {
448         update_region_name_number_map (region);
449
450         Glib::Threads::Mutex::Lock lm (region_name_maps_mutex);
451
452         map<string, PBD::ID>::iterator i = region_name_map.begin();
453         while (i != region_name_map.end() && i->second != region->id ()) {
454                 ++i;
455         }
456
457         /* Erase the entry for the old name and put in a new one */
458         if (i != region_name_map.end()) {
459                 region_name_map.erase (i);
460                 region_name_map[region->name()] = region->id ();
461         }
462 }
463
464 /** Remove a region's details from the region_name_map */
465 void
466 RegionFactory::remove_from_region_name_map (string n)
467 {
468         map<string, PBD::ID>::iterator i = region_name_map.find (n);
469         if (i != region_name_map.end ()) {
470                 region_name_map.erase (i);
471         }
472 }
473
474 /** Update a region's entry in the region_name_number_map */
475 void
476 RegionFactory::update_region_name_number_map (boost::shared_ptr<Region> region)
477 {
478         string::size_type const last_period = region->name().find_last_of ('.');
479
480         if (last_period != string::npos && last_period < region->name().length() - 1) {
481
482                 string const base = region->name().substr (0, last_period);
483                 string const number = region->name().substr (last_period + 1);
484
485                 /* note that if there is no number, we get zero from atoi,
486                    which is just fine
487                 */
488
489                 Glib::Threads::Mutex::Lock lm (region_name_maps_mutex);
490                 region_name_number_map[base] = atoi (number.c_str ());
491         }
492 }
493
494 void
495 RegionFactory::region_changed (PropertyChange const & what_changed, boost::weak_ptr<Region> w)
496 {
497         boost::shared_ptr<Region> r = w.lock ();
498         if (!r) {
499                 return;
500         }
501
502         if (what_changed.contains (Properties::name)) {
503                 rename_in_region_name_maps (r);
504         }
505 }
506
507 int
508 RegionFactory::region_name (string& result, string base, bool newlevel)
509 {
510         char buf[16];
511         string subbase;
512
513         if (base.find("/") != string::npos) {
514                 base = base.substr(base.find_last_of("/") + 1);
515         }
516
517         if (base == "") {
518
519                 snprintf (buf, sizeof (buf), "%d", RegionFactory::nregions() + 1);
520                 result = "region.";
521                 result += buf;
522
523         } else {
524
525                 if (newlevel) {
526                         subbase = base;
527                 } else {
528                         string::size_type pos;
529
530                         pos = base.find_last_of ('.');
531
532                         /* pos may be npos, but then we just use entire base */
533
534                         subbase = base.substr (0, pos);
535
536                 }
537
538                 {
539                         Glib::Threads::Mutex::Lock lm (region_name_maps_mutex);
540
541                         map<string,uint32_t>::iterator x;
542
543                         result = subbase;
544
545                         if ((x = region_name_number_map.find (subbase)) == region_name_number_map.end()) {
546                                 result += ".1";
547                                 region_name_number_map[subbase] = 1;
548                         } else {
549                                 x->second++;
550                                 snprintf (buf, sizeof (buf), ".%d", x->second);
551
552                                 result += buf;
553                         }
554                 }
555         }
556
557         return 0;
558 }
559
560 string
561 RegionFactory::compound_region_name (const string& playlist, uint32_t compound_ops, uint32_t depth, bool whole_source)
562 {
563         if (whole_source) {
564                 return string_compose (_("%1 compound-%2 (%3)"), playlist, compound_ops+1, depth+1);
565         } else {
566                 return string_compose (_("%1 compound-%2.1 (%3)"), playlist, compound_ops+1, depth+1);
567         }
568 }
569
570 string
571 RegionFactory::new_region_name (string old)
572 {
573         string::size_type last_period;
574         uint32_t number;
575         string::size_type len = old.length() + 64;
576         string remainder;
577         std::vector<char> buf(len);
578
579         if ((last_period = old.find_last_of ('.')) == string::npos) {
580
581                 /* no period present - add one explicitly */
582
583                 old += '.';
584                 last_period = old.length() - 1;
585                 number = 0;
586
587         } else {
588
589                 if (last_period < old.length() - 1) {
590
591                         string period_to_end = old.substr (last_period+1);
592
593                         /* extra material after the period */
594
595                         string::size_type numerals_end = period_to_end.find_first_not_of ("0123456789");
596
597                         number = atoi (period_to_end);
598
599                         if (numerals_end < period_to_end.length() - 1) {
600                                 /* extra material after the end of the digits */
601                                 remainder = period_to_end.substr (numerals_end);
602                         }
603
604                 } else {
605                         last_period = old.length();
606                         number = 0;
607                 }
608         }
609
610         while (number < (UINT_MAX-1)) {
611
612                 string sbuf;
613
614                 number++;
615
616                 snprintf (&buf[0], len, "%s%" PRIu32 "%s", old.substr (0, last_period + 1).c_str(), number, remainder.c_str());
617                 sbuf = &buf[0];
618
619                 if (region_name_map.find (sbuf) == region_name_map.end ()) {
620                         break;
621                 }
622         }
623
624         if (number != (UINT_MAX-1)) {
625                 return &buf[0];
626         }
627
628         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
629         return old;
630 }
631
632 void
633 RegionFactory::get_regions_using_source (boost::shared_ptr<Source> s, std::set<boost::shared_ptr<Region> >& r)
634 {
635         Glib::Threads::Mutex::Lock lm (region_map_lock);
636
637         for (RegionMap::const_iterator i = region_map.begin(); i != region_map.end(); ++i) {
638                 if (i->second->uses_source (s)) {
639                         r.insert (i->second);
640                 }
641         }
642 }
643
644 void
645 RegionFactory::remove_regions_using_source (boost::shared_ptr<Source> src)
646 {
647         Glib::Threads::Mutex::Lock lm (region_map_lock);
648
649         RegionMap::iterator i = region_map.begin();
650         while (i != region_map.end()) {
651
652                 RegionMap::iterator j = i;
653                 ++j;
654
655                 if (i->second->uses_source (src)) {
656                         remove_from_region_name_map (i->second->name ());
657                         region_map.erase (i);
658                 }
659
660                 i = j;
661         }
662 }
663
664 void
665 RegionFactory::add_compound_association (boost::shared_ptr<Region> orig, boost::shared_ptr<Region> copy)
666 {
667         Glib::Threads::Mutex::Lock lm (region_map_lock);
668         _compound_associations[copy] = orig;
669 }