media_audio.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "media/audio/media_audio.h"
  8. #include "media/audio/media_audio_ffmpeg_loader.h"
  9. #include "media/audio/media_child_ffmpeg_loader.h"
  10. #include "media/audio/media_audio_loaders.h"
  11. #include "media/audio/media_audio_track.h"
  12. #include "media/media_common.h"
  13. #include "media/streaming/media_streaming_utility.h"
  14. #include "webrtc/webrtc_environment.h"
  15. #include "data/data_document.h"
  16. #include "data/data_file_origin.h"
  17. #include "data/data_session.h"
  18. #include "core/application.h"
  19. #include "core/core_settings.h"
  20. #include "main/main_session.h"
  21. #include "ui/chat/attach/attach_prepare.h"
  22. #include <al.h>
  23. #include <alc.h>
  24. #include <numeric>
  25. Q_DECLARE_METATYPE(AudioMsgId);
  26. Q_DECLARE_METATYPE(VoiceWaveform);
  27. namespace {
  28. constexpr auto kSuppressRatioAll = 0.2;
  29. constexpr auto kSuppressRatioSong = 0.05;
  30. constexpr auto kWaveformCounterBufferSize = 256 * 1024;
  31. QMutex AudioMutex;
  32. ALCdevice *AudioDevice = nullptr;
  33. ALCcontext *AudioContext = nullptr;
  34. Webrtc::DeviceResolvedId AudioDeviceLastUsedId{
  35. .type = Webrtc::DeviceType::Playback
  36. };
  37. auto VolumeMultiplierAll = 1.;
  38. auto VolumeMultiplierSong = 1.;
  39. } // namespace
  40. namespace Media {
  41. namespace Audio {
  42. namespace {
  43. Player::Mixer *MixerInstance = nullptr;
  44. // Thread: Any.
  45. bool ContextErrorHappened() {
  46. ALenum errCode;
  47. if ((errCode = alcGetError(AudioDevice)) != ALC_NO_ERROR) {
  48. LOG(("Audio Context Error: %1, %2").arg(errCode).arg((const char *)alcGetString(AudioDevice, errCode)));
  49. return true;
  50. }
  51. return false;
  52. }
  53. // Thread: Any.
  54. bool PlaybackErrorHappened() {
  55. ALenum errCode;
  56. if ((errCode = alGetError()) != AL_NO_ERROR) {
  57. LOG(("Audio Playback Error: %1, %2").arg(errCode).arg((const char *)alGetString(errCode)));
  58. return true;
  59. }
  60. return false;
  61. }
  62. // Thread: Any. Must be locked: AudioMutex.
  63. void DestroyPlaybackDevice() {
  64. if (AudioContext) {
  65. alcMakeContextCurrent(nullptr);
  66. alcDestroyContext(AudioContext);
  67. AudioContext = nullptr;
  68. }
  69. if (AudioDevice) {
  70. alcCloseDevice(AudioDevice);
  71. AudioDevice = nullptr;
  72. }
  73. }
  74. // Thread: Any. Must be locked: AudioMutex.
  75. bool CreatePlaybackDevice() {
  76. if (AudioDevice) return true;
  77. AudioDeviceLastUsedId = Current().playbackDeviceId();
  78. const auto id = AudioDeviceLastUsedId.isDefault()
  79. ? std::string()
  80. : AudioDeviceLastUsedId.value.toStdString();
  81. AudioDevice = alcOpenDevice(id.empty() ? nullptr : id.c_str());
  82. if (!AudioDevice) {
  83. LOG(("Audio Error: Could not create default playback device, refreshing.."));
  84. crl::on_main([] {
  85. const auto type = Webrtc::DeviceType::Playback;
  86. Core::App().mediaDevices().forceRefresh(type);
  87. });
  88. return false;
  89. }
  90. AudioContext = alcCreateContext(AudioDevice, nullptr);
  91. alcMakeContextCurrent(AudioContext);
  92. if (ContextErrorHappened()) {
  93. DestroyPlaybackDevice();
  94. return false;
  95. }
  96. ALfloat v[] = { 0.f, 0.f, -1.f, 0.f, 1.f, 0.f };
  97. alListener3f(AL_POSITION, 0.f, 0.f, 0.f);
  98. alListener3f(AL_VELOCITY, 0.f, 0.f, 0.f);
  99. alListenerfv(AL_ORIENTATION, v);
  100. alDistanceModel(AL_NONE);
  101. return true;
  102. }
  103. // Thread: Main. Must be locked: AudioMutex.
  104. void ClosePlaybackDevice(not_null<Instance*> instance) {
  105. if (!AudioDevice) return;
  106. LOG(("Audio Info: Closing audio playback device."));
  107. if (Player::mixer()) {
  108. Player::mixer()->prepareToCloseDevice();
  109. }
  110. instance->detachTracks();
  111. DestroyPlaybackDevice();
  112. }
  113. } // namespace
  114. // Thread: Main.
  115. void Start(not_null<Instance*> instance) {
  116. Assert(AudioDevice == nullptr);
  117. qRegisterMetaType<AudioMsgId>();
  118. qRegisterMetaType<VoiceWaveform>();
  119. const auto loglevel = getenv("ALSOFT_LOGLEVEL");
  120. LOG(("OpenAL Logging Level: %1").arg(loglevel ? loglevel : "(not set)"));
  121. MixerInstance = new Player::Mixer(instance);
  122. }
  123. // Thread: Main.
  124. void Finish(not_null<Instance*> instance) {
  125. // MixerInstance variable should be modified under AudioMutex protection.
  126. // So it is modified in the ~Mixer() destructor after all tracks are cleared.
  127. delete MixerInstance;
  128. // No sync required already.
  129. ClosePlaybackDevice(instance);
  130. }
  131. // Thread: Main. Locks: AudioMutex.
  132. bool IsAttachedToDevice() {
  133. QMutexLocker lock(&AudioMutex);
  134. return (AudioDevice != nullptr);
  135. }
  136. // Thread: Any. Must be locked: AudioMutex.
  137. bool AttachToDevice() {
  138. if (AudioDevice) {
  139. return true;
  140. }
  141. LOG(("Audio Info: recreating audio device and reattaching the tracks"));
  142. CreatePlaybackDevice();
  143. if (!AudioDevice) {
  144. return false;
  145. }
  146. if (const auto m = Player::mixer()) {
  147. m->reattachTracks();
  148. m->scheduleFaderCallback();
  149. }
  150. crl::on_main([] {
  151. if (!Core::Quitting()) {
  152. Current().reattachTracks();
  153. }
  154. });
  155. return true;
  156. }
  157. void ScheduleDetachFromDeviceSafe() {
  158. crl::on_main([] {
  159. if (!Core::Quitting()) {
  160. Current().scheduleDetachFromDevice();
  161. }
  162. });
  163. }
  164. void ScheduleDetachIfNotUsedSafe() {
  165. crl::on_main([] {
  166. if (!Core::Quitting()) {
  167. Current().scheduleDetachIfNotUsed();
  168. }
  169. });
  170. }
  171. void StopDetachIfNotUsedSafe() {
  172. crl::on_main([] {
  173. if (!Core::Quitting()) {
  174. Current().stopDetachIfNotUsed();
  175. }
  176. });
  177. }
  178. bool SupportsSpeedControl() {
  179. static const auto result = [] {
  180. return avfilter_get_by_name("abuffer")
  181. && avfilter_get_by_name("abuffersink")
  182. && avfilter_get_by_name("atempo");
  183. }();
  184. return result;
  185. }
  186. } // namespace Audio
  187. namespace Player {
  188. namespace {
  189. constexpr auto kVolumeRound = 10000;
  190. constexpr auto kPreloadSeconds = 2LL; // preload next part if less than 2 seconds remains
  191. constexpr auto kFadeDuration = crl::time(500);
  192. constexpr auto kCheckPlaybackPositionTimeout = crl::time(100); // 100ms per check audio position
  193. constexpr auto kCheckPlaybackPositionDelta = 2400LL; // update position called each 2400 samples
  194. constexpr auto kCheckFadingTimeout = crl::time(7); // 7ms
  195. rpl::event_stream<AudioMsgId> UpdatedStream;
  196. } // namespace
  197. rpl::producer<AudioMsgId> Updated() {
  198. return UpdatedStream.events();
  199. }
  200. // Thread: Any. Must be locked: AudioMutex.
  201. float64 ComputeVolume(AudioMsgId::Type type) {
  202. const auto gain = [&] {
  203. switch (type) {
  204. case AudioMsgId::Type::Voice:
  205. return VolumeMultiplierAll * mixer()->getSongVolume();
  206. case AudioMsgId::Type::Song:
  207. return VolumeMultiplierSong * mixer()->getSongVolume();
  208. case AudioMsgId::Type::Video: return mixer()->getVideoVolume();
  209. }
  210. return 1.;
  211. }();
  212. return gain * gain * gain;
  213. }
  214. Mixer *mixer() {
  215. return Audio::MixerInstance;
  216. }
  217. void Mixer::Track::createStream(AudioMsgId::Type type) {
  218. alGenSources(1, &stream.source);
  219. alSourcef(stream.source, AL_PITCH, 1.f);
  220. alSource3f(stream.source, AL_POSITION, 0, 0, 0);
  221. alSource3f(stream.source, AL_VELOCITY, 0, 0, 0);
  222. alSourcei(stream.source, AL_LOOPING, 0);
  223. alSourcei(stream.source, AL_SOURCE_RELATIVE, 1);
  224. alSourcei(stream.source, AL_ROLLOFF_FACTOR, 0);
  225. if (alIsExtensionPresent("AL_SOFT_direct_channels_remix")) {
  226. alSourcei(
  227. stream.source,
  228. alGetEnumValue("AL_DIRECT_CHANNELS_SOFT"),
  229. alGetEnumValue("AL_REMIX_UNMATCHED_SOFT"));
  230. }
  231. alGenBuffers(3, stream.buffers);
  232. }
  233. void Mixer::Track::destroyStream() {
  234. if (isStreamCreated()) {
  235. alDeleteBuffers(3, stream.buffers);
  236. alDeleteSources(1, &stream.source);
  237. }
  238. stream.source = 0;
  239. for (auto i = 0; i != 3; ++i) {
  240. stream.buffers[i] = 0;
  241. }
  242. }
  243. void Mixer::Track::reattach(AudioMsgId::Type type) {
  244. if (isStreamCreated()
  245. || (!withSpeed.samples[0] && !state.id.externalPlayId())) {
  246. return;
  247. }
  248. createStream(type);
  249. for (auto i = 0; i != kBuffersCount; ++i) {
  250. if (!withSpeed.samples[i]) {
  251. break;
  252. }
  253. alBufferData(
  254. stream.buffers[i],
  255. format,
  256. withSpeed.buffered[i].constData(),
  257. withSpeed.buffered[i].size(),
  258. state.frequency);
  259. alSourceQueueBuffers(stream.source, 1, stream.buffers + i);
  260. }
  261. alSourcei(
  262. stream.source,
  263. AL_SAMPLE_OFFSET,
  264. qMax(withSpeed.position - withSpeed.bufferedPosition, 0LL));
  265. if (!IsStopped(state.state)
  266. && (state.state != State::PausedAtEnd)
  267. && !state.waitingForData) {
  268. alSourcef(stream.source, AL_GAIN, ComputeVolume(type));
  269. alSourcePlay(stream.source);
  270. if (IsPaused(state.state)) {
  271. // We must always start the source if we want the AL_SAMPLE_OFFSET to be applied.
  272. // Otherwise it won't be read by alGetSource and we'll get a corrupt position.
  273. // So in case of a paused source we start it and then immediately pause it.
  274. alSourcePause(stream.source);
  275. }
  276. }
  277. }
  278. void Mixer::Track::detach() {
  279. getNotQueuedBufferIndex();
  280. resetStream();
  281. destroyStream();
  282. }
  283. void Mixer::Track::clear() {
  284. detach();
  285. state = TrackState();
  286. file = Core::FileLocation();
  287. data = QByteArray();
  288. format = 0;
  289. loading = false;
  290. loaded = false;
  291. waitingForBuffer = false;
  292. withSpeed = WithSpeed();
  293. speed = 1.;
  294. setExternalData(nullptr);
  295. lastUpdateWhen = 0;
  296. lastUpdatePosition = 0;
  297. }
  298. void Mixer::Track::started() {
  299. resetStream();
  300. format = 0;
  301. loaded = false;
  302. withSpeed = WithSpeed();
  303. }
  304. bool Mixer::Track::isStreamCreated() const {
  305. return alIsSource(stream.source);
  306. }
  307. void Mixer::Track::ensureStreamCreated(AudioMsgId::Type type) {
  308. if (!isStreamCreated()) {
  309. createStream(type);
  310. }
  311. }
  312. int Mixer::Track::getNotQueuedBufferIndex() {
  313. // See if there are no free buffers right now.
  314. while (withSpeed.samples[kBuffersCount - 1] != 0) {
  315. // Try to unqueue some buffer.
  316. ALint processed = 0;
  317. alGetSourcei(stream.source, AL_BUFFERS_PROCESSED, &processed);
  318. if (processed < 1) { // No processed buffers, wait.
  319. return -1;
  320. }
  321. // Unqueue some processed buffer.
  322. ALuint buffer = 0;
  323. alSourceUnqueueBuffers(stream.source, 1, &buffer);
  324. // Find it in the list and clear it.
  325. bool found = false;
  326. for (auto i = 0; i != kBuffersCount; ++i) {
  327. if (stream.buffers[i] == buffer) {
  328. const auto samplesInBuffer = withSpeed.samples[i];
  329. withSpeed.bufferedPosition += samplesInBuffer;
  330. withSpeed.bufferedLength -= samplesInBuffer;
  331. for (auto j = i + 1; j != kBuffersCount; ++j) {
  332. withSpeed.samples[j - 1] = withSpeed.samples[j];
  333. stream.buffers[j - 1] = stream.buffers[j];
  334. withSpeed.buffered[j - 1] = withSpeed.buffered[j];
  335. }
  336. withSpeed.samples[kBuffersCount - 1] = 0;
  337. stream.buffers[kBuffersCount - 1] = buffer;
  338. withSpeed.buffered[kBuffersCount - 1] = QByteArray();
  339. found = true;
  340. break;
  341. }
  342. }
  343. if (!found) {
  344. LOG(("Audio Error: Could not find the unqueued buffer! Buffer %1 in source %2 with processed count %3").arg(buffer).arg(stream.source).arg(processed));
  345. return -1;
  346. }
  347. }
  348. for (auto i = 0; i != kBuffersCount; ++i) {
  349. if (!withSpeed.samples[i]) {
  350. return i;
  351. }
  352. }
  353. return -1;
  354. }
  355. void Mixer::Track::setExternalData(
  356. std::unique_ptr<ExternalSoundData> data) {
  357. nextSpeed = speed = data ? data->speed : 1.;
  358. externalData = std::move(data);
  359. }
  360. void Mixer::Track::updateStatePosition() {
  361. state.position = SpeedIndependentPosition(withSpeed.position, speed);
  362. }
  363. void Mixer::Track::updateWithSpeedPosition() {
  364. withSpeed.position = SpeedDependentPosition(state.position, speed);
  365. withSpeed.fineTunedPosition = withSpeed.position;
  366. }
  367. int64 Mixer::Track::SpeedIndependentPosition(
  368. int64 position,
  369. float64 speed) {
  370. Expects(speed <= kSpeedMax);
  371. return int64(base::SafeRound(position * speed));
  372. }
  373. int64 Mixer::Track::SpeedDependentPosition(
  374. int64 position,
  375. float64 speed) {
  376. Expects(speed >= kSpeedMin);
  377. return int64(base::SafeRound(position / speed));
  378. }
  379. void Mixer::Track::resetStream() {
  380. if (isStreamCreated()) {
  381. alSourceStop(stream.source);
  382. alSourcei(stream.source, AL_BUFFER, AL_NONE);
  383. }
  384. }
  385. Mixer::Track::~Track() = default;
  386. Mixer::Mixer(not_null<Audio::Instance*> instance)
  387. : _instance(instance)
  388. , _volumeVideo(kVolumeRound)
  389. , _volumeSong(kVolumeRound)
  390. , _fader(new Fader(&_faderThread))
  391. , _loader(new Loaders(&_loaderThread)) {
  392. connect(this, SIGNAL(suppressSong()), _fader, SLOT(onSuppressSong()));
  393. connect(this, SIGNAL(unsuppressSong()), _fader, SLOT(onUnsuppressSong()));
  394. connect(this, SIGNAL(suppressAll(qint64)), _fader, SLOT(onSuppressAll(qint64)));
  395. Core::App().settings().songVolumeChanges(
  396. ) | rpl::start_with_next([=] {
  397. InvokeQueued(_fader, [fader = _fader] {
  398. fader->songVolumeChanged();
  399. });
  400. }, _lifetime);
  401. Core::App().settings().videoVolumeChanges(
  402. ) | rpl::start_with_next([=] {
  403. InvokeQueued(_fader, [fader = _fader] {
  404. fader->videoVolumeChanged();
  405. });
  406. }, _lifetime);
  407. connect(this, SIGNAL(loaderOnStart(AudioMsgId,qint64)), _loader, SLOT(onStart(AudioMsgId,qint64)));
  408. connect(this, SIGNAL(loaderOnCancel(AudioMsgId)), _loader, SLOT(onCancel(AudioMsgId)), Qt::QueuedConnection);
  409. connect(_loader, SIGNAL(needToCheck()), _fader, SLOT(onTimer()));
  410. connect(_loader, SIGNAL(error(AudioMsgId)), this, SLOT(onError(AudioMsgId)));
  411. connect(_fader, SIGNAL(needToPreload(AudioMsgId)), _loader, SLOT(onLoad(AudioMsgId)));
  412. connect(_fader, SIGNAL(playPositionUpdated(AudioMsgId)), this, SIGNAL(updated(AudioMsgId)));
  413. connect(_fader, SIGNAL(audioStopped(AudioMsgId)), this, SLOT(onStopped(AudioMsgId)));
  414. connect(_fader, SIGNAL(error(AudioMsgId)), this, SLOT(onError(AudioMsgId)));
  415. connect(this, SIGNAL(stoppedOnError(AudioMsgId)), this, SIGNAL(updated(AudioMsgId)), Qt::QueuedConnection);
  416. connect(this, SIGNAL(updated(AudioMsgId)), this, SLOT(onUpdated(AudioMsgId)));
  417. _loaderThread.start();
  418. _faderThread.start();
  419. }
  420. // Thread: Main. Locks: AudioMutex.
  421. Mixer::~Mixer() {
  422. {
  423. QMutexLocker lock(&AudioMutex);
  424. for (auto i = 0; i != kTogetherLimit; ++i) {
  425. trackForType(AudioMsgId::Type::Voice, i)->clear();
  426. trackForType(AudioMsgId::Type::Song, i)->clear();
  427. }
  428. _videoTrack.clear();
  429. Audio::ClosePlaybackDevice(_instance);
  430. Audio::MixerInstance = nullptr;
  431. }
  432. _faderThread.quit();
  433. _loaderThread.quit();
  434. _faderThread.wait();
  435. _loaderThread.wait();
  436. }
  437. void Mixer::scheduleFaderCallback() {
  438. InvokeQueued(_fader, [fader = _fader] {
  439. fader->onTimer();
  440. });
  441. }
  442. void Mixer::onUpdated(const AudioMsgId &audio) {
  443. if (audio.externalPlayId()) {
  444. externalSoundProgress(audio);
  445. }
  446. crl::on_main([=] {
  447. // We've replaced base::Observable with on_main, because
  448. // base::Observable::notify is not syncronous by default.
  449. UpdatedStream.fire_copy(audio);
  450. });
  451. }
  452. void Mixer::onError(const AudioMsgId &audio) {
  453. stoppedOnError(audio);
  454. QMutexLocker lock(&AudioMutex);
  455. auto type = audio.type();
  456. if (type == AudioMsgId::Type::Voice) {
  457. if (auto current = trackForType(type)) {
  458. if (current->state.id == audio) {
  459. unsuppressSong();
  460. }
  461. }
  462. }
  463. }
  464. void Mixer::onStopped(const AudioMsgId &audio) {
  465. updated(audio);
  466. QMutexLocker lock(&AudioMutex);
  467. auto type = audio.type();
  468. if (type == AudioMsgId::Type::Voice) {
  469. if (auto current = trackForType(type)) {
  470. if (current->state.id == audio) {
  471. unsuppressSong();
  472. }
  473. }
  474. }
  475. }
  476. Mixer::Track *Mixer::trackForType(AudioMsgId::Type type, int index) {
  477. if (index < 0) {
  478. if (auto indexPtr = currentIndex(type)) {
  479. index = *indexPtr;
  480. } else {
  481. return nullptr;
  482. }
  483. }
  484. switch (type) {
  485. case AudioMsgId::Type::Voice: return &_audioTracks[index];
  486. case AudioMsgId::Type::Song: return &_songTracks[index];
  487. case AudioMsgId::Type::Video: return &_videoTrack;
  488. }
  489. return nullptr;
  490. }
  491. const Mixer::Track *Mixer::trackForType(AudioMsgId::Type type, int index) const {
  492. return const_cast<Mixer*>(this)->trackForType(type, index);
  493. }
  494. int *Mixer::currentIndex(AudioMsgId::Type type) {
  495. switch (type) {
  496. case AudioMsgId::Type::Voice: return &_audioCurrent;
  497. case AudioMsgId::Type::Song: return &_songCurrent;
  498. case AudioMsgId::Type::Video: { static int videoIndex = 0; return &videoIndex; }
  499. }
  500. return nullptr;
  501. }
  502. const int *Mixer::currentIndex(AudioMsgId::Type type) const {
  503. return const_cast<Mixer*>(this)->currentIndex(type);
  504. }
  505. void Mixer::resetFadeStartPosition(AudioMsgId::Type type, int positionInBuffered) {
  506. auto track = trackForType(type);
  507. if (!track) return;
  508. if (positionInBuffered < 0) {
  509. Audio::AttachToDevice();
  510. if (track->isStreamCreated()) {
  511. ALint alSampleOffset = 0;
  512. ALint alState = AL_INITIAL;
  513. alGetSourcei(track->stream.source, AL_SAMPLE_OFFSET, &alSampleOffset);
  514. alGetSourcei(track->stream.source, AL_SOURCE_STATE, &alState);
  515. if (Audio::PlaybackErrorHappened()) {
  516. setStoppedState(track, State::StoppedAtError);
  517. onError(track->state.id);
  518. return;
  519. } else if ((alState == AL_STOPPED)
  520. && (alSampleOffset == 0)
  521. && !internal::CheckAudioDeviceConnected()) {
  522. track->withSpeed.fadeStartPosition = track->withSpeed.position;
  523. return;
  524. }
  525. const auto stoppedAtEnd = track->state.waitingForData
  526. || ((alState == AL_STOPPED)
  527. && (!IsStopped(track->state.state)
  528. || IsStoppedAtEnd(track->state.state)));
  529. positionInBuffered = stoppedAtEnd
  530. ? track->withSpeed.bufferedLength
  531. : alSampleOffset;
  532. } else {
  533. positionInBuffered = 0;
  534. }
  535. }
  536. const auto withSpeedPosition = track->withSpeed.samples[0]
  537. ? (track->withSpeed.bufferedPosition + positionInBuffered)
  538. : track->withSpeed.position;
  539. track->withSpeed.fineTunedPosition = withSpeedPosition;
  540. track->withSpeed.position = withSpeedPosition;
  541. track->withSpeed.fadeStartPosition = withSpeedPosition;
  542. track->updateStatePosition();
  543. }
  544. bool Mixer::fadedStop(AudioMsgId::Type type, bool *fadedStart) {
  545. auto current = trackForType(type);
  546. if (!current) return false;
  547. switch (current->state.state) {
  548. case State::Starting:
  549. case State::Resuming:
  550. case State::Playing: {
  551. current->state.state = State::Stopping;
  552. resetFadeStartPosition(type);
  553. if (fadedStart) *fadedStart = true;
  554. } break;
  555. case State::Pausing: {
  556. current->state.state = State::Stopping;
  557. if (fadedStart) *fadedStart = true;
  558. } break;
  559. case State::Paused:
  560. case State::PausedAtEnd: {
  561. setStoppedState(current);
  562. } return true;
  563. }
  564. return false;
  565. }
  566. void Mixer::play(
  567. const AudioMsgId &audio,
  568. std::unique_ptr<ExternalSoundData> externalData,
  569. crl::time positionMs) {
  570. Expects(externalData != nullptr);
  571. Expects(audio.externalPlayId() != 0);
  572. setSongVolume(Core::App().settings().songVolume());
  573. setVideoVolume(Core::App().settings().videoVolume());
  574. auto type = audio.type();
  575. AudioMsgId stopped;
  576. {
  577. QMutexLocker lock(&AudioMutex);
  578. Audio::AttachToDevice();
  579. if (!AudioDevice) return;
  580. auto fadedStart = false;
  581. auto current = trackForType(type);
  582. if (!current) return;
  583. if (current->state.id != audio) {
  584. if (fadedStop(type, &fadedStart)) {
  585. stopped = current->state.id;
  586. }
  587. if (current->state.id) {
  588. loaderOnCancel(current->state.id);
  589. scheduleFaderCallback();
  590. }
  591. if (type != AudioMsgId::Type::Video) {
  592. auto foundCurrent = currentIndex(type);
  593. auto index = 0;
  594. for (; index != kTogetherLimit; ++index) {
  595. if (trackForType(type, index)->state.id == audio) {
  596. *foundCurrent = index;
  597. break;
  598. }
  599. }
  600. if (index == kTogetherLimit && ++*foundCurrent >= kTogetherLimit) {
  601. *foundCurrent -= kTogetherLimit;
  602. }
  603. current = trackForType(type);
  604. }
  605. }
  606. current->clear(); // Clear all previous state.
  607. current->state.id = audio;
  608. current->lastUpdateWhen = 0;
  609. current->lastUpdatePosition = 0;
  610. current->setExternalData(std::move(externalData));
  611. current->state.position = (positionMs * current->state.frequency)
  612. / 1000LL;
  613. current->updateWithSpeedPosition();
  614. current->state.state = current->externalData
  615. ? State::Paused
  616. : fadedStart
  617. ? State::Starting
  618. : State::Playing;
  619. current->loading = true;
  620. loaderOnStart(current->state.id, positionMs);
  621. if (type == AudioMsgId::Type::Voice) {
  622. suppressSong();
  623. }
  624. }
  625. if (stopped) {
  626. updated(stopped);
  627. }
  628. }
  629. void Mixer::feedFromExternal(ExternalSoundPart &&part) {
  630. _loader->feedFromExternal(std::move(part));
  631. }
  632. void Mixer::forceToBufferExternal(const AudioMsgId &audioId) {
  633. _loader->forceToBufferExternal(audioId);
  634. }
  635. // Thread: Main. Locks: AudioMutex.
  636. void Mixer::setSpeedFromExternal(const AudioMsgId &audioId, float64 speed) {
  637. QMutexLocker lock(&AudioMutex);
  638. const auto track = trackForType(audioId.type());
  639. if (track->state.id == audioId) {
  640. track->nextSpeed = speed;
  641. if (!EqualSpeeds(track->speed, track->nextSpeed)
  642. && !IsStoppedOrStopping(track->state.state)) {
  643. track->loading = true;
  644. track->loaded = false;
  645. InvokeQueued(_loader, [loader = _loader, id = audioId] {
  646. loader->onLoad(id);
  647. });
  648. }
  649. }
  650. }
  651. Streaming::TimePoint Mixer::getExternalSyncTimePoint(
  652. const AudioMsgId &audio) const {
  653. Expects(audio.externalPlayId() != 0);
  654. auto result = Streaming::TimePoint();
  655. const auto type = audio.type();
  656. QMutexLocker lock(&AudioMutex);
  657. const auto track = trackForType(type);
  658. if (track && track->state.id == audio && track->lastUpdateWhen > 0) {
  659. result.trackTime = track->lastUpdatePosition;
  660. result.worldTime = track->lastUpdateWhen;
  661. }
  662. return result;
  663. }
  664. crl::time Mixer::getExternalCorrectedTime(const AudioMsgId &audio, crl::time frameMs, crl::time systemMs) {
  665. auto result = frameMs;
  666. const auto type = audio.type();
  667. QMutexLocker lock(&AudioMutex);
  668. const auto track = trackForType(type);
  669. if (track && track->state.id == audio && track->lastUpdateWhen > 0) {
  670. result = static_cast<crl::time>(track->lastUpdatePosition);
  671. if (systemMs > track->lastUpdateWhen) {
  672. result += (systemMs - track->lastUpdateWhen);
  673. }
  674. }
  675. return result;
  676. }
  677. void Mixer::externalSoundProgress(const AudioMsgId &audio) {
  678. const auto type = audio.type();
  679. QMutexLocker lock(&AudioMutex);
  680. const auto current = trackForType(type);
  681. if (current && current->state.length && current->state.frequency) {
  682. if (current->state.id == audio
  683. && current->state.state == State::Playing) {
  684. current->lastUpdateWhen = crl::now();
  685. current->lastUpdatePosition = (current->state.position * 1000LL)
  686. / current->state.frequency;
  687. }
  688. }
  689. }
  690. bool Mixer::checkCurrentALError(AudioMsgId::Type type) {
  691. if (!Audio::PlaybackErrorHappened()) {
  692. return true;
  693. } else if (const auto data = trackForType(type)) {
  694. setStoppedState(data, State::StoppedAtError);
  695. onError(data->state.id);
  696. }
  697. return false;
  698. }
  699. void Mixer::pause(const AudioMsgId &audio, bool fast) {
  700. AudioMsgId current;
  701. {
  702. QMutexLocker lock(&AudioMutex);
  703. auto type = audio.type();
  704. auto track = trackForType(type);
  705. if (!track || track->state.id != audio) {
  706. return;
  707. }
  708. current = track->state.id;
  709. switch (track->state.state) {
  710. case State::Starting:
  711. case State::Resuming:
  712. case State::Playing: {
  713. track->state.state = fast ? State::Paused : State::Pausing;
  714. resetFadeStartPosition(type);
  715. if (type == AudioMsgId::Type::Voice) {
  716. unsuppressSong();
  717. }
  718. } break;
  719. case State::Pausing:
  720. case State::Stopping: {
  721. track->state.state = fast ? State::Paused : State::Pausing;
  722. } break;
  723. }
  724. if (fast && track->isStreamCreated()) {
  725. ALint state = AL_INITIAL;
  726. alGetSourcei(track->stream.source, AL_SOURCE_STATE, &state);
  727. if (!checkCurrentALError(type)) return;
  728. if (state == AL_PLAYING) {
  729. alSourcePause(track->stream.source);
  730. if (!checkCurrentALError(type)) return;
  731. }
  732. }
  733. scheduleFaderCallback();
  734. track->lastUpdateWhen = 0;
  735. track->lastUpdatePosition = 0;
  736. }
  737. if (current) updated(current);
  738. }
  739. void Mixer::resume(const AudioMsgId &audio, bool fast) {
  740. AudioMsgId current;
  741. {
  742. QMutexLocker lock(&AudioMutex);
  743. auto type = audio.type();
  744. auto track = trackForType(type);
  745. if (!track || track->state.id != audio) {
  746. return;
  747. }
  748. current = track->state.id;
  749. switch (track->state.state) {
  750. case State::Pausing:
  751. case State::Paused:
  752. case State::PausedAtEnd: {
  753. if (track->state.state == State::Paused) {
  754. // This calls Audio::AttachToDevice().
  755. resetFadeStartPosition(type);
  756. } else {
  757. Audio::AttachToDevice();
  758. }
  759. track->state.state = fast ? State::Playing : State::Resuming;
  760. if (track->isStreamCreated()) {
  761. // When starting the video audio is in paused state and
  762. // gets resumed before the stream is created with any data.
  763. ALint state = AL_INITIAL;
  764. alGetSourcei(track->stream.source, AL_SOURCE_STATE, &state);
  765. if (!checkCurrentALError(type)) return;
  766. if (state != AL_PLAYING) {
  767. if (state == AL_STOPPED && !internal::CheckAudioDeviceConnected()) {
  768. return;
  769. }
  770. alSourcef(track->stream.source, AL_GAIN, ComputeVolume(type));
  771. if (!checkCurrentALError(type)) return;
  772. if (state == AL_STOPPED) {
  773. alSourcei(
  774. track->stream.source,
  775. AL_SAMPLE_OFFSET,
  776. qMax(track->withSpeed.position - track->withSpeed.bufferedPosition, 0LL));
  777. if (!checkCurrentALError(type)) return;
  778. }
  779. alSourcePlay(track->stream.source);
  780. if (!checkCurrentALError(type)) return;
  781. }
  782. if (type == AudioMsgId::Type::Voice) {
  783. suppressSong();
  784. }
  785. }
  786. } break;
  787. }
  788. scheduleFaderCallback();
  789. }
  790. if (current) updated(current);
  791. }
  792. void Mixer::stop(const AudioMsgId &audio) {
  793. AudioMsgId current;
  794. {
  795. QMutexLocker lock(&AudioMutex);
  796. auto type = audio.type();
  797. auto track = trackForType(type);
  798. if (!track || track->state.id != audio) {
  799. return;
  800. }
  801. current = audio;
  802. fadedStop(type);
  803. if (type == AudioMsgId::Type::Voice) {
  804. unsuppressSong();
  805. } else if (type == AudioMsgId::Type::Video) {
  806. track->clear();
  807. loaderOnCancel(audio);
  808. }
  809. }
  810. if (current) updated(current);
  811. }
  812. void Mixer::stop(const AudioMsgId &audio, State state) {
  813. Expects(IsStopped(state));
  814. AudioMsgId current;
  815. {
  816. QMutexLocker lock(&AudioMutex);
  817. auto type = audio.type();
  818. auto track = trackForType(type);
  819. if (!track
  820. || track->state.id != audio
  821. || IsStopped(track->state.state)) {
  822. return;
  823. }
  824. current = audio;
  825. setStoppedState(track, state);
  826. if (type == AudioMsgId::Type::Voice) {
  827. unsuppressSong();
  828. } else if (type == AudioMsgId::Type::Video) {
  829. track->clear();
  830. }
  831. }
  832. if (current) updated(current);
  833. }
  834. void Mixer::stopAndClear() {
  835. Track *current_audio = nullptr, *current_song = nullptr;
  836. {
  837. QMutexLocker lock(&AudioMutex);
  838. if ((current_audio = trackForType(AudioMsgId::Type::Voice))) {
  839. setStoppedState(current_audio);
  840. }
  841. if ((current_song = trackForType(AudioMsgId::Type::Song))) {
  842. setStoppedState(current_song);
  843. }
  844. }
  845. if (current_song) {
  846. updated(current_song->state.id);
  847. }
  848. if (current_audio) {
  849. updated(current_audio->state.id);
  850. }
  851. {
  852. QMutexLocker lock(&AudioMutex);
  853. auto clearAndCancel = [this](AudioMsgId::Type type, int index) {
  854. auto track = trackForType(type, index);
  855. if (track->state.id) {
  856. loaderOnCancel(track->state.id);
  857. }
  858. track->clear();
  859. };
  860. for (auto index = 0; index != kTogetherLimit; ++index) {
  861. clearAndCancel(AudioMsgId::Type::Voice, index);
  862. clearAndCancel(AudioMsgId::Type::Song, index);
  863. }
  864. _videoTrack.clear();
  865. }
  866. }
  867. TrackState Mixer::currentState(AudioMsgId::Type type) {
  868. QMutexLocker lock(&AudioMutex);
  869. auto current = trackForType(type);
  870. if (!current) {
  871. return TrackState();
  872. }
  873. return current->state;
  874. }
  875. void Mixer::setStoppedState(Track *current, State state) {
  876. current->state.state = state;
  877. current->state.position = 0;
  878. current->withSpeed.position = 0;
  879. current->withSpeed.fineTunedPosition = 0;
  880. if (current->isStreamCreated()) {
  881. alSourceStop(current->stream.source);
  882. alSourcef(current->stream.source, AL_GAIN, 1);
  883. }
  884. if (current->state.id) {
  885. loaderOnCancel(current->state.id);
  886. }
  887. }
  888. // Thread: Main. Must be locked: AudioMutex.
  889. void Mixer::prepareToCloseDevice() {
  890. for (auto i = 0; i != kTogetherLimit; ++i) {
  891. trackForType(AudioMsgId::Type::Voice, i)->detach();
  892. trackForType(AudioMsgId::Type::Song, i)->detach();
  893. }
  894. _videoTrack.detach();
  895. }
  896. // Thread: Main. Must be locked: AudioMutex.
  897. void Mixer::reattachIfNeeded() {
  898. Audio::Current().stopDetachIfNotUsed();
  899. auto reattachNeeded = [this] {
  900. auto isPlayingState = [](const Track &track) {
  901. auto state = track.state.state;
  902. return (state == State::Playing) || IsFading(state);
  903. };
  904. for (auto i = 0; i != kTogetherLimit; ++i) {
  905. if (isPlayingState(*trackForType(AudioMsgId::Type::Voice, i))
  906. || isPlayingState(*trackForType(AudioMsgId::Type::Song, i))) {
  907. return true;
  908. }
  909. }
  910. return isPlayingState(_videoTrack);
  911. };
  912. if (reattachNeeded() || Audio::Current().hasActiveTracks()) {
  913. Audio::AttachToDevice();
  914. }
  915. }
  916. // Thread: Any. Must be locked: AudioMutex.
  917. void Mixer::reattachTracks() {
  918. for (auto i = 0; i != kTogetherLimit; ++i) {
  919. trackForType(AudioMsgId::Type::Voice, i)->reattach(AudioMsgId::Type::Voice);
  920. trackForType(AudioMsgId::Type::Song, i)->reattach(AudioMsgId::Type::Song);
  921. }
  922. _videoTrack.reattach(AudioMsgId::Type::Video);
  923. }
  924. void Mixer::setSongVolume(float64 volume) {
  925. _volumeSong.storeRelease(qRound(volume * kVolumeRound));
  926. }
  927. float64 Mixer::getSongVolume() const {
  928. return float64(_volumeSong.loadAcquire()) / kVolumeRound;
  929. }
  930. void Mixer::setVideoVolume(float64 volume) {
  931. _volumeVideo.storeRelease(qRound(volume * kVolumeRound));
  932. }
  933. float64 Mixer::getVideoVolume() const {
  934. return float64(_volumeVideo.loadAcquire()) / kVolumeRound;
  935. }
  936. Fader::Fader(QThread *thread) : QObject()
  937. , _timer(this)
  938. , _suppressVolumeAll(1., 1.)
  939. , _suppressVolumeSong(1., 1.) {
  940. moveToThread(thread);
  941. _timer.moveToThread(thread);
  942. connect(thread, SIGNAL(started()), this, SLOT(onInit()));
  943. connect(thread, SIGNAL(finished()), this, SLOT(deleteLater()));
  944. _timer.setSingleShot(true);
  945. connect(&_timer, SIGNAL(timeout()), this, SLOT(onTimer()));
  946. }
  947. void Fader::onInit() {
  948. }
  949. void Fader::onTimer() {
  950. QMutexLocker lock(&AudioMutex);
  951. if (!mixer()) return;
  952. constexpr auto kMediaPlayerSuppressDuration = crl::time(150);
  953. auto volumeChangedAll = false;
  954. auto volumeChangedSong = false;
  955. if (_suppressAll || _suppressSongAnim) {
  956. auto ms = crl::now();
  957. if (_suppressAll) {
  958. if (ms >= _suppressAllEnd || ms < _suppressAllStart) {
  959. _suppressAll = _suppressAllAnim = false;
  960. _suppressVolumeAll = anim::value(1., 1.);
  961. } else if (ms > _suppressAllEnd - kFadeDuration) {
  962. if (_suppressVolumeAll.to() != 1.) _suppressVolumeAll.start(1.);
  963. _suppressVolumeAll.update(1. - ((_suppressAllEnd - ms) / float64(kFadeDuration)), anim::linear);
  964. } else if (ms >= _suppressAllStart + kMediaPlayerSuppressDuration) {
  965. if (_suppressAllAnim) {
  966. _suppressVolumeAll.finish();
  967. _suppressAllAnim = false;
  968. }
  969. } else if (ms > _suppressAllStart) {
  970. _suppressVolumeAll.update((ms - _suppressAllStart) / float64(kMediaPlayerSuppressDuration), anim::linear);
  971. }
  972. auto wasVolumeMultiplierAll = VolumeMultiplierAll;
  973. VolumeMultiplierAll = _suppressVolumeAll.current();
  974. volumeChangedAll = (VolumeMultiplierAll != wasVolumeMultiplierAll);
  975. }
  976. if (_suppressSongAnim) {
  977. if (ms >= _suppressSongStart + kFadeDuration) {
  978. _suppressVolumeSong.finish();
  979. _suppressSongAnim = false;
  980. } else {
  981. _suppressVolumeSong.update((ms - _suppressSongStart) / float64(kFadeDuration), anim::linear);
  982. }
  983. }
  984. auto wasVolumeMultiplierSong = VolumeMultiplierSong;
  985. VolumeMultiplierSong = _suppressVolumeSong.current();
  986. accumulate_min(VolumeMultiplierSong, VolumeMultiplierAll);
  987. volumeChangedSong = (VolumeMultiplierSong != wasVolumeMultiplierSong);
  988. }
  989. auto hasFading = (_suppressAll || _suppressSongAnim);
  990. auto hasPlaying = false;
  991. auto updatePlayback = [this, &hasPlaying, &hasFading](AudioMsgId::Type type, int index, float64 volumeMultiplier, bool suppressGainChanged) {
  992. auto track = mixer()->trackForType(type, index);
  993. if (IsStopped(track->state.state) || track->state.state == State::Paused || !track->isStreamCreated()) return;
  994. auto emitSignals = updateOnePlayback(track, hasPlaying, hasFading, volumeMultiplier, suppressGainChanged);
  995. if (emitSignals & EmitError) error(track->state.id);
  996. if (emitSignals & EmitStopped) audioStopped(track->state.id);
  997. if (emitSignals & EmitPositionUpdated) playPositionUpdated(track->state.id);
  998. if (emitSignals & EmitNeedToPreload) needToPreload(track->state.id);
  999. };
  1000. auto suppressGainForMusic = ComputeVolume(AudioMsgId::Type::Song);
  1001. auto suppressGainForMusicChanged = volumeChangedSong || _volumeChangedSong;
  1002. auto suppressGainForVoice = ComputeVolume(AudioMsgId::Type::Voice);
  1003. for (auto i = 0; i != kTogetherLimit; ++i) {
  1004. updatePlayback(AudioMsgId::Type::Voice, i, suppressGainForVoice, suppressGainForMusicChanged);
  1005. updatePlayback(AudioMsgId::Type::Song, i, suppressGainForMusic, suppressGainForMusicChanged);
  1006. }
  1007. auto suppressGainForVideo = ComputeVolume(AudioMsgId::Type::Video);
  1008. auto suppressGainForVideoChanged = volumeChangedAll || _volumeChangedVideo;
  1009. updatePlayback(AudioMsgId::Type::Video, 0, suppressGainForVideo, suppressGainForVideoChanged);
  1010. _volumeChangedSong = _volumeChangedVideo = false;
  1011. if (hasFading) {
  1012. _timer.start(kCheckFadingTimeout);
  1013. Audio::StopDetachIfNotUsedSafe();
  1014. } else if (hasPlaying) {
  1015. _timer.start(kCheckPlaybackPositionTimeout);
  1016. Audio::StopDetachIfNotUsedSafe();
  1017. } else {
  1018. Audio::ScheduleDetachIfNotUsedSafe();
  1019. }
  1020. }
  1021. int32 Fader::updateOnePlayback(Mixer::Track *track, bool &hasPlaying, bool &hasFading, float64 volumeMultiplier, bool volumeChanged) {
  1022. const auto errorHappened = [&] {
  1023. if (Audio::PlaybackErrorHappened()) {
  1024. setStoppedState(track, State::StoppedAtError);
  1025. return true;
  1026. }
  1027. return false;
  1028. };
  1029. ALint alSampleOffset = 0;
  1030. ALint alState = AL_INITIAL;
  1031. alGetSourcei(track->stream.source, AL_SAMPLE_OFFSET, &alSampleOffset);
  1032. alGetSourcei(track->stream.source, AL_SOURCE_STATE, &alState);
  1033. if (errorHappened()) {
  1034. return EmitError;
  1035. } else if ((alState == AL_STOPPED)
  1036. && (alSampleOffset == 0)
  1037. && !internal::CheckAudioDeviceConnected()) {
  1038. return 0;
  1039. }
  1040. int32 emitSignals = 0;
  1041. const auto stoppedAtEnd = track->state.waitingForData
  1042. || ((alState == AL_STOPPED)
  1043. && (!IsStopped(track->state.state)
  1044. || IsStoppedAtEnd(track->state.state)));
  1045. const auto positionInBuffered = stoppedAtEnd
  1046. ? track->withSpeed.bufferedLength
  1047. : alSampleOffset;
  1048. const auto waitingForDataOld = track->state.waitingForData;
  1049. track->state.waitingForData = stoppedAtEnd
  1050. && (track->state.state != State::Stopping);
  1051. const auto withSpeedPosition = track->withSpeed.bufferedPosition
  1052. + positionInBuffered;
  1053. auto playing = (track->state.state == State::Playing);
  1054. auto fading = IsFading(track->state.state);
  1055. if (alState != AL_PLAYING && !track->loading) {
  1056. if (fading || playing) {
  1057. fading = false;
  1058. playing = false;
  1059. if (track->state.state == State::Pausing) {
  1060. setStoppedState(track, State::PausedAtEnd);
  1061. } else if (track->state.state == State::Stopping) {
  1062. setStoppedState(track, State::Stopped);
  1063. } else {
  1064. setStoppedState(track, State::StoppedAtEnd);
  1065. }
  1066. if (errorHappened()) return EmitError;
  1067. emitSignals |= EmitStopped;
  1068. }
  1069. } else if (fading && alState == AL_PLAYING) {
  1070. const auto fadingForSamplesCount = withSpeedPosition
  1071. - track->withSpeed.fadeStartPosition;
  1072. if (crl::time(1000) * fadingForSamplesCount >= kFadeDuration * track->state.frequency) {
  1073. fading = false;
  1074. alSourcef(track->stream.source, AL_GAIN, 1. * volumeMultiplier);
  1075. if (errorHappened()) return EmitError;
  1076. switch (track->state.state) {
  1077. case State::Stopping: {
  1078. setStoppedState(track);
  1079. alState = AL_STOPPED;
  1080. } break;
  1081. case State::Pausing: {
  1082. alSourcePause(track->stream.source);
  1083. if (errorHappened()) return EmitError;
  1084. track->state.state = State::Paused;
  1085. } break;
  1086. case State::Starting:
  1087. case State::Resuming: {
  1088. track->state.state = State::Playing;
  1089. playing = true;
  1090. } break;
  1091. }
  1092. } else {
  1093. auto newGain = crl::time(1000) * fadingForSamplesCount / float64(kFadeDuration * track->state.frequency);
  1094. if (track->state.state == State::Pausing || track->state.state == State::Stopping) {
  1095. newGain = 1. - newGain;
  1096. }
  1097. alSourcef(track->stream.source, AL_GAIN, newGain * volumeMultiplier);
  1098. if (errorHappened()) return EmitError;
  1099. }
  1100. } else if (playing && alState == AL_PLAYING) {
  1101. if (volumeChanged) {
  1102. alSourcef(track->stream.source, AL_GAIN, 1. * volumeMultiplier);
  1103. if (errorHappened()) return EmitError;
  1104. }
  1105. }
  1106. track->withSpeed.fineTunedPosition = withSpeedPosition;
  1107. if (alState == AL_PLAYING && withSpeedPosition >= track->withSpeed.position + kCheckPlaybackPositionDelta) {
  1108. track->withSpeed.position = withSpeedPosition;
  1109. track->updateStatePosition();
  1110. emitSignals |= EmitPositionUpdated;
  1111. } else if (track->state.waitingForData && !waitingForDataOld) {
  1112. if (withSpeedPosition > track->withSpeed.position) {
  1113. track->withSpeed.position = withSpeedPosition;
  1114. }
  1115. // When stopped because of insufficient data while streaming,
  1116. // inform the player about the last position we were at.
  1117. emitSignals |= EmitPositionUpdated;
  1118. }
  1119. if (playing || track->state.state == State::Starting || track->state.state == State::Resuming) {
  1120. if ((!track->loaded && !track->loading) || track->waitingForBuffer) {
  1121. auto needPreload = (track->withSpeed.position + kPreloadSeconds * track->state.frequency > track->withSpeed.bufferedPosition + track->withSpeed.bufferedLength);
  1122. if (needPreload) {
  1123. track->loading = true;
  1124. emitSignals |= EmitNeedToPreload;
  1125. }
  1126. }
  1127. }
  1128. if (playing) hasPlaying = true;
  1129. if (fading) hasFading = true;
  1130. return emitSignals;
  1131. }
  1132. void Fader::setStoppedState(Mixer::Track *track, State state) {
  1133. mixer()->setStoppedState(track, state);
  1134. }
  1135. void Fader::onSuppressSong() {
  1136. if (!_suppressSong) {
  1137. _suppressSong = true;
  1138. _suppressSongAnim = true;
  1139. _suppressSongStart = crl::now();
  1140. _suppressVolumeSong.start(kSuppressRatioSong);
  1141. onTimer();
  1142. }
  1143. }
  1144. void Fader::onUnsuppressSong() {
  1145. if (_suppressSong) {
  1146. _suppressSong = false;
  1147. _suppressSongAnim = true;
  1148. _suppressSongStart = crl::now();
  1149. _suppressVolumeSong.start(1.);
  1150. onTimer();
  1151. }
  1152. }
  1153. void Fader::onSuppressAll(qint64 duration) {
  1154. _suppressAll = true;
  1155. auto now = crl::now();
  1156. if (_suppressAllEnd < now + kFadeDuration) {
  1157. _suppressAllStart = now;
  1158. }
  1159. _suppressAllEnd = now + duration;
  1160. _suppressVolumeAll.start(kSuppressRatioAll);
  1161. onTimer();
  1162. }
  1163. void Fader::songVolumeChanged() {
  1164. _volumeChangedSong = true;
  1165. onTimer();
  1166. }
  1167. void Fader::videoVolumeChanged() {
  1168. _volumeChangedVideo = true;
  1169. onTimer();
  1170. }
  1171. namespace internal {
  1172. // Thread: Any.
  1173. QMutex *audioPlayerMutex() {
  1174. return &AudioMutex;
  1175. }
  1176. // Thread: Any.
  1177. bool audioCheckError() {
  1178. return !Audio::PlaybackErrorHappened();
  1179. }
  1180. // Thread: Any. Must be locked: AudioMutex.
  1181. bool audioDeviceIsConnected() {
  1182. if (!AudioDevice) {
  1183. return false;
  1184. }
  1185. // always connected in the basic OpenAL, disconnect status is an extension
  1186. auto isConnected = ALint(1);
  1187. if (alcIsExtensionPresent(nullptr, "ALC_EXT_disconnect")) {
  1188. alcGetIntegerv(AudioDevice, alcGetEnumValue(nullptr, "ALC_CONNECTED"), 1, &isConnected);
  1189. }
  1190. if (Audio::ContextErrorHappened()) {
  1191. return false;
  1192. }
  1193. return (isConnected != 0);
  1194. }
  1195. // Thread: Any. Must be locked: AudioMutex.
  1196. bool CheckAudioDeviceConnected() {
  1197. if (audioDeviceIsConnected()) {
  1198. return true;
  1199. }
  1200. Audio::ScheduleDetachFromDeviceSafe();
  1201. return false;
  1202. }
  1203. // Thread: Main. Locks: AudioMutex.
  1204. void DetachFromDevice(not_null<Audio::Instance*> instance) {
  1205. QMutexLocker lock(&AudioMutex);
  1206. Audio::ClosePlaybackDevice(instance);
  1207. if (mixer()) {
  1208. mixer()->reattachIfNeeded();
  1209. }
  1210. }
  1211. bool DetachIfDeviceChanged(
  1212. not_null<Audio::Instance*> instance,
  1213. const Webrtc::DeviceResolvedId &nowDeviceId) {
  1214. QMutexLocker lock(&AudioMutex);
  1215. if (AudioDeviceLastUsedId == nowDeviceId) {
  1216. return false;
  1217. }
  1218. Audio::ClosePlaybackDevice(instance);
  1219. if (mixer()) {
  1220. mixer()->reattachIfNeeded();
  1221. }
  1222. return true;
  1223. }
  1224. } // namespace internal
  1225. } // namespace Player
  1226. class FFMpegAttributesReader : public AbstractFFMpegLoader {
  1227. public:
  1228. FFMpegAttributesReader(const Core::FileLocation &file, const QByteArray &data)
  1229. : AbstractFFMpegLoader(file, data, bytes::vector()) {
  1230. }
  1231. bool open(crl::time positionMs, float64 speed = 1.) override {
  1232. if (!AbstractFFMpegLoader::open(positionMs, speed)) {
  1233. return false;
  1234. }
  1235. for (int32 i = 0, l = fmtContext->nb_streams; i < l; ++i) {
  1236. const auto stream = fmtContext->streams[i];
  1237. if (stream->disposition & AV_DISPOSITION_ATTACHED_PIC) {
  1238. if (!_cover.isNull()) {
  1239. continue;
  1240. }
  1241. const auto &packet = stream->attached_pic;
  1242. if (packet.size) {
  1243. const auto coverBytes = QByteArray(
  1244. (const char*)packet.data,
  1245. packet.size);
  1246. auto read = Images::Read({
  1247. .content = coverBytes,
  1248. .forceOpaque = true,
  1249. });
  1250. if (!read.image.isNull()) {
  1251. _cover = std::move(read.image);
  1252. _coverBytes = coverBytes;
  1253. _coverFormat = read.format;
  1254. }
  1255. }
  1256. } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  1257. DEBUG_LOG(("Audio Read Error: Found video stream in file '%1', data size '%2', stream %3.")
  1258. .arg(_file.name())
  1259. .arg(_data.size())
  1260. .arg(i));
  1261. return false;
  1262. }
  1263. }
  1264. extractMetaData(fmtContext->streams[streamId]->metadata);
  1265. extractMetaData(fmtContext->metadata);
  1266. return true;
  1267. }
  1268. void trySet(QString &to, AVDictionary *dict, const char *key) {
  1269. if (!to.isEmpty()) return;
  1270. if (AVDictionaryEntry* tag = av_dict_get(dict, key, nullptr, 0)) {
  1271. to = QString::fromUtf8(tag->value);
  1272. }
  1273. }
  1274. void extractMetaData(AVDictionary *dict) {
  1275. trySet(_title, dict, "title");
  1276. trySet(_performer, dict, "artist");
  1277. trySet(_performer, dict, "performer");
  1278. trySet(_performer, dict, "album_artist");
  1279. //for (AVDictionaryEntry *tag = av_dict_get(dict, "", 0, AV_DICT_IGNORE_SUFFIX); tag; tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX)) {
  1280. // const char *key = tag->key;
  1281. // const char *value = tag->value;
  1282. // QString tmp = QString::fromUtf8(value);
  1283. //}
  1284. }
  1285. int sampleSize() override {
  1286. Unexpected("We shouldn't try to read sample size here.");
  1287. }
  1288. int format() override {
  1289. return 0;
  1290. }
  1291. QString title() {
  1292. return _title;
  1293. }
  1294. QString performer() {
  1295. return _performer;
  1296. }
  1297. QImage cover() {
  1298. return _cover;
  1299. }
  1300. QByteArray coverBytes() {
  1301. return _coverBytes;
  1302. }
  1303. QByteArray coverFormat() {
  1304. return _coverFormat;
  1305. }
  1306. ReadResult readMore() override {
  1307. DEBUG_LOG(("Audio Read Error: should not call this"));
  1308. return ReadError::Other;
  1309. }
  1310. ~FFMpegAttributesReader() {
  1311. }
  1312. private:
  1313. QString _title, _performer;
  1314. QImage _cover;
  1315. QByteArray _coverBytes, _coverFormat;
  1316. };
  1317. namespace Player {
  1318. Ui::PreparedFileInformation PrepareForSending(
  1319. const QString &fname,
  1320. const QByteArray &data) {
  1321. auto result = Ui::PreparedFileInformation::Song();
  1322. FFMpegAttributesReader reader(Core::FileLocation(fname), data);
  1323. const auto positionMs = crl::time(0);
  1324. if (reader.open(positionMs) && reader.duration() > 0) {
  1325. result.duration = reader.duration();
  1326. result.title = reader.title();
  1327. result.performer = reader.performer();
  1328. result.cover = reader.cover();
  1329. }
  1330. return { .media = result };
  1331. }
  1332. } // namespace Player
  1333. class FFMpegWaveformCounter : public FFMpegLoader {
  1334. public:
  1335. FFMpegWaveformCounter(const Core::FileLocation &file, const QByteArray &data) : FFMpegLoader(file, data, bytes::vector()) {
  1336. }
  1337. bool open(crl::time positionMs, float64 speed = 1.) override {
  1338. if (!FFMpegLoader::open(positionMs, speed)) {
  1339. return false;
  1340. }
  1341. QByteArray buffer;
  1342. buffer.reserve(kWaveformCounterBufferSize);
  1343. const auto samplesCount = samplesFrequency() * duration() / 1000;
  1344. int64 countbytes = sampleSize() * samplesCount;
  1345. int64 processed = 0;
  1346. int64 sumbytes = 0;
  1347. if (samplesCount < Media::Player::kWaveformSamplesCount) {
  1348. return false;
  1349. }
  1350. QVector<uint16> peaks;
  1351. peaks.reserve(Media::Player::kWaveformSamplesCount);
  1352. auto fmt = format();
  1353. auto peak = uint16(0);
  1354. auto callback = [&](uint16 sample) {
  1355. accumulate_max(peak, sample);
  1356. sumbytes += Media::Player::kWaveformSamplesCount;
  1357. if (sumbytes >= countbytes) {
  1358. sumbytes -= countbytes;
  1359. peaks.push_back(peak);
  1360. peak = 0;
  1361. }
  1362. };
  1363. while (processed < countbytes) {
  1364. const auto result = readMore();
  1365. Assert(result != ReadError::Wait); // Not a child loader.
  1366. if (result == ReadError::Retry) {
  1367. continue;
  1368. } else if (result == ReadError::Other
  1369. || result == ReadError::EndOfFile) {
  1370. break;
  1371. }
  1372. Assert(v::is<bytes::const_span>(result));
  1373. const auto sampleBytes = v::get<bytes::const_span>(result);
  1374. Assert(!sampleBytes.empty());
  1375. if (fmt == AL_FORMAT_MONO8 || fmt == AL_FORMAT_STEREO8) {
  1376. Media::Audio::IterateSamples<uchar>(sampleBytes, callback);
  1377. } else if (fmt == AL_FORMAT_MONO16 || fmt == AL_FORMAT_STEREO16) {
  1378. Media::Audio::IterateSamples<int16>(sampleBytes, callback);
  1379. }
  1380. processed += sampleBytes.size();
  1381. }
  1382. if (sumbytes > 0 && peaks.size() < Media::Player::kWaveformSamplesCount) {
  1383. peaks.push_back(peak);
  1384. }
  1385. if (peaks.isEmpty()) {
  1386. return false;
  1387. }
  1388. auto sum = std::accumulate(peaks.cbegin(), peaks.cend(), 0LL);
  1389. peak = qMax(int32(sum * 1.8 / peaks.size()), 2500);
  1390. result.resize(peaks.size());
  1391. for (int32 i = 0, l = peaks.size(); i != l; ++i) {
  1392. result[i] = char(qMin(31U, uint32(qMin(peaks.at(i), peak)) * 31 / peak));
  1393. }
  1394. return true;
  1395. }
  1396. const VoiceWaveform &waveform() const {
  1397. return result;
  1398. }
  1399. ~FFMpegWaveformCounter() {
  1400. }
  1401. private:
  1402. VoiceWaveform result;
  1403. };
  1404. } // namespace Media
  1405. VoiceWaveform audioCountWaveform(
  1406. const Core::FileLocation &file,
  1407. const QByteArray &data) {
  1408. Media::FFMpegWaveformCounter counter(file, data);
  1409. const auto positionMs = crl::time(0);
  1410. if (counter.open(positionMs)) {
  1411. return counter.waveform();
  1412. }
  1413. return VoiceWaveform();
  1414. }