165 lines
11 KiB
C++
165 lines
11 KiB
C++
#pragma once
|
|
#include <winrt/Windows.Foundation.h>
|
|
#include <winrt/Windows.Foundation.Collections.h>
|
|
#include <winrt/Windows.Media.Control.h>
|
|
#include <winrt/Windows.Storage.Streams.h>
|
|
#include <wincodec.h>
|
|
#include <wrl/client.h>
|
|
#include <memory>
|
|
#include <atomic>
|
|
#include <thread>
|
|
#include <mutex>
|
|
#include <condition_variable>
|
|
#include <deque>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <algorithm>
|
|
#pragma comment(lib,"windowsapp.lib")
|
|
#pragma comment(lib,"windowscodecs.lib")
|
|
#pragma comment(lib,"ole32.lib")
|
|
|
|
namespace media {
|
|
struct artwork {unsigned width=0,height=0;std::vector<unsigned char> rgba;};
|
|
inline std::shared_ptr<const artwork> decode_art(std::vector<unsigned char>& bytes) {
|
|
using Microsoft::WRL::ComPtr;
|
|
if(bytes.empty() || bytes.size()>4*1024*1024)return {};
|
|
ComPtr<IWICImagingFactory> factory;ComPtr<IWICStream> stream;ComPtr<IWICBitmapDecoder> decoder;
|
|
ComPtr<IWICBitmapFrameDecode> frame;ComPtr<IWICBitmapScaler> scaler;ComPtr<IWICFormatConverter> converter;
|
|
if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory))) ||
|
|
FAILED(factory->CreateStream(&stream)) || FAILED(stream->InitializeFromMemory(bytes.data(),DWORD(bytes.size()))) ||
|
|
FAILED(factory->CreateDecoderFromStream(stream.Get(),nullptr,WICDecodeMetadataCacheOnLoad,&decoder)) ||
|
|
FAILED(decoder->GetFrame(0,&frame)))return {};
|
|
UINT w=0,h=0;if(FAILED(frame->GetSize(&w,&h)) || !w || !h || w>16384 || h>16384)return {};
|
|
const double scale=(std::min)(1.,256./(std::max)(w,h));
|
|
w=(std::max)(1u,unsigned(w*scale));h=(std::max)(1u,unsigned(h*scale));
|
|
if(FAILED(factory->CreateBitmapScaler(&scaler)) || FAILED(scaler->Initialize(frame.Get(),w,h,WICBitmapInterpolationModeFant)) ||
|
|
FAILED(factory->CreateFormatConverter(&converter)) || FAILED(converter->Initialize(scaler.Get(),GUID_WICPixelFormat32bppRGBA,
|
|
WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom)))return {};
|
|
auto result=std::make_shared<artwork>();result->width=w;result->height=h;result->rgba.resize(w*h*4);
|
|
if(FAILED(converter->CopyPixels(nullptr,w*4,UINT(result->rgba.size()),result->rgba.data())))return {};
|
|
return result;
|
|
}
|
|
struct snapshot {
|
|
bool available=false,playing=false,previous=false,next=false,pause=false;
|
|
std::string title,artist,app,message="Looking for a media player...";
|
|
std::vector<std::string> players;
|
|
double position=0,duration=0,rate=1;uint64_t stamp=0;
|
|
std::shared_ptr<const artwork> art;
|
|
};
|
|
enum class command {previous,pause,next};
|
|
struct request {command action;std::string app;};
|
|
class reader {
|
|
public:
|
|
~reader(){stop();}
|
|
void start(){if(worker_.joinable())return;stopping_=false;worker_=std::thread([this]{run();});}
|
|
void stop(){stopping_=true;wake_.notify_all();if(worker_.joinable())worker_.join();std::lock_guard lock(mutex_);commands_.clear();state_={};}
|
|
snapshot latest(){std::lock_guard lock(mutex_);return state_;}
|
|
void prefer(const std::string& app){std::lock_guard lock(mutex_);preferred_=app;}
|
|
void send(command action){std::lock_guard lock(mutex_);if(state_.available && commands_.size()<8){commands_.push_back({action,state_.app});wake_.notify_all();}}
|
|
private:
|
|
std::thread worker_;std::atomic<bool> stopping_{false};std::mutex mutex_;std::condition_variable wake_;
|
|
snapshot state_;std::string preferred_;std::deque<request> commands_;
|
|
template<class Operation> bool finish(Operation const& op) {
|
|
using winrt::Windows::Foundation::AsyncStatus;
|
|
const auto deadline=GetTickCount64()+3000;
|
|
while(op.Status()==AsyncStatus::Started) {
|
|
if(stopping_ || GetTickCount64()>deadline){op.Cancel();return false;}
|
|
std::unique_lock lock(mutex_);wake_.wait_for(lock,std::chrono::milliseconds(20),[this]{return stopping_.load();});
|
|
}
|
|
if(!stopping_ && op.Status()==AsyncStatus::Error)op.GetResults();
|
|
return !stopping_ && op.Status()==AsyncStatus::Completed;
|
|
}
|
|
static std::string utf8(winrt::hstring const& value) {return winrt::to_string(value);}
|
|
void publish(snapshot state){std::lock_guard lock(mutex_);state_=std::move(state);}
|
|
void run() {
|
|
using namespace winrt::Windows::Media::Control;
|
|
bool initialized=false;
|
|
try {
|
|
winrt::init_apartment(winrt::apartment_type::multi_threaded);initialized=true;
|
|
{
|
|
auto pending=GlobalSystemMediaTransportControlsSessionManager::RequestAsync();
|
|
if(!finish(pending))throw winrt::hresult_error(E_ABORT);
|
|
auto manager=pending.GetResults();std::string art_key;
|
|
std::shared_ptr<const artwork> cover;uint64_t art_attempt=0;
|
|
while(!stopping_) {
|
|
try {
|
|
snapshot result;result.message.clear();std::string preferred;std::deque<request> commands;
|
|
{std::lock_guard lock(mutex_);preferred=preferred_;commands.swap(commands_);}
|
|
auto sessions=manager.GetSessions();auto selected=manager.GetCurrentSession();
|
|
for(auto const& session:sessions) {
|
|
const auto app=utf8(session.SourceAppUserModelId());result.players.push_back(app);
|
|
if(!preferred.empty() && app==preferred)selected=session;
|
|
}
|
|
if(!preferred.empty() && (!selected || utf8(selected.SourceAppUserModelId())!=preferred))selected=nullptr;
|
|
if(selected) {
|
|
result.app=utf8(selected.SourceAppUserModelId());
|
|
for(auto const& command:commands) {
|
|
// A queued click must never control a different player after a session switch.
|
|
if(command.app!=result.app || stopping_)continue;
|
|
auto op=command.action==media::command::previous ? selected.TrySkipPreviousAsync() :
|
|
command.action==media::command::next ? selected.TrySkipNextAsync() : selected.TryTogglePlayPauseAsync();
|
|
if(finish(op) && !op.GetResults())result.message="Player declined that control";
|
|
}
|
|
auto properties=selected.TryGetMediaPropertiesAsync();
|
|
if(!finish(properties))throw winrt::hresult_error(E_ABORT);
|
|
auto info=properties.GetResults();
|
|
result.title=utf8(info.Title());result.artist=utf8(info.Artist());
|
|
const auto key=result.app+"\n"+result.title+"\n"+result.artist+"\n"+utf8(info.AlbumTitle());
|
|
if(key!=art_key || (!cover && GetTickCount64()-art_attempt>10000)) {
|
|
art_key=key;cover.reset();art_attempt=GetTickCount64();
|
|
try {
|
|
if(auto thumbnail=info.Thumbnail()) {
|
|
auto opening=thumbnail.OpenReadAsync();
|
|
if(finish(opening)) {
|
|
auto stream=opening.GetResults();const auto size=stream.Size();
|
|
if(size>0 && size<=4*1024*1024) {
|
|
auto data=winrt::Windows::Storage::Streams::DataReader(stream);
|
|
auto loading=data.LoadAsync(uint32_t(size));
|
|
if(finish(loading) && loading.GetResults()==size) {
|
|
std::vector<unsigned char> bytes(size);data.ReadBytes(bytes);cover=decode_art(bytes);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch(winrt::hresult_error const&) {cover.reset();}
|
|
}
|
|
result.art=cover;
|
|
auto playback=selected.GetPlaybackInfo();auto controls=playback.Controls();
|
|
result.playing=playback.PlaybackStatus()==GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing;
|
|
result.previous=controls.IsPreviousEnabled();result.next=controls.IsNextEnabled();
|
|
result.pause=controls.IsPlayPauseToggleEnabled();
|
|
if(auto rate=playback.PlaybackRate())result.rate=std::clamp(rate.Value(),0.,16.);
|
|
const auto time=selected.GetTimelineProperties();
|
|
const double start=double(time.StartTime().count())/1e7;
|
|
result.duration=(std::max)(0.,double(time.EndTime().count())/1e7-start);
|
|
result.position=std::clamp(double(time.Position().count())/1e7-start,0.,result.duration);
|
|
if(result.playing) {
|
|
const double elapsed=double((winrt::clock::now()-time.LastUpdatedTime()).count())/1e7;
|
|
if(elapsed>=0 && elapsed<86400)result.position=std::clamp(result.position+elapsed*result.rate,0.,result.duration);
|
|
}
|
|
result.available=true;result.stamp=GetTickCount64();
|
|
if(result.title.empty())result.title="Untitled track";
|
|
} else result.message=preferred.empty() ? "No active media session" : "Selected player is unavailable";
|
|
publish(std::move(result));
|
|
} catch(winrt::hresult_error const& error) {
|
|
if(!stopping_) {snapshot result;result.message="Media unavailable: "+utf8(error.message());publish(std::move(result));}
|
|
}
|
|
std::unique_lock lock(mutex_);
|
|
wake_.wait_for(lock,std::chrono::milliseconds(500),[this]{return stopping_ || !commands_.empty();});
|
|
}
|
|
}
|
|
} catch(winrt::hresult_error const& error) {
|
|
if(!stopping_){snapshot result;result.message="Windows media access unavailable: "+utf8(error.message());publish(std::move(result));}
|
|
} catch(...) {
|
|
snapshot result;result.message="Windows media access unavailable";publish(std::move(result));
|
|
}
|
|
if(initialized)winrt::uninit_apartment();
|
|
}
|
|
};
|
|
// Explicit lifetime: joining a COM worker from a DLL static destructor
|
|
// would run under the loader lock. The exported unload path owns shutdown.
|
|
inline reader* instance=nullptr;
|
|
inline reader& system(){if(!instance)instance=new reader;return *instance;}
|
|
inline void shutdown(){delete instance;instance=nullptr;}
|
|
}
|