1/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const WINSCOPE_META_MAGIC_STRING = [0x23, 0x56, 0x56, 0x31, 0x4e, 0x53, 0x43, 0x30, 0x50, 0x45, 0x54, 0x31, 0x4d, 0x45, 0x21, 0x23]; // #VV1NSC0PET1ME!#
18
19// Suitable only for short patterns
20function findFirstInArray(array, pattern) {
21  for (var i = 0; i < array.length; i++) {
22    var match = true;
23    for (var j = 0; j < pattern.length; j++) {
24      if (array[i + j] != pattern[j]) {
25        match = false;
26        break;
27      }
28    }
29    if (match) {
30      return i;
31    }
32  }
33  return -1;
34}
35
36function parseUintNLE(buffer, position, bytes) {
37  var num = 0;
38  for (var i = bytes - 1; i >= 0; i--) {
39    num = num * 256
40    num += buffer[position + i];
41  }
42  return num;
43}
44
45function parseUint32LE(buffer, position) {
46  return parseUintNLE(buffer, position, 4)
47}
48
49function parseUint64LE(buffer, position) {
50  return parseUintNLE(buffer, position, 8)
51}
52
53function mp4Decoder(buffer) {
54  var dataStart = findFirstInArray(buffer, WINSCOPE_META_MAGIC_STRING);
55  if (dataStart < 0) {
56    throw new Error('Unable to find sync metadata in the file. Are you using the latest Android ScreenRecorder version?');
57  }
58  dataStart += WINSCOPE_META_MAGIC_STRING.length;
59  var frameNum = parseUint32LE(buffer, dataStart);
60  dataStart += 4;
61  var timeline = [];
62  for (var i = 0; i < frameNum; i++) {
63    timeline.push(parseUint64LE(buffer, dataStart) * 1000);
64    dataStart += 8;
65  }
66  return [buffer, timeline]
67}
68
69export { mp4Decoder };
70