<?php namespace Api\Lib;
use Dever;
class Video
{
    # 获取远程视频信息
    public function remote($content, $type = false, $local = false)
    {
        if (!$type) {
            $type = $this->getType($content);
        }
        if (!$type) {
            Dever::error('不支持的站点类型');
        }
        return Dever::load('remote/' . $type, 'api', 'video')->info($content, $local);
    }

    # 获取本地视频信息
    public function info($file, $print = false)
    {
        return Dever::load('handle/clip', 'api', 'video')->info($file, $print);
    }

    # 视频处理
    public function handle($input, $output, $option, $print = false)
    {
        if (!$output) {
            $output = $input . '_clip.mp4';
        }
        return Dever::load('handle/clip', 'api', 'video')->act($input, $output, $option, $print);
    }

    # 视频转码 主要是转换成不同的类型 视频处理也能做到
    public function convert()
    {

    }

    # 视频合并
    public function merge($video, $output = '', $option = array())
    {
        $file = array();
        foreach ($video as $v) {
            $o = array
            (
                'file' => $v . '.ts',
                //-c copy -bsf:v h264_mp4toannexb -y -f
                'option' => array
                (
                    'c' => 'copy',
                    'bsf:v' => 'h264_mp4toannexb',
                    'y' => '',
                    'f' => 'mpegts',
                ),
            );
            $file[] = Dever::load('handle/clip', 'api', 'video')->act($v, $o);
        }
        $input = '"concat:'.implode('|', $file).'"';
        $output = Dever::file('upload/merge/' . $this->getName($output, 'mp4'));
        $output = array
        (
            'file' => $output,
            //-c copy -bsf:v h264_mp4toannexb -y -f
            'option' => array
            (
                'y' => '',
                'an' => '',
                'sn' => '',
                'c' => 'copy',
                'bsf:a' => 'aac_adtstoasc',
                'movflags' => '+faststart',
            ),
        );
        return Dever::load('handle/clip', 'api', 'video')->act($input, $output, $option);
    }

    private function getType($content)
    {
        if (strstr($content, 'douyin')) {
            return 'douyin';
        } elseif (strstr($content, 'xiaohongshu') || strstr($content, 'xhslink')) {
            return 'xiaohongshu';
        }
    }

    protected function getName($name, $ext)
    {
        $name = md5($name);
        $path = array_slice(str_split($name, 2), 0, 3);
        $dest = implode(DIRECTORY_SEPARATOR, $path) . DIRECTORY_SEPARATOR . $name . '.' . $ext;
        return $dest;
    }
}