1 /*
2  * Copyright (C) 2009-2011 Carl Hetherington <carl@carlh.net>
3  * Copyright (C) 2009-2012 David Robillard <d@drobilla.net>
4  * Copyright (C) 2009-2017 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2015-2019 Robin Gareus <robin@gareus.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21 
22 #include <iostream>
23 
24 #include <gtkmm/table.h>
25 #include <gtkmm/label.h>
26 #include <gtkmm/progressbar.h>
27 #include <gtkmm/stock.h>
28 
29 #include "pbd/pthread_utils.h"
30 
31 #include "ardour/audioregion.h"
32 #include "ardour/dB.h"
33 #include "ardour/logmeter.h"
34 #include "ardour_ui.h"
35 
36 #include "audio_clock.h"
37 #include "gui_thread.h"
38 #include "strip_silence_dialog.h"
39 #include "region_view.h"
40 #include "rgb_macros.h"
41 #include "pbd/i18n.h"
42 
43 using namespace ARDOUR;
44 using namespace std;
45 using namespace ArdourCanvas;
46 
47 /** Construct Strip silence dialog box */
StripSilenceDialog(Session * s,list<RegionView * > const & v)48 StripSilenceDialog::StripSilenceDialog (Session* s, list<RegionView*> const & v)
49 	: ArdourDialog (_("Strip Silence"))
50 	, ProgressReporter ()
51 	, _minimum_length (new AudioClock (X_("silence duration"), true, "", true, false, true, false))
52 	, _fade_length (new AudioClock (X_("silence duration"), true, "", true, false, true, false))
53 	, _destroying (false)
54 	, analysis_progress_cur (0)
55 	, analysis_progress_max (0)
56 	, _threshold_value (-60)
57 	, _minimum_length_value (1000)
58 	, _fade_length_value (64)
59 {
60 	set_session (s);
61 
62 	for (list<RegionView*>::const_iterator r = v.begin(); r != v.end(); ++r) {
63 		views.push_back (ViewInterval (*r));
64 	}
65 
66 	Gtk::HBox* hbox = Gtk::manage (new Gtk::HBox);
67 
68 	Gtk::Table* table = Gtk::manage (new Gtk::Table (3, 3));
69 	table->set_spacings (6);
70 
71 	//get the last used settings for this
72 	XMLNode* node = _session->extra_xml(X_("StripSilence"));
73 	if (node) {
74 		node->get_property(X_("threshold"), _threshold_value);
75 		node->get_property(X_("min-length"), _minimum_length_value);
76 		node->get_property(X_("fade-length"), _fade_length_value);
77 	}
78 
79 	int n = 0;
80 
81 	table->attach (*Gtk::manage (new Gtk::Label (_("Threshold"), 1, 0.5)), 0, 1, n, n + 1, Gtk::FILL);
82 	table->attach (_threshold, 1, 2, n, n + 1, Gtk::FILL);
83 	table->attach (*Gtk::manage (new Gtk::Label (_("dBFS"))), 2, 3, n, n + 1, Gtk::FILL);
84 	++n;
85 
86 	_threshold.set_digits (1);
87 	_threshold.set_increments (1, 10);
88 	_threshold.set_range (-120, 0);
89 	_threshold.set_value (_threshold_value);
90 	_threshold.set_activates_default ();
91 
92 	table->attach (*Gtk::manage (new Gtk::Label (_("Minimum length"), 1, 0.5)), 0, 1, n, n + 1, Gtk::FILL);
93 	table->attach (*_minimum_length, 1, 2, n, n + 1, Gtk::FILL);
94 	++n;
95 
96 	_minimum_length->set_session (s);
97 	_minimum_length->set_mode (AudioClock::Samples);
98 	_minimum_length->set (_minimum_length_value, true);
99 
100 	table->attach (*Gtk::manage (new Gtk::Label (_("Fade length"), 1, 0.5)), 0, 1, n, n + 1, Gtk::FILL);
101 	table->attach (*_fade_length, 1, 2, n, n + 1, Gtk::FILL);
102 	++n;
103 
104 	_fade_length->set_session (s);
105 	_fade_length->set_mode (AudioClock::Samples);
106 	_fade_length->set (_fade_length_value, true);
107 
108 	hbox->pack_start (*table);
109 
110 	get_vbox()->pack_start (*hbox, false, false);
111 
112 	cancel_button = add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
113 	apply_button = add_button (Gtk::Stock::APPLY, Gtk::RESPONSE_OK);
114 	set_default_response (Gtk::RESPONSE_OK);
115 
116 	get_vbox()->pack_start (_progress_bar, true, true, 12);
117 
118 	show_all ();
119 
120 	_threshold.get_adjustment()->signal_value_changed().connect (sigc::mem_fun (*this, &StripSilenceDialog::threshold_changed));
121 	_minimum_length->ValueChanged.connect (sigc::mem_fun (*this, &StripSilenceDialog::restart_thread));
122 	_fade_length->ValueChanged.connect (sigc::mem_fun (*this, &StripSilenceDialog::restart_thread));
123 
124 	update_silence_rects ();
125 	update_threshold_line ();
126 
127 	_progress_bar.set_text (_("Analyzing"));
128 	update_progress_gui (0);
129 	apply_button->set_sensitive (false);
130 	progress_idle_connection = Glib::signal_idle().connect (sigc::mem_fun (*this, &StripSilenceDialog::idle_update_progress));
131 
132 	/* Create a thread which runs while the dialogue is open to compute the silence regions */
133 	Completed.connect (_completed_connection, invalidator(*this), boost::bind (&StripSilenceDialog::update, this), gui_context ());
134 	_thread_should_finish = false;
135 	pthread_create (&_thread, 0, StripSilenceDialog::_detection_thread_work, this);
136 
137 	signal_response().connect(sigc::mem_fun (*this, &StripSilenceDialog::finished));
138 }
139 
140 
~StripSilenceDialog()141 StripSilenceDialog::~StripSilenceDialog ()
142 {
143 	_destroying = true;
144 	progress_idle_connection.disconnect();
145 
146 	/* Terminate our thread */
147 	_interthread_info.cancel = true;
148 	_lock.lock ();
149 	_thread_should_finish = true;
150 	_lock.unlock ();
151 
152 	_run_cond.signal ();
153 	pthread_join (_thread, 0);
154 
155 	delete _minimum_length;
156 	delete _fade_length;
157 }
158 
159 bool
idle_update_progress()160 StripSilenceDialog::idle_update_progress()
161 {
162 	if (analysis_progress_max > 0) {
163 		// AudioRegion::find_silence() has
164 		// itt.progress = (end - pos) / length
165 		// not sure if that's intentional, but let's use (1. - val)
166 		float rp = std::min(1.f, std::max (0.f, (1.f - _interthread_info.progress)));
167 		float p = analysis_progress_cur / (float) analysis_progress_max
168 		        + rp / (float) analysis_progress_max;
169 		update_progress_gui (p);
170 	}
171 	return !_destroying;
172 }
173 
174 void
silences(AudioIntervalMap & m)175 StripSilenceDialog::silences (AudioIntervalMap& m)
176 {
177 	for (list<ViewInterval>::iterator v = views.begin(); v != views.end(); ++v) {
178 		pair<boost::shared_ptr<Region>,AudioIntervalResult> newpair (v->view->region(), v->intervals);
179 		m.insert (newpair);
180 	}
181 }
182 
183 void
drop_rects()184 StripSilenceDialog::drop_rects ()
185 {
186 	// called by parent when starting to progess (dialog::run returned),
187 	// but before the dialog is destoyed.
188 
189 	_interthread_info.cancel = true;
190 
191 	/* Block until the thread is idle */
192 	_lock.lock ();
193 	_lock.unlock ();
194 
195 	for (list<ViewInterval>::iterator v = views.begin(); v != views.end(); ++v) {
196 		v->view->drop_silent_frames ();
197 	}
198 
199 	cancel_button->set_sensitive (false);
200 	apply_button->set_sensitive (false);
201 }
202 
203 void
update_threshold_line()204 StripSilenceDialog::update_threshold_line ()
205 {
206 #if 0
207 	int n = 0;
208 
209 	/* Don't need to lock here as we're not reading the _waves silence details */
210 
211 	for (list<Wave*>::iterator i = _waves.begin(); i != _waves.end(); ++i) {
212 		(*i)->threshold_line->property_x1() = 0;
213 		(*i)->threshold_line->property_x2() = _wave_width;
214 
215 		double const y = alt_log_meter (_threshold.get_value());
216 
217 		(*i)->threshold_line->property_y1() = (n + 1 - y) * _wave_height;
218 		(*i)->threshold_line->property_y2() = (n + 1 - y) * _wave_height;
219 	}
220 
221 	++n;
222 #endif
223 }
224 
225 void
update()226 StripSilenceDialog::update ()
227 {
228 	update_threshold_line ();
229 	update_silence_rects ();
230 	_progress_bar.set_text ("");
231 	update_progress_gui (0);
232 	apply_button->set_sensitive(true);
233 }
234 
235 void
update_silence_rects()236 StripSilenceDialog::update_silence_rects ()
237 {
238 	/* Lock so that we don't contend with the detection thread for access to the silence regions */
239 	Glib::Threads::Mutex::Lock lm (_lock);
240 	double const y = _threshold.get_value();
241 
242 	for (list<ViewInterval>::iterator v = views.begin(); v != views.end(); ++v) {
243 		v->view->set_silent_frames (v->intervals, y);
244 	}
245 }
246 
247 void *
_detection_thread_work(void * arg)248 StripSilenceDialog::_detection_thread_work (void* arg)
249 {
250 	StripSilenceDialog* d = reinterpret_cast<StripSilenceDialog*> (arg);
251 	pthread_set_name ("SilenceDetect");
252 	return d->detection_thread_work ();
253 }
254 
255 /** Body of our silence detection thread */
256 void *
detection_thread_work()257 StripSilenceDialog::detection_thread_work ()
258 {
259 	/* Do not register with all UIs, but do register with the GUI,
260 	   because we will need to queue some GUI (only) requests
261 	*/
262 	ARDOUR_UI::instance()->register_thread (pthread_self(), "silence", 32);
263 
264 	/* Hold this lock when we are doing work */
265 	_lock.lock ();
266 
267 	while (1) {
268 		analysis_progress_cur = 0;
269 		analysis_progress_max = views.size();
270 		for (list<ViewInterval>::iterator i = views.begin(); i != views.end(); ++i) {
271 			boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> ((*i).view->region());
272 
273 			if (ar) {
274 				i->intervals = ar->find_silence (dB_to_coefficient (threshold ()), minimum_length (), fade_length(), _interthread_info);
275 			}
276 
277 			if (_interthread_info.cancel) {
278 				break;
279 			}
280 			++analysis_progress_cur;
281 			_interthread_info.progress = 1.0;
282 			ARDOUR::GUIIdle ();
283 		}
284 
285 		analysis_progress_max = 0;
286 
287 		if (!_interthread_info.cancel) {
288 			Completed (); /* EMIT SIGNAL */
289 		}
290 
291 		/* Our work is done; sleep until there is more to do.
292 		 * The lock is released while we are waiting.
293 		 */
294 		_run_cond.wait (_lock);
295 
296 		if (_thread_should_finish) {
297 			_lock.unlock ();
298 			return 0;
299 		}
300 	}
301 
302 	return 0;
303 }
304 
305 void
restart_thread()306 StripSilenceDialog::restart_thread ()
307 {
308 	if (_destroying) {
309 		/* I don't know how this happens, but it seems to be possible for this
310 		   method to be called after our destructor has finished executing.
311 		   If this happens, bad things follow; _lock cannot be locked and
312 		   Ardour hangs.  So if we are destroying, just bail early.
313 		   */
314 		return;
315 	}
316 
317 	_progress_bar.set_text (_("Analyzing"));
318 	update_progress_gui (0);
319 	apply_button->set_sensitive (false);
320 
321 	/* Cancel any current run */
322 	_interthread_info.cancel = true;
323 
324 	/* Block until the thread waits() */
325 	_lock.lock ();
326 	/* Reset the flag */
327 	_interthread_info.cancel = false;
328 	_lock.unlock ();
329 
330 	/* And re-awake the thread */
331 	_run_cond.signal ();
332 }
333 
334 void
threshold_changed()335 StripSilenceDialog::threshold_changed ()
336 {
337 	update_threshold_line ();
338 	restart_thread ();
339 }
340 
341 samplecnt_t
minimum_length() const342 StripSilenceDialog::minimum_length () const
343 {
344 	return std::max((samplecnt_t)1, _minimum_length->current_duration (views.front().view->region()->position()));
345 }
346 
347 samplecnt_t
fade_length() const348 StripSilenceDialog::fade_length () const
349 {
350 	return std::max((samplecnt_t)0, _fade_length->current_duration (views.front().view->region()->position()));
351 }
352 
353 void
update_progress_gui(float p)354 StripSilenceDialog::update_progress_gui (float p)
355 {
356 	_progress_bar.set_fraction (p);
357 }
358 
359 XMLNode&
get_state()360 StripSilenceDialog::get_state ()
361 {
362 	XMLNode* node = new XMLNode(X_("StripSilence"));
363 	node->set_property(X_("threshold"), threshold());
364 	node->set_property(X_("min-length"), minimum_length());
365 	node->set_property(X_("fade-length"), fade_length());
366 	return *node;
367 }
368 
369 void
set_state(const XMLNode &)370 StripSilenceDialog::set_state (const XMLNode &)
371 {
372 }
373 
374 void
finished(int response)375 StripSilenceDialog::finished(int response)
376 {
377 	if(response == Gtk::RESPONSE_OK) {
378 		_session->add_extra_xml(get_state());
379 	}
380 }
381