Subtitle Support

One of the more frequent questions from users of Serenity for Google TV, is the ability to play back subtitles with the movie. Plex does provide the information if it is there, but until Android 4.1 (aka Jelly Bean), there was no native subtitle support for the video player. Even then it seems to have problems with reading streams for the subtitles. Google TV devices are currently based on Android 3.2 (Honeycomb) which doesn’t have an api to play subtitles back. Plex in these cases would normally Transcode the subtitles into the video stream, however, Serenity doesn’t support transcoding. So what to do. Simple turn to open source software for some help.


Get it on Google Play

Hidden on GitHub is subtitleConverter by J. David Requejo. This was a PHD research project, and allows for converting from one subtitle format to another. The nice thing is that the TimedTextObject contains a general format for subtitles. Once it is in this format it is a matter of navigating the tree and checking the time offsets for when the title is displayed and when it should disappear.

Since Google TV devices don’t have native support for displaying the subtitles, how do we go about this. Serenity uses a modified version of the MediaController, and SurfaceView. The main activity contains the following layout xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/video_playeback"
    android:background="#000000"
    android:keepScreenOn="true" >
    
    <SurfaceView android:id="@+id/surfaceView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        />
    
    <TextView android:id="@+id/txtSubtitles"
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:visibility="invisible"
        style="@android:style/TextAppearance.Large"/>

</RelativeLayout>

This contains the surfaceview for the video to be drawn on, and a TextView to be used to display the subtitles.

For knowing when to display the subtitles during playback we use a Handler with a small time delay for when it should execute. The first time it is called with it’s runnable, it executes immediately. Every subsequent execution is delayed by 100 milliseconds.

private Handler subtitleDisplayHandler = new Handler();
private Runnable subtitle = new Runnable() {
 public void run() {
   if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
      int currentPos = mediaPlayer.getCurrentPosition();
      Collection<Caption> subtitles =  srt.captions.values();
      for(Caption caption : subtitles) {
         if (currentPos >= caption.start.getMilliseconds() && currentPos <= caption.end.getMilliseconds()) {
            onTimedText(caption);
            break;
  	 } else if (currentPos > caption.end.getMilliseconds()) {
	    onTimedText(null);
         }
      }
   }
   subtitleDisplayHandler.postDelayed(this, SUBTITLE_DISPLAY_CHECK);
 };
};

The postDelayed will re-execute the Handler with the runnable by the amount of milliseconds specified.

The onTimedText is what is responsible for displaying or hiding the subtitles during playback.


public void onTimedText(Caption text) {
   TextView subtitles = (TextView) findViewById(R.id.txtSubtitles);
   if (text == null) {
      subtitles.setVisibility(View.INVISIBLE);
      return;
   }
   subtitles.setText(Html.fromHtml(text.content));
   subtitles.setVisibility(View.VISIBLE);
}

Since the subtitles can be marked up with HTML to specify italics, bold, or underline we use the Html.fromHtml method to set the text as appropriate and set the visibility. If text came in null, the view is hidden.

The whole process is kicked off by a Async task that retrieves the Subtitles from Plex as a stream.

public class SubtitleAsyncTask extends AsyncTask<Void, Void, Void> {

  @Override
  protected Void doInBackground(Void... params) {
    if (subtitleURL != null) {
       try {
          URL url = new URL(subtitleURL);
          InputStream stream = url.openStream();
          FormatSRT formatSRT = new FormatSRT();
          srt = formatSRT.parseFile(stream);
          subtitleDisplayHandler.post(subtitle);
       } catch (Exception e) {
          Log.e(getClass().getName(), e.getMessage(), e);
       }
    }
    // TODO Auto-generated method stub
    return null;
  }
}

This just reads the stream, and parses the SubRip (SRT) formatted subtitles files into a TimedTextObject, and then starts the handler.

It is important to make sure when your Activity finishes that you remove any callbacks on the Handler. So make sure to do the following in your onFinish method:

   subtitleDisplayHandler.removeCallbacks(subtitle);

This should work regardless of Android version. It has been tested on Android 3.2 through the lastest JellyBean release. If you need to manipulate Subtitles, use them, or covert them to other formats, you may want to try out the subtitleConverter project. Expect to see this support with Serenity for Google TV v1.1.0.

About these ads
This entry was posted in android, googletv, open source, serenity. Bookmark the permalink.

10 Responses to Subtitle Support

  1. Sri says:

    Awesome post, worked like charm on Pre-Jellybean devices.
    Thanks buddy :)

  2. Sharath says:

    hi myself sharath, android developer (beginner) i need to provide different subtiles to the video on selection by user while playing server video please can anybody suggest me on this thanks in advance.

    • kingargyle says:

      You are probably better asking this on Stackoverflow than here. The basics though would be that you would need to have an on screen overlay that is displayed when they tap the screen, and then an on screen touchable item to bring up a selection for changing the subtitles.

  3. Sharath says:

    hi Sri, this is sharath i need to know that how did you implement FormatSRT class in displaying subtitle using above code snipet.

  4. Arvind says:

    I have to play a video of m3u8 format to which subtitle of webvtt format needs to be embedded. Both m3u8 video and vtt files are coming from server. I have used frame layout in which, video view to play the video and text view to display subtitle. But facing issue to display subtitles of webvtt format in android. Anyone can provide some suggestion.

  5. makis says:

    Is it possible to give me an example of a working code so i could understand it better and and it to my project?

  6. Sharath says:

    hi Is it possible to share project source download link so it will be very clear to us??

  7. Sharath says:

    hi can you pls add the download link soon,it will full fill my one module in my project.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s