LCOV - code coverage report
Current view: top level - media/server/gstplayer/source - GstWebAudioPlayer.cpp (source / functions) Coverage Total Hit
Test: coverage.info Lines: 97.1 % 210 204
Test Date: 2025-02-18 13:13:53 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           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           64 :     : m_gstPlayerClient(client), m_gstWrapper{gstWrapper}, m_glibWrapper{glibWrapper}, m_taskFactory{
     100           64 :                                                                                            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           11 :         termWebAudioPipeline();
     123           11 :         resetWorkerThread();
     124           11 :         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          144 : }
     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           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            4 :         RIALTO_SERVER_LOG_INFO("Use rtkaudiosink");
     188            4 :         sink = createRtkAudioSink();
     189            4 :         m_gstWrapper->gstObjectUnref(feature);
     190              :     }
     191              :     else
     192              :     {
     193           20 :         RIALTO_SERVER_LOG_INFO("Use autoaudiosink");
     194           20 :         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            4 : GstElement *GstWebAudioPlayer::createRtkAudioSink()
     223              : {
     224            4 :     GstElement *sink = m_gstWrapper->gstElementFactoryMake("rtkaudiosink", "webaudiosink");
     225            4 :     if (!sink)
     226              :     {
     227            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the rtkaudiosink");
     228            1 :         return nullptr;
     229              :     }
     230            3 :     m_glibWrapper->gObjectSet(G_OBJECT(sink), "media-tunnel", FALSE, NULL);
     231            3 :     m_glibWrapper->gObjectSet(G_OBJECT(sink), "audio-service", TRUE, NULL);
     232              : 
     233            3 :     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           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              : 
     259           24 :     convert = m_gstWrapper->gstElementFactoryMake("audioconvert", NULL);
     260           24 :     if (!convert)
     261              :     {
     262            1 :         RIALTO_SERVER_LOG_ERROR("Failed create the audioconvert");
     263            1 :         status = false;
     264              :     }
     265              : 
     266           24 :     if (status)
     267              :     {
     268           23 :         resample = m_gstWrapper->gstElementFactoryMake("audioresample", NULL);
     269           23 :         if (!resample)
     270              :         {
     271            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the audioresample");
     272            1 :             status = false;
     273              :         }
     274              :     }
     275              : 
     276           24 :     if (status)
     277              :     {
     278           22 :         volume = m_gstWrapper->gstElementFactoryMake("volume", NULL);
     279           22 :         if (!volume)
     280              :         {
     281            1 :             RIALTO_SERVER_LOG_ERROR("Failed create the volume");
     282            1 :             status = false;
     283              :         }
     284              :     }
     285              : 
     286           24 :     std::queue<GstElement *> elementsToAdd;
     287           24 :     elementsToAdd.push(m_context.source);
     288           24 :     if (convert)
     289           23 :         elementsToAdd.push(convert);
     290           24 :     if (resample)
     291           22 :         elementsToAdd.push(resample);
     292           24 :     if (volume)
     293           21 :         elementsToAdd.push(volume);
     294           24 :     elementsToAdd.push(sink);
     295              : 
     296           24 :     if (status)
     297              :     {
     298              :         // Add elements to the pipeline
     299           21 :         GstBin *pipelineBin = GST_BIN(m_context.pipeline);
     300          125 :         while (!elementsToAdd.empty())
     301              :         {
     302          105 :             if (m_gstWrapper->gstBinAdd(pipelineBin, elementsToAdd.front()))
     303          104 :                 elementsToAdd.pop();
     304              :             else
     305              :             {
     306            1 :                 RIALTO_SERVER_LOG_ERROR("Failed to add element to the bin");
     307            1 :                 status = false;
     308            1 :                 break;
     309              :             }
     310              :         }
     311              :     }
     312              : 
     313           24 :     if (status)
     314              :     {
     315           20 :         if ((!m_gstWrapper->gstElementLink(m_context.source, convert)) ||
     316           39 :             (!m_gstWrapper->gstElementLink(convert, resample)) || (!m_gstWrapper->gstElementLink(resample, volume)) ||
     317           19 :             (!m_gstWrapper->gstElementLink(volume, sink)))
     318              :         {
     319            1 :             RIALTO_SERVER_LOG_ERROR("Failed to link elements");
     320            1 :             status = false;
     321              :         }
     322           20 :         m_context.gstVolumeElement = GST_STREAM_VOLUME(volume);
     323              :     }
     324              : 
     325           24 :     if (!status)
     326              :     {
     327              :         // Unref anything that wasn't added to the pipeline
     328           15 :         while (!elementsToAdd.empty())
     329              :         {
     330           10 :             m_gstWrapper->gstObjectUnref(elementsToAdd.front());
     331           10 :             elementsToAdd.pop();
     332              :         }
     333            5 :         m_context.source = nullptr;
     334              :     }
     335              : 
     336           24 :     return status;
     337              : }
     338              : 
     339           30 : void GstWebAudioPlayer::termWebAudioPipeline()
     340              : {
     341           30 :     if (m_context.pipeline)
     342              :     {
     343           29 :         m_taskFactory->createStop(*this)->execute();
     344           29 :         GstBus *bus = m_gstWrapper->gstPipelineGetBus(GST_PIPELINE(m_context.pipeline));
     345           29 :         if (bus)
     346              :         {
     347           28 :             m_gstWrapper->gstBusSetSyncHandler(bus, nullptr, nullptr, nullptr);
     348           28 :             m_gstWrapper->gstObjectUnref(bus);
     349              :         }
     350              : 
     351           29 :         m_gstWrapper->gstObjectUnref(m_context.pipeline);
     352              :     }
     353           30 : }
     354              : 
     355           30 : void GstWebAudioPlayer::resetWorkerThread()
     356              : {
     357           30 :     m_workerThread->enqueueTask(m_taskFactory->createShutdown(*this));
     358           30 :     m_workerThread->join();
     359           30 :     m_workerThread.reset();
     360              : }
     361              : 
     362            1 : void GstWebAudioPlayer::setCaps(const std::string &audioMimeType, std::weak_ptr<const WebAudioConfig> config)
     363              : {
     364            1 :     m_workerThread->enqueueTask(m_taskFactory->createSetCaps(m_context, audioMimeType, config));
     365              : }
     366              : 
     367            1 : void GstWebAudioPlayer::play()
     368              : {
     369            1 :     m_workerThread->enqueueTask(m_taskFactory->createPlay(*this));
     370              : }
     371              : 
     372            1 : void GstWebAudioPlayer::pause()
     373              : {
     374            1 :     m_workerThread->enqueueTask(m_taskFactory->createPause(*this));
     375              : }
     376              : 
     377            1 : void GstWebAudioPlayer::setVolume(double volume)
     378              : {
     379            1 :     m_workerThread->enqueueTask(m_taskFactory->createSetVolume(m_context, volume));
     380              : }
     381              : 
     382            1 : bool GstWebAudioPlayer::getVolume(double &volume)
     383              : {
     384              :     // Must be called on the main thread, otherwise the pipeline can be destroyed during the query.
     385            1 :     volume = m_gstWrapper->gstStreamVolumeGetVolume(m_context.gstVolumeElement, GST_STREAM_VOLUME_FORMAT_LINEAR);
     386            1 :     return true;
     387              : }
     388              : 
     389            2 : uint32_t GstWebAudioPlayer::writeBuffer(uint8_t *mainPtr, uint32_t mainLength, uint8_t *wrapPtr, uint32_t wrapLength)
     390              : {
     391              :     // Must block and wait for the data to be written from the shared buffer.
     392            2 :     std::unique_lock<std::mutex> lock(m_context.writeBufferMutex);
     393            2 :     m_workerThread->enqueueTask(m_taskFactory->createWriteBuffer(m_context, mainPtr, mainLength, wrapPtr, wrapLength));
     394            2 :     std::cv_status status = m_context.writeBufferCond.wait_for(lock, std::chrono::milliseconds(kMaxWriteBufferTimeoutMs));
     395            2 :     if (std::cv_status::timeout == status)
     396              :     {
     397            1 :         RIALTO_SERVER_LOG_ERROR("Timed out writing to the gstreamer buffers");
     398            1 :         return 0;
     399              :     }
     400              :     else
     401              :     {
     402            1 :         return m_context.lastBytesWritten;
     403              :     }
     404            2 : }
     405              : 
     406            1 : void GstWebAudioPlayer::setEos()
     407              : {
     408            1 :     m_workerThread->enqueueTask(m_taskFactory->createEos(m_context));
     409              : }
     410              : 
     411            1 : uint64_t GstWebAudioPlayer::getQueuedBytes()
     412              : {
     413              :     // Must be called on the main thread, otherwise the pipeline can be destroyed during the query.
     414            1 :     return m_gstWrapper->gstAppSrcGetCurrentLevelBytes(GST_APP_SRC(m_context.source));
     415              : }
     416              : 
     417            3 : bool GstWebAudioPlayer::changePipelineState(GstState newState)
     418              : {
     419            3 :     if (m_gstWrapper->gstElementSetState(m_context.pipeline, newState) == GST_STATE_CHANGE_FAILURE)
     420              :     {
     421            1 :         RIALTO_SERVER_LOG_ERROR("Change state failed - Gstreamer returned an error");
     422            1 :         if (m_gstPlayerClient)
     423            1 :             m_gstPlayerClient->notifyState(WebAudioPlayerState::FAILURE);
     424            1 :         return false;
     425              :     }
     426            2 :     return true;
     427              : }
     428              : 
     429            2 : void GstWebAudioPlayer::stopWorkerThread()
     430              : {
     431            2 :     if (m_workerThread)
     432              :     {
     433            2 :         m_workerThread->stop();
     434              :     }
     435              : }
     436              : 
     437            1 : void GstWebAudioPlayer::handleBusMessage(GstMessage *message)
     438              : {
     439            1 :     if (m_workerThread)
     440              :     {
     441            1 :         m_workerThread->enqueueTask(m_taskFactory->createHandleBusMessage(m_context, *this, message));
     442              :     }
     443              : }
     444              : 
     445            1 : void GstWebAudioPlayer::ping(std::unique_ptr<IHeartbeatHandler> &&heartbeatHandler)
     446              : {
     447            1 :     if (m_workerThread)
     448              :     {
     449            1 :         m_workerThread->enqueueTask(m_taskFactory->createPing(std::move(heartbeatHandler)));
     450              :     }
     451              : }
     452              : 
     453              : }; // namespace firebolt::rialto::server
        

Generated by: LCOV version 2.0-1