<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//-----------------------------------------------------------------------------------
///
/// @file p9_pcie_scominit.H
/// @brief Perform PCIE Phase1 init sequence (FAPI2)
///
// *HWP HWP Owner: Christina Graves clgraves@us.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 1
// *HWP Consumed by: HB

#ifndef _P9_PCIE_SCOMINIT_H_
#define _P9_PCIE_SCOMINIT_H_

//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <fapi2.H>

//-----------------------------------------------------------------------------------
// Helper Macros
//-----------------------------------------------------------------------------------
#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \
    FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
    FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
    FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
    FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
    l_buf = 0; \
    FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
    FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
    FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------

//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//-----------------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------------

const uint8_t NUM_PCS_CONFIG = 4;
const uint8_t NUM_PCIE_LANES = 16;
const uint8_t NUM_M_CONFIG = 4;
const uint8_t PEC0_IOP_CONFIG_START_BIT = 13;
const uint8_t PEC1_IOP_CONFIG_START_BIT = 14;
const uint8_t PEC2_IOP_CONFIG_START_BIT = 10;
const uint8_t PEC0_IOP_BIT_COUNT = 1;
const uint8_t PEC1_IOP_BIT_COUNT = 2;
const uint8_t PEC2_IOP_BIT_COUNT = 3;
const uint8_t PEC0_IOP_SWAP_START_BIT = 12;
const uint8_t PEC1_IOP_SWAP_START_BIT = 12;
const uint8_t PEC2_IOP_SWAP_START_BIT = 7;
const uint8_t PEC0_IOP_IOVALID_ENABLE_START_BIT = 4;
const uint8_t PEC1_IOP_IOVALID_ENABLE_START_BIT = 4;
const uint8_t PEC2_IOP_IOVALID_ENABLE_START_BIT = 4;
const uint8_t PEC_IOP_REFCLOCK_ENABLE_START_BIT = 32;
const uint8_t PEC_IOP_PMA_RESET_START_BIT = 29;
const uint8_t PEC_IOP_PIPE_RESET_START_BIT = 28;
const uint8_t PEC_IOP_HSS_PORT_READY_START_BIT = 58;

const uint64_t  PEC_IOP_PLLA_VCO_COURSE_CAL_REGISTER1 = 0x800005010D010C3F;
const uint64_t  PEC_IOP_PLLB_VCO_COURSE_CAL_REGISTER1 = 0x800005410D010C3F;
const uint64_t  PEC_IOP_RX_DFE_FUNC_REGISTER1 = 0x8000049F0D010C3F;
const uint64_t  PEC_IOP_RX_DFE_FUNC_REGISTER2 = 0x800004A00D010C3F;

const uint64_t  RX_VGA_CTRL3_REGISTER[NUM_PCIE_LANES] =
{
    0x8000008D0D010C3F,
    0x800000CD0D010C3F,
    0x8000018D0D010C3F,
    0x800001CD0D010C3F,
    0x8000028D0D010C3F,
    0x800002CD0D010C3F,
    0x8000038D0D010C3F,
    0x800003CD0D010C3F,
    0x8000088D0D010C3F,
    0x800008CD0D010C3F,
    0x8000098D0D010C3F,
    0x800009CD0D010C3F,
    0x80000A8D0D010C3F,
    0x80000ACD0D010C3F,
    0x80000B8D0D010C3F,
    0x80000BCD0D010C3F,
};

const uint64_t  RX_LOFF_CNTL_REGISTER[NUM_PCIE_LANES] =
{
    0x800000A60D010C3F,
    0x800000E60D010C3F,
    0x800001A60D010C3F,
    0x800001E60D010C3F,
    0x800002A60D010C3F,
    0x800002E60D010C3F,
    0x800003A60D010C3F,
    0x800003E60D010C3F,
    0x800008A60D010C3F,
    0x800008E60D010C3F,
    0x800009A60D010C3F,
    0x800009E60D010C3F,
    0x80000AA60D010C3F,
    0x80000AE60D010C3F,
    0x80000BA60D010C3F,
    0x80000BE60D010C3F,

};

const uint32_t PCS_CONFIG_MODE0 = 0xA006;
const uint32_t PCS_CONFIG_MODE1 = 0xA805;
const uint32_t PCS_CONFIG_MODE2 = 0xB071;
const uint32_t PCS_CONFIG_MODE3 = 0xB870;

const uint32_t MAX_NUM_POLLS = 100; //Maximum number of iterations (So, 400ns * 100 = 40us before timeout)
const uint64_t PMA_RESET_NANO_SEC_DELAY = 400; //400ns to wait for PMA RESET to go through
const uint64_t PMA_RESET_CYC_DELAY = 400; //400ns to wait for PMA RESET to go through

extern "C" {

//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------

/// @brief Perform PCIE Phase1 init sequence
/// @param[in] i_target => P9 chip target
/// @return FAPI_RC_SUCCESS if the setup completes successfully,
//
    fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
} //extern"C"

#endif //_P9_PCIE_SCOMINIT_H_
<commit_msg>L3 Update - p9_pcie_scominit HWP<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/// ---------------------------------------------------------------------------
///
/// @file p9_pcie_scominit.H
/// @brief Perform PCIE Phase1 init sequence (FAPI2)
///
/// *HWP HWP Owner: Ricardo Mata Jr. ricmata@us.ibm.com
/// *HWP FW Owner: Thi Tran thi@us.ibm.com
/// *HWP Team: Nest
/// *HWP Level: 3
/// *HWP Consumed by: HB
/// ---------------------------------------------------------------------------
#ifndef _P9_PCIE_SCOMINIT_H_
#define _P9_PCIE_SCOMINIT_H_

//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <fapi2.H>

//-----------------------------------------------------------------------------------
// Helper Macros
//-----------------------------------------------------------------------------------
#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \
    FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
    FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
    FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
    FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
    l_buf = 0; \
    FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
    FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
    FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\
    FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
    FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
    FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));

//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------
//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

extern "C" {

//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------

/// @brief Perform PCIE Phase1 init sequence
/// @param[in] i_target => P9 chip target
/// @return FAPI_RC_SUCCESS if the setup completes successfully,
//
    fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

} //extern"C"

#endif //_P9_PCIE_SCOMINIT_H_
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_throttle_sync.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// ----------------------------------------------------------------------------
/// @file  p9_throttle_sync.H
///
/// @brief Perform p9_throttle_sync HWP
///
/// The purpose of this procedure is to triggers sync command from a 'master'
/// MC to other MCs that have attached memory in a processor.
///
/// ----------------------------------------------------------------------------
/// *HWP HWP Owner   : Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner    : Thi Tran <thi@us.ibm.com>
/// *HWP Team        : Nest
/// *HWP Level       : 2
/// *HWP Consumed by : HB
/// ----------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_throttle_sync.H>
#include <fapi2.H>
#include <lib/utils/find.H>

///----------------------------------------------------------------------------
/// Constant definitions
///----------------------------------------------------------------------------
const uint8_t SUPER_SYNC_BIT   = 14;

///
/// @brief Perform throttle sync on the Memory Controllers
///
/// @tparam T template parameter, passed in targets.
/// @param[in]  i_mcTargets     Vector of reference of MC targets (MCS or MI)
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
///
template< fapi2::TargetType T>
fapi2::ReturnCode throttleSync(
    const std::vector< fapi2::Target<T> >& i_mcTargets);

/// TARGET_TYPE_MCS
template<>
fapi2::ReturnCode throttleSync(
    const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_mcTargets)
{
    FAPI_DBG("Entering");
    fapi2::ReturnCode l_rc;
    fapi2::buffer<uint64_t> l_scomData(0);
    fapi2::buffer<uint64_t> l_scomMask(0);
    bool l_mcaWithDimm[MAX_MCA_PER_PROC];
    fapi2::Target<fapi2::TARGET_TYPE_MCS> l_masterMcs;
    fapi2::Target<fapi2::TARGET_TYPE_MCA> l_mca;
    uint8_t l_masterMcsPos = 0;
    uint8_t l_mcaPos = 0;

    // Initialize
    memset(l_mcaWithDimm, false, sizeof(l_mcaWithDimm));

    // --------------------------------------------------------------
    // 1. Determine the 'master' MCS and mark which MCA ports have
    //    dimms attached
    // --------------------------------------------------------------
    bool l_masterMcsFound = false;

    for (auto l_mcs :  i_mcTargets)
    {
        // Find first MCS that has DIMM attached
        std::vector< fapi2::Target<fapi2::TARGET_TYPE_DIMM> > l_dimms =
            mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mcs);

        if (l_dimms.size() > 0)
        {
            // Set first MCS with DIMM attached to be master
            if (l_masterMcsFound == false)
            {
                l_masterMcs = l_mcs;
                l_masterMcsFound = true;
            }

            // Loop over the DIMM list to mark the MCAs that own them
            for (auto l_thisDimm : l_dimms)
            {
                l_mca = mss::find_target<fapi2::TARGET_TYPE_MCA>(l_thisDimm);
                FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mca, l_mcaPos),
                         "Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X",
                         (uint64_t)fapi2::current_err);
                l_mcaWithDimm[l_mcaPos] = true;
            }
        }
    }

    // No master found
    if (l_masterMcsFound == false)
    {
        // Nothing to do with this proc, exit
        // Note: This is a common scenario on Cronus platform.
        goto fapi_try_exit;
    }

    // Display MCS/MCA with DIMM attached
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_masterMcs,
                           l_masterMcsPos),
             "Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X",
             (uint64_t)fapi2::current_err);
    FAPI_INF("Master MCS pos %u", l_masterMcsPos);
    FAPI_DBG("MCA with DIMM attached:");

    for (uint8_t ii = 0; ii < MAX_MCA_PER_PROC; ii++)
    {
        FAPI_DBG("    MCA[%u] %u", ii, l_mcaWithDimm[ii]);
    }

    // -------------------------------------------------------------------
    // 2. Reset sync command on both channels to make sure they are clean
    // -------------------------------------------------------------------
    // Reset the sync command on both channels to make sure they are clean
    l_scomMask.flush<0>().setBit<MCS_MCSYNC_SYNC_GO_CH0>();
    l_scomData.flush<0>();

    FAPI_TRY(fapi2::putScomUnderMask(l_masterMcs, MCS_MCSYNC,
                                     l_scomData, l_scomMask),
             "putScomUnderMask() returns an error (Sync reset), Addr 0x%.16llX",
             MCS_MCSYNC);

    // --------------------------------------------------------------
    // 3. Setup MC Sync Command Register data for master MCS
    // --------------------------------------------------------------

    // Clear buffers
    l_scomData.flush<0>();
    l_scomMask.flush<0>();

    // Setup MCSYNC_CHANNEL_SELECT
    // Set ALL channels with or without DIMMs (bits 0:7)
    l_scomData.setBit<MCS_MCSYNC_CHANNEL_SELECT,
                      MCS_MCSYNC_CHANNEL_SELECT_LEN>();
    l_scomMask.setBit<MCS_MCSYNC_CHANNEL_SELECT,
                      MCS_MCSYNC_CHANNEL_SELECT_LEN>();

    // Setup MCSYNC_SYNC_TYPE
    // Set all sync types except Super Sync
    l_scomData.setBit<MCS_MCSYNC_SYNC_TYPE,
                      MCS_MCSYNC_SYNC_TYPE_LEN>().clearBit(SUPER_SYNC_BIT);
    l_scomMask.setBit<MCS_MCSYNC_SYNC_TYPE,
                      MCS_MCSYNC_SYNC_TYPE_LEN>();

    // Setup SYNC_GO, pick either MCA port of the master MCS, but the port
    // must have DIMM connected.
    l_mcaPos = l_masterMcsPos * 2; // 1st MCS postion of the master MCS

    if (l_mcaWithDimm[l_mcaPos] == true)
    {
        l_scomMask.setBit<MCS_MCSYNC_SYNC_GO_CH0>();
        l_scomData.setBit<MCS_MCSYNC_SYNC_GO_CH0>();
    }

    // --------------------------------------------------------------
    // 4. Write to MC Sync Command Register of master MCS
    // --------------------------------------------------------------

    // Write to MCSYNC reg
    FAPI_INF("Writing MCS_MCSYNC reg 0x%.16llX: Mask 0x%.16llX , Data 0x%.16llX",
             MCS_MCSYNC, l_scomMask, l_scomData);

    FAPI_TRY(fapi2::putScomUnderMask(l_masterMcs, MCS_MCSYNC,
                                     l_scomData, l_scomMask),
             "putScomUnderMask() returns an error (Sync), MCS_MCSYNC reg 0x%.16llX",
             MCS_MCSYNC);

    // Note: No need to read Sync replay count and retry in P9.

fapi_try_exit:
    FAPI_DBG("Exiting");
    return fapi2::current_err;
}

/// TARGET_TYPE_MI
template<>
fapi2::ReturnCode throttleSync(
    const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MI> >& i_mcTargets)
{
    FAPI_DBG("Entering");
    fapi2::ReturnCode l_rc;

    // Note: Add code for Cumulus

    FAPI_DBG("Exiting");
    return fapi2::current_err;
}

extern "C"
{

///----------------------------------------------------------------------------
/// Function definitions
///----------------------------------------------------------------------------

///
/// @brief p9_throttle_sync procedure entry point
/// See doxygen in p9_throttle_sync.H
///
    fapi2::ReturnCode p9_throttle_sync(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
    {
        FAPI_DBG("Entering");
        fapi2::ReturnCode l_rc;

        auto l_mcsChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>();
        auto l_miChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MI>();

        // Get the functional MCS on this proc
        if (l_mcsChiplets.size() > 0)
        {
            FAPI_TRY(throttleSync(l_mcsChiplets),
                     "throttleSync() returns error l_rc 0x%.8X",
                     (uint64_t)fapi2::current_err);
        }

        // Cumulus
        if (l_miChiplets.size() > 0)
        {
            FAPI_TRY(throttleSync(l_miChiplets),
                     "throttleSync() returns error l_rc 0x%.8X",
                     (uint64_t)fapi2::current_err);
        }

    fapi_try_exit:
        FAPI_DBG("Exiting");
        return fapi2::current_err;
    }

} // extern "C"
<commit_msg>HW397255 Sync Enablement workaround<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_throttle_sync.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// ----------------------------------------------------------------------------
/// @file  p9_throttle_sync.H
///
/// @brief Perform p9_throttle_sync HWP
///
/// The purpose of this procedure is to triggers sync command from a 'master'
/// MC to other MCs that have attached memory in a processor.
///
/// ----------------------------------------------------------------------------
/// *HWP HWP Owner   : Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner    : Thi Tran <thi@us.ibm.com>
/// *HWP Team        : Nest
/// *HWP Level       : 2
/// *HWP Consumed by : HB
/// ----------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_throttle_sync.H>
#include <fapi2.H>
#include <lib/utils/find.H>

///----------------------------------------------------------------------------
/// Constant definitions
///----------------------------------------------------------------------------
const uint8_t SUPER_SYNC_BIT   = 14;
const uint8_t MAX_MC_SIDES_PER_PROC = 2; // MC01, MC23

// Structure that holds the potential master MCS for a MC side (MC01/MC23)
struct mcSideInfo_t
{
    bool masterMcsFound = false;
    // Master MCS for this MC side
    fapi2::Target<fapi2::TARGET_TYPE_MCS> masterMcs;
};

///
/// @brief Programming master MCS
///        Writes MCS_MCSYNC reg to set the input MCS as the master.
///
/// @param[in]  i_mcsTarget  The MCS target to be programmed as master.
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
///
fapi2::ReturnCode progMasterMcs(
    const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_mcsTarget)
{
    FAPI_DBG("Entering");
    fapi2::ReturnCode l_rc;
    fapi2::buffer<uint64_t> l_scomData(0);
    fapi2::buffer<uint64_t> l_scomMask(0);

    // -------------------------------------------------------------------
    // 1. Reset sync command
    // -------------------------------------------------------------------

    // Note:
    // MCS_MCSYNC reg bit 16 is now used to setup SYNC_GO for both channels.
    // Bit 17 is now reserved (it was MCS_MCSYNC_SYNC_GO_CH1 before)
    //   REGISTER MCSYNC(mcsync(0:27), 0x000000000);
    //      MCSYNC.address(SCOM) += 0x00000015;
    //      MCSYNC.comment = "MC Sync Command Register (MCSYNC)";
    //      MCSYNC.attr(part_decl) = "0:7   = MCSYNC_Channel_Select"
    //                               "8:15  = MCSYNC_Sync_Type"
    //                               "16    = MCSYNC_Sync_Go"
    //                               "17:27 = MCSYNC_Reserved";
    //      MCSYNC.attr(access) = "**::SCOM = RW";
    //      MCSYNC.attr(parity) = "mcSYNC_pe";
    //      MCSYNC.attr(wpulse) = "act_sc15";

    l_scomMask.flush<0>().setBit<MCS_MCSYNC_SYNC_GO_CH0>();
    l_scomData.flush<0>();
    FAPI_TRY(fapi2::putScomUnderMask(i_mcsTarget, MCS_MCSYNC,
                                     l_scomData, l_scomMask),
             "putScomUnderMask() returns an error (Sync reset), Addr 0x%.16llX",
             MCS_MCSYNC);

    // --------------------------------------------------------------
    // 2. Setup MC Sync Command Register data for master MCS
    // --------------------------------------------------------------
    // Clear buffers
    l_scomData.flush<0>();
    l_scomMask.flush<0>();

    // Setup MCSYNC_CHANNEL_SELECT
    // Set ALL channels with or without DIMMs (bits 0:7)
    l_scomData.setBit<MCS_MCSYNC_CHANNEL_SELECT,
                      MCS_MCSYNC_CHANNEL_SELECT_LEN>();
    l_scomMask.setBit<MCS_MCSYNC_CHANNEL_SELECT,
                      MCS_MCSYNC_CHANNEL_SELECT_LEN>();

    // Setup MCSYNC_SYNC_TYPE
    // Set all sync types except Super Sync
    l_scomData.setBit<MCS_MCSYNC_SYNC_TYPE,
                      MCS_MCSYNC_SYNC_TYPE_LEN>().clearBit(SUPER_SYNC_BIT);
    l_scomMask.setBit<MCS_MCSYNC_SYNC_TYPE,
                      MCS_MCSYNC_SYNC_TYPE_LEN>();

    // Setup SYNC_GO (bit 16 is now used for both channels)
    l_scomMask.setBit<MCS_MCSYNC_SYNC_GO_CH0>();
    l_scomData.setBit<MCS_MCSYNC_SYNC_GO_CH0>();

    // --------------------------------------------------------------
    // 3. Write to MC Sync Command Register of master MCS
    // --------------------------------------------------------------
    // Write to MCSYNC reg
    FAPI_INF("Writing MCS_MCSYNC reg 0x%.16llX: Mask 0x%.16llX , Data 0x%.16llX",
             MCS_MCSYNC, l_scomMask, l_scomData);

    FAPI_TRY(fapi2::putScomUnderMask(i_mcsTarget, MCS_MCSYNC,
                                     l_scomData, l_scomMask),
             "putScomUnderMask() returns an error (Sync), MCS_MCSYNC reg 0x%.16llX",
             MCS_MCSYNC);

    // Note: No need to read Sync replay count and retry in P9.

fapi_try_exit:
    FAPI_DBG("Exiting");
    return fapi2::current_err;
}

///
/// @brief Perform throttle sync on the Memory Controllers
///
/// @tparam T template parameter, passed in targets.
/// @param[in]  i_mcTargets     Vector of reference of MC targets (MCS or MI)
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
///
template< fapi2::TargetType T>
fapi2::ReturnCode throttleSync(
    const std::vector< fapi2::Target<T> >& i_mcTargets);

/// TARGET_TYPE_MCS
template<>
fapi2::ReturnCode throttleSync(
    const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_mcTargets)
{
    FAPI_DBG("Entering");
    fapi2::ReturnCode l_rc;
    mcSideInfo_t l_mcSide[MAX_MC_SIDES_PER_PROC];
    uint8_t l_sideNum = 0;
    uint8_t l_pos = 0;
    uint8_t l_numMasterProgrammed = 0;

    // Initialization
    for (l_sideNum = 0; l_sideNum < MAX_MC_SIDES_PER_PROC; l_sideNum++)
    {
        l_mcSide[l_sideNum].masterMcsFound = false;
    }

    // ---------------------------------------------------------------------
    // 1. Pick the first MCS with DIMMS as potential master
    //    for both MC sides (MC01/MC23)
    // ---------------------------------------------------------------------
    for (auto l_mcs : i_mcTargets)
    {
        std::vector< fapi2::Target<fapi2::TARGET_TYPE_DIMM> > l_dimms =
            mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mcs);

        if (l_dimms.size() > 0)
        {
            // This MCS has DIMMs attached, find out which MC side it
            // belongs to:
            //    l_sideNum = 0 --> MC01
            //                1 --> MC23
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mcs,
                                   l_pos),
                     "Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X",
                     (uint64_t)fapi2::current_err);
            l_sideNum = l_pos / MAX_MC_SIDES_PER_PROC;

            FAPI_INF("MCS %u has DIMMs", l_pos);

            // If there's no master MCS marked for this side yet, mark
            // this MCS as master
            if (l_mcSide[l_sideNum].masterMcsFound == false)
            {
                FAPI_INF("Mark MCS %u as master for MC side %",
                         l_pos, l_sideNum);
                l_mcSide[l_sideNum].masterMcsFound = true;
                l_mcSide[l_sideNum].masterMcs = l_mcs;
            }
        }
    }

    // --------------------------------------------------------------
    // 2. Program the master MCS
    // --------------------------------------------------------------
    for (l_sideNum = 0; l_sideNum < MAX_MC_SIDES_PER_PROC; l_sideNum++)
    {
        // If there is a potential master MCS found for this side
        if (l_mcSide[l_sideNum].masterMcsFound == true)
        {
            // No master MCS programmed for either side yet,
            // go ahead and program this MCS as master.
            if (l_numMasterProgrammed == 0)
            {
                FAPI_TRY(progMasterMcs(l_mcSide[l_sideNum].masterMcs),
                         "programMasterMcs() returns error"
                         "NumMasterProgrammed %d, l_rc 0x%.8X",
                         l_numMasterProgrammed, (uint64_t)fapi2::current_err);
                l_numMasterProgrammed++;
            }
            else
            {
                // A master MCS is already programmed on MC side 0 (MC01).
                // HW397255 requires to also program a master MCS on MC23 if
                // it has DIMMs.
                fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_chip =
                    l_mcSide[l_sideNum].masterMcs.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
                fapi2::ATTR_CHIP_EC_FEATURE_HW397255_Type l_HW397255_enabled;
                FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW397255,
                                       l_chip, l_HW397255_enabled),
                         "Error getting the ATTR_CHIP_EC_FEATURE_HW397255");

                if (l_HW397255_enabled)
                {
                    FAPI_TRY(progMasterMcs(l_mcSide[l_sideNum].masterMcs),
                             "programMasterMcs() returns error"
                             "NumMasterProgrammed %d, l_rc 0x%.8X",
                             l_numMasterProgrammed, (uint64_t)fapi2::current_err);
                }
            }
        }
    }

fapi_try_exit:
    FAPI_DBG("Exiting");
    return fapi2::current_err;
}

/// TARGET_TYPE_MI
template<>
fapi2::ReturnCode throttleSync(
    const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MI> >& i_mcTargets)
{
    FAPI_DBG("Entering");
    fapi2::ReturnCode l_rc;

    // Note: Add code for Cumulus

    FAPI_DBG("Exiting");
    return fapi2::current_err;
}

extern "C"
{

///----------------------------------------------------------------------------
/// Function definitions
///----------------------------------------------------------------------------

///
/// @brief p9_throttle_sync procedure entry point
/// See doxygen in p9_throttle_sync.H
///
    fapi2::ReturnCode p9_throttle_sync(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
    {
        FAPI_DBG("Entering");
        fapi2::ReturnCode l_rc;

        auto l_mcsChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>();
        auto l_miChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MI>();

        // Get the functional MCS on this proc
        if (l_mcsChiplets.size() > 0)
        {
            FAPI_TRY(throttleSync(l_mcsChiplets),
                     "throttleSync() returns error l_rc 0x%.8X",
                     (uint64_t)fapi2::current_err);
        }

        // Cumulus
        if (l_miChiplets.size() > 0)
        {
            FAPI_TRY(throttleSync(l_miChiplets),
                     "throttleSync() returns error l_rc 0x%.8X",
                     (uint64_t)fapi2::current_err);
        }

    fapi_try_exit:
        FAPI_DBG("Exiting");
        return fapi2::current_err;
    }

} // extern "C"
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _P9_INFRASTRUCT_HELP_H_
#define _P9_INFRASTRUCT_HELP_H_

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>     //memcpy()
#include <errno.h>

//
// Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)
//
//@FIXME: CMO: get rid of FIXED_RING_BUF_SIZE when ring_apply no longer uses it.
const uint32_t  FIXED_RING_BUF_SIZE     = 60000; // Fixed ring buf size for _fixed.
const uint32_t  MAX_SEEPROM_IMAGE_SIZE  = 4 * 56 * 1024 - 256; // Max Seeprom size, excl ECC bits (4 banks).
const uint32_t  MAX_RT_IMAGE_SIZE       = 1024 * 1024;   // Max Runtime size.
const uint32_t  MAX_RING_BUF_SIZE       = 60000;         // Max ring buffer size.
const uint32_t  MAX_OVERRIDES_SIZE      = 2 * 1024;      // Max overrides section size.
const uint32_t  MAX_HBBL_SIZE           = 20 * 1024;     // Max hbbl section size.

//@FIXME: CMO: Aren't these defined somewhere else?
#define NUM_OF_CORES    24
#define NUM_OF_CMES     12
#define NUM_OF_QUADS     6
#define CORES_PER_QUAD  (NUM_OF_CORES/NUM_OF_QUADS)

enum SYSPHASE
{
    SYSPHASE_HB_SBE = 0,
    SYSPHASE_RT_CME = 1,
    SYSPHASE_RT_SGPE = 2,
    NOOF_SYSPHASES = 3,
};

enum MODEBUILD
{
    MODEBUILD_IPL = 0,
    MODEBUILD_REBUILD = 1,
    NOOF_MODEBUILDS = 2,
};

#if defined(__FAPI)
    #include <fapi2.H>
    #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
    #define MY_ERR(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
    #define MY_DBG(_fmt_, _args_...) FAPI_DBG(_fmt_, ##_args_)
#else
    #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
    #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
    #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)
#endif

// N-byte align an address, offset or size (aos)
inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)
{
    return ((aos + nBytes - 1) / nBytes) * nBytes;
}

#endif //_P9_INFRASTRUCT_HELP_H_
<commit_msg>Cleanup: ring_apply and associated routines<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _P9_INFRASTRUCT_HELP_H_
#define _P9_INFRASTRUCT_HELP_H_

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>     //memcpy()
#include <errno.h>

//
// Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)
//
const uint32_t  MAX_SEEPROM_IMAGE_SIZE  = 4 * 56 * 1024 - 256; // Max Seeprom size, excl ECC bits (4 banks).
const uint32_t  MAX_RT_IMAGE_SIZE       = 1024 * 1024;   // Max Runtime size.
const uint32_t  MAX_RING_BUF_SIZE       = 60000;         // Max ring buffer size.
const uint32_t  FIXED_RING_BUF_SIZE     = 60000;         //@TODO: RTC156706
const uint32_t  MAX_OVERRIDES_SIZE      = 2 * 1024;      // Max overrides section size.
const uint32_t  MAX_HBBL_SIZE           = 20 * 1024;     // Max hbbl section size.

//@FIXME: CMO: Aren't these defined somewhere else?
#define NUM_OF_CORES    24
#define NUM_OF_CMES     12
#define NUM_OF_QUADS     6
#define CORES_PER_QUAD  (NUM_OF_CORES/NUM_OF_QUADS)

enum SYSPHASE
{
    SYSPHASE_HB_SBE = 0,
    SYSPHASE_RT_CME = 1,
    SYSPHASE_RT_SGPE = 2,
    NOOF_SYSPHASES = 3,
};

enum MODEBUILD
{
    MODEBUILD_IPL = 0,
    MODEBUILD_REBUILD = 1,
    NOOF_MODEBUILDS = 2,
};

#if defined(__FAPI)
    #include <fapi2.H>
    #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
    #define MY_ERR(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
    #define MY_DBG(_fmt_, _args_...) FAPI_DBG(_fmt_, ##_args_)
#else
    #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
    #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
    #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)
#endif

// N-byte align an address, offset or size (aos)
inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)
{
    return ((aos + nBytes - 1) / nBytes) * nBytes;
}

#endif //_P9_INFRASTRUCT_HELP_H_
<|endoftext|>


<commit_before>#include "projet.h"
#include <QtDebug>
#include <QProcess>
#include <QException>
#include <QPainter>

const QSize Projet::sizeOutput = QSize(1002, 561);

Projet::Projet()
{

}

QImage* Projet::getImageVideo(int number)
{
    return _imagesVideo.at(number);
}

QImage* Projet::getImageOutput(int number)
{
    return _imagesOutput.at(number);
}

int Projet::getNbFrameVideo()
{
    return _nbFrameVideo;
}

Projet* Projet::create(QString &name, QDir &workspace, QFile &video, int frequenceVideo)
{
    Projet *projet = new Projet();

    projet->_frequenceVideo = frequenceVideo;

    if(workspace.exists())
    {
        if(video.exists())
        {
            if(workspace.mkdir(name))
            {
                projet->_project = new QDir(workspace.path()+"/"+name);
                qDebug() << projet->_project->path();
                projet->_project->mkdir("input");
                projet->_input = new QDir(projet->_project->path()+"/input");
                projet->_project->mkdir("output");
                projet->_output = new QDir(projet->_project->path()+"/output");
                video.copy(projet->_project->path()+"/input/video");
                projet->_video = new QFile(projet->_project->path()+"/input/video");

                QProcess process;
                process.start("avconv -i " + projet->_project->path() +"/input/video -vsync 1 -s " + QString::number(sizeOutput.width()) + "x" + QString::number(projet->sizeOutput.height()) + " -r " +  QString::number(projet->_frequenceVideo) + " -y " + projet->_project->path() + "/input/img%d.bmp");
                process.waitForFinished(-1);

                QStringList filters;
                filters << "img*.bmp";
                projet->_nbFrameVideo = projet->_input->entryList(filters).count();
                qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;

                QFile file(projet->_project->path() + "/info");
                file.open(QIODevice::WriteOnly | QIODevice::Text);
                QTextStream out(&file);

                out << QString::number(projet->_frequenceVideo) << "\n" << QString::number(projet->_nbFrameVideo);

                file.close();

                for(int i = 1; i <= projet->_nbFrameVideo; i++)
                {
                    projet->_imagesVideo.push_back(new QImage(projet->_input->path()+"/img"+QString::number(i)+".bmp"));
                    QImage *image = new QImage(projet->sizeOutput.width(),projet->sizeOutput.height(),QImage::Format_ARGB32);
                    image->save(projet->_output->path() + "/img" + QString::number(i) + ".png");
                    projet->_imagesOutput.push_back(image);
                }
            }
            else
            {
                throw QString("Ce projet existe déjà");
            }
        }
        else
        {
            throw QString("La vidéo n'existe pas");
        }
    }
    else
    {
        throw QString("Le workspace n'existe pas");
    }

    return projet;
}

Projet* Projet::open(QDir &path)
{
    Projet *projet = new Projet();

    if(path.exists())
    {
        projet->_project = new QDir(path.path());
        projet->_input = new QDir(path.path() + "/input");
        projet->_output = new QDir(path.path() + "/output");

        QFile info(projet->_project->path() + "/info");

        if(info.exists())
        {
            info.open(QIODevice::ReadOnly | QIODevice::Text);
            QTextStream in(&info);

            QString string;
            in >> string;
            projet->_frequenceVideo = string.toInt();

            in >> string;
            projet->_nbFrameVideo = string.toInt();

            qDebug() << "Frequence : " << projet->_frequenceVideo;
            qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;
        }
        else
        {
            throw QString("Le projet n'est pas complet");
        }

        if(projet->_input->exists() && projet->_output->exists())
        {
            projet->_video = new QFile(projet->_input->path() + "/video");

            if(!projet->_video->exists())
            {
                throw QString("Le projet n'est pas complet");
            }

            for(int i = 1; i <= projet->_nbFrameVideo; i++)
            {
                try
                {
                    projet->_imagesVideo.push_back(new QImage(projet->_input->path() + "/img" + QString::number(i) + ".bmp"));
                    projet->_imagesOutput.push_back(new QImage(projet->_output->path() + "/img" + QString::number(i) + ".png"));
                }
                catch(QException e)
                {
                    throw QString("Le projet n'est pas complet");
                }
            }
        }
        else
        {
            throw QString("Ce projet est mal formé");
        }
    }
    else
    {
        throw QString("Ce projet n'existe pas");
    }

    return projet;
}

void Projet::save()
{
    for(size_t i = 0; i < _imagesOutput.size(); i++)
    {
        _imagesOutput.at(i)->save(_output->path()+"/img" + QString::number(i+1) + ".png");
    }
}

