/*
 * Copyright (C) 2022, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: Xin Li <lixin@kylinos.cn>
 */
#include "audiofileprocess.h"
#include "mainwindow.h"
#include "clipwidget.h"

AudioFileProcess::AudioFileProcess(QObject *parent) : QObject(parent)
{
    //    datanum = 0;
    //    datalength = 0;
    //    totalsample = 0;
    //    bitpersample = 0;
}

int AudioFileProcess::wavFile_Analy(QString fileWav)
{
    if (!QFile(fileWav).exists()) {
        return -2; //不存在
    }
    FFUtil fu;
    fu.open(fileWav);
    int dur_time = fu.getDuration(fileWav);
    //fu.close();
    int minute = dur_time / 1000 / 60;
    if (minute >= 600) {
        QFile file(fileWav);
        qint64 fileSize;
        fileSize = file.size();
        // byterate(每秒字节数或单位时间内生成的文件大小) = 采样率(Hz)*样本数据位数(bit)*声道数/8
        minute = fileSize / (stuWavHead.sampleRate * stuWavHead.bitsPerSample * stuWavHead.numChannels / 8) / 60;
    }
    qDebug() << "文件时长:" << dur_time / 1000;
    if (dur_time / 1000 < 1) {
        return 0; //时间太短
    }
    if (minute == 0) {
        minute = 1;
    }
    qDebug() << minute << "分钟"
             << "采样率:" << stuWavHead.sampleRate << "样本数据位数:" << stuWavHead.bitsPerSample
             << "声道数:" << stuWavHead.numChannels;
    if (fileWav.endsWith(".mp3", Qt::CaseInsensitive) && QFile(fileWav).exists()) {
        FILE *fp;
        if ((fp = fopen(fileWav.toLocal8Bit().toStdString().c_str(), "rb")) != nullptr) {
            fread(&stuWavHead, sizeof(stuWavHead), 1, fp);
            //只支持声道数为1，2的非压缩格式（PCM）
            qDebug() << stuWavHead.numChannels << stuWavHead.audioFormat;
            if ((stuWavHead.numChannels != 1 && stuWavHead.numChannels != 2) || stuWavHead.audioFormat != 1) {
                fclose(fp);
                return -1; //不能分析非录音产生的音频
            }
            int dataSize = stuWavHead.chunkSize - sizeof(stuWavHead) - 8;
            //qDebug() << "stuWavHead.chunkSize:" << stuWavHead.chunkSize << "sizeof(stuWavHead):" << sizeof(stuWavHead);
            //样本总数
            int sampleCount = 0;
            int linePerSample = 0;
            if (stuWavHead.bitsPerSample / 8 != 0) {
                sampleCount = dataSize / (stuWavHead.bitsPerSample / 8);
            }
            qDebug() << "样本个数:" << sampleCount << "dur_time:/minute" << dur_time / 1000 / 60
                     << "n秒字节数:" << dur_time / 1000 * 96000;
            //只去左声道样本
            if (sampleCount < 16777216 && sampleCount > 0) {
                sampleCount = sampleCount / stuWavHead.numChannels;

            } else if (sampleCount >= 16777216) {
                sampleCount = sampleCount / stuWavHead.numChannels / minute;
            } else {
                fclose(fp);
                return 0;
            }
            //每条竖线的样本数
            linePerSample = sampleCount / 100;
            if(linePerSample == 0) {
                qDebug() << "样本数太少";
                fclose(fp);
                return 2;
            }
            if (stuWavHead.bitsPerSample == 16) {
                qint16 data;
                qint16 min = 32767;
                qint16 max = min + 1;
                int x = 0;
                for (int i = 1; i <= sampleCount; i++) {
                    fread(&data, 2, 1, fp);
                    if (min > data) {
                        min = data;
                    }

                    if (max < data) {
                        max = data;
                    }

                    if (i % linePerSample == 0) {
                        //                        qDebug()<<"MAX:"<<abs(max)<<"MIN:"<<abs(min);
                        emit toPaintWave(x, abs(max));
                        min = 32767;
                        max = min + 1;
                        x++;
                    }
                }
                qDebug() << "x:" << x;
            }
        }
        fclose(fp);
        return 1;
    } else {
        return -1; //不能分析非录音产生的音频
    }
    return 0;
}

AudioFileProcess::~AudioFileProcess() {}
