#!/usr/bin/env python
#version    :       2023.04.04
#language   :       en
import pyaudio, av, os,_thread
from maix import display, camera, image
# ffmpeg -r 30 -i badapple_240_60fps.mp4 -vf scale=240:240,setdar=1:1 output.mp4
# adb push ./output.mp4 /root/
path_to_video = '/root/preset/video/output_240_240.mp4'
try:
    container = av.open(path_to_video)
    ai_stream = container.streams.audio[0]
    vi_stream = container.streams.video[0]
    fifo = av.AudioFifo()
    p = pyaudio.PyAudio()
    ao = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=True)
    audio = [p, ao, fifo]
    def play_audio(audio):
        try:
            while len(audio):
                for frame in audio[2].read_many(4096):
                    audio[1].write(frame.planes[0].to_bytes())
        except Exception as e:
            print(e)
    _thread.start_new_thread(play_audio, (audio, ) )
    for frame in container.decode(video=0, audio=0):
        if 'Audio' in repr(frame):
            frame.pts = None
            frame.time_base = None
            fifo.write(frame)
        if 'Video' in repr(frame):
            img = image.load(bytes(frame.to_rgb().planes[0]), (vi_stream.width, vi_stream.height))
            display.show(img)
finally:
    ao.stop_stream()
    ao.close()
    p.terminate()
    audio = []