Commit c7b5ec92 by Prem Sichanugrist

Refactor video caption to use binary search

parent b7c44a43
class VideoCaption class VideoCaption
constructor: (@player, @youtubeId) -> constructor: (@player, @youtubeId) ->
@index = []
@render() @render()
@bind() @bind()
...@@ -29,6 +28,12 @@ class VideoCaption ...@@ -29,6 +28,12 @@ class VideoCaption
@$('.subtitles').css maxHeight: @$('.video-wrapper').height() - 5 @$('.subtitles').css maxHeight: @$('.video-wrapper').height() - 5
@fetchCaption() @fetchCaption()
fetchCaption: ->
$.getWithPrefix @captionURL(), (captions) =>
@captions = captions.text
@start = captions.start
@renderCaption()
renderCaption: -> renderCaption: ->
container = $('<ol>') container = $('<ol>')
...@@ -44,28 +49,28 @@ class VideoCaption ...@@ -44,28 +49,28 @@ class VideoCaption
@$('.subtitles').prepend($('<li class="spacing">').height(@topSpacingHeight())) @$('.subtitles').prepend($('<li class="spacing">').height(@topSpacingHeight()))
.append($('<li class="spacing">').height(@bottomSpacingHeight())) .append($('<li class="spacing">').height(@bottomSpacingHeight()))
fetchCaption: -> search: (time) ->
$.getWithPrefix @captionURL(), (captions) => min = 0
@captions = captions.text max = @start.length - 1
@start = captions.start
for index in [0...captions.start.length] while min < max
for time in [captions.start[index]..captions.end[index]] index = Math.ceil((max + min) / 2)
@index[time] ||= [] if time < @start[index]
@index[time].push(index) max = index - 1
@renderCaption() if time >= @start[index]
min = index
return min
onUpdatePlayTime: (event, time) => onUpdatePlayTime: (event, time) =>
# This 250ms offset is required to match the video speed # This 250ms offset is required to match the video speed
time = Math.round(Time.convert(time, @player.currentSpeed(), '1.0') * 1000 + 250) time = Math.round(Time.convert(time, @player.currentSpeed(), '1.0') * 1000 + 250)
newIndex = @index[time] newIndex = @search time
if newIndex != undefined && @currentIndex != newIndex if newIndex != undefined && @currentIndex != newIndex
if @currentIndex if @currentIndex
for index in @currentIndex @$(".subtitles li.current").removeClass('current')
@$(".subtitles li[data-index='#{index}']").removeClass('current') @$(".subtitles li[data-index='#{newIndex}']").addClass('current')
for index in newIndex
@$(".subtitles li[data-index='#{newIndex}']").addClass('current')
@currentIndex = newIndex @currentIndex = newIndex
@scrollCaption() @scrollCaption()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment