/*---------------------------------------------------------------------------*/
/* audio_endpoint.cpp                                                        */
/* copyright (c) innovaphone 2017                                            */
/*---------------------------------------------------------------------------*/

#include <platform.h>

#include "sdk/common/interface/socket.h"
#include "sdk/common/interface/media.h"
#include "sdk/common/interface/time.h"

#include "audio_endpoint.h"

AudioEndpoint::AudioEndpoint(AudioCoder coder, class UMediaEndpoint * channel, class IInstanceLog * const log):
    channel(channel),
    log(log),
    coder(coder)
{
    firstTimestamp = 0;
    totalSize = 0;
    totalNumPacket = 0;
    totalNumLost = 0;
    totalNumOoO = 0;
    totalNumPacketLost = 0;
    totalNumPacketOoO = 0;
}

AudioEndpoint::~AudioEndpoint()
{
    if(totalSize) {
        int diff = (int)(lastTimestamp - firstTimestamp);
        debug->printf("AudioEndpoint(%p)::AudioEndpoint stats seq=%d ooo(%d)=%d lost(%d)=%d bitrate(%d,%d)=%d kbps", this, totalNumPacket, totalNumPacketOoO, totalNumOoO, totalNumPacketLost, totalNumLost, totalSize, diff, diff ? ((totalSize * 8) / diff) : 0);
    }
}

void AudioEndpoint::Recv(char * buf, int len, dword timestamp, short sequenceNumberDiff, bool marker)
{
 //   log->Log(LOG_AUDIO, "AudioEndpoint(%p)::Recv len=%d timestamp=%x marker=%d", this, len, timestamp, marker);
    channel->RtpRecvResult(buf, len, timestamp, sequenceNumberDiff, marker);
    if (!firstTimestamp) firstTimestamp = ITime::TimeStampMilliseconds();
    lastTimestamp = ITime::TimeStampMilliseconds();
    totalNumPacket++;
    if (sequenceNumberDiff > 0) {
        totalNumLost += sequenceNumberDiff;
        totalNumPacketLost++;
    }
    else if (sequenceNumberDiff < 0) {
        totalNumOoO += sequenceNumberDiff;
        totalNumPacketOoO++;
    }
    totalSize += len;
}

void AudioEndpoint::Send(char * buf, int len, dword timestamp, unsigned num, enum MediaType mediaTye, bool isConference)
{
    channel->RtpSend(buf, len, timestamp);
}
