1#!/usr/bin/env python3
2# Copyright (c) 2021 Huawei Device Co., Ltd.
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import sys
16import cv2 as cv
17from oled.img2code import convert_frame_to_bytes
18
19DEFAULT_PORT = 5678
20
21def convert_video_to_bin(videoFile, binFile):
22    cap = cv.VideoCapture(videoFile)
23    frameCount = cap.get(cv.CAP_PROP_FRAME_COUNT)
24    print('frame count:', frameCount)
25    print('frame width:', cap.get(cv.CAP_PROP_FRAME_WIDTH))
26    print('frame height:', cap.get(cv.CAP_PROP_FRAME_HEIGHT))
27    lastPercent = 0
28    with open(binFile, 'wb+') as f:
29        while True:
30            retval, frame = cap.read()
31            if not retval:
32                print('video done!')
33                break
34            bitmap = convert_frame_to_bytes(frame)
35            f.write(bitmap)
36            pos = cap.get(cv.CAP_PROP_POS_FRAMES)
37            percent = pos /  frameCount * 100
38            if percent - lastPercent >= 1:
39                lastPercent = percent
40                sys.stdout.write('=')
41                sys.stdout.flush()
42    print('convert all frames done!')
43    cap.release()
44
45def main():
46    if len(sys.argv) < 3:
47        print("Usage: {} videoFile binFile\n\t".format(sys.argv[0]))
48        exit(-1)
49
50    try:
51        videoFile = sys.argv[1]
52        binFile = sys.argv[2]
53        convert_video_to_bin(videoFile, binFile)
54    except Exception as e:
55        print('exception raised:', e)
56
57if __name__ == "__main__":
58    main()
59