Auto-pause: make the unpause delay proportional to the pause duration.

We only unpause the music player, after auto-pausing it, if it's been
paused for longer than some minimum length of time. This commit reduces
that time if the music player hasn't been paused for long.
This commit is contained in:
Kyle Neideck 2016-12-29 02:25:44 +11:00
parent 651b91aeee
commit 8d5ea9c67c
No known key found for this signature in database
GPG key ID: CAA8D9B8E39EC18C
4 changed files with 122 additions and 15 deletions

View file

@ -27,6 +27,9 @@
#include "BGM_Types.h"
#import "BGMMusicPlayer.h"
// STL Includes
#import <algorithm> // std::max, std::min
// System Includes
#include <CoreAudio/AudioHardware.h>
#include <mach/mach_time.h>
@ -36,10 +39,21 @@
// and other audio can have short periods of silence without causing music to play and quickly pause again. Of course, it's a
// trade-off against how long the music will overlap the other audio before it gets paused and how long the music will stay paused
// after a sound that was only slightly longer than the pause delay.
static UInt64 const kPauseDelayNSec = 1500 * NSEC_PER_MSEC;
// The delay before unpausing the music player is proportional to how long we paused it for, bounded by these limits. This makes it
// a bit less annoying when a sound is just long enough to cause an auto-pause.
//
// TODO: Make these settable in advanced settings?
static int const kPauseDelayMSecs = 1500;
static int const kUnpauseDelayMSecs = 3000;
// I haven't spent much time experimenting with different values for these constants, so they could probably be improved a fair
// bit.
//
// TODO: Would it be worth listening for kAudioDeviceCustomPropertyDeviceIsRunningSomewhereOtherThanBGMApp so we can unpause
// immediately if we haven't been paused for long and the non-music-player client stops IO? That would usually indicate that
// it doesn't intend to start playing audio again soon. We'd also have to deal with music players that don't stop IO when
// they're paused.
static UInt64 const kMaxUnpauseDelayNSec = 3000 * NSEC_PER_MSEC;
static UInt64 const kMinUnpauseDelayNSec = kMaxUnpauseDelayNSec / 10;
// We multiply the time spent paused by this factor to calculate the delay before we consider unpausing.
static Float32 const kUnpauseDelayWeightingFactor = 0.25f;
@implementation BGMAutoPauseMusic {
BOOL enabled;
@ -53,8 +67,8 @@ static int const kUnpauseDelayMSecs = 3000;
dispatch_queue_t pauseUnpauseMusicQueue;
// True if BGMApp has paused musicPlayer and hasn't unpaused it yet. (Will be out of sync with the music player app if the user
// has unpaused it themselves.)
// True if BGMApp has paused musicPlayer and hasn't unpaused it yet. (Will be out of sync with the music player app if the
// user has unpaused it themselves.)
BOOL wePaused;
// The times, in absolute time, that the BGMDevice last changed its audible state to silent...
UInt64 wentSilent;
@ -101,6 +115,8 @@ static int const kUnpauseDelayMSecs = 3000;
audibleStateStr);
#endif
// TODO: We shouldn't assume this block will only get called when BGMDevice's audible state changes. (Even if
// the Core Audio docs did specify that, there's no reason not to be fault tolerant.)
if (audibleState == kBGMDeviceIsAudible) {
[weakSelf queuePauseBlock];
} else if (audibleState == kBGMDeviceIsSilent) {
@ -119,9 +135,12 @@ static int const kUnpauseDelayMSecs = 3000;
- (SInt32) deviceAudibleState {
SInt32 audibleState;
CFNumberRef audibleStateRef = static_cast<CFNumberRef>([audioDevices bgmDevice].GetPropertyData_CFType(kBGMAudibleStateAddress));
CFNumberRef audibleStateRef =
static_cast<CFNumberRef>([audioDevices bgmDevice].GetPropertyData_CFType(kBGMAudibleStateAddress));
CFNumberGetValue(audibleStateRef, kCFNumberSInt32Type, &audibleState);
CFRelease(audibleStateRef);
return audibleState;
}
@ -131,7 +150,7 @@ static int const kUnpauseDelayMSecs = 3000;
UInt64 startedPauseDelay = now;
DebugMsg("BGMAutoPauseMusic::queuePauseBlock: Dispatching pause block at %llu", now);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kPauseDelayMSecs * NSEC_PER_MSEC),
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kPauseDelayNSec),
pauseUnpauseMusicQueue,
^{
BOOL stillAudible = ([self deviceAudibleState] == kBGMDeviceIsAudible);
@ -155,8 +174,28 @@ static int const kUnpauseDelayMSecs = 3000;
wentSilent = now;
UInt64 startedUnpauseDelay = now;
DebugMsg("BGMAutoPauseMusic::queueUnpauseBlock: Dispatched unpause block at %llu", now);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kUnpauseDelayMSecs * NSEC_PER_MSEC),
// Unpause sooner if we've only been paused for a short time. This is so a notification sound causing an auto-pause is
// less of an interruption.
//
// TODO: Would it help much if we ignored all audio played on the "system default" device rather than the "default"
// device? IIRC apps are supposed to use the former for UI sounds.
UInt64 unpauseDelayNsec =
static_cast<UInt64>((wentSilent - wentAudible) * kUnpauseDelayWeightingFactor);
// Convert from absolute time to nanos.
mach_timebase_info_data_t info;
mach_timebase_info(&info);
unpauseDelayNsec = unpauseDelayNsec * info.numer / info.denom;
// Clamp.
unpauseDelayNsec = std::min(kMaxUnpauseDelayNSec, unpauseDelayNsec);
unpauseDelayNsec = std::max(kMinUnpauseDelayNSec, unpauseDelayNsec);
DebugMsg("BGMAutoPauseMusic::queueUnpauseBlock: Dispatched unpause block at %llu. unpauseDelayNsec=%llu",
now,
unpauseDelayNsec);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, unpauseDelayNsec),
pauseUnpauseMusicQueue,
^{
BOOL stillSilent = ([self deviceAudibleState] == kBGMDeviceIsSilent);

View file

@ -48,4 +48,7 @@ Overview](https://developer.apple.com/library/mac/documentation/MusicAudio/Conce
and the [Core Audio
Glossary](https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioGlossary/Glossary/core_audio_glossary.html).
If you remember to, add a copyright notice with your name to any source files you change substantially. Let us know in
the PR if you've intentionally not added one so we know not to add one for you.

56
LICENSE-Apple-Sample-Code Normal file
View file

@ -0,0 +1,56 @@
Background Music includes code from Core Audio User-Space Driver
Examples, see
<https://developer.apple.com/library/mac/samplecode/AudioDriverExamples>,
which was provided with the following copyright notice and the license
below.
Copyright (C) 2013 Apple Inc. All Rights Reserved.
Background Music includes code from Core Audio Utility Classes, see
<https://developer.apple.com/library/content/samplecode/CoreAudioUtilityClasses>,
which was provided with the following copyright notice and the license
below.
Copyright (C) 2014 Apple Inc. All Rights Reserved.
------------------------------------------------------------------------
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View file

@ -14,8 +14,7 @@
- No restart required to install
- Runs entirely in userspace
**Version 0.1.0**, first release. Probably very buggy. Not very polished. Pretty much only tested on one system. (A
MacBook running OS X 10.11 using the built-in audio device.)
**Version 0.1.0**, first release. Probably very buggy. Not very polished or well tested.
**Requires OS X 10.10+**. Might work on 10.9, but I haven't tried it. Currently unable to build in Xcode 6.
@ -112,7 +111,8 @@ change the default device and then change it back again. Failing that, you might
General tab of Skype's preferences.
- Plugging in or unplugging headphones when Background Music isn't running can silence system audio. To fix it, go to
the Sound section in System Preferences, click the Output tab and change your default output device to something other
than Background Music Device. Alternatively, you may Option+Click on the Sound icon in the menu bar to select a different output device.
than Background Music Device. Alternatively, you may Option+Click on the Sound icon in the menu bar to select a
different output device.
This happens when macOS remembers that Background Music Device was your default audio device the last time you last
used (or didn't use) headphones.
@ -120,10 +120,10 @@ change the default device and then change it back again. Failing that, you might
Background Music Device after you open Background Music. Chrome's audio will still play, but Background Music won't be
aware of it.
- Some apps play notification sounds that are only just long enough to trigger an auto-pause. The only workaround right
now is to increase the `kPauseDelayMSecs` constant in `BGMApp/BGMAutoPauseMusic.mm`. That will make your music overlap
the other audio for longer, though, so you don't want to increase it too much. See
now is to increase the `kPauseDelayNSec` constant in [BGMAutoPauseMusic.mm](/BGMApp/BGMApp/BGMAutoPauseMusic.mm).
That will make your music overlap the other audio for longer, though, so you don't want to increase it too much. See
[#5](https://github.com/kyleneideck/BackgroundMusic/issues/5) for details.
- Plenty more. Some are in listed in TODO.md.
- Plenty more. Some are in listed in [TODO.md](/TODO.md).
## Related projects
@ -159,6 +159,15 @@ change the default device and then change it back again. Failing that, you might
Copyright © 2016 [Background Music contributors](https://github.com/kyleneideck/BackgroundMusic/graphs/contributors).
Licensed under [GPLv2](https://www.gnu.org/licenses/gpl-2.0.html), or any later version.
Background Music includes code from:
- [Core Audio User-Space Driver
Examples](https://developer.apple.com/library/mac/samplecode/AudioDriverExamples/Introduction/Intro.html), [original
license](LICENSE-Apple-Sample-Code), Copyright (C) 2013 Apple Inc. All Rights Reserved.
- [Core Audio Utility
Classes](https://developer.apple.com/library/content/samplecode/CoreAudioUtilityClasses/Introduction/Intro.html),
[original license](LICENSE-Apple-Sample-Code), Copyright (C) 2014 Apple Inc. All Rights Reserved.
----
<b id="f1">[1]</b> However, if the music player doesn't support AppleScript, or doesn't support the events Background