//----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2022-2025, Paul Higgs
// BSD-2-Clause license, see LICENSE.txt file or https://tsduck.io/license
//
//----------------------------------------------------------------------------

#include "tsEVCTimingAndHRDDescriptor.h"
#include "tsDescriptor.h"
#include "tsTablesDisplay.h"
#include "tsPSIRepository.h"
#include "tsPSIBuffer.h"
#include "tsDuckContext.h"
#include "tsxmlElement.h"

#define MY_XML_NAME u"EVC_timing_and_HRD_descriptor"
#define MY_CLASS    ts::EVCTimingAndHRDDescriptor
#define MY_EDID     ts::EDID::ExtensionMPEG(ts::XDID_MPEG_EVC_TIM_HRD)

TS_REGISTER_DESCRIPTOR(MY_CLASS, MY_EDID, MY_XML_NAME, MY_CLASS::DisplayDescriptor);


//----------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------

ts::EVCTimingAndHRDDescriptor::EVCTimingAndHRDDescriptor() :
    AbstractDescriptor(MY_EDID, MY_XML_NAME)
{
}

void ts::EVCTimingAndHRDDescriptor::clearContent()
{
    hrd_management_valid = false;
    N.reset();
    K.reset();
    num_units_in_tick.reset();
}

ts::EVCTimingAndHRDDescriptor::EVCTimingAndHRDDescriptor(DuckContext& duck, const Descriptor& desc) :
    EVCTimingAndHRDDescriptor()
{
    deserialize(duck, desc);
}


//----------------------------------------------------------------------------
// Serialization
//----------------------------------------------------------------------------

void ts::EVCTimingAndHRDDescriptor::serializePayload(PSIBuffer& buf) const
{
    const bool is_90kHz = !(N.has_value() && K.has_value());
    const bool info_present = num_units_in_tick.has_value();
    buf.putBit(hrd_management_valid);
    buf.putReserved(6);
    buf.putBit(info_present);
    if (info_present) {
        buf.putBit(is_90kHz);
        buf.putReserved(7);
        if (!is_90kHz) {  // N and K only present with time_base is not 90kHz
            buf.putUInt32(N.value());
            buf.putUInt32(K.value());
        }
        buf.putUInt32(num_units_in_tick.value());
    }
}


//----------------------------------------------------------------------------
// Deserialization
//----------------------------------------------------------------------------

void ts::EVCTimingAndHRDDescriptor::deserializePayload(PSIBuffer& buf)
{
    hrd_management_valid = buf.getBool();
    buf.skipReservedBits(6);
    if (buf.getBool()) { // info_present
        const bool is_90kHz = buf.getBool();
        buf.skipReservedBits(7);
        if (!is_90kHz) {
            N = buf.getUInt32();
            K = buf.getUInt32();
        }
        num_units_in_tick = buf.getUInt32();
    }
}


//----------------------------------------------------------------------------
// Static method to display a descriptor.
//----------------------------------------------------------------------------

void ts::EVCTimingAndHRDDescriptor::DisplayDescriptor(TablesDisplay& disp, const ts::Descriptor& desc, PSIBuffer& buf, const UString& margin, const ts::DescriptorContext& context)
{
    if (buf.canReadBytes(1)) {
        disp << margin << "HRD management valid: " << UString::TrueFalse(buf.getBool()) << std::endl;
        buf.skipReservedBits(6);
        if (buf.getBool()) { // info_present
            const bool is_90kHz = buf.getBool();
            buf.skipReservedBits(7);
            if (is_90kHz) {
                disp << margin << "EVC time base is 90 kHz" << std::endl;
            }
            else if (buf.canReadBytes(8)) {
                disp << margin << UString::Format(u"time_scale: N = %'d", buf.getUInt32());
                disp << UString::Format(u", K = %'d", buf.getUInt32()) << std::endl;
            }
            if (buf.canReadBytes(4)) {
                disp << margin << UString::Format(u"Num. units in tick: %'d", buf.getUInt32()) << std::endl;
            }
        }
    }
}


//----------------------------------------------------------------------------
// XML serialization
//----------------------------------------------------------------------------

void ts::EVCTimingAndHRDDescriptor::buildXML(DuckContext& duck, xml::Element* root) const
{
    root->setBoolAttribute(u"hrd_management_valid", hrd_management_valid);
    root->setOptionalIntAttribute(u"N", N);
    root->setOptionalIntAttribute(u"K", K);
    root->setOptionalIntAttribute(u"num_units_in_tick", num_units_in_tick);
}


//----------------------------------------------------------------------------
// XML deserialization
//----------------------------------------------------------------------------

bool ts::EVCTimingAndHRDDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element)
{
    bool ok = element->getBoolAttribute(hrd_management_valid, u"hrd_management_valid", true) &&
              element->getOptionalIntAttribute(N, u"N") &&
              element->getOptionalIntAttribute(K, u"K") &&
              element->getOptionalIntAttribute(num_units_in_tick, u"num_units_in_tick");
    if (ok && (N.has_value() + K.has_value() == 1)) {
        element->report().error(u"neither or both of N and K must be specified in <%s>, line %d", element->name(), element->lineNumber());
        ok = false;
    }
    return ok;
}
