package com.example.math.controller;

import com.example.math.controller.AudioTransformProcess;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class FfmpegPipeExample {

    static ExecutorService executor = Executors.newFixedThreadPool(5);


    public static void main(String[] args) throws IOException {
        long startTimestamp = System.currentTimeMillis();
        String[] command = AudioTransformProcess.getAudioToPcmPipeCommandExample();
        AudioTransformProcess process = new AudioTransformProcess(command);
        String file ="00.wav";
        String outputFile = "00_t.pcm";
        FfmpegPipeExample example = new FfmpegPipeExample();

        executor.execute(()-> example.write(file,process));

        try(OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(outputFile)));
            InputStream stdout = process.getReaderFromPipe();){
            log.info("开始读取输出管道");

            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = stdout.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                outputStream.flush();
                log.info("从输出管道读取{}字节", bytesRead);
            }

            process.waitFor(100, TimeUnit.SECONDS);
            log.info("cost time:{} ms.",System.currentTimeMillis() - startTimestamp);
        } catch ( InterruptedException e) {
            log.error(e.getMessage());
        }
    }

    //    @Async
    public void write(String file, AudioTransformProcess process){
        try(InputStream inputStream = new BufferedInputStream(Files.newInputStream(Paths.get(file)))){
            process.asyncWriteToPipe(inputStream);//异步写入管道
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }




}

