In this article you will find an implementation of a stream player control.

Introduction

This article is a sort of continuation of my previous article, which shows an implementation of a web camera control. Recently I created another control and would like to share my experience with community. It is a FFmpeg-based stream player control, which can do the following:

  1. Play a RTSP/RTMP video stream or local video file
  2. Retrieve the current frame being displayed by the control

The control has no additional dependencies and a minimalistic interface.

Requirements

  1. The WinForms version of the control is implemented using .NET Framework 2.0
  2. The WPF version of the control is implemented using .NET Framework 4 Client Profile

The control supports both x86 and x64 platform targets.

Background

Streaming audio, video and data over the Internet is a very usual thing these days. However, when I tried to find a .NET control to play a video stream sent over the network, I found almost nothing. This project tries to fill up that gap.

Implementation details

If you are not interested in implementation details, then you can skip this section.

The implementation is divided into three layers.

  1. The bottom layer is implemented as a native DLL module, which forwards our calls to the FFmpeg framework.
  2. For distribution convenience, the native DLL module is embedded into the control’s assembly as a resource. On the runtime stage, the DLL module will be extracted to a temporary file on disk and used via late binding technique. Once the control is disposed, the temporary file will be deleted. In other words, the control is distributed as a single file. All those operations are implemented by the middle layer.
  3. The top layer implements the control class itself.

The following diagram shows a logical structure of the implementation.

Only the top layer is supposed to be used by clients.

The Bottom Layer

The bottom layer uses the facade pattern to provide a simplified interface to the FFmpeg framework. The facade consists of three classes: the StreamPlayer class, which implements a stream playback functionality

Hide    Shrink     Copy Code
/// <summary>
/// The StreamPlayer class implements a stream playback functionality.
/// </summary>
class StreamPlayer : private boost::noncopyable
{
public: /// <summary>
/// Initializes a new instance of the StreamPlayer class.
/// </summary>
StreamPlayer(); /// <summary>
/// Initializes the player.
/// </summary>
/// <param name="playerParams">The StreamPlayerParams object that contains the information that is used to initialize the player.</param>
void Initialize(StreamPlayerParams playerParams); /// <summary>
/// Asynchronously plays a stream.
/// </summary>
/// <param name="streamUrl">The url of a stream to play.</param>
void StartPlay(std::string const& streamUrl); /// <summary>
/// Retrieves the current frame being displayed by the player.
/// </summary>
/// <param name="bmpPtr">Address of a pointer to a byte that will receive the DIB.</param>
void GetCurrentFrame(uint8_t **bmpPtr); /// <summary>
/// Retrieves the unstretched frame size, in pixels.
/// </summary>
/// <param name="widthPtr">A pointer to an int that will receive the width.</param>
/// <param name="heightPtr">A pointer to an int that will receive the height.</param>
void GetFrameSize(uint32_t *widthPtr, uint32_t *heightPtr); /// <summary>
/// Uninitializes the player.
/// </summary>
void Uninitialize();
};

the Stream class, which converts a video stream into series of frames

Hide    Copy Code
/// <summary>
/// A Stream class converts a stream into series of frames.
/// </summary>
class Stream : private boost::noncopyable
{
public:
/// <summary>
/// Initializes a new instance of the Stream class.
/// </summary>
/// <param name="streamUrl">The url of a stream to decode.</param>
Stream(std::string const& streamUrl); /// <summary>
/// Gets the next frame in the stream.
/// </summary>
/// <returns>The next frame in the stream.</returns>
std::unique_ptr<Frame> GetNextFrame(); /// <summary>
/// Gets an interframe delay, in milliseconds.
/// </summary>
int32_t InterframeDelayInMilliseconds() const; /// <summary>
/// Releases all resources used by the stream.
/// </summary>
~Stream();
};

and the Frame class, which is a set of frame related utilities.

