Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / media / test / data / eme_player_js / media_source_utils.js
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // MediaSourceUtils provides basic functionality to load content using MSE API.
6 var MediaSourceUtils = new function() {
7 }
8
9 MediaSourceUtils.loadMediaSourceFromTestConfig = function(testConfig,
10                                                           appendCallbackFn) {
11   return this.loadMediaSource(testConfig.mediaFile,
12                               testConfig.mediaType,
13                               appendCallbackFn);
14 };
15
16 MediaSourceUtils.loadMediaSource = function(mediaFiles,
17                                             mediaTypes,
18                                             appendCallbackFn) {
19   if (!mediaFiles || !mediaTypes)
20     Utils.failTest('Missing parameters in loadMediaSource().');
21
22   var mediaFiles = Utils.convertToArray(mediaFiles);
23   var mediaTypes = Utils.convertToArray(mediaTypes);
24   var totalAppended = 0;
25   function onSourceOpen(e) {
26     Utils.timeLog('onSourceOpen', e);
27     // We can load multiple media files using the same media type. However, if
28     // more than one media type is used, we expect to have a media type entry
29     // for each corresponding media file.
30     var srcBuffer = null;
31     for (var i = 0; i < mediaFiles.length; i++) {
32       if (i == 0 || mediaFiles.length == mediaTypes.length) {
33         Utils.timeLog('Creating a source buffer for type ' + mediaTypes[i]);
34         try {
35           srcBuffer = mediaSource.addSourceBuffer(mediaTypes[i]);
36         } catch (e) {
37           Utils.failTest('Exception adding source buffer: ' + e.message);
38           return;
39         }
40       }
41       doAppend(mediaFiles[i], srcBuffer);
42     }
43   }
44
45   function doAppend(mediaFile, srcBuffer) {
46     var xhr = new XMLHttpRequest();
47     xhr.open('GET', mediaFile);
48     xhr.responseType = 'arraybuffer';
49     xhr.addEventListener('load', function(e) {
50       var onUpdateEnd = function(e) {
51         Utils.timeLog('End of appending buffer from ' + mediaFile);
52         srcBuffer.removeEventListener('updateend', onUpdateEnd);
53         totalAppended++;
54         if (totalAppended == mediaFiles.length) {
55           if (appendCallbackFn)
56             appendCallbackFn(mediaSource);
57           else
58             mediaSource.endOfStream();
59         }
60       };
61       srcBuffer.addEventListener('updateend', onUpdateEnd);
62       srcBuffer.appendBuffer(new Uint8Array(e.target.response));
63     });
64     xhr.send();
65   }
66
67   var mediaSource = new MediaSource();
68   mediaSource.addEventListener('sourceopen', onSourceOpen);
69   return mediaSource;
70 };