LCOV - code coverage report
Current view: top level - media/server/gstplayer/source - GstWebAudioPlayer.cpp (source / functions) Coverage Total Hit
Test: coverage.info Lines: 97.3 % 220 214
Test Date: 2025-07-18 12:35:13 Functions: 100.0 % 23 23

            Line data    Source code
       1              : /*
       2              :  * If not stated otherwise in this file or this component's LICENSE file the
       3              :  * following copyright and licenses apply:
       4              :  *
       5              :  * Copyright 2023 Sky UK
       6              :  *
       7              :  * Licensed under the Apache License, Version 2.0 (the "License");
       8              :  * you may not use this file except in compliance with the License.
       9              :  * You may obtain a copy of the License at
      10              :  *
      11              :  * http://www.apache.org/licenses/LICENSE-2.0
      12              :  *
      13              :  * Unless required by applicable law or agreed to in writing, software
      14              :  * distributed under the License is distributed on an "AS IS" BASIS,
      15              :  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      16              :  * See the License for the specific language governing permissions and
      17              :  * limitations under the License.
      18              :  */
      19              : 
      20              : #include "GstWebAudioPlayer.h"
      21              : #include "GstDispatcherThread.h"
      22              : #include "RialtoServerLogging.h"
      23              : #include "WorkerThread.h"
      24              : #include "tasks/webAudio/WebAudioPlayerTaskFactory.h"
      25              : #include <stdexcept>
      26              : 
      27              : namespace
      28              : {
      29              : constexpr uint32_t kMaxWriteBufferTimeoutMs{2000};
      30              : } // namespace
      31              : 
      32              : namespace firebolt::rialto::server
      33              : {
      34              : std::weak_ptr<IGstWebAudioPlayerFactory> GstWebAudioPlayerFactory::m_factory;
      35              : 
      36           25 : std::shared_ptr<IGstWebAudioPlayerFactory> IGstWebAudioPlayerFactory::getFactory()
      37              : {
      38           25 :     std::shared_ptr<IGstWebAudioPlayerFactory> factory = GstWebAudioPlayerFactory::m_factory.lock();
      39              : 
      40           25 :     if (!factory)
      41              :     {
      42              :         try
      43              :         {
      44           25 :             factory = std::make_shared<GstWebAudioPlayerFactory>();
      45              :         }
      46            0 :         catch (const std::exception &e)
      47              :         {
      48            0 :             RIALTO_SERVER_LOG_ERROR("Failed to create the gstreamer player factory, reason: %s", e.what());
      49              :         }
      50              : 
      51           25 :         GstWebAudioPlayerFactory::m_factory = factory;
      52              :     }
      53              : 
      54           25 :     return factory;
      55              : }
      56              : 
      57            1 : std::unique_ptr<IGstWebAudioPlayer> GstWebAudioPlayerFactory::createGstWebAudioPlayer(IGstWebAudioPlayerClient *client,
      58              :                                                                                       const uint32_t priority)
      59              : {
      60            1 :     std::unique_ptr<IGstWebAudioPlayer> gstPlayer;
      61              : 
      62              :     try
      63              :     {
      64            1 :         auto gstWrapperFactory = firebolt::rialto::wrappers::IGstWrapperFactory::getFactory();
      65            1 :         auto glibWrapperFactory = firebolt::rialto::wrappers::IGlibWrapperFactory::getFactory();
      66            1 :         std::shared_ptr<firebolt::rialto::wrappers::IGstWrapper> gstWrapper;
      67            1 :         std::shared_ptr<firebolt::rialto::wrappers::IGlibWrapper> glibWrapper;
      68            1 :         if ((!gstWrapperFactory) || (!(gstWrapper = gstWrapperFactory->getGstWrapper())))
      69              :         {
      70            0 :             throw std::runtime_error("Cannot create GstWrapper");
      71              :         }
      72            1 :         if ((!glibWrapperFactory) || (!(glibWrapper = glibWrapperFactory->getGlibWrapper())))
      73              :         {
      74            0 :             throw std::runtime_error("Cannot create GlibWrapper");
      75              :         }
      76            2 :         gstPlayer = std::make_unique<GstWebAudioPlayer>(client, priority, gstWrapper, glibWrapper,
      77            2 :                                                         IGstInitialiser::instance(), IGstSrcFactory::getFactory(),
      78            2 :                                                         std::make_unique<WebAudioPlayerTaskFactory>(client, gstWrapper,
      79              :                                                                                                     glibWrapper),
      80            2 :                                                         std::make_unique<WorkerThreadFactory>(),
      81            3 :                                                         std::make_unique<GstDispatcherThreadFactory>());
      82            1 :     }
      83            0 :     catch (const std::exception &e)
      84              :     {
      85            0 :         RIALTO_SERVER_LOG_ERROR("Failed to create the gstreamer player, reason: %s", e.what());
      86              :     }
      87              : 
      88            1 :     return gstPlayer;
      89              : }
      90              : 
      91           33 : GstWebAudioPlayer::GstWebAudioPlayer(IGstWebAudioPlayerClient *client, const uint32_t priority,
      92              :                                      const std::shared_ptr<firebolt::rialto::wrappers::IGstWrapper> &gstWrapper,
      93              :                                      const std::shared_ptr<firebolt::rialto::wrappers::IGlibWrapper> &glibWrapper,
      94              :                                      const IGstInitialiser &gstInitialiser,
      95              :                                      const std::shared_ptr<IGstSrcFactory> &gstSrcFactory,
      96              :                                      std::unique_ptr<IWebAudioPlayerTaskFactory> taskFactory,
      97              :                                      std::unique_ptr<IWorkerThreadFactory> workerThreadFactory,
      98           33 :                                      std::unique_ptr<IGstDispatcherThreadFactory> gstDispatcherThreadFactory)
      99           33 :     : m_gstPlayerClient(client), m_gstWrapper{gstWrapper}, m_glibWrapper{glibWrapper},
     100           66 :       m_taskFactory{std::move(taskFactory)}
     101              : {
     102           33 :     RIALTO_SERVER_LOG_DEBUG("GstWebAudioPlayer is constructed.");
     103              : 
     104           33 :     gstInitialiser.waitForInitialisation();
     105              : 
     106           33 :     if ((!gstSrcFactory) || (!(m_context.gstSrc = gstSrcFactory->getGstSrc())))
     107              :     {
     108            1 :         throw std::runtime_error("Cannot create GstSrc");
     109              :     }
     110              : 
     111              :     // Ensure that rialtosrc has been initalised
     112           32 :     m_context.gstSrc->initSrc();
     113              : 
     114              :     // Start task thread
     115           32 :     if ((!workerThreadFactory) || (!(m_workerThread = workerThreadFactory->createWorkerThread())))
     116              :     {
     117            1 :         throw std::runtime_error("Failed to create the worker thread");
     118              :     }
     119              : 
     120           31 :     if (!initWebAudioPipeline(priority))
     121              :     {
     122           12 :         termWebAudioPipeline();
     123           12 :         resetWorkerThread();
     124           12 :         throw std::runtime_error("Failed to initalise the pipeline");
     125              :     }
     126              : 
     127           38 :     if ((!gstDispatcherThreadFactory) ||
     128           19 :         (!(m_gstDispatcherThread =
     129           38 :                gstDispatcherThreadFactory->createGstDispatcherThread(*this, m_context.pipeline, m_gstWrapper))))
     130              :     {
     131            1 :         termWebAudioPipeline();
     132            1 :         resetWorkerThread();
     133            1 :         throw std::runtime_error("Failed to create the dispatcher thread");
     134              :     }
     135          153 : }
     136              : 
     137           36 : GstWebAudioPlayer::~GstWebAudioPlayer()
     138              : {
     139           18 :     RIALTO_SERVER_LOG_DEBUG("GstWebAudioPlayer is destructed.");
     140              : 
     141           18 :     m_gstDispatcherThread.reset();
     142              : 
     143           18 :     resetWorkerThread();
     144              : 
     145           18 :     termWebAudioPipeline();
     146           36 : }
     147              : 
     148           31 : bool GstWebAudioPlayer::initWebAudioPipeline(const uint32_t priority)
     149              : {
     150           31 :     m_context.pipeline = m_gstWrapper->gstPipelineNew(std::string("webaudiopipeline" + std::to_string(priority)).c_str());
     151           31 :     if (!m_context.pipeline)
     152              :     {
     153            1 :         RIALTO_SERVER_LOG_ERROR("Failed to create the webaudiopipeline");
     154            1 :         return false;
     155              :     }
     156              : 
     157              :     // Create and initalise appsrc
     158           30 :     m_context.source = m_gstWrapper->gstElementFactoryMake("appsrc", "audsrc");
     159           30 :     if (!m_context.source)
     160              :     {
     161            1 :         RIALTO_SERVER_LOG_ERROR("Failed to create the appsrc");
     162            1 :         return false;
     163              :     }
     164           29 :     m_gstWrapper->gstAppSrcSetMaxBytes(GST_APP_SRC(m_context.source), kMaxWebAudioBytes);
     165           29 :     m_glibWrapper->gObjectSet(m_context.source, "format", GST_FORMAT_TIME, nullptr);
     166              : 
     167              :     // Perform sink specific initalisation
     168           29 :     GstPluginFeature *feature = nullptr;
     169           29 :     GstRegistry *reg = m_gstWrapper->gstRegistryGet();
     170           29 :     if (!reg)
     171              :     {
     172            1 :         RIALTO_SERVER_LOG_ERROR("Failed get the gst registry");
     173            1 :         return false;
     174              :     }
     175              : 
     176           28 :     GstElement *sink = nullptr;
     177           28 :     if (nullptr != (feature = m_gstWrapper->gstRegistryLookupFeature(reg, "amlhalasink")))
     178              :     {
     179              :         // LLama
     180            3 :         RIALTO_SERVER_LOG_INFO("Use amlhalasink");
     181            3 :         sink = createAmlhalaSink();
     182            3 :         m_gstWrapper->gstObjectUnref(feature);
     183              :     }
     184           25 :     else if (nullptr != (feature = m_gstWrapper->gstRegistryLookupFeature(reg, "rtkaudiosink")))
     185              :     {
     186              :         // XiOne
     187            5 :         RIALTO_SERVER_LOG_INFO("Use rtkaudiosink");
     188            5 :         sink = createRtkAudioSink();
     189            5 :         m_gstWrapper->gstObjectUnref(feature);
     190              :     }
     191              :     else
     192              :     {
     193           20 :         RIALTO_SERVER_LOG_INFO("Use autoaudiosink");
     194           20 :         sink = createAutoSink();
     195              :     }
     196              : 
     197           28 :     if (sink)
     198              :     {
     199           25 :         return linkElementsToSrc(sink);
     200              :     }
     201              :     else
     202              :     {
     203            3 :         m_gstWrapper->gstObjectUnref(m_context.source);
     204            3 :         m_context.source = nullptr;
     205              :     }
     206            3 :     return false;
     207              : }
     208              : 
     209            3 : GstElement *GstWebAudioPlayer::createAmlhalaSink()
     210              : {
     211            3 :     GstElement *sink = m_gstWrapper->gstElementFactoryMake("amlhalasink", "webaudiosink");
     212            3 :     if (!sink)
     213              :     {
     214            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the amlhalasink");
     215            1 :         return nullptr;
     216              :     }
     217            2 :     m_glibWrapper->gObjectSet(G_OBJECT(sink), "direct-mode", FALSE, NULL);
     218              : 
     219            2 :     return sink;
     220              : }
     221              : 
     222            5 : GstElement *GstWebAudioPlayer::createRtkAudioSink()
     223              : {
     224            5 :     GstElement *sink = m_gstWrapper->gstElementFactoryMake("rtkaudiosink", "webaudiosink");
     225            5 :     if (!sink)
     226              :     {
     227            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the rtkaudiosink");
     228            1 :         return nullptr;
     229              :     }
     230            4 :     m_glibWrapper->gObjectSet(G_OBJECT(sink), "media-tunnel", FALSE, NULL);
     231            4 :     m_glibWrapper->gObjectSet(G_OBJECT(sink), "audio-service", TRUE, NULL);
     232              : 
     233            4 :     return sink;
     234              : }
     235              : 
     236           20 : GstElement *GstWebAudioPlayer::createAutoSink()
     237              : {
     238           20 :     GstElement *sink = m_gstWrapper->gstElementFactoryMake("autoaudiosink", "webaudiosink");
     239           20 :     if (!sink)
     240              :     {
     241            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the autoaudiosink");
     242            1 :         return nullptr;
     243              :     }
     244              : 
     245           19 :     return sink;
     246              : }
     247              : 
     248              : // NOTE:-
     249              : //   This method hands the responsibility for the destruction of both { "sink", "m_context.source" }
     250              : //   over to the pipeline (or if handover wasn't possible, it will unref)
     251           25 : bool GstWebAudioPlayer::linkElementsToSrc(GstElement *sink)
     252              : {
     253           25 :     bool status{true};
     254              : 
     255           25 :     GstElement *convert{nullptr};
     256           25 :     GstElement *resample{nullptr};
     257           25 :     GstElement *volume{nullptr};
     258           25 :     GstElement *queue{nullptr};
     259              : 
     260           25 :     convert = m_gstWrapper->gstElementFactoryMake("audioconvert", NULL);
     261           25 :     if (!convert)
     262              :     {
     263            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the audioconvert");
     264            1 :         status = false;
     265              :     }
     266              : 
     267           25 :     if (status)
     268              :     {
     269           24 :         resample = m_gstWrapper->gstElementFactoryMake("audioresample", NULL);
     270           24 :         if (!resample)
     271              :         {
     272            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the audioresample");
     273            1 :             status = false;
     274              :         }
     275              :     }
     276              : 
     277           25 :     if (status)
     278              :     {
     279           23 :         volume = m_gstWrapper->gstElementFactoryMake("volume", NULL);
     280           23 :         if (!volume)
     281              :         {
     282            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the volume");
     283            1 :             status = false;
     284              :         }
     285              :     }
     286           25 :     if (status)
     287              :     {
     288           22 :         queue = m_gstWrapper->gstElementFactoryMake("queue", NULL);
     289           22 :         if (!queue)
     290              :         {
     291            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the queue");
     292            1 :             status = false;
     293              :         }
     294              :         else
     295              :         {
     296           21 :             constexpr guint kWebAudioQueueSize{8192};
     297           21 :             m_glibWrapper->gObjectSet(queue, "max-size-bytes", kWebAudioQueueSize, nullptr);
     298              :         }
     299              :     }
     300              : 
     301           25 :     std::queue<GstElement *> elementsToAdd;
     302           25 :     elementsToAdd.push(m_context.source);
     303           25 :     if (convert)
     304           24 :         elementsToAdd.push(convert);
     305           25 :     if (resample)
     306           23 :         elementsToAdd.push(resample);
     307           25 :     if (volume)
     308           22 :         elementsToAdd.push(volume);
     309           25 :     if (queue)
     310           21 :         elementsToAdd.push(queue);
     311           25 :     elementsToAdd.push(sink);
     312              : 
     313           25 :     if (status)
     314              :     {
     315              :         // Add elements to the pipeline
     316           21 :         GstBin *pipelineBin = GST_BIN(m_context.pipeline);
     317          146 :         while (!elementsToAdd.empty())
     318              :         {
     319          126 :             if (m_gstWrapper->gstBinAdd(pipelineBin, elementsToAdd.front()))
     320          125 :                 elementsToAdd.pop();
     321              :             else
     322              :             {
     323            1 :                 RIALTO_SERVER_LOG_ERROR("Failed to add element to the bin");
     324            1 :                 status = false;
     325            1 :                 break;
     326              :             }
     327              :         }
     328              :     }
     329              : 
     330           25 :     if (status)
     331              :     {
     332           20 :         if ((!m_gstWrapper->gstElementLink(m_context.source, convert)) ||
     333           19 :             (!m_gstWrapper->gstElementLink(convert, resample)) || (!m_gstWrapper->gstElementLink(resample, volume)) ||
     334           39 :             (!m_gstWrapper->gstElementLink(volume, queue)) || (!m_gstWrapper->gstElementLink(queue, sink)))
     335              :         {
     336            1 :             RIALTO_SERVER_LOG_ERROR("Failed to link elements");
     337            1 :             status = false;
     338              :         }
     339           20 :         m_context.gstVolumeElement = GST_STREAM_VOLUME(volume);
     340              :     }
     341              : 
     342           25 :     if (!status)
     343              :     {
     344              :         // Unref anything that wasn't added to the pipeline
     345           21 :         while (!elementsToAdd.empty())
     346              :         {
     347           15 :             m_gstWrapper->gstObjectUnref(elementsToAdd.front());
     348           15 :             elementsToAdd.pop();
     349              :         }
     350            6 :         m_context.source = nullptr;
     351              :     }
     352              : 
     353           25 :     return status;
     354              : }
     355              : 
     356           31 : void GstWebAudioPlayer::termWebAudioPipeline()
     357              : {
     358           31 :     if (m_context.pipeline)
     359              :     {
     360           30 :         m_taskFactory->createStop(*this)->execute();
     361           30 :         GstBus *bus = m_gstWrapper->gstPipelineGetBus(GST_PIPELINE(m_context.pipeline));
     362           30 :         if (bus)
     363              :         {
     364           29 :             m_gstWrapper->gstBusSetSyncHandler(bus, nullptr, nullptr, nullptr);
     365           29 :             m_gstWrapper->gstObjectUnref(bus);
     366              :         }
     367              : 
     368           30 :         m_gstWrapper->gstObjectUnref(m_context.pipeline);
     369              :     }
     370           31 : }
     371              : 
     372           31 : void GstWebAudioPlayer::resetWorkerThread()
     373              : {
     374           31 :     m_workerThread->enqueueTask(m_taskFactory->createShutdown(*this));
     375           31 :     m_workerThread->join();
     376           31 :     m_workerThread.reset();
     377              : }
     378              : 
     379            1 : void GstWebAudioPlayer::setCaps(const std::string &audioMimeType, std::weak_ptr<const WebAudioConfig> config)
     380              : {
     381            1 :     m_workerThread->enqueueTask(m_taskFactory->createSetCaps(m_context, audioMimeType, config));
     382              : }
     383              : 
     384            1 : void GstWebAudioPlayer::play()
     385              : {
     386            1 :     m_workerThread->enqueueTask(m_taskFactory->createPlay(*this));
     387              : }
     388              : 
     389            1 : void GstWebAudioPlayer::pause()
     390              : {
     391            1 :     m_workerThread->enqueueTask(m_taskFactory->createPause(*this));
     392              : }
     393              : 
     394            1 : void GstWebAudioPlayer::setVolume(double volume)
     395              : {
     396            1 :     m_workerThread->enqueueTask(m_taskFactory->createSetVolume(m_context, volume));
     397              : }
     398              : 
     399            1 : bool GstWebAudioPlayer::getVolume(double &volume)
     400              : {
     401              :     // Must be called on the main thread, otherwise the pipeline can be destroyed during the query.
     402            1 :     volume = m_gstWrapper->gstStreamVolumeGetVolume(m_context.gstVolumeElement, GST_STREAM_VOLUME_FORMAT_LINEAR);
     403            1 :     return true;
     404              : }
     405              : 
     406            2 : uint32_t GstWebAudioPlayer::writeBuffer(uint8_t *mainPtr, uint32_t mainLength, uint8_t *wrapPtr, uint32_t wrapLength)
     407              : {
     408              :     // Must block and wait for the data to be written from the shared buffer.
     409            2 :     std::unique_lock<std::mutex> lock(m_context.writeBufferMutex);
     410            2 :     m_workerThread->enqueueTask(m_taskFactory->createWriteBuffer(m_context, mainPtr, mainLength, wrapPtr, wrapLength));
     411            2 :     std::cv_status status = m_context.writeBufferCond.wait_for(lock, std::chrono::milliseconds(kMaxWriteBufferTimeoutMs));
     412            2 :     if (std::cv_status::timeout == status)
     413              :     {
     414            1 :         RIALTO_SERVER_LOG_ERROR("Timed out writing to the gstreamer buffers");
     415            1 :         return 0;
     416              :     }
     417              :     else
     418              :     {
     419            1 :         return m_context.lastBytesWritten;
     420              :     }
     421            2 : }
     422              : 
     423            1 : void GstWebAudioPlayer::setEos()
     424              : {
     425            1 :     m_workerThread->enqueueTask(m_taskFactory->createEos(m_context));
     426              : }
     427              : 
     428            1 : uint64_t GstWebAudioPlayer::getQueuedBytes()
     429              : {
     430              :     // Must be called on the main thread, otherwise the pipeline can be destroyed during the query.
     431            1 :     return m_gstWrapper->gstAppSrcGetCurrentLevelBytes(GST_APP_SRC(m_context.source));
     432              : }
     433              : 
     434            3 : bool GstWebAudioPlayer::changePipelineState(GstState newState)
     435              : {
     436            3 :     if (m_gstWrapper->gstElementSetState(m_context.pipeline, newState) == GST_STATE_CHANGE_FAILURE)
     437              :     {
     438            1 :         RIALTO_SERVER_LOG_ERROR("Change state failed - Gstreamer returned an error");
     439            1 :         if (m_gstPlayerClient)
     440            1 :             m_gstPlayerClient->notifyState(WebAudioPlayerState::FAILURE);
     441            1 :         return false;
     442              :     }
     443            2 :     return true;
     444              : }
     445              : 
     446            2 : void GstWebAudioPlayer::stopWorkerThread()
     447              : {
     448            2 :     if (m_workerThread)
     449              :     {
     450            2 :         m_workerThread->stop();
     451              :     }
     452              : }
     453              : 
     454            1 : void GstWebAudioPlayer::handleBusMessage(GstMessage *message)
     455              : {
     456            1 :     if (m_workerThread)
     457              :     {
     458            1 :         m_workerThread->enqueueTask(m_taskFactory->createHandleBusMessage(m_context, *this, message));
     459              :     }
     460              : }
     461              : 
     462            1 : void GstWebAudioPlayer::ping(std::unique_ptr<IHeartbeatHandler> &&heartbeatHandler)
     463              : {
     464            1 :     if (m_workerThread)
     465              :     {
     466            1 :         m_workerThread->enqueueTask(m_taskFactory->createPing(std::move(heartbeatHandler)));
     467              :     }
     468              : }
     469              : 
     470              : }; // namespace firebolt::rialto::server
        

Generated by: LCOV version 2.0-1