stickyworld 的网页应用已经支持视频拨放一段时间,但都是通过youtube的嵌入模式实现。我们开始提供新的版本支持视频操作,可以让我们的用户不用受制于youtube的服务。
我过去曾经参与过一个项目,客户需要视频转码功能,这实在不是个容易达成的需求。需要大量的读取每一个视频、音讯与视频容器的格式再输出符合网页使用与喜好的视频格式。
考虑到这一点,我们决定将转码的工作交给 encoding.com 。这个网站可以免费让你编码1gb大小的视频,超过1gb容量的文件将采取分级计价收费。
开发的代码如下,我上传了一个178kb容量的两秒视频来测试代码是否成功运作。当测试过程没有发生任何的例外错误后,我继续测试其它更大的外部文件。
阶段一:用户上传视频文件
现在这的新的代码段提供了一个基于 html5且可以快速上手的 的上传机制。用coffeescript撰写的代码,可以从客户端上传文件到服务器端。
$scope.upload_slide = (upload_slide_form) ->
file = document.getelementbyid(“slide_file”).files[0]
reader = new filereader()
reader.readasdataurl file
reader.onload = (event) ->
result = event.target.result
filename = document.getelementbyid(“slide_file”).files[0].name
$.post “/world/upload_slide”,
data: result
name: filename
room_id: $scope.room.id
(response_data) ->
if response_data.success? is not yes
console.error “there was an error uploading the file”, response_data
else
console.log “upload successful”, response_data
reader.onloadstart = ->
console.log “onloadstart”
reader.onprogress = (event) ->
console.log “onprogress”, event.total, event.loaded, (event.loaded / event.total) * 100
reader.onabort = ->
console.log “onabort”
reader.onerror = ->
console.log “onerror”
reader.onloadend = (event) ->
console.log “onloadend”, event
最好可以通过 (“slide_file”).files 且经由独立的post上传每个文件,而不是由一个post需求上传所有文件。稍后我们会解释这点。
阶段二:验证并上传至 amazon s3
后端我们运行了django与rabbitmq。主要的模块如下:
$ pip install ‘django>=1.5.2’ ‘django-celery>=3.0.21’ \
‘django-storages>=1.1.8’ ‘lxml>=3.2.3’ ‘python-magic>=0.4.3’
我建立了两个模块:slideuploadqueue 用来储存每一次上传的数据,slidevideomedia 则是用来储存每个要上传影片的数据。
class slideuploadqueue(models.model):
created_by = models.foreignkey(user)
created_time = models.datetimefield(db_index=true)
original_file = models.filefield(
upload_to=filename_sanitiser, blank=true, default=”)
media_type = models.foreignkey(mediatype)
encoding_com_tracking_code = models.charfield(
default=”, max_length=24, blank=true)
status_awaiting_data = 0
status_awaiting_processing = 1
status_processing = 2
status_awaiting_3rd_party_processing = 5
status_finished = 3
status_failed = 4
status_list = (
(status_awaiting_data, ‘awaiting data’),
(status_awaiting_processing, ‘awaiting processing’),
(status_processing, ‘processing’),
(status_awaiting_3rd_party_processing,
‘awaiting 3rd-party processing’),
(status_finished, ‘finished’),
(status_failed, ‘failed’),
)
status = models.positivesmallintegerfield(
default=status_awaiting_data, choices=status_list)
class meta:
verbose_name = ‘slide’
verbose_name_plural = ‘slide upload queue’
def save(self, *args, **kwargs):
if not self.created_time:
self.created_time = \
datetime.utcnow().replace(tzinfo=pytz.utc)
return super(slideuploadqueue, self).save(*args, **kwargs)
def __unicode__(self):
if self.id is none:
return ‘new ‘
return ‘ %d’ % self.id
class slidevideomedia(models.model):
converted_file = models.filefield(
upload_to=filename_sanitiser, blank=true, default=”)
format_mp4 = 0
format_webm = 1
format_ogg = 2
format_fl9 = 3
format_thumb = 4
supported_formats = (
(format_mp4, ‘mpeg 4’),
(format_webm, ‘webm’),
(format_ogg, ‘ogg’),
(format_fl9, ‘flash 9 video’),
(format_thumb, ‘thumbnail’),
)
mime_types = (
(format_mp4, ‘video/mp4’),
(format_webm, ‘video/webm’),
(format_ogg, ‘video/ogg’),
(format_fl9, ‘video/mp4’),
(format_thumb, ‘image/jpeg’),
)
format = models.positivesmallintegerfield(
default=format_mp4, choices=supported_formats)
class meta:
verbose_name = ‘slide video’
verbose_name_plural = ‘slide videos’
def __unicode__(self):
if self.id is none:
return ‘new ‘
return ‘ %d’ % self.id
我们的模块皆使用 filename_sanitiser。filefield 自动的将文件名调整成 /. 格式。整理每个文件名并确保其独一性。我们采用了有时效性签署的网址列让我们可以掌控哪些使用者在使用我们的服务,使用了多久。
def filename_sanitiser(instance, filename):
folder = instance.__class__.__name__.lower()
ext = ‘jpg’
if ‘.’ in filename:
t_ext = filename.split(‘.’)[-1].strip().lower()
if t_ext != ”:
ext = t_ext
return ‘%s/%s.%s’ % (folder, str(uuid.uuid4()), ext)
拿来测试的文件 testing.mov 将会转换成以下网址:https://our-bucket.s3.amazonaws.com/slideuploadqueue/3fe27193-e87f-4244-9aa2-66409f70ebd3.mov 并经由django storages 模块上传。
我们通过 magic 验证从使用者端浏览器上传的文件。magic可以从文件内容侦测是何种类型的文件。
@verify_auth_token
@return_json
def upload_slide(request):
file_data = request.post.get(‘data’, ”)
file_data = base64.b64decode(file_data.split(‘;base64,’)[1])
description = magic.from_buffer(file_data)
如果文件类型符合mpeg v4 系统或是apple quicktime 电影,我们就知道该文件转码不会有太大问题。如果格式不是上述所提的几种,我们会标志给用户知悉。
接着,我们将通过slideuploadqueue 模块将视频储存到队列并发送一个需求给 rabbitmq。因为我们使用了django storages 模块,文件将自动被上传到 amazon s3。
slide_upload = slideuploadqueue()
…
slide_upload.status = slideuploadqueue.status_awaiting_processing
slide_upload.save()
slide_upload.original_file.\
save(‘anything.%s’ % file_ext, contentfile(file_data))
slide_upload.save()
task = convertrawslidetoslide()
task.delay(slide_upload)
阶段3:发送视频到第三方.
rabbitmq 将控管 task.delay(slide_upload) 的呼叫。
我们现在只需要发送视频档网址与输出格式给encoding.com。该网站会回复我们一个工作码让我们检查视频转码的进度。
class convertrawslidetoslide(task):
queue = ‘backend_convert_raw_slides’
…
def _handle_video(self, slide_upload):
mp4 = {
‘output’: ‘mp4’,
‘size’: ‘320×240’,
‘bitrate’: ‘256k’,
‘audio_bitrate’: ’64k’,
‘audio_channels_number’: ‘2’,
‘keep_aspect_ratio’: ‘yes’,
‘video_codec’: ‘mpeg4’,
‘profile’: ‘main’,
‘vcodecparameters’: ‘no’,
‘audio_codec’: ‘libfaac’,
‘two_pass’: ‘no’,
‘cbr’: ‘no’,
‘deinterlacing’: ‘no’,
‘keyframe’: ‘300’,
‘audio_volume’: ‘100’,
‘file_extension’: ‘mp4’,
‘hint’: ‘no’,
}
webm = {
‘output’: ‘webm’,
‘size’: ‘320×240’,
‘bitrate’: ‘256k’,
‘audio_bitrate’: ’64k’,
‘audio_sample_rate’: ‘44100’,
‘audio_channels_number’: ‘2’,
‘keep_aspect_ratio’: ‘yes’,
‘video_codec’: ‘libvpx’,
‘profile’: ‘baseline’,
‘vcodecparameters’: ‘no’,
‘audio_codec’: ‘libvorbis’,
‘two_pass’: ‘no’,
‘cbr’: ‘no’,
‘deinterlacing’: ‘no’,
‘keyframe’: ‘300’,
‘audio_volume’: ‘100’,
‘preset’: ‘6’,
‘file_extension’: ‘webm’,
‘acbr’: ‘no’,
}
ogg = {
‘output’: ‘ogg’,
‘size’: ‘320×240’,
‘bitrate’: ‘256k’,
‘audio_bitrate’: ’64k’,
‘audio_sample_rate’: ‘44100’,
‘audio_channels_number’: ‘2’,
‘keep_aspect_ratio’: ‘yes’,
‘video_codec’: ‘libtheora’,
‘profile’: ‘baseline’,
‘vcodecparameters’: ‘no’,
‘audio_codec’: ‘libvorbis’,
‘two_pass’: ‘no’,
‘cbr’: ‘no’,
‘deinterlacing’: ‘no’,
‘keyframe’: ‘300’,
‘audio_volume’: ‘100’,
‘file_extension’: ‘ogg’,
‘acbr’: ‘no’,
}
flv = {
‘output’: ‘fl9’,
‘size’: ‘320×240’,
‘bitrate’: ‘256k’,
‘audio_bitrate’: ’64k’,
‘audio_channels_number’: ‘2’,
‘keep_aspect_ratio’: ‘yes’,
‘video_codec’: ‘libx264’,
‘profile’: ‘high’,
‘vcodecparameters’: ‘no’,
‘audio_codec’: ‘libfaac’,
‘two_pass’: ‘no’,
‘cbr’: ‘no’,
‘deinterlacing’: ‘no’,
‘keyframe’: ‘300’,
‘audio_volume’: ‘100’,
‘file_extension’: ‘mp4’,
}
thumbnail = {
‘output’: ‘thumbnail’,
‘time’: ‘5’,
‘video_codec’: ‘mjpeg’,
‘keep_aspect_ratio’: ‘yes’,
‘file_extension’: ‘jpg’,
}
encoder = encoding(settings.encoding_api_user_id,
settings.encoding_api_user_key)
resp = encoder.add_media(source=[slide_upload.original_file.url],
formats=[mp4, webm, ogg, flv, thumbnail])
media_id = none
if resp is not none and resp.get(‘response’) is not none:
media_id = resp.get(‘response’).get(‘mediaid’)
if media_id is none:
slide_upload.status = slideuploadqueue.status_failed
slide_upload.save()
log.error(‘unable to communicate with encoding.com’)
return false
slide_upload.encoding_com_tracking_code = media_id
slide_upload.status = \
slideuploadqueue.status_awaiting_3rd_party_processing
slide_upload.save()
return true
encoding.com 推荐一些堪用的python程序,可用来与它们的服务沟通。我修改了模块一些地方,但还需要修改一些功能才能达到我满意的状态。以下是修改过后目前正在使用的程序代码:
import httplib
from lxml import etree
import urllib
from xml.parsers.expat import expaterror
import xmltodict
encoding_api_url = ‘manage.encoding.com:80′
class encoding(object):
def __init__(self, userid, userkey, url=encoding_api_url):
self.url = url
self.userid = userid
self.userkey = userkey
def get_media_info(self, action=’getmediainfo’, ids=[],
headers={‘content-type’: ‘application/x-www-form-urlencoded’}):
query = etree.element(‘query’)
nodes = {
‘userid’: self.userid,
‘userkey’: self.userkey,
‘action’: action,
‘mediaid’: ‘,’.join(ids),
}
query = self._build_tree(etree.element(‘query’), nodes)
results = self._execute_request(query, headers)
return self._parse_results(results)
def get_status(self, action=’getstatus’, ids=[], extended=’no’,
headers={‘content-type’: ‘application/x-www-form-urlencoded’}):
query = etree.element(‘query’)
nodes = {
‘userid’: self.userid,
‘userkey’: self.userkey,
‘action’: action,
‘extended’: extended,
‘mediaid’: ‘,’.join(ids),
}
query = self._build_tree(etree.element(‘query’), nodes)
results = self._execute_request(query, headers)
return self._parse_results(results)
def add_media(self, action=’addmedia’, source=[], notify=”, formats=[],
instant=’no’,
headers={‘content-type’: ‘application/x-www-form-urlencoded’}):
query = etree.element(‘query’)
nodes = {
‘userid’: self.userid,
‘userkey’: self.userkey,
‘action’: action,
‘source’: source,
‘notify’: notify,
‘instant’: instant,
}
query = self._build_tree(etree.element(‘query’), nodes)
for format in formats:
format_node = self._build_tree(etree.element(‘format’), format)
query.append(format_node)
results = self._execute_request(query, headers)
return self._parse_results(results)
def _build_tree(self, node, data):
for k, v in data.items():
if isinstance(v, list):
for item in v:
element = etree.element(k)
element.text = item
node.append(element)
else:
element = etree.element(k)
element.text = v
node.append(element)
return node
def _execute_request(self, xml, headers, path=”, method=’post’):
params = urllib.urlencode({‘xml’: etree.tostring(xml)})
conn = httplib.httpconnection(self.url)
conn.request(method, path, params, headers)
response = conn.getresponse()
data = response.read()
conn.close()
return data
def _parse_results(self, results):
try:
return xmltodict.parse(results)
except expaterror, e:
print ‘error parsing encoding.com response’
print e
return none
其他待完成事项包括通过https-only (加密联机) 使用encoding.com 严谨的ssl验证,还有一些单元测试。
阶段4:下载所有新的视频档格式
我们有个定期执行的程序,通过rabbitmq每15秒检查视频转码的进度:
class checkuponthirdparties(periodictask):
run_every = timedelta(seconds=settings.third_party_check_up_interval)
…
def _handle_encoding_com(self, slides):
format_lookup = {
‘mp4’: slidevideomedia.format_mp4,
‘webm’: slidevideomedia.format_webm,
‘ogg’: slidevideomedia.format_ogg,
‘fl9’: slidevideomedia.format_fl9,
‘thumbnail’: slidevideomedia.format_thumb,
}
encoder = encoding(settings.encoding_api_user_id,
settings.encoding_api_user_key)
job_ids = [item.encoding_com_tracking_code for item in slides]
resp = encoder.get_status(ids=job_ids)
if resp is none:
log.error(‘unable to check up on encoding.com’)
return false
检查encoding.com的响应来验证每个部分是否正确以利我们继续下去。
if resp.get(‘response’) is none:
log.error(‘unable to get response node from encoding.com’)
return false
resp_id = resp.get(‘response’).get(‘id’)
if resp_id is none:
log.error(‘unable to get media id from encoding.com’)
return false
slide = slideuploadqueue.objects.filter(
status=slideuploadqueue.status_awaiting_3rd_party_processing,
encoding_com_tracking_code=resp_id)
if len(slide) != 1:
log.error(‘unable to find a single record for %s’ % resp_id)
return false
resp_status = resp.get(‘response’).get(‘status’)
if resp_status is none:
log.error(‘unable to get status from encoding.com’)
return false
if resp_status != u’finished’:
log.debug(“%s isn’t finished, will check back later” % resp_id)
return true
formats = resp.get(‘response’).get(‘format’)
if formats is none:
log.error(“no output formats were found. something’s wrong.”)
return false
for format in formats:
try:
assert format.get(‘status’) == u’finished’, \
“%s is not finished. something’s wrong.” % format.get(‘id’)
output = format.get(‘output’)
assert output in (‘mp4’, ‘webm’, ‘ogg’, ‘fl9’,
‘thumbnail’), ‘unknown output format %s’ % output
s3_dest = format.get(‘s3_destination’)
assert ‘http://encoding.com.result.s3.amazonaws.com/’\
in s3_dest, ‘suspicious s3 url: %s’ % s3_dest
https_link = \
‘https://s3.amazonaws.com/encoding.com.result/%s’ %\
s3_dest.split(‘/’)[-1]
file_ext = https_link.split(‘.’)[-1].strip()
assert len(file_ext) > 0,\
‘unable to get file extension from %s’ % https_link
count = slidevideomedia.objects.filter(slide_upload=slide,
format=format_lookup[output]).count()
if count != 0:
print ‘there is already a %s file for this slide’ % output
continue
content = self.download_content(https_link)
assert content is not none,\
‘there is no content for %s’ % format.get(‘id’)
except assertionerror, e:
log.error(‘a format did not pass all assertions: %s’ % e)
continue
到这里我们已确认所有事项皆正常,所以我们可以储存所有的视频档了:
media = slidevideomedia()
media.format = format_lookup[output]
media.converted_file.save(‘blah.%s’ % file_ext, contentfile(content))
media.save()
阶段5:经由html5播放视频档
在我们的前端网页已经新增了一个有html5的影像单元的网页。并采用对每个浏览器都有最佳支持的video.js来显示视频。
? bower install video.js
bower caching git://github.com/videojs/video.js-component.git
bower cloning git://github.com/videojs/video.js-component.git
bower fetching video.js
bower checking out video.js#v4.0.3
bower copying /home/mark/.bower/cache/video.js/5ab058cd60c5615aa38e8e706cd0f307
bower installing video.js#4.0.3
在我们的首页有包含其他相依的文件:
!!! 5
html(lang=”en”, )
head
meta(http-equiv=’content-type’, content=’text/html; charset=utf-8′)
…
link(rel=’stylesheet’, type=’text/css’, href=’/components/video-js-4.1.0/video-js.css’)
script(type=’text/javascript’, src=’/components/video-js-4.1.0/video.js’)
在angular.js/jade-based 框架下的模块,我们引入卷标 与其子卷标。每个视频文件都会有缩图通过卷标的 poster 组件显示,缩图的图像是由我们从视频的前几秒撷取下来。
#main.span12
video#example_video_1.video-js.vjs-default-skin(controls, preload=”auto”, width=”640″, height=”264″, poster=”{{video_thumbnail}}”, data-setup='{“example_option”:true}’, ng-show=”videos”)
source(ng-repeat=”video in videos”, src=”{{video.src}}”, type=”{{video.type}}”)
还会显示出我们转换的每个视频文件格式,并使用在标签。video.js 会根据使用者使用的浏览器决定播放哪种格式的视频。
我们仍然有许多工作需要完成,建立单元测试与加强和encoding.com服务沟通的程序。如果你对这些工作感兴趣请与我连络。