diff --git a/api/source/mk_media.cpp b/api/source/mk_media.cpp index 1c6c9d76..402546fa 100755 --- a/api/source/mk_media.cpp +++ b/api/source/mk_media.cpp @@ -20,8 +20,10 @@ class MediaHelper : public MediaSourceEvent , public std::enable_shared_from_thi public: using Ptr = std::shared_ptr; template - MediaHelper(ArgsType &&...args){ - _channel = std::make_shared(std::forward(args)...); + MediaHelper(ArgsType &&...args) { + _poller = EventPollerPool::Instance().getPoller(); + // 在poller线程中创建DevChannel(MultiMediaSourceMuxer)对象,确保严格的线程安全限制 + _poller->sync([&]() { _channel = std::make_shared(std::forward(args)...); }); } ~MediaHelper() = default; @@ -102,7 +104,12 @@ protected: } } + toolkit::EventPoller::Ptr getOwnerPoller(MediaSource &sender) { + return _poller; + } + private: + EventPoller::Ptr _poller; DevChannel::Ptr _channel; on_mk_media_close _on_close = nullptr; on_mk_media_seek _on_seek = nullptr; diff --git a/src/Common/Device.cpp b/src/Common/Device.cpp index f858f12f..2b1edfab 100644 --- a/src/Common/Device.cpp +++ b/src/Common/Device.cpp @@ -179,6 +179,27 @@ bool DevChannel::initAudio(const AudioInfo &info) { } } +bool DevChannel::inputFrame(const Frame::Ptr &frame) { + auto cached_frame = Frame::getCacheAbleFrame(frame); + weak_ptr weak_self = shared_from_this(); + getOwnerPoller(MediaSource::NullMediaSource())->async([weak_self, cached_frame]() { + if (auto strong_self = weak_self.lock()) { + strong_self->MultiMediaSourceMuxer::inputFrame(cached_frame); + } + }); + return true; +} + +bool DevChannel::addTrack(const Track::Ptr &track) { + bool ret; + getOwnerPoller(MediaSource::NullMediaSource())->sync([&]() { ret = MultiMediaSourceMuxer::addTrack(track); }); + return ret; +} + +void DevChannel::addTrackCompleted() { + getOwnerPoller(MediaSource::NullMediaSource())->sync([&]() { MultiMediaSourceMuxer::addTrackCompleted(); }); +} + MediaOriginType DevChannel::getOriginType(MediaSource &sender) const { return MediaOriginType::device_chn; } diff --git a/src/Common/Device.h b/src/Common/Device.h index 8c78da46..963fb0dc 100644 --- a/src/Common/Device.h +++ b/src/Common/Device.h @@ -118,6 +118,11 @@ public: */ bool inputPCM(char *data, int len, uint64_t cts); + //// 重载基类方法,确保线程安全 //// + bool inputFrame(const Frame::Ptr &frame) override; + bool addTrack(const Track::Ptr & track) override; + void addTrackCompleted() override; + private: MediaOriginType getOriginType(MediaSource &sender) const override; diff --git a/src/Common/MediaSink.cpp b/src/Common/MediaSink.cpp index e88f56ee..66062b97 100644 --- a/src/Common/MediaSink.cpp +++ b/src/Common/MediaSink.cpp @@ -172,7 +172,7 @@ void MediaSink::emitAllTrackReady() { continue; } pr.second.for_each([&](const Frame::Ptr &frame) { - inputFrame(frame); + MediaSink::inputFrame(frame); }); } _frame_unread.clear();