Linux基於webRTC的二次開發(二) 實現遠程桌面共享


webRTC中的desktop_capture模塊提供了捕獲桌面和捕獲窗口的相關功能,而實現遠程桌面共享功能需要將desktop_capture捕獲的畫面作為peerconnection的視頻源,下面介紹一下相關的方法

peerconnection添加視頻源時調用AddTrack(rtc::scoped_refptr<MediaStreamTrackInterface> track,const std::vector<std::string>& stream_ids);,我們需要傳入一個rtc::scoped_refptr<webrtc::VideoTrackInterface>類型作為視頻源,使用PeerConnectionFactoryInterface::CreateVideoTrack(const std::string& label,VideoTrackSourceInterface* source)創建。

可以看到,我們需要獲得VideoTrackSourceInterface*
webrtc提供了AdaptedVideoTrackSource類,該類繼承自VideoTrackSourceInterface。我們需要繼承實現AdaptedVideoTrackSource,在其中添加捕獲桌面獲得的圖像,然后將其傳入父類的OnFrame函數即可
簡單代碼如下

class MyDesktopCapture : public rtc::AdaptedVideoTrackSource, public webrtc::DesktopCapturer::Callback
{
public:
  explicit MyDesktopCapture();

  static rtc::scoped_refptr<MyDesktopCapture> Create();

  void OnCaptureResult(webrtc::DesktopCapturer::Result result, std::unique_ptr<webrtc::DesktopFrame> desktopframe) override;

  bool is_screencast() const override;

  absl::optional<bool> needs_denoising() const override;

  webrtc::MediaSourceInterface::SourceState state() const override;

  bool remote() const override;

private:

  std::unique_ptr<CaptureThread> capture_;

};

其中OnCaptureResult作為DesktopCatpure的回調,在桌面捕獲獲得圖像時會調用該方法
由於桌面捕獲獲得的DesktopFrame都是RGBA數據,我們需要將其轉換成存放I420數據的VideoFrame,然后調用OnFrame

現在新版本的webrtc不提供ConvertToI420方法,我們需要自己用libyuv實現,將RGBA轉換為I420

void MyDesktopCapture::OnCaptureResult(webrtc::DesktopCapturer::Result result, std::unique_ptr<webrtc::DesktopFrame> desktopframe)
{
    if(result!=webrtc::DesktopCapturer::Result::SUCCESS)
        return;
    int width=desktopframe->size().width();
    int height=desktopframe->size().height();

    rtc::scoped_refptr<webrtc::I420Buffer> buffer=webrtc::I420Buffer::Create(width,height);
    int stride=width;
    uint8_t* yplane=buffer->MutableDataY();
    uint8_t* uplane=buffer->MutableDataU();
    uint8_t* vplane=buffer->MutableDataV();
    libyuv::ConvertToI420(desktopframe->data(),0,
                          yplane,stride,
                          uplane,(stride+1)/2,
                          vplane,(stride+1)/2,
                          0,0,
                          width,height,
                          width,height,
                          libyuv::kRotate0,libyuv::FOURCC_ARGB);
    webrtc::VideoFrame frame=webrtc::VideoFrame(buffer,0,0,webrtc::kVideoRotation_0);
    this->OnFrame(frame);

}

最后我們使用該類創建VideoTrack,添加進peerconnection即可
實現效果如下圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM