LCOV - code coverage report
Current view: top level - media/server/gstplayer/source - GstWebAudioPlayer.cpp (source / functions) Coverage Total Hit
Test: coverage.info Lines: 97.2 % 215 209
Test Date: 2025-06-30 09:40:50 Functions: 100.0 % 22 22

            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           32 : 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           32 :                                      std::unique_ptr<IGstDispatcherThreadFactory> gstDispatcherThreadFactory)
      99           32 :     : m_gstPlayerClient(client), m_gstWrapper{gstWrapper}, m_glibWrapper{glibWrapper},
     100           64 :       m_taskFactory{std::move(taskFactory)}
     101              : {
     102           32 :     RIALTO_SERVER_LOG_DEBUG("GstWebAudioPlayer is constructed.");
     103              : 
     104           32 :     gstInitialiser.waitForInitialisation();
     105              : 
     106           32 :     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           31 :     m_context.gstSrc->initSrc();
     113              : 
     114              :     // Start task thread
     115           31 :     if ((!workerThreadFactory) || (!(m_workerThread = workerThreadFactory->createWorkerThread())))
     116              :     {
     117            1 :         throw std::runtime_error("Failed to create the worker thread");
     118              :     }
     119              : 
     120           30 :     if (!initWebAudioPipeline(priority))
     121              :     {
     122           12 :         termWebAudioPipeline();
     123           12 :         resetWorkerThread();
     124           12 :         throw std::runtime_error("Failed to initalise the pipeline");
     125              :     }
     126              : 
     127           36 :     if ((!gstDispatcherThreadFactory) ||
     128           18 :         (!(m_gstDispatcherThread =
     129           36 :                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          152 : }
     136              : 
     137           34 : GstWebAudioPlayer::~GstWebAudioPlayer()
     138              : {
     139           17 :     RIALTO_SERVER_LOG_DEBUG("GstWebAudioPlayer is destructed.");
     140              : 
     141           17 :     m_gstDispatcherThread.reset();
     142              : 
     143           17 :     resetWorkerThread();
     144              : 
     145           17 :     termWebAudioPipeline();
     146           34 : }
     147              : 
     148           30 : bool GstWebAudioPlayer::initWebAudioPipeline(const uint32_t priority)
     149              : {
     150           30 :     m_context.pipeline = m_gstWrapper->gstPipelineNew(std::string("webaudiopipeline" + std::to_string(priority)).c_str());
     151           30 :     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           29 :     m_context.source = m_gstWrapper->gstElementFactoryMake("appsrc", "audsrc");
     159           29 :     if (!m_context.source)
     160              :     {
     161            1 :         RIALTO_SERVER_LOG_ERROR("Failed to create the appsrc");
     162            1 :         return false;
     163              :     }
     164           28 :     m_gstWrapper->gstAppSrcSetMaxBytes(GST_APP_SRC(m_context.source), kMaxWebAudioBytes);
     165           28 :     m_glibWrapper->gObjectSet(m_context.source, "format", GST_FORMAT_TIME, nullptr);
     166              : 
     167              :     // Perform sink specific initalisation
     168           28 :     GstPluginFeature *feature = nullptr;
     169           28 :     GstRegistry *reg = m_gstWrapper->gstRegistryGet();
     170           28 :     if (!reg)
     171              :     {
     172            1 :         RIALTO_SERVER_LOG_ERROR("Failed get the gst registry");
     173            1 :         return false;
     174              :     }
     175              : 
     176           27 :     GstElement *sink = nullptr;
     177           27 :     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           24 :     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           19 :         RIALTO_SERVER_LOG_INFO("Use autoaudiosink");
     194           19 :         sink = createAutoSink();
     195              :     }
     196              : 
     197           27 :     if (sink)
     198              :     {
     199           24 :         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           19 : GstElement *GstWebAudioPlayer::createAutoSink()
     237              : {
     238           19 :     GstElement *sink = m_gstWrapper->gstElementFactoryMake("autoaudiosink", "webaudiosink");
     239           19 :     if (!sink)
     240              :     {
     241            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the autoaudiosink");
     242            1 :         return nullptr;
     243              :     }
     244              : 
     245           18 :     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           24 : bool GstWebAudioPlayer::linkElementsToSrc(GstElement *sink)
     252              : {
     253           24 :     bool status{true};
     254              : 
     255           24 :     GstElement *convert{nullptr};
     256           24 :     GstElement *resample{nullptr};
     257           24 :     GstElement *volume{nullptr};
     258           24 :     GstElement *queue{nullptr};
     259              : 
     260           24 :     convert = m_gstWrapper->gstElementFactoryMake("audioconvert", NULL);
     261           24 :     if (!convert)
     262              :     {
     263            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the audioconvert");
     264            1 :         status = false;
     265              :     }
     266              : 
     267           24 :     if (status)
     268              :     {
     269           23 :         resample = m_gstWrapper->gstElementFactoryMake("audioresample", NULL);
     270           23 :         if (!resample)
     271              :         {
     272            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the audioresample");
     273            1 :             status = false;
     274              :         }
     275              :     }
     276              : 
     277           24 :     if (status)
     278              :     {
     279           22 :         volume = m_gstWrapper->gstElementFactoryMake("volume", NULL);
     280           22 :         if (!volume)
     281              :         {
     282            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the volume");
     283            1 :             status = false;
     284              :         }
     285              :     }
     286           24 :     if (status)
     287              :     {
     288           21 :         queue = m_gstWrapper->gstElementFactoryMake("queue", NULL);
     289           21 :         if (!queue)
     290              :         {
     291            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the queue");
     292            1 :             status = false;
     293              :         }
     294              :         else
     295              :         {
     296           20 :             constexpr guint kWebAudioQueueSize{8192};
     297           20 :             m_glibWrapper->gObjectSet(queue, "max-size-bytes", kWebAudioQueueSize, nullptr);
     298              :         }
     299              :     }
     300              : 
     301           24 :     std::queue<GstElement *> elementsToAdd;
     302           24 :     elementsToAdd.push(m_context.source);
     303           24 :     if (convert)
     304           23 :         elementsToAdd.push(convert);
     305           24 :     if (resample)
     306           22 :         elementsToAdd.push(resample);
     307           24 :     if (volume)
     308           21 :         elementsToAdd.push(volume);
     309           24 :     if (queue)
     310           20 :         elementsToAdd.push(queue);
     311           24 :     elementsToAdd.push(sink);
     312              : 
     313           24 :     if (status)
     314              :     {
     315              :         // Add elements to the pipeline
     316           20 :         GstBin *pipelineBin = GST_BIN(m_context.pipeline);
     317          139 :         while (!elementsToAdd.empty())
     318              :         {
     319          120 :             if (m_gstWrapper->gstBinAdd(pipelineBin, elementsToAdd.front()))
     320          119 :                 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           24 :     if (status)
     331              :     {
     332           19 :         if ((!m_gstWrapper->gstElementLink(m_context.source, convert)) ||
     333           18 :             (!m_gstWrapper->gstElementLink(convert, resample)) || (!m_gstWrapper->gstElementLink(resample, volume)) ||
     334           37 :             (!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           19 :         m_context.gstVolumeElement = GST_STREAM_VOLUME(volume);
     340              :     }
     341              : 
     342           24 :     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           24 :     return status;
     354              : }
     355              : 
     356           30 : void GstWebAudioPlayer::termWebAudioPipeline()
     357              : {
     358           30 :     if (m_context.pipeline)
     359              :     {
     360           29 :         m_taskFactory->createStop(*this)->execute();
     361           29 :         GstBus *bus = m_gstWrapper->gstPipelineGetBus(GST_PIPELINE(m_context.pipeline));
     362           29 :         if (bus)
     363              :         {
     364           28 :             m_gstWrapper->gstBusSetSyncHandler(bus, nullptr, nullptr, nullptr);
     365           28 :             m_gstWrapper->gstObjectUnref(bus);
     366              :         }
     367              : 
     368           29 :         m_gstWrapper->gstObjectUnref(m_context.pipeline);
     369              :     }
     370           30 : }
     371              : 
     372           30 : void GstWebAudioPlayer::resetWorkerThread()
     373              : {
     374           30 :     m_workerThread.reset();
     375              : }
     376              : 
     377            1 : void GstWebAudioPlayer::setCaps(const std::string &audioMimeType, std::weak_ptr<const WebAudioConfig> config)
     378              : {
     379            1 :     m_workerThread->enqueueTask(m_taskFactory->createSetCaps(m_context, audioMimeType, config));
     380              : }
     381              : 
     382            1 : void GstWebAudioPlayer::play()
     383              : {
     384            1 :     m_workerThread->enqueueTask(m_taskFactory->createPlay(*this));
     385              : }
     386              : 
     387            1 : void GstWebAudioPlayer::pause()
     388              : {
     389            1 :     m_workerThread->enqueueTask(m_taskFactory->createPause(*this));
     390              : }
     391              : 
     392            1 : void GstWebAudioPlayer::setVolume(double volume)
     393              : {
     394            1 :     m_workerThread->enqueueTask(m_taskFactory->createSetVolume(m_context, volume));
     395              : }
     396              : 
     397            1 : bool GstWebAudioPlayer::getVolume(double &volume)
     398              : {
     399              :     // Must be called on the main thread, otherwise the pipeline can be destroyed during the query.
     400            1 :     volume = m_gstWrapper->gstStreamVolumeGetVolume(m_context.gstVolumeElement, GST_STREAM_VOLUME_FORMAT_LINEAR);
     401            1 :     return true;
     402              : }
     403              : 
     404            2 : uint32_t GstWebAudioPlayer::writeBuffer(uint8_t *mainPtr, uint32_t mainLength, uint8_t *wrapPtr, uint32_t wrapLength)
     405              : {
     406              :     // Must block and wait for the data to be written from the shared buffer.
     407            2 :     std::unique_lock<std::mutex> lock(m_context.writeBufferMutex);
     408            2 :     m_workerThread->enqueueTask(m_taskFactory->createWriteBuffer(m_context, mainPtr, mainLength, wrapPtr, wrapLength));
     409            2 :     std::cv_status status = m_context.writeBufferCond.wait_for(lock, std::chrono::milliseconds(kMaxWriteBufferTimeoutMs));
     410            2 :     if (std::cv_status::timeout == status)
     411              :     {
     412            1 :         RIALTO_SERVER_LOG_ERROR("Timed out writing to the gstreamer buffers");
     413            1 :         return 0;
     414              :     }
     415              :     else
     416              :     {
     417            1 :         return m_context.lastBytesWritten;
     418              :     }
     419            2 : }
     420              : 
     421            1 : void GstWebAudioPlayer::setEos()
     422              : {
     423            1 :     m_workerThread->enqueueTask(m_taskFactory->createEos(m_context));
     424              : }
     425              : 
     426            1 : uint64_t GstWebAudioPlayer::getQueuedBytes()
     427              : {
     428              :     // Must be called on the main thread, otherwise the pipeline can be destroyed during the query.
     429            1 :     return m_gstWrapper->gstAppSrcGetCurrentLevelBytes(GST_APP_SRC(m_context.source));
     430              : }
     431              : 
     432            3 : bool GstWebAudioPlayer::changePipelineState(GstState newState)
     433              : {
     434            3 :     if (m_gstWrapper->gstElementSetState(m_context.pipeline, newState) == GST_STATE_CHANGE_FAILURE)
     435              :     {
     436            1 :         RIALTO_SERVER_LOG_ERROR("Change state failed - Gstreamer returned an error");
     437            1 :         if (m_gstPlayerClient)
     438            1 :             m_gstPlayerClient->notifyState(WebAudioPlayerState::FAILURE);
     439            1 :         return false;
     440              :     }
     441            2 :     return true;
     442              : }
     443              : 
     444            1 : void GstWebAudioPlayer::handleBusMessage(GstMessage *message)
     445              : {
     446            1 :     if (m_workerThread)
     447              :     {
     448            1 :         m_workerThread->enqueueTask(m_taskFactory->createHandleBusMessage(m_context, *this, message));
     449              :     }
     450              : }
     451              : 
     452            1 : void GstWebAudioPlayer::ping(std::unique_ptr<IHeartbeatHandler> &&heartbeatHandler)
     453              : {
     454            1 :     if (m_workerThread)
     455              :     {
     456            1 :         m_workerThread->enqueueTask(m_taskFactory->createPing(std::move(heartbeatHandler)));
     457              :     }
     458              : }
     459              : 
     460              : }; // namespace firebolt::rialto::server
        

Generated by: LCOV version 2.0-1