Hide    Shrink     Copy Code
/// <summary>
/// The Frame class implements a set of frame-related utilities.
/// </summary>
class Frame : private boost::noncopyable
{
public:
/// <summary>
/// Initializes a new instance of the Frame class.
/// </summary>
Frame(uint32_t width, uint32_t height, AVPicture &avPicture); /// <summary>
/// Gets the width, in pixels, of the frame.
/// </summary>
uint32_t Width() const { return width_; } /// <summary>
/// Gets the height, in pixels, of the frame.
/// </summary>
uint32_t Height() const { return height_; } /// <summary>
/// Draws the frame.
/// </summary>
/// <param name="window">A container window that frame should be drawn on.</param>
void Draw(HWND window); /// <summary>
/// Converts the frame to a bitmap.
/// </summary>
/// <param name="bmpPtr">Address of a pointer to a byte that will receive the DIB.</param>
void ToBmp(uint8_t **bmpPtr); /// <summary>
/// Releases all resources used by the frame.
/// </summary>
~Frame();
};

These tree classes form a heart of the FFmpeg Facade DLL module.

The Middle Layer

The middle layer is implemented by the StreamPlayerProxy class, which serves as a proxy to the FFmpeg Facade DLL module.

First, what we should do is extract the FFmpeg Facade DLL module from the resources and save it to a temporary file.

Hide    Copy Code
_dllFile = Path.GetTempFileName();
using (FileStream stream = new FileStream(_dllFile, FileMode.Create, FileAccess.Write))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(Resources.StreamPlayer);
}
}

Then we load our DLL module into the address space of the calling process.

Hide    Copy Code
_hDll = LoadLibrary(_dllFile);
if (_hDll == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

And bind the DLL module functions to the class instance methods.

Hide    Copy Code
private delegate Int32 StopDelegate();
private StopDelegate _stop; // ... IntPtr procPtr = GetProcAddress(_hDll, "Stop");
_stop =
(StopDelegate)Marshal.GetDelegateForFunctionPointer(procPtr,
typeof(StopDelegate));

When the control is being disposed, we unload the DLL module and delete it.

Hide    Copy Code
private void Dispose()
{
if (_hDll != IntPtr.Zero)
{
FreeLibrary(_hDll);
_hDll = IntPtr.Zero;
} if (File.Exists(_dllFile))
{
File.Delete(_dllFile);
}
}

The Top Layer

The top layer is implemented by the StreamPlayerControl class with the following interface.

Hide    Shrink     Copy Code
/// <summary>
/// Asynchronously plays a stream.
/// </summary>
/// <param name="uri">The url of a stream to play.</param>
/// <exception cref="ArgumentException">An invalid string is passed as an argument.</exception>
/// <exception cref="Win32Exception">Failed to load the FFmpeg facade dll.</exception>
/// <exception cref="StreamPlayerException">Failed to play the stream.</exception>
public void StartPlay(Uri uri) /// <summary>
/// Retrieves the image being played.
/// </summary>
/// <returns>The current image.</returns>
/// <exception cref="InvalidOperationException">The control is not playing a video stream.</exception>
/// <exception cref="StreamPlayerException">Failed to get the current image.</exception>
public Bitmap GetCurrentFrame(); /// <summary>
/// Stops a stream.
/// </summary>
/// <exception cref="InvalidOperationException">The control is not playing a stream.</exception>
/// <exception cref="StreamPlayerException">Failed to stop a stream.</exception>
public void Stop(); /// <summary>
/// Gets a value indicating whether the control is playing a video stream.
/// </summary>
public Boolean IsPlaying { get; } /// <summary>
/// Gets the unstretched frame size, in pixels.
/// </summary>
public Size VideoSize { get; } /// <summary>
/// Occurs when the first frame is read from a stream.
/// </summary>
public event EventHandler StreamStarted; /// <summary>
/// Occurs when there are no more frames to read from a stream.
/// </summary>
public event EventHandler StreamStopped; /// <summary>
/// Occurs when the player fails to play a stream.
/// </summary>
public event EventHandler StreamFailed;

Usage

First, we need to add the control to the Visual Studio Designer Toolbox, using a right-click and then the "Choose Items..." menu item. Then we place the control on a form at the desired location and with the desired size. The default name of the control instance variable will be streamPlayerControl1.

The following code asynchronously plays a stream using the supplied address.

Hide    Copy Code
streamPlayerControl1.StartPlay(new Uri("rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov"));

To get a frame being played just call the GetCurrentFrame() method. The resolution and quality of the frame depend on the stream quality.

Hide    Copy Code
using (Bitmap image = streamPlayerControl1.GetCurrentFrame())
{
// image processing...
}

To stop the stream the Stop() method is used.

Hide    Copy Code
streamPlayerControl1.Stop();

You can always check the playing state using the following code.

Hide    Copy Code
if (streamPlayerControl1.IsPlaying)
{
streamPlayerControl1.Stop();
}

Also, the StreamStarted, StreamStopped and StreamFailed events can be used to monitor the playback state.

To report errors, exceptions are used, so do not forget to wrap your code in a try/catch block. That is all about using it. To see a complete example please check the demo application sources.

WPF version

The FFmpeg facade expects a WinAPI window handle (HWND) in order to use it as a render target. The issue is that in the WPF world windows do not have handles anymore. The VideoWindow class workarounds this issue.

Hide    Copy Code
<UserControl x:Class="WebEye.StreamPlayerControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
xmlns:local="clr-namespace:WebEye">
<local:VideoWindow x:Name="_videoWindow"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</UserControl>

GitHub

The project has a GitHub repository available on the following page.

https://github.com/jacobbo/WebEye/tree/master/StreamPlayerControl

Any questions, remarks, and comments are welcome.

Licensing

  1. The FFmpeg facade sources, the same as the FFmpegframework, are licensed under The LGPL license.
  2. The .NET controls' sources and demos' sources are licensed under The Code Project Open License (CPOL).

You can use the control in your commercial product, the only thing is that you should mention that your product uses the FFmpeg library, here are the details.

History

  • March 19th, 2015 - The initial version.
  • August 22nd, 2015 - Added the x64 platform support.
  • October 25th, 2015 - Added asyncronous stream start and stream status events.
  • November 8th, 2015 - Added support for local files playback.
  • November 30th, 2015 - Added stream connection timeout.
&amp;amp;amp;lt;a href="https://pubads.g.doubleclick.net/gampad/jump?iu=/6839/lqm.codeproject.site/Multimedia/Audio-and-Video/Video&amp;amp;amp;amp;sz=300x250&amp;amp;amp;amp;c=774823"&amp;amp;amp;gt;&amp;amp;amp;lt;img src="https://pubads.g.doubleclick.net/gampad/jump?iu=/6839/lqm.codeproject.site/Multimedia/Audio-and-Video/Video&amp;amp;amp;amp;sz=300x250&amp;amp;amp;amp;c=774823" width="300px" height="250px" target="_blank"/&amp;amp;amp;gt;&amp;amp;amp;lt;/a&amp;amp;amp;gt;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Stream Player control的更多相关文章

  1. [Winform]Media Player组件全屏播放的设置

    摘要 在设置程序开始运行时,让视频全屏播放时,直接设置 windowsMediaPlay.fullScreen = true; 会报错,代码如下 windowsMediaPlay.URL = _vid ...

  2. 关于 datasnap Stream的英文博客能容

    转载:http://blogs.embarcadero.com/jimtierney/2009/04/06/31461/ DataSnap Server Method Stream Parameter ...

  3. 使用Quicktime 实现视频直播(Live video using Quicktime) (转)

    Quicktime是一个跨浏览器的播放插件,可以实现RTSP视频直播,可用于电视直播或视频监控平台.本文主要讲了关于播放器如何实现直播.事件响应.播放器全屏.动态修改播放路径等问题. 需要准备的软件: ...

  4. Unity3D 第一人称控制器 C#脚本

    CharacterMotor.cs using UnityEngine; using System.Collections; /** * @Author : www.xuanyusong.com */ ...

  5. http2协议翻译(转)

    超文本传输协议版本 2 IETF HTTP2草案(draft-ietf-httpbis-http2-13) 摘要 本规范描述了一种优化的超文本传输协议(HTTP).HTTP/2通过引进报头字段压缩以及 ...

  6. Cisco IOS Debug Command Reference I through L

    debug iapp through debug ip ftp debug iapp : to begin debugging of IAPP operations(in privileged EXE ...

  7. The Brain as a Universal Learning Machine

    The Brain as a Universal Learning Machine This article presents an emerging architectural hypothesis ...

  8. PhysX

    [PhysX] 1.施加力: ))) { //施加一个力,X轴方向力度为1000,Y轴方向力度为1000 addFrceObj.rigidbody.AddForce (, , ); } ))) { / ...

  9. (史上最全的ios源码汇总)

    按钮类         按钮 Drop Down Control         http://www.apkbus.com/android-106661-1-1.html 按钮-Circular M ...

随机推荐

  1. SWT:获取字符串实际宽度

    由于SWT取用的是系统文字size,有个简单方式可以获取一整段包含中文\英文\数字\特殊字符的字符串宽度. 即是利用Label的computeSize方法,我们知道Label的大小可以随着内容文字伸缩 ...

  2. Java虚拟机12:Java内存模型

    什么是Java内存模型 Java虚拟机规范中试图定义一种Java内存模型(Java Memory Model,JMM)来屏蔽掉各种硬件和操作系统的访问差异,以实现让Java程序在各种平台下都能达到一致 ...

  3. js只需5分钟创建一个跨三大平台纯原生APP

    DeviceOne之前介绍过了,现在来介绍一下DeviceOne快速开发到什么程度 使用js只需要5分钟就可以打出垮Android.ios.windows三大平台的纯原生UI的安装包. 只需要6个小时 ...

  4. 用curl向指定地址POST一个JSON格式的数据

    昨天的一个任务,用POST 方式向一个指定的URL推送数据.以前都用的数组来完成这个工作. 现在要求用json格式.感觉应该是一样的.开写. <?php $post_url = "ht ...

  5. 自制Unity小游戏TankHero-2D(1)制作主角坦克

    自制Unity小游戏TankHero-2D(1)制作主角坦克 我在做这样一个坦克游戏,是仿照(http://game.kid.qq.com/a/20140221/028931.htm)这个游戏制作的. ...

  6. 人机大战之AlphaGo的硬件配置和算法研究

    AlphaGo的硬件配置 最近AlphaGo与李世石的比赛如火如荼,关于第四盘李世石神之一手不在我们的讨论范围之内.我们重点讨论下AlphaGo的硬件配置: AlphaGo有多个版本,其中最强的是分布 ...

  7. Windows 10 下安装 npm 后全局 node_modules 和 npm-cache 文件夹的设置

    npm 指 Node Package Manager,是 Node.js 中一个流行的包管理和分发工具.Node.js 在某个版本的 Windows 安装包开始已经加入了 npm,现在可以进入 htt ...

  8. IOS Socket 04-利用框架CocoaAsyncSocket实现客户端/服务器端

    这篇文章,我们介绍CocoaAsyncSocket框架的使用,主要介绍实现客户端/服务器端代码,相信在网上已经很多这样的文章了,这里做一下自己的总结.这里介绍使用GCD方式 一.客户端 1.下载地址 ...

  9. jmx : ClientCommunicatorAdmin Checker-run

    今天遇到一个问题: 执行bat,关闭jmx的时候,由于程序关闭之后又去连接了一次,cmd窗口报错,类似: 2013-7-11 15:58:05 ClientCommunicatorAdmin rest ...

  10. MVVM架构~Knockoutjs系列之text,value,attr,visible,with的数据绑定

    返回目录 Knockoutjs是微软mvc4里一个新东西,用这在MVC环境里实现MVVM,小微这次没有大张旗鼓,而是愉愉的为我们开发者嵌入了一个实现MVVM的插件,这下面的几篇文章中,我和大家将一起去 ...