void Projet::saveAs(QDir &projet)
{
    if(projet.exists())
    {
        if(projet.count() == 0)
        {
            QProcess process;
            process.start("cp -R " + _project->path() + " " + workspace.path() + "/" + name );
            process.waitForFinished(-1);
        }
        else
        {
            throw QString("Ce dossier n'est pas vide");
        }
    }
    else
    {
        throw QString("Ce dossier n'existe pas");
    }
}
<commit_msg>Correction of saveAs<commit_after>#include "projet.h"
#include <QtDebug>
#include <QProcess>
#include <QException>
#include <QPainter>

const QSize Projet::sizeOutput = QSize(1002, 561);

Projet::Projet()
{

}

QImage* Projet::getImageVideo(int number)
{
    return _imagesVideo.at(number);
}

QImage* Projet::getImageOutput(int number)
{
    return _imagesOutput.at(number);
}

int Projet::getNbFrameVideo()
{
    return _nbFrameVideo;
}

Projet* Projet::create(QString &name, QDir &workspace, QFile &video, int frequenceVideo)
{
    Projet *projet = new Projet();

    projet->_frequenceVideo = frequenceVideo;

    if(workspace.exists())
    {
        if(video.exists())
        {
            if(workspace.mkdir(name))
            {
                projet->_project = new QDir(workspace.path()+"/"+name);
                qDebug() << projet->_project->path();
                projet->_project->mkdir("input");
                projet->_input = new QDir(projet->_project->path()+"/input");
                projet->_project->mkdir("output");
                projet->_output = new QDir(projet->_project->path()+"/output");
                video.copy(projet->_project->path()+"/input/video");
                projet->_video = new QFile(projet->_project->path()+"/input/video");

                QProcess process;
                process.start("avconv -i " + projet->_project->path() +"/input/video -vsync 1 -s " + QString::number(sizeOutput.width()) + "x" + QString::number(projet->sizeOutput.height()) + " -r " +  QString::number(projet->_frequenceVideo) + " -y " + projet->_project->path() + "/input/img%d.bmp");
                process.waitForFinished(-1);

                QStringList filters;
                filters << "img*.bmp";
                projet->_nbFrameVideo = projet->_input->entryList(filters).count();
                qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;

                QFile file(projet->_project->path() + "/info");
                file.open(QIODevice::WriteOnly | QIODevice::Text);
                QTextStream out(&file);

                out << QString::number(projet->_frequenceVideo) << "\n" << QString::number(projet->_nbFrameVideo);

                file.close();

                for(int i = 1; i <= projet->_nbFrameVideo; i++)
                {
                    projet->_imagesVideo.push_back(new QImage(projet->_input->path()+"/img"+QString::number(i)+".bmp"));
                    QImage *image = new QImage(projet->sizeOutput.width(),projet->sizeOutput.height(),QImage::Format_ARGB32);
                    image->save(projet->_output->path() + "/img" + QString::number(i) + ".png");
                    projet->_imagesOutput.push_back(image);
                }
            }
            else
            {
                throw QString("Ce projet existe déjà");
            }
        }
        else
        {
            throw QString("La vidéo n'existe pas");
        }
    }
    else
    {
        throw QString("Le workspace n'existe pas");
    }

    return projet;
}

Projet* Projet::open(QDir &path)
{
    Projet *projet = new Projet();

    if(path.exists())
    {
        projet->_project = new QDir(path.path());
        projet->_input = new QDir(path.path() + "/input");
        projet->_output = new QDir(path.path() + "/output");

        QFile info(projet->_project->path() + "/info");

        if(info.exists())
        {
            info.open(QIODevice::ReadOnly | QIODevice::Text);
            QTextStream in(&info);

            QString string;
            in >> string;
            projet->_frequenceVideo = string.toInt();

            in >> string;
            projet->_nbFrameVideo = string.toInt();

            qDebug() << "Frequence : " << projet->_frequenceVideo;
            qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;
        }
        else
        {
            throw QString("Le projet n'est pas complet");
        }

        if(projet->_input->exists() && projet->_output->exists())
        {
            projet->_video = new QFile(projet->_input->path() + "/video");

            if(!projet->_video->exists())
            {
                throw QString("Le projet n'est pas complet");
            }

            for(int i = 1; i <= projet->_nbFrameVideo; i++)
            {
                try
                {
                    projet->_imagesVideo.push_back(new QImage(projet->_input->path() + "/img" + QString::number(i) + ".bmp"));
                    projet->_imagesOutput.push_back(new QImage(projet->_output->path() + "/img" + QString::number(i) + ".png"));
                }
                catch(QException e)
                {
                    throw QString("Le projet n'est pas complet");
                }
            }
        }
        else
        {
            throw QString("Ce projet est mal formé");
        }
    }
    else
    {
        throw QString("Ce projet n'existe pas");
    }

    return projet;
}

void Projet::save()
{
    for(size_t i = 0; i < _imagesOutput.size(); i++)
    {
        _imagesOutput.at(i)->save(_output->path()+"/img" + QString::number(i+1) + ".png");
    }
}

void Projet::saveAs(QDir &projet)
{
    if(projet.exists())
    {
        if(projet.count() == 2) //Les 2 correspond à . et ..
        {
            QProcess::execute("cp -r " + _project->absolutePath() + "/input " + projet.absolutePath() + "/" + name + "/");
            QProcess::execute("cp -r " + _project->absolutePath() + "/output " + projet.absolutePath() + "/" + name + "/");
            QProcess::execute("cp -r " + _project->absolutePath() + "/info " + projet.absolutePath() + "/" + name + "/");
        }
        else
        {
            throw QString("Ce dossier n'est pas vide");
        }
    }
    else
    {
        QString name(projet.dirName());
        if(projet.cdUp() && projet.mkdir(name))
        {
            QProcess::execute("cp -r " + _project->absolutePath() + "/input " + projet.absolutePath() + "/" + name + "/");
            QProcess::execute("cp -r " + _project->absolutePath() + "/output " + projet.absolutePath() + "/" + name + "/");
            QProcess::execute("cp -r " + _project->absolutePath() + "/info " + projet.absolutePath() + "/" + name + "/");
        }
        else
        {
            throw QString("Ce dossier n'existe pas");
        }
    }
}
<|endoftext|>


<commit_before>#include "Debug.h"
#include "Editor.h"
#include "Renderer.h"
#include "Color.h"
#include <cstdio>

Editor::Editor(EditorState& editorState, bool wantsFocus)
	: mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mNumChildren(0), mWantsFocus(wantsFocus)
{
	mThisArea.x = 0;
	mThisArea.y = 0;
}

Editor::~Editor() {}

Editor * Editor::getFocus()
{
	if (mParent)
		return mParent->getFocus();

	return mFocus;
}

void Editor::setFocus(Editor *editor)
{
	if (mParent)
		mParent->setFocus(editor);
	else
	{
		if (mFocus)
			mFocus->setDirty(true);
		mFocus = editor;

		if (editor)
			editor->setDirty(true);
	}
}

bool Editor::onEvent(SDL_Event& event)
{
	return false;
}

void Editor::setDirty(bool dirty)
{
	mIsDirty =  dirty;

	if (!dirty)
		mRedraw = false;

	if (dirty && mParent != NULL)
		mParent->setDirty(true);
}

bool Editor::shouldRedrawBackground() const
{
	return mRedraw;
}

bool Editor::isDirty() const
{
	return mIsDirty || hasDirty();
}

void Editor::addChild(Editor *child, int x, int y, int w, int h)
{
	child->mParent = this;
	SDL_Rect& area = mChildrenArea[mNumChildren];
	area.x = x;
	area.y = y;
	area.w = w;
	area.h = h;
	mChildren[mNumChildren++] = child;

	SDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h};

	child->setArea(absArea);
}

void Editor::setArea(const SDL_Rect& area)
{
	mThisArea.x = area.x;
	mThisArea.y = area.y;
	mThisArea.w = area.w;
	mThisArea.h = area.h;

	if (mParent) mParent->childAreaChanged(this);

	onAreaChanged(mThisArea);
}

const SDL_Rect& Editor::getArea() const
{
	return mThisArea;
}

void Editor::onAreaChanged(const SDL_Rect& area)
{
}

bool Editor::hasDirty() const
{
	for (int i = 0 ; i < mNumChildren ; ++i)
		if (mChildren[i]->isDirty())
			return true;

	return false;
}

bool Editor::hasFocus()
{
	return getFocus() == this;
}

bool Editor::isFocusable() const
{
	return mWantsFocus;
}

void Editor::onListenableChange(Listenable *listenable)
{
	setDirty(true);
}

void Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex)
{
	renderer.renderBackground(childArea);

	for (int index = 0 ; index <= maxIndex && index < mNumChildren ; ++index)
	{
		SDL_Rect thisChildArea = mChildrenArea[index];
		thisChildArea.x += area.x;
		thisChildArea.y += area.y;

		SDL_Rect intersection;

		if (intersectRect(childArea, thisChildArea, intersection))
		{
			renderer.setClip(intersection);
			mChildren[index]->draw(renderer, thisChildArea);
		}
	}
}

void Editor::drawChildren(Renderer& renderer, const SDL_Rect& area)
{
	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		if (mChildren[index]->isDirty())
		{
			SDL_Rect childArea = mChildrenArea[index];
			childArea.x += area.x;
			childArea.y += area.y;

			drawCoveredChildren(renderer, area, childArea, index - 1);

			renderer.setClip(childArea);

			mChildren[index]->draw(renderer, childArea);
		}
	}
}

void Editor::drawModal(Renderer& renderer)
{
	if (mModal != NULL)
	{
		if (mModal->shouldRedrawBackground())
		{
			// Draw plain black background with white border
			renderer.clearRect(mModal->getArea(), Color(0, 0, 0));
			renderer.drawRect(mModal->getArea(), Color(255, 255, 255));
		}

		SDL_Rect modalContent = mModal->getArea();
		modalContent.x += 2;
		modalContent.y += 2;
		modalContent.w -= 4;
		modalContent.h -= 4;

		mModal->draw(renderer, modalContent);
	}
}

void Editor::setModal(Editor *modal)
{
	if (mModal != NULL)
		mModal->mParent = NULL;

	mModal = modal;

	if (mModal != NULL)
	{
		mModal->mParent = this;
		SDL_Rect modalArea = { mThisArea.x + 16, mThisArea.y + 16, mThisArea.w - 32, mThisArea.h - 32 };
		mModal->setArea(modalArea);
	}

	invalidateAll();
}

void Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept)
{
}

void Editor::invalidateAll()
{
	setDirty(true);
	mRedraw = true;

	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		mChildren[index]->invalidateAll();
	}

	if (mModal)
		mModal->invalidateAll();
}

void Editor::onMessageBoxEvent(const Editor& messageBox, int code)
{
}

void Editor::draw(Renderer& renderer, const SDL_Rect& area)
{
	// This should fix problems with modal backgrounds not being updated
	// and perhaps also other child Editors.

	invalidateAll();

	if (mModal == NULL)
	{
		this->onDraw(renderer, area);
		drawChildren(renderer, area);
	}
	else
	{
		drawModal(renderer);
	}

	setDirty(false);
}

void Editor::invalidateParent()
{
	if (mParent)
		mParent->invalidateAll();
}

bool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect)
{
#ifdef SDL_PointInRect
	return SDL_PointInRect(&point, &rect);
#else
	// In case we are using SDL <2.0.4 (of whatever the version is
	// where the rect built-in functions are introduced. E.g. my
	// PocketCHIP only goes up to 2.0.2 by default.

	return point.x >= rect.x && point.x < rect.x + rect.w &&
		point.y >= rect.y && point.y < rect.y + rect.h;
#endif
}

bool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result)
{
#ifdef SDL_IntersectRect
	return SDL_IntersectRect(&point, &rect, &result);
#else
	// In case we are using SDL <2.0.4 (of whatever the version is
	// where the rect built-in functions are introduced. E.g. my
	// PocketCHIP only goes up to 2.0.2 by default.

	int aRight = a.x + a.w;
	int aBottom = a.y + a.h;
	int bRight = b.x + b.w;
	int bBottom = b.y + b.h;

	if (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y))
		return false;

	result.x = std::max(a.x, b.x);
	result.y = std::max(a.y, b.y);
	result.w = std::min(aRight, bRight) - result.x;
	result.h = std::min(aBottom, bBottom) - result.y;

	return true;
#endif
}

void Editor::showTooltipV(const SDL_Rect& area, const char* message, ...)
{
	char dest[1024];
    va_list argptr;
    va_start(argptr, message);
    vsnprintf(dest, sizeof(dest), message, argptr);
    va_end(argptr);

	showTooltip(area, dest);
}

void Editor::showTooltip(const SDL_Rect& area, const char* message)
{
	if (mParent != NULL)
		mParent->showTooltip(area, message);
}

void Editor::showMessageV(MessageClass messageClass, const char* message, ...)
{
	char dest[1024];
    va_list argptr;
    va_start(argptr, message);
    vsnprintf(dest, sizeof(dest), message, argptr);
    va_end(argptr);

	showMessage(messageClass, dest);
}

void Editor::showMessage(MessageClass messageClass, const char* message)
{
	if (mParent != NULL)
		mParent->showMessage(messageClass, message);
	else
		debug("[%s] %s", messageClass == MessageInfo ? "INFO" : "ERROR", message);
}

void Editor::onUpdate(int ms)
{

}

void Editor::update(int ms)
{
	onUpdate(ms);

	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		mChildren[index]->update(ms);
	}
}

void Editor::onLoaded()
{
	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		mChildren[index]->onLoaded();
	}
}

void Editor::childAreaChanged(Editor *child)
{
	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		if (mChildren[index] == child)
			mChildrenArea[index] = child->getArea();
	}
}
<commit_msg>Render modal border outside window area<commit_after>#include "Debug.h"
#include "Editor.h"
#include "Renderer.h"
#include "Color.h"
#include <cstdio>

#define MODAL_BORDER 2

Editor::Editor(EditorState& editorState, bool wantsFocus)
	: mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mNumChildren(0), mWantsFocus(wantsFocus)
{
	mThisArea.x = 0;
	mThisArea.y = 0;
}

Editor::~Editor() {}

Editor * Editor::getFocus()
{
	if (mParent)
		return mParent->getFocus();

	return mFocus;
}

void Editor::setFocus(Editor *editor)
{
	if (mParent)
		mParent->setFocus(editor);
	else
	{
		if (mFocus)
			mFocus->setDirty(true);
		mFocus = editor;

		if (editor)
			editor->setDirty(true);
	}
}

bool Editor::onEvent(SDL_Event& event)
{
	return false;
}

void Editor::setDirty(bool dirty)
{
	mIsDirty =  dirty;

	if (!dirty)
		mRedraw = false;

	if (dirty && mParent != NULL)
		mParent->setDirty(true);
}

bool Editor::shouldRedrawBackground() const
{
	return mRedraw;
}

bool Editor::isDirty() const
{
	return mIsDirty || hasDirty();
}

void Editor::addChild(Editor *child, int x, int y, int w, int h)
{
	child->mParent = this;
	SDL_Rect& area = mChildrenArea[mNumChildren];
	area.x = x;
	area.y = y;
	area.w = w;
	area.h = h;
	mChildren[mNumChildren++] = child;

	SDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h};

	child->setArea(absArea);
}

void Editor::setArea(const SDL_Rect& area)
{
	mThisArea.x = area.x;
	mThisArea.y = area.y;
	mThisArea.w = area.w;
	mThisArea.h = area.h;

	if (mParent) mParent->childAreaChanged(this);

	onAreaChanged(mThisArea);
}

const SDL_Rect& Editor::getArea() const
{
	return mThisArea;
}

void Editor::onAreaChanged(const SDL_Rect& area)
{
}

bool Editor::hasDirty() const
{
	for (int i = 0 ; i < mNumChildren ; ++i)
		if (mChildren[i]->isDirty())
			return true;

	return false;
}

bool Editor::hasFocus()
{
	return getFocus() == this;
}

bool Editor::isFocusable() const
{
	return mWantsFocus;
}

void Editor::onListenableChange(Listenable *listenable)
{
	setDirty(true);
}

void Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex)
{
	renderer.renderBackground(childArea);

	for (int index = 0 ; index <= maxIndex && index < mNumChildren ; ++index)
	{
		SDL_Rect thisChildArea = mChildrenArea[index];
		thisChildArea.x += area.x;
		thisChildArea.y += area.y;

		SDL_Rect intersection;

		if (intersectRect(childArea, thisChildArea, intersection))
		{
			renderer.setClip(intersection);
			mChildren[index]->draw(renderer, thisChildArea);
		}
	}
}

void Editor::drawChildren(Renderer& renderer, const SDL_Rect& area)
{
	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		if (mChildren[index]->isDirty())
		{
			SDL_Rect childArea = mChildrenArea[index];
			childArea.x += area.x;
			childArea.y += area.y;

			drawCoveredChildren(renderer, area, childArea, index - 1);

			renderer.setClip(childArea);

			mChildren[index]->draw(renderer, childArea);
		}
	}
}

void Editor::drawModal(Renderer& renderer)
{
	if (mModal != NULL)
	{
		if (mModal->shouldRedrawBackground())
		{
			// Draw plain black background with white border
			SDL_Rect modalBorder = mModal->getArea();
			modalBorder.x -= MODAL_BORDER;
			modalBorder.y -= MODAL_BORDER;
			modalBorder.w += MODAL_BORDER * 2;
			modalBorder.h += MODAL_BORDER * 2;
			renderer.clearRect(modalBorder, Color(0, 0, 0));
			renderer.drawRect(modalBorder, Color(255, 255, 255));
		}

		mModal->draw(renderer, mModal->getArea());
	}
}

void Editor::setModal(Editor *modal)
{
	if (mModal != NULL)
		mModal->mParent = NULL;

	mModal = modal;

	if (mModal != NULL)
	{
		mModal->mParent = this;
		SDL_Rect modalArea = { mThisArea.x + 16, mThisArea.y + 16,
			mThisArea.w - 32, mThisArea.h - 32 };
		mModal->setArea(modalArea);
	}

	invalidateAll();
}

void Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept)
{
}

void Editor::invalidateAll()
{
	setDirty(true);
	mRedraw = true;

	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		mChildren[index]->invalidateAll();
	}

	if (mModal)
		mModal->invalidateAll();
}

void Editor::onMessageBoxEvent(const Editor& messageBox, int code)
{
}

void Editor::draw(Renderer& renderer, const SDL_Rect& area)
{
	// This should fix problems with modal backgrounds not being updated
	// and perhaps also other child Editors.

	invalidateAll();

	if (mModal == NULL)
	{
		this->onDraw(renderer, area);
		drawChildren(renderer, area);
	}
	else
	{
		drawModal(renderer);
	}

	setDirty(false);
}

void Editor::invalidateParent()
{
	if (mParent)
		mParent->invalidateAll();
}

bool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect)
{
#ifdef SDL_PointInRect
	return SDL_PointInRect(&point, &rect);
#else
	// In case we are using SDL <2.0.4 (of whatever the version is
	// where the rect built-in functions are introduced. E.g. my
	// PocketCHIP only goes up to 2.0.2 by default.

	return point.x >= rect.x && point.x < rect.x + rect.w &&
		point.y >= rect.y && point.y < rect.y + rect.h;
#endif
}

bool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result)
{
#ifdef SDL_IntersectRect
	return SDL_IntersectRect(&point, &rect, &result);
#else
	// In case we are using SDL <2.0.4 (of whatever the version is
	// where the rect built-in functions are introduced. E.g. my
	// PocketCHIP only goes up to 2.0.2 by default.

	int aRight = a.x + a.w;
	int aBottom = a.y + a.h;
	int bRight = b.x + b.w;
	int bBottom = b.y + b.h;

	if (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y))
		return false;

	result.x = std::max(a.x, b.x);
	result.y = std::max(a.y, b.y);
	result.w = std::min(aRight, bRight) - result.x;
	result.h = std::min(aBottom, bBottom) - result.y;

	return true;
#endif
}

void Editor::showTooltipV(const SDL_Rect& area, const char* message, ...)
{
	char dest[1024];
    va_list argptr;
    va_start(argptr, message);
    vsnprintf(dest, sizeof(dest), message, argptr);
    va_end(argptr);

	showTooltip(area, dest);
}

void Editor::showTooltip(const SDL_Rect& area, const char* message)
{
	if (mParent != NULL)
		mParent->showTooltip(area, message);
}

void Editor::showMessageV(MessageClass messageClass, const char* message, ...)
{
	char dest[1024];
    va_list argptr;
    va_start(argptr, message);
    vsnprintf(dest, sizeof(dest), message, argptr);
    va_end(argptr);

	showMessage(messageClass, dest);
}

void Editor::showMessage(MessageClass messageClass, const char* message)
{
	if (mParent != NULL)
		mParent->showMessage(messageClass, message);
	else
		debug("[%s] %s", messageClass == MessageInfo ? "INFO" : "ERROR", message);
}

void Editor::onUpdate(int ms)
{

}

void Editor::update(int ms)
{
	onUpdate(ms);

	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		mChildren[index]->update(ms);
	}
}

void Editor::onLoaded()
{
	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		mChildren[index]->onLoaded();
	}
}

void Editor::childAreaChanged(Editor *child)
{
	for (int index = 0 ; index < mNumChildren ; ++index)
	{
		if (mChildren[index] == child)
			mChildrenArea[index] = child->getArea();
	}
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2012 Kolibre

This file is part of kolibre-narrator.

Kolibre-narrator is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 of the License, or
(at your option) any later version.

Kolibre-narrator 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with kolibre-narrator. If not, see <http://www.gnu.org/licenses/>.
*/

#include "Filter.h"

Filter::Filter()
{
    setSetting(SETTING_USE_AA_FILTER, true);
    setSetting(SETTING_AA_FILTER_LENGTH, 64);
    setSetting(SETTING_USE_QUICKSEEK, false);

    setSetting(SETTING_SEQUENCE_MS, 41);
    setSetting(SETTING_SEEKWINDOW_MS, 28);
    setSetting(SETTING_OVERLAP_MS, 8);

    mTempo = 1.0;
    mPitch = 1.0;
    mGain = 1.0;

    setTempo(mTempo);
    setPitch(mPitch);

    // Set sane defaults
    open(44100, 2);
}

Filter::~Filter()
{
    clear();
}

bool Filter::open(long rate, int channels)
{
    if(mRate != rate || mChannels != channels) {
        mRate = rate;
        setSampleRate(mRate);
        mChannels = channels;
        setChannels(mChannels);
    }
    return true;
}

bool Filter::write(float *buffer, unsigned int samples)
{
    putSamples(buffer, samples); // One sample contains data from all channels
    return true;
}

unsigned int Filter::read(float *buffer, unsigned int bytes)
{
    bytes = receiveSamples(buffer, bytes);
    applyGain(buffer, bytes);
    return bytes;
}

void Filter::applyGain(float *buffer, unsigned int samples)
{
    // Change the gain on the buffer
    static unsigned int i;

    if(mGain == 1.0) return;

    for(i = 0; i < samples; i++) {
        buffer[i] = buffer[i] * mGain;
    }
}

void Filter::fadeout(float *buffer, unsigned int bytes)
{
    // Linear fadeout on the samples in the buffer
    static unsigned int i;
    float val = 1;
    for(i = 0; i < bytes; i++) {
        val = (bytes - i) / bytes;
        buffer[i] = buffer[i] * val;
    }
}
<commit_msg>Initialize variables<commit_after>/*
Copyright (C) 2012 Kolibre

This file is part of kolibre-narrator.

Kolibre-narrator is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 of the License, or
(at your option) any later version.

Kolibre-narrator 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with kolibre-narrator. If not, see <http://www.gnu.org/licenses/>.
*/

#include "Filter.h"

Filter::Filter()
{
    setSetting(SETTING_USE_AA_FILTER, true);
    setSetting(SETTING_AA_FILTER_LENGTH, 64);
    setSetting(SETTING_USE_QUICKSEEK, false);

    setSetting(SETTING_SEQUENCE_MS, 41);
    setSetting(SETTING_SEEKWINDOW_MS, 28);
    setSetting(SETTING_OVERLAP_MS, 8);

    mTempo = 1.0;
    mPitch = 1.0;
    mGain = 1.0;
    mRate = 0;
    mChannels = 0;

    setTempo(mTempo);
    setPitch(mPitch);

    // Set sane defaults
    open(44100, 2);
}

Filter::~Filter()
{
    clear();
}

bool Filter::open(long rate, int channels)
{
    if(mRate != rate || mChannels != channels) {
        mRate = rate;
        setSampleRate(mRate);
        mChannels = channels;
        setChannels(mChannels);
    }
    return true;
}

bool Filter::write(float *buffer, unsigned int samples)
{
    putSamples(buffer, samples); // One sample contains data from all channels
    return true;
}

unsigned int Filter::read(float *buffer, unsigned int bytes)
{
    bytes = receiveSamples(buffer, bytes);
    applyGain(buffer, bytes);
    return bytes;
}

void Filter::applyGain(float *buffer, unsigned int samples)
{
    // Change the gain on the buffer
    static unsigned int i;

    if(mGain == 1.0) return;

    for(i = 0; i < samples; i++) {
        buffer[i] = buffer[i] * mGain;
    }
}

void Filter::fadeout(float *buffer, unsigned int bytes)
{
    // Linear fadeout on the samples in the buffer
    static unsigned int i;
    float val = 1;
    for(i = 0; i < bytes; i++) {
        val = (bytes - i) / bytes;
        buffer[i] = buffer[i] * val;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <wait.h>
#include <vector>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <sys/stat.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

void execfunction(char **argv, string command)
{
	int pid = fork();
	if(-1 == pid)
	{
		perror("There was an error with fork(). ");
	}
	else if(pid == 0)
	{
		if(-1 == execvp(command.c_str(), argv))
		{
			perror("There was an error with execvp() ");
			exit(1);
		}
		_exit(0);
	}
	else
	{
		int status;
		wait(&status);
		if(-1 == status)
		{
			perror("There was an error with wait(). ");
		}
	}
}

int main()
{
	int savestdout;
	if(-1 == (savestdout = dup(1)))
	{
		perror("There was an error with dup(). ");
	}
	if(-1 == close(1))
	{
		perror("There was an error with close(). ");
	}
	vector<string> branches;
	//call execvp to run git branch
	string file_name = "tempfile";
	int write_to;
	char **argv = new char*[3];
	argv[0] = const_cast<char*>("git");
	argv[1] = const_cast<char*>("branch");
	argv[2] = 0;
	if(-1 == (write_to = open(file_name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))
	{
		perror("There was an error with open(). ");
		exit(1);
	}
	execfunction(argv, "git");
	delete []argv;
	if(-1 == close(write_to))
	{
		perror("There was an error with close(). ");
	}
	if(-1 == dup2(savestdout, 1))
	{
		perror("There was an error with dup2(). ");
	}
	int read_from;
	if(-1 == (read_from = open(file_name.c_str(), O_RDONLY)))
	{
		perror("There was an error with open(). ");
	}
	int size;
	char c[BUFSIZ];
	if(-1 == (size = read(read_from, &c, BUFSIZ)))
	{
		perror("There was an error with read(). ");
	}
	while(size > 0)
	{
		branches.push_back(string(c));
		if(-1 == (size = read(read_from, &c, BUFSIZ)))
		{
			perror("There was an error with read(). ");
		}
	}
	if(-1 == close(read_from))
	{
		perror("There was an error with close(). ");
	}
	//take all branch names and put into vector
	//for each branch name, call execvp git checkout branchname
	string currBranch;
	for(unsigned int i = 0; i < branches.size(); ++i)
	{
		if((branches.at(i)).at(0) == '*')
		{
			currBranch = (branches.at(i)).substr(2, (branches.at(i)).size()-3);
		}
		branches.at(i) = (branches.at(i)).substr(2, (branches.at(i)).size()-3);
		cout << branches.at(i) << endl;
	}
	argv = new char*[3];
	argv[0] = const_cast<char*>("rm");
	argv[1] = const_cast<char*>(file_name.c_str());
	argv[2] = 0;
	execfunction(argv, "rm");
	delete []argv;
	//then open/create a file called branchname for whatever branch we are on
	if(-1 == (savestdout = dup(1)))
	{
		perror("There was an error with dup(). ");
	}
	if(-1 == close(1))
	{
		perror("There was an error with close(). ");
	}
	int changed = 0;
	for(unsigned int i = 0; i < branches.size(); ++i)
	{
		if(currBranch != branches.at(i))
		{
			argv = new char*[4];
			argv[0] = const_cast<char*>("git");
			argv[1] = const_cast<char*>("checkout");
			argv[2] = const_cast<char*>((branches.at(i)).c_str());
			argv[3] = 0;
			execfunction(argv, "git");
			delete []argv;
			changed++;
		}
		string name = branches.at(i);
		name += "Branch";
		if(-1 == (write_to = open(name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))
		{
			perror("There was an error with open(). ");
			exit(1);
		}
		argv = new char*[3];
		argv[0] = const_cast<char*>("git");
		argv[1] = const_cast<char*>("log");
		argv[2] = 0;
		execfunction(argv, "git");
		delete []argv;
		if(-1 == close(write_to))
		{
			perror("There was an error with close(). ");
		}
	}
	if(-1 == dup2(savestdout, 1))
	{
		perror("There was an error with dup2(). ");
	}
	if(changed > 0)
	{
		argv = new char*[4];
		argv[0] = const_cast<char*>("git");
		argv[1] = const_cast<char*>("checkout");
		argv[2] = const_cast<char*>(currBranch.c_str());
		argv[3] = 0;
		execfunction(argv, "git");
		delete []argv;
	}
	//then call execvp git log to have all the output go to file
	//close file
	return 0;
}
<commit_msg>updated fork<commit_after>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <wait.h>
#include <vector>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <fstream>
#include <sys/stat.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

void execfunction(char **argv, string command)
{
	int pid = fork();
	if(-1 == pid)
	{
		perror("There was an error with fork(). ");
	}
	else if(pid == 0)
	{
		if(-1 == execvp(command.c_str(), argv))
		{
			perror("There was an error with execvp() ");
			exit(1);
		}
		_exit(0);
	}
	else
	{
		int status;
		wait(&status);
		if(-1 == status)
		{
			perror("There was an error with wait(). ");
		}
	}
}

int main()
{
	int savestdout;
	if(-1 == (savestdout = dup(1)))
	{
		perror("There was an error with dup(). ");
	}
	if(-1 == close(1))
	{
		perror("There was an error with close(). ");
	}
	vector<string> branches;
	//call execvp to run git branch
	char file_name[7] = {'X','X','X','X','X','X',0};
	int write_to;
	char **argv = new char*[3];
	argv[0] = const_cast<char*>("git");
	argv[1] = const_cast<char*>("branch");
	argv[2] = 0;
	if(-1 == (write_to = mkstemp(file_name))) {
		perror("There was an error with mkstemp(). ");
		exit(1);
	}

	execfunction(argv, "git");
	delete []argv;
	if(-1 == close(write_to))
	{
		perror("There was an error with close(). ");
	}
	if(-1 == dup2(savestdout, 1))
	{
		perror("There was an error with dup2(). ");
	}
	string line;
	ifstream myfile(file_name);
	while(myfile.good())
	{
		getline(myfile, line);
		branches.push_back(line);
	}
	myfile.close();
	argv = new char*[3];
	argv[0] = const_cast<char*>("rm");
	argv[1] = const_cast<char*>(file_name);
	argv[2] = 0;
	execfunction(argv, "rm");
	delete []argv;
	//take all branch names and put into vector
	//for each branch name, call execvp git checkout branchname
	string currBranch;
	string temp;
	for(unsigned int i = 0; i < branches.size()-1; ++i)
	{
		temp = branches.at(i);
		if(temp.at(0) == '*')
		{
			currBranch = (temp).substr(2, temp.size()-2);
			branches.at(i) = currBranch;
		}
		else
		{
			branches.at(i) = (temp).substr(2, temp.size()-2);
		}
		cout << branches.at(i) << endl;
	}
	//then open/create a file called branchname for whatever branch we are on
	if(-1 == (savestdout = dup(1)))
	{
		perror("There was an error with dup(). ");
	}
	if(-1 == close(1))
	{
		perror("There was an error with close(). ");
	}
	int changed = 0;
	for(unsigned int i = 0; i < branches.size(); ++i)
	{
		if(currBranch != branches.at(i))
		{
			argv = new char*[4];
			argv[0] = const_cast<char*>("git");
			argv[1] = const_cast<char*>("checkout");
			argv[2] = const_cast<char*>((branches.at(i)).c_str());
			argv[3] = 0;
			execfunction(argv, "git");
			delete []argv;
			changed++;
		}
		string name = branches.at(i);
		name += "Branch";
		if(-1 == (write_to = open(name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))
		{
			perror("There was an error with open(). ");
			exit(1);
		}
		argv = new char*[3];
		argv[0] = const_cast<char*>("git");
		argv[1] = const_cast<char*>("log");
		argv[2] = 0;
		execfunction(argv, "git");
		delete []argv;
		if(-1 == close(write_to))
		{
			perror("There was an error with close(). ");
		}
	}
	if(-1 == dup2(savestdout, 1))
	{
		perror("There was an error with dup2(). ");
	}
	if(changed > 0)
	{
		argv = new char*[4];
		argv[0] = const_cast<char*>("git");
		argv[1] = const_cast<char*>("checkout");
		argv[2] = const_cast<char*>(currBranch.c_str());
		argv[3] = 0;
		execfunction(argv, "git");
		delete []argv;
	}
	//then call execvp git log to have all the output go to file
	//close file
	return 0;
}
<|endoftext|>