Click here to Skip to main content
14,022,164 members
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 20 Sep 2011
Licenced CPOL

Creating a Subtitle/Closed Captions Plugin for SMF (Silverlight Media Framework)

, 20 Sep 2011
Rate this:
Please Sign up or sign in to vote.
This will walk you through the creation of a custom IMarkerProvider implementation, allowing to display SAMI subtitles in SMF (Silverlight Media Framework).


Silverlight Media Framework (or SMF), now a part of Microsoft Media Platform: Player Framework, is a feature-rich framework for developing media players in Silverlight. It contains a fairly comprehensive and skinnable UI, and supports a reasonable amount of video formats and delivery methods out-of-the-box. But currently, it's really lacking in the area of subtitles/closed-captions. This article will walk you through the creation of custom caption plugins to support any format you like.

The Code: Preamble

  • At the time of writing, MMPPF version 2.5 is the latest 'stable'. All development has been done against this version.
  • As this is extracted from a large scale closed-source commercial project, I cannot just provide the whole source, due to company rules, etc... Sorry about that!
  • I will start by creating a base class, which isn't very useful if you only want to support one format, but I swear this is not due to over-engineering! Once again, this is an excerpt from a much larger codebase, which features more than one supported format.
  • The file downloading part will be left out of the scope of this article. In my case, I have a complex utility class that handles both downloading and local IsolatedStorage caching. You can choose to handle the downloading in the plugin or outside, or use local files, whatever suits you best. A simplistic download solution is provided here.
  • This has been moderately tested only, as the code is quite 'fresh', so some bugs can still be present. Please report them in the comments!

SMF Plugin Basics

Before writing SMF plugins, you can read some official documentation:

  • The 'Plugin Developer Guide' is useful, it gives an overview and some details about the process of creating plugins, but it is not quite complete.
  • The API documentation (CHM) comes in handy quite often, but is sometimes outdated (see the 'Architecture' page for an example: no IMarkerProvider!)
  • The source code is sometimes the only real help, especially since it features some interesting samples, see 'Samples.MarkerProvider' in this case.

As SMF plugins make use of MEF (Managed Extensibility Framework), it could be useful to get acquainted with this beast. This is not mandatory if you just want to get going, but it could help a lot when debugging plugin loading, concurrency or performance issues.

The Implementation

The Common Base Class: SubTitlePlugin

The IPlugin interfaces contain quite a lot of members (see picture). Fortunately, you're probably using Visual Studio 2008 or 2010 to work with Silverlight, so you'll be able to save a lot of typing using the awesome 'implement interface' feature.

IMarkerProvider members

So let's get started writing code! First, I'll be creating a new empty class, named SubTitlePlugin, abstract and which implements Microsoft.SilverlightMediaFramework.Plugins.IMarkerProvider. This class will provide all common features for subtitle plugins, reducing code 'noise' when working with actual plugins. This will be very much 'required boilerplate'. Anyway, if you're not copy/pasting my code, you will want to right-click IMarkerProvider and select 'Implement interface' => 'Implement interface' in Visual Studio. This will generate stubs for all interface members, properties, methods and events. Now, let's fill our first public method.

/// <span class="code-SummaryComment"><summary>
</span>/// Start the retrieval of markers.
/// This is asynchronous.
/// <span class="code-SummaryComment"></summary>
</span>public void BeginRetrievingMarkers()
    if (Source == null)
        throw new ArgumentNullException("This requires a valid Source to download from");

    _cancelRequested = false;

    // Initiate file download.
    var localFileName = GetFileName(Source);
    DownloadManager.DownloadFile(url = Source, localFileName = localFileName, 
	source = this, maxAge = null, completed = ReadSubtitles, error = DownloadError);
    // Basic WebClient version:
    var client = new WebClient();
    client.DownloadStringCompleted += client_DownloadStringCompleted;

I've provided here a basic WebClient-based retrieval that you might use, but in the next steps, I will use my custom DownloadManager-based code. The DownloadManager method parameters should be self-explanatory, anyway, the interesting point here is that once the file is successfully downloaded, it will call ReadSubtitles, which will be our next method below, along with some private members and the other callback method DownloadError. If you were using the WebClient method, the main difference is that you get a string result instead of a byte[].

private bool _cancelRequested;
private MediaMarkerCollection<MediaMarker> _subtitles;

private void ReadSubtitles(object source, byte[] data)
    if (_cancelRequested)
        _cancelRequested = false;

        _subtitles = LoadMarkers(data);
    catch (Exception ex)
        if (RetrieveMarkersFailed != null)
            RetrieveMarkersFailed(this, ex);

    if (NewMarkers != null)
        NewMarkers(this, _subtitles);

private void DownloadError(object source, Exception error)
    if (RetrieveMarkersFailed != null)
        RetrieveMarkersFailed(this, error);

This is a very important method for our plugins. It calls the abstract protected LoadMarkers method, which will do the actual parsing of our chosen format. It also handles some mandatory event handling, especially the NewMarkers call, where the plugin is notifying the SMFPlayer that it has some content to provide, remember the interface name IMarkerProvider? If you were to forget this call, nothing would happen at all for the end user! Your plugin could properly parse the plugins and all, but they would never show up in the player!

Note: If you don't like the endless if (x != null) x(...); event firing constructs, the SMF source contains an extension method IfNotNull, that you might want to check out.

Now we have the core of the code for SubTitlePlugin! Most of the rest is automatic properties and events, except for the below two methods: Load and Unload. As their names imply, they contain initialization and cleanup code respectively.

/// <span class="code-SummaryComment"><summary>
</span>/// Loads the plug-in.
/// <span class="code-SummaryComment"></summary>
</span>public void Load()
        IsLoaded = true;
        if (PluginLoaded != null)
    catch (Exception ex)
        if (PluginLoadFailed != null)
            PluginLoadFailed(this, ex);

/// <span class="code-SummaryComment"><summary>
</span>/// Unloads the plug-in.
/// <span class="code-SummaryComment"></summary>
</span>public void Unload()
        _subtitles = null;

        IsLoaded = false;
        if (PluginUnloaded != null)
    catch (Exception ex)
        if (PluginUnloadFailed != null)
            PluginUnloadFailed(this, ex);

These methods are pretty straightforward: they handle event firing and provide two protected virtual (hence optional) methods to allow derived class to perform specific loading/unloading tasks.

That's all for the base class. You can find it in the source package here.

A Concrete Sub-class: SamiProvider

Up to this point, we didn't have to use anything related to MEF. The base class isn't instanciable, so it doesn't require MEF decorators. Our concrete format-specific classes on the other hand require some decorator 'magic' to be found by the SMFPlayer when it looks for plugins. The 'Plugin Developer Guide' provides good information here.

So, let's create a second class named SamiProvider which will be derived from SubTitlePlugin. Here is the whole code for this class:

/// <span class="code-SummaryComment"><summary>
</span>/// This class provides SAMI subtitle support as a SMF player plugin.
/// <span class="code-SummaryComment"></summary>
    PluginName = PluginName,
    PluginDescription = PluginDescription,
    PluginVersion = PluginVersion,
    SupportsPolling = false,
    SupportedFormat = "SAMI")]
public class SamiProvider : SubTitlePlugin
    #region MetaData
    private const string PluginName = "SAMICaptionsPlugin";
    private const string TypeAttribute = "type";
    private const string SubTypeAttribute = "subtype";
    private const string PluginDescription = 
	"Provides SMF with the ability to parse and display SAMI captions.";
    private const string PluginVersion = "1.0";

    /// <span class="code-SummaryComment"><summary>
</span>    /// Load the markers from the data.
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><param name="data">A SAMI file as a byte array</param>
</span>    /// <span class="code-SummaryComment"><returns>A collection of markers suitable for use with SMF</returns>
</span>    protected override MediaMarkerCollection<MediaMarker> LoadMarkers(byte[] data)
        SamiLoader loader = new SamiLoader();
        return loader.ParseSAMI(data);

Note: The whole MEF part is heavily based on the official sample mentioned earlier ('Samples.MarkerProvider' in the sources for MMPPF).

The first decorator is ExportMarkerProvider. Its three first parameters come from IPlugin, they are just a textual identity for the plugin. The other parameters are specific to IMarkerProvider.

  • SupportsPolling is false for this family of plugins, it's disabled in the SubTitlePlugin (see PollingInterval), it is not relevant for file-based, downloaded subtitles. It would be useful if using for instance a stream of markers.
  • The last parameter SupportedFormat is actually the most important of all. It's this parameter that will allow selection of this plugin to handle SAMI subtitles.

The second decorator, PartCreationPolicy, configures the instantiation of the plugin. I will direct you to the almighty MSDN for details. Here, we're saying we want one instance of the plugin per subtitle file. This is important as the retrieval and parsing are asynchronous, so we don't want multiple requests to mess up our plugin.

The SamiLoader class is where I parse the downloaded data into a collection of MediaMarkers. The real gotcha there is the use of CaptionRegion. You should create one for each continuous block of text that you wish to display.

Using the Plugin

Now we have the structure to create plugins, but they won't be activated yet. In my project, I'm using a CustomPlaylistItem, but for the sake of simplicity, I will just explain the method used. If you're interested by the custom playlist item, you can find it in the sources.

void SetupMarkers(PlaylistItem playListItem, string subtitleUrl)
    string format = "SAMI";
    var markers = new MarkerResource { Source = new Uri(subtitleUrl), Format = format };
    if (playListItem.MarkerResources != null)
        playListItem.MarkerResources = new List<MarkerResource>();

The key point here is the format specification. This will allow the right plugin to be selected. If you have multiple plugins, you can pick the one that matches your subtitle format by passing the corresponding string here.


  • 20 Sept 2011 - First version


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


About the Author

Julien Villers
Team Leader Multicam Systems
France France
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionWhere's the SAMILoader class? Pin
George I. Birbilis9-Jun-12 7:43
memberGeorge I. Birbilis9-Jun-12 7:43 
AnswerRe: Where's the SAMILoader class? Pin
Julien Villers9-Jun-12 9:02
professionalJulien Villers9-Jun-12 9:02 
QuestionRe: Where's the SAMILoader class? Pin
Leonardo Cabral19-Jul-12 3:15
memberLeonardo Cabral19-Jul-12 3:15 
AnswerRe: Where's the SAMILoader class? Pin
Julien Villers6-Aug-12 23:03
professionalJulien Villers6-Aug-12 23:03 
QuestionGreat Article! Pin
Member 859903914-Mar-12 7:20
memberMember 859903914-Mar-12 7:20 
AnswerRe: Great Article! Pin
Julien Villers14-Mar-12 7:28
professionalJulien Villers14-Mar-12 7:28 
GeneralRe: Great Article! Pin
Member 859903914-Mar-12 7:38
memberMember 859903914-Mar-12 7:38 
GeneralRe: Great Article! Pin
Julien Villers14-Mar-12 23:09
professionalJulien Villers14-Mar-12 23:09 
GeneralRe: Great Article! Pin
Member 859903915-Mar-12 4:37
memberMember 859903915-Mar-12 4:37 
GeneralRe: Great Article! Pin
Julien Villers15-Mar-12 4:49
professionalJulien Villers15-Mar-12 4:49 
GeneralRe: Great Article! Pin
Member 859903915-Mar-12 6:06
memberMember 859903915-Mar-12 6:06 
GeneralRe: Great Article! Pin
George I. Birbilis8-Aug-12 2:42
memberGeorge I. Birbilis8-Aug-12 2:42 
GeneralCode Sample Pin
yasmin.fathy11-Oct-11 1:18
memberyasmin.fathy11-Oct-11 1:18 
GeneralRe: Code Sample Pin
Julien Villers11-Oct-11 1:27
professionalJulien Villers11-Oct-11 1:27 
GeneralRe: Code Sample Pin
Member 431023513-Nov-11 9:17
memberMember 431023513-Nov-11 9:17 
GeneralRe: Code Sample Pin
Julien Villers14-Dec-11 0:16
professionalJulien Villers14-Dec-11 0:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190417.4 | Last Updated 20 Sep 2011
Article Copyright 2011 by Julien Villers
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid