blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e42ea4ce0f4beb0bece48ea1e6e4d8fcd148278b | b24c5c71797a780f8710dd750ccf2b5f1b749c98 | /Classes/Models/Master/BaseConditionMaster.h | 51188c2fa6ea07b8da88a042e47ecd20db757082 | [] | no_license | ume3003/Koumechan | 088066ba8dc95a2c820f20a41ca77545dd88f413 | 4d8e597515d0e1d03510ca92b73f3735caa27f7f | refs/heads/master | 2021-05-27T22:06:05.407570 | 2014-08-18T01:53:57 | 2014-08-18T01:53:57 | 22,201,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | h | BaseConditionMaster.h | //
// BaseConditionMaster.h
// koumeChan
//
// Created by 上野 彰三 on 2014/04/01.
//
//
#ifndef __koumeChan__BaseConditionMaster__
#define __koumeChan__BaseConditionMaster__
#include "cocos2d.h"
#include "BaseMaster.h"
class BaseConditionMaster : public BaseMaster
{
protected:
virtual bool initWithJson(Json* json);
CC_SYNTHESIZE(long,m_parentNo,ParentNo);
CC_SYNTHESIZE(long,m_conditionNo,ConditionNo);
CC_SYNTHESIZE(long,m_Kind,Kind);
CC_SYNTHESIZE(long,m_KeyNo,KeyNo);
CC_SYNTHESIZE(long long,m_Val,Val);
public:
virtual std::string toJsonString();
};
#endif /* defined(__koumeChan__BaseConditionMaster__) */
|
c4b671d57eaac896578d05d7259f24cfba72de83 | 13f17d09b28a8628d86c32b7934ca246efeab684 | /audio.cpp | 35948260eacf69345ad5291410fa778288f5d296 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | permissive | nbonaker/ticker | 5b84bfbab79a6f42ad2d38d74491d3902b73f8d6 | 4a9bab2916344914cbc96910c7eff4d9f0e10570 | refs/heads/master | 2020-04-18T03:27:20.480226 | 2019-03-31T00:55:41 | 2019-03-31T00:55:41 | 167,199,299 | 0 | 0 | MIT | 2019-01-23T14:46:11 | 2019-01-23T14:46:10 | null | UTF-8 | C++ | false | false | 1,492 | cpp | audio.cpp | #include "audio.h"
#include "fmod_alphabet_player.h"
#include <iostream>
static AlphabetPlayer alphabet_player = AlphabetPlayer();
void playNext(void) { alphabet_player.playNext(); }
int isReady(void) { return alphabet_player.isReady(); }
void setChannels(int i_nchannels) { alphabet_player.setChannels(i_nchannels); }
void restart(void) { alphabet_player.restart(); }
void stop(void) { alphabet_player.stop(); }
void playInstruction(char *i_instruction_name, char *i_file_type)
{
std::string instruction_name(i_instruction_name);
std::string file_type(i_file_type);
alphabet_player.playInstruction(instruction_name, i_file_type);
}
void setRootDir(char *i_dir_name)
{
std::string dir_name(i_dir_name);
alphabet_player.setRootDir(dir_name);
}
void setAlphabetDir(char *i_dir_name)
{
std::string dir_name(i_dir_name);
alphabet_player.setAlphabetDir(dir_name);
}
void setConfigDir(char *i_dir_name)
{
std::string dir_name(i_dir_name);
alphabet_player.setConfigDir(dir_name);
}
void setVolume(float i_val, int i_channel)
{
alphabet_player.setVolume(i_val, i_channel);
}
int isPlayingInstruction(void)
{
return (int)alphabet_player.getIsPlayingInstruction();
}
const int *getCurLetterTimes(int *o_size)
{
const std::vector< int > &letter_times =
alphabet_player.getCurLetterTimes();
*o_size = letter_times.size();
return &letter_times[0];
}
void setTicks(unsigned int i_nticks) { alphabet_player.setTicks(i_nticks); }
|
3c2ece2066177bf94fe07c07a219c5dc8e95ea34 | 284f2e73ce5c4a3274167993fafcdfc18d2d0564 | /rhythmslashtestsuite.cpp | 374c1d35120d1b70634cf5a476128dff4ac93802 | [] | no_license | powertab/ptparser | c9b466307e54ca64389749eccdecb79c0c7f2057 | 66dd75676b938f4f238ced4a7d219669e276f162 | refs/heads/master | 2022-11-12T15:31:55.742576 | 2020-06-25T21:35:35 | 2020-06-25T21:35:35 | 275,019,279 | 0 | 0 | null | 2020-06-25T21:32:27 | 2020-06-25T21:32:27 | null | UTF-8 | C++ | false | false | 39,556 | cpp | rhythmslashtestsuite.cpp | /////////////////////////////////////////////////////////////////////////////
// Name: rhythmslashtestsuite.cpp
// Purpose: Performs unit testing on the RhythmSlash class
// Author: Brad Larsen
// Modified by:
// Created: Jan 5, 2005
// RCS-ID:
// Copyright: (c) Brad Larsen
// License: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#include "stdwx.h"
#include "rhythmslashtestsuite.h"
#include "rhythmslash.h"
#include "powertabfileheader.h" // Needed for file version constants
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNAMIC_CLASS(RhythmSlashTestSuite, TestSuite)
/// Default Constructor
RhythmSlashTestSuite::RhythmSlashTestSuite()
{
//------Last Checked------//
// - Jan 7, 2005
}
/// Destructor
RhythmSlashTestSuite::~RhythmSlashTestSuite()
{
//------Last Checked------//
// - Jan 7, 2005
}
/// Gets the total number of tests in the test suite
/// @return The total number of tests in the test suite
size_t RhythmSlashTestSuite::GetTestCount() const
{
//------Last Checked------//
// - Sep 27, 2007
return (693);
}
/// Executes all test cases in the test suite
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::RunTestCases()
{
//------Last Checked------//
// - Jan 7, 2005
if (!TestCaseConstructor())
return (false);
if (!TestCaseCreation())
return (false);
if (!TestCaseOperator())
return (false);
if (!TestCaseSerialize())
return (false);
if (!TestCasePosition())
return (false);
if (!TestCaseDurationType())
return (false);
if (!TestCaseBeaming())
return (false);
if (!TestCaseTriplet())
return (false);
if (!TestCaseDotted())
return (false);
if (!TestCaseRest())
return (false);
if (!TestCaseTied())
return (false);
if (!TestCaseMuted())
return (false);
if (!TestCaseStaccato())
return (false);
if (!TestCasePickStroke())
return (false);
if (!TestCaseArpeggio())
return (false);
if (!TestCaseTripletFeel())
return (false);
if (!TestCaseAccent())
return (false);
if (!TestCaseSlideInto())
return (false);
if (!TestCaseSlideOutOf())
return (false);
if (!TestCaseSingleNoteData())
return (false);
return (true);
}
/// Tests the Constructors
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseConstructor()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: Default Constructor
{
RhythmSlash rhythmSlash;
TEST(wxT("Default Constructor"),
(rhythmSlash.m_position == RhythmSlash::DEFAULT_POSITION) &&
(rhythmSlash.m_beaming == RhythmSlash::DEFAULT_BEAMING) &&
(rhythmSlash.GetDurationType() == 8) &&
(rhythmSlash.m_data == RhythmSlash::DEFAULT_DATA)
);
}
// TEST CASE: Primary Constructor
{
RhythmSlash rhythmSlash(12,4,2);
TEST(wxT("Primary Constructor"),
(rhythmSlash.GetPosition() == 12) &&
(rhythmSlash.m_beaming == 0) &&
(rhythmSlash.GetDurationType() == 4) &&
(rhythmSlash.IsDoubleDotted())
);
}
// TEST CASE: Copy Constructor
{
RhythmSlash rhythmSlash(12,4,2);
RhythmSlash rhythmSlash2(rhythmSlash);
TEST(wxT("Copy Constructor"),
(rhythmSlash == rhythmSlash2)
);
}
return (true);
}
/// Tests the Creation Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseCreation()
{
//------Last Checked------//
// - Jan 9, 2005
RhythmSlash rhythmSlash(12,4,2);
RhythmSlash* clone = (RhythmSlash*)rhythmSlash.CloneObject();
TEST(wxT("CloneObject"),
(*clone == rhythmSlash)
);
delete clone;
return (true);
}
/// Tests the Operators
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseOperator()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: Assignment Operator
{
RhythmSlash rhythmSlash(12,4,2);
RhythmSlash rhythmSlash2 = rhythmSlash;
TEST(wxT("Operator="),
(rhythmSlash == rhythmSlash2)
);
// TEST CASE: Operator= (self-assignment)
rhythmSlash = rhythmSlash;
TEST(wxT("Operator= (self-assignment)"),
(rhythmSlash == rhythmSlash)
);
}
// TEST CASE: Equality Operator
{
RhythmSlash rhythmSlash(12,4,2);
RhythmSlash rhythmSlash2(12,4,2);
RhythmSlash rhythmSlash3(13,4,2);
RhythmSlash rhythmSlash4(12,8,2);
RhythmSlash rhythmSlash5(12,4,1);
RhythmSlash rhythmSlash6(12,4,2);
rhythmSlash6.SetPreviousBeamDurationType(8);
RhythmSlash rhythmSlash7(12,4,2);
rhythmSlash7.SetBeamStart();
RhythmSlash rhythmSlash8(12,4,2);
rhythmSlash8.SetFractionalBeam();
RhythmSlash rhythmSlash9(12,4,2);
rhythmSlash9.SetBeamEnd();
RhythmSlash rhythmSlash10(12,4,2);
rhythmSlash10.SetTripletStart();
RhythmSlash rhythmSlash11(12,4,2);
rhythmSlash11.SetTripletMiddle();
RhythmSlash rhythmSlash12(12,4,2);
rhythmSlash12.SetTripletEnd();
RhythmSlash rhythmSlash13(12,4,2);
rhythmSlash13.SetDotted();
RhythmSlash rhythmSlash14(11,4,2);
rhythmSlash14.SetDoubleDotted();
RhythmSlash rhythmSlash15(12,4,2);
rhythmSlash15.SetRest();
RhythmSlash rhythmSlash16(12,4,2);
rhythmSlash16.SetTied();
RhythmSlash rhythmSlash17(12,4,2);
rhythmSlash17.SetMuted();
RhythmSlash rhythmSlash18(12,4,2);
rhythmSlash18.SetStaccato();
RhythmSlash rhythmSlash19(12,4,2);
rhythmSlash19.SetPickStrokeUp();
RhythmSlash rhythmSlash20(12,4,2);
rhythmSlash20.SetPickStrokeDown();
RhythmSlash rhythmSlash21(12,4,2);
rhythmSlash21.SetArpeggioUp();
RhythmSlash rhythmSlash22(12,4,2);
rhythmSlash22.SetArpeggioDown();
RhythmSlash rhythmSlash23(12,4,2);
rhythmSlash23.SetTripletFeel1st();
RhythmSlash rhythmSlash24(12,4,2);
rhythmSlash24.SetTripletFeel2nd();
RhythmSlash rhythmSlash25(12,4,2);
rhythmSlash25.SetMarcato();
RhythmSlash rhythmSlash26(12,4,2);
rhythmSlash26.SetSforzando();
RhythmSlash rhythmSlash27(12,4,2);
rhythmSlash27.SetSlideIntoFromAbove();
RhythmSlash rhythmSlash28(12,4,2);
rhythmSlash28.SetSlideIntoFromBelow();
RhythmSlash rhythmSlash29(12,4,2);
rhythmSlash29.SetSlideOutOfDownwards();
RhythmSlash rhythmSlash30(12,4,2);
rhythmSlash30.SetSlideOutOfUpwards();
RhythmSlash rhythmSlash31(12,4,2);
rhythmSlash31.SetSingleNoteData(4,5);
TEST(wxT("Operator== - rhythmSlash == rhythmSlash"),
(rhythmSlash == rhythmSlash2));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash"),
!(rhythmSlash == rhythmSlash3));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 2"),
!(rhythmSlash == rhythmSlash4));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 3"),
!(rhythmSlash == rhythmSlash5));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 4"),
!(rhythmSlash == rhythmSlash6));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 5"),
!(rhythmSlash == rhythmSlash7));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 6"),
!(rhythmSlash == rhythmSlash8));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 7"),
!(rhythmSlash == rhythmSlash9));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 8"),
!(rhythmSlash == rhythmSlash10));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 9"),
!(rhythmSlash == rhythmSlash11));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 10"),
!(rhythmSlash == rhythmSlash12));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 11"),
!(rhythmSlash == rhythmSlash13));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 12"),
!(rhythmSlash == rhythmSlash14));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 13"),
!(rhythmSlash == rhythmSlash15));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 14"),
!(rhythmSlash == rhythmSlash16));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 15"),
!(rhythmSlash == rhythmSlash17));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 16"),
!(rhythmSlash == rhythmSlash18));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 17"),
!(rhythmSlash == rhythmSlash19));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 18"),
!(rhythmSlash == rhythmSlash20));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 19"),
!(rhythmSlash == rhythmSlash21));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 20"),
!(rhythmSlash == rhythmSlash22));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 21"),
!(rhythmSlash == rhythmSlash23));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 22"),
!(rhythmSlash == rhythmSlash24));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 23"),
!(rhythmSlash == rhythmSlash25));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 24"),
!(rhythmSlash == rhythmSlash26));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 25"),
!(rhythmSlash == rhythmSlash27));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 26"),
!(rhythmSlash == rhythmSlash28));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 27"),
!(rhythmSlash == rhythmSlash29));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 28"),
!(rhythmSlash == rhythmSlash30));
TEST(wxT("Operator== - rhythmSlash != rhythmSlash 29"),
!(rhythmSlash == rhythmSlash31));
}
// Inequality Operator
{
RhythmSlash rhythmSlash(12,4,2);
RhythmSlash rhythmSlash2(12,4,2);
RhythmSlash rhythmSlash3(13,4,2);
RhythmSlash rhythmSlash4(12,8,2);
RhythmSlash rhythmSlash5(12,4,1);
RhythmSlash rhythmSlash6(12,4,2);
rhythmSlash6.SetPreviousBeamDurationType(8);
RhythmSlash rhythmSlash7(12,4,2);
rhythmSlash7.SetBeamStart();
RhythmSlash rhythmSlash8(12,4,2);
rhythmSlash8.SetFractionalBeam();
RhythmSlash rhythmSlash9(12,4,2);
rhythmSlash9.SetBeamEnd();
RhythmSlash rhythmSlash10(12,4,2);
rhythmSlash10.SetTripletStart();
RhythmSlash rhythmSlash11(12,4,2);
rhythmSlash11.SetTripletMiddle();
RhythmSlash rhythmSlash12(12,4,2);
rhythmSlash12.SetTripletEnd();
RhythmSlash rhythmSlash13(12,4,2);
rhythmSlash13.SetDotted();
RhythmSlash rhythmSlash14(11,4,2);
rhythmSlash14.SetDoubleDotted();
RhythmSlash rhythmSlash15(12,4,2);
rhythmSlash15.SetRest();
RhythmSlash rhythmSlash16(12,4,2);
rhythmSlash16.SetTied();
RhythmSlash rhythmSlash17(12,4,2);
rhythmSlash17.SetMuted();
RhythmSlash rhythmSlash18(12,4,2);
rhythmSlash18.SetStaccato();
RhythmSlash rhythmSlash19(12,4,2);
rhythmSlash19.SetPickStrokeUp();
RhythmSlash rhythmSlash20(12,4,2);
rhythmSlash20.SetPickStrokeDown();
RhythmSlash rhythmSlash21(12,4,2);
rhythmSlash21.SetArpeggioUp();
RhythmSlash rhythmSlash22(12,4,2);
rhythmSlash22.SetArpeggioDown();
RhythmSlash rhythmSlash23(12,4,2);
rhythmSlash23.SetTripletFeel1st();
RhythmSlash rhythmSlash24(12,4,2);
rhythmSlash24.SetTripletFeel2nd();
RhythmSlash rhythmSlash25(12,4,2);
rhythmSlash25.SetMarcato();
RhythmSlash rhythmSlash26(12,4,2);
rhythmSlash26.SetSforzando();
RhythmSlash rhythmSlash27(12,4,2);
rhythmSlash27.SetSlideIntoFromAbove();
RhythmSlash rhythmSlash28(12,4,2);
rhythmSlash28.SetSlideIntoFromBelow();
RhythmSlash rhythmSlash29(12,4,2);
rhythmSlash29.SetSlideOutOfDownwards();
RhythmSlash rhythmSlash30(12,4,2);
rhythmSlash30.SetSlideOutOfUpwards();
RhythmSlash rhythmSlash31(12,4,2);
rhythmSlash31.SetSingleNoteData(4,5);
TEST(wxT("Operator!= - rhythmSlash == rhythmSlash"),
!(rhythmSlash != rhythmSlash2));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash"),
(rhythmSlash != rhythmSlash3));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 2"),
(rhythmSlash != rhythmSlash4));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 3"),
(rhythmSlash != rhythmSlash5));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 4"),
(rhythmSlash != rhythmSlash6));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 5"),
(rhythmSlash != rhythmSlash7));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 6"),
(rhythmSlash != rhythmSlash8));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 7"),
(rhythmSlash != rhythmSlash9));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 8"),
(rhythmSlash != rhythmSlash10));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 9"),
(rhythmSlash != rhythmSlash11));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 10"),
(rhythmSlash != rhythmSlash12));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 11"),
(rhythmSlash != rhythmSlash13));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 12"),
(rhythmSlash != rhythmSlash14));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 13"),
(rhythmSlash != rhythmSlash15));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 14"),
(rhythmSlash != rhythmSlash16));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 15"),
(rhythmSlash != rhythmSlash17));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 16"),
(rhythmSlash != rhythmSlash18));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 17"),
(rhythmSlash != rhythmSlash19));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 18"),
(rhythmSlash != rhythmSlash20));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 19"),
(rhythmSlash != rhythmSlash21));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 20"),
(rhythmSlash != rhythmSlash22));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 21"),
(rhythmSlash != rhythmSlash23));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 22"),
(rhythmSlash != rhythmSlash24));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 23"),
(rhythmSlash != rhythmSlash25));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 24"),
(rhythmSlash != rhythmSlash26));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 25"),
(rhythmSlash != rhythmSlash27));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 26"),
(rhythmSlash != rhythmSlash28));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 27"),
(rhythmSlash != rhythmSlash29));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 28"),
(rhythmSlash != rhythmSlash30));
TEST(wxT("Operator!= - rhythmSlash != rhythmSlash 29"),
(rhythmSlash != rhythmSlash31));
}
return (true);
}
/// Tests the Serialization Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseSerialize()
{
//------Last Checked------//
// - Jan 7, 2005
bool ok = false;
TestStream testStream;
PowerTabOutputStream streamOut(testStream.GetOutputStream());
// Write test data to stream
RhythmSlash rhythmSlashOut(12, 4, 2);
rhythmSlashOut.Serialize(streamOut);
// Output must be OK before using input
if (testStream.CheckOutputState())
{
PowerTabInputStream streamIn(testStream.GetInputStream());
// Read test data back from stream
RhythmSlash rhythmSlashIn;
rhythmSlashIn.Deserialize(streamIn,
PowerTabFileHeader::FILEVERSION_CURRENT);
// Validate the data
ok = ((rhythmSlashIn == rhythmSlashOut)
&& (streamIn.CheckState()));
}
TEST(wxT("Serialize"), ok);
return (true);
}
/// Tests the Position Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCasePosition()
{
//------Last Checked------//
// - Jan 3, 2005
// TEST CASE: IsValidPosition
{
wxUint32 i = RhythmSlash::MIN_POSITION;
for (; i <= (RhythmSlash::MAX_POSITION + 1); i++)
{
TEST(wxString::Format(wxT("IsValidPosition - %d"), i),
(RhythmSlash::IsValidPosition(i) ==
(i <= RhythmSlash::MAX_POSITION))
);
}
}
// TEST CASE: SetPosition
{
RhythmSlash rhythmSlash;
wxUint32 i = 0;
for (; i <= (RhythmSlash::MAX_POSITION + 1); i++)
{
TEST(wxT("SetPosition - %d"),
(rhythmSlash.SetPosition(i) ==
(i <= RhythmSlash::MAX_POSITION)) &&
((i > RhythmSlash::MAX_POSITION) ? 1 :
(rhythmSlash.GetPosition() == i))
);
}
}
return (true);
}
/// Tests the Duration Type Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseDurationType()
{
//------Last Checked------//
// - Jan 6, 2005
// TEST CASE: IsValidDurationType
{
TEST(wxT("IsValidDurationType - 0"),
!RhythmSlash::IsValidDurationType(0));
wxByte i = 1;
for (; i <= 32; i = i * 2)
TEST(wxString::Format(wxT("IsValidDurationType - %d"), i),
(RhythmSlash::IsValidDurationType(i) == (i < 32))
);
}
// TEST CASE: SetDurationType
{
RhythmSlash rhythmSlash;
TEST(wxT("SetDurationType - 0"), !rhythmSlash.SetDurationType(0));
wxByte i = 1;
for (; i <= 32; i = i * 2)
TEST(wxString::Format(wxT("SetDurationType - %d"), i),
(rhythmSlash.SetDurationType(i) == (i < 32)) &&
((i >= 32) ? 1 : (rhythmSlash.GetDurationType() == i))
);
}
return (true);
}
/// Tests the Beaming Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseBeaming()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: IsValidPreviousBeamDurationType
{
TEST(wxT("IsValidPreviousBeamDurationType - 0"),
RhythmSlash::IsValidPreviousBeamDurationType(0));
wxByte i = 1;
for (; i <= 32; i = i * 2)
TEST(wxString::Format(wxT("IsValidPreviousBeamDurationType - %d"), i),
(RhythmSlash::IsValidPreviousBeamDurationType(i) ==
((i == 0) || (i == 8) || (i == 16)))
);
}
// TEST CASE: SetDurationType
{
RhythmSlash rhythmSlash;
TEST(wxT("SetPreviousBeamDurationType - 0"),
rhythmSlash.SetPreviousBeamDurationType(0));
wxByte i = 1;
for (; i <= 32; i = i * 2)
TEST(wxString::Format(wxT("SetPreviousBeamDurationType - %d"), i),
(rhythmSlash.SetPreviousBeamDurationType(i) ==
((i == 0) || (i == 8) || (i == 16))) &&
(!((i == 0) || (i == 8) || (i == 16)) ? 1 :
(rhythmSlash.GetPreviousBeamDurationType() == i))
);
}
// TEST CASE: SetBeamStart
{
RhythmSlash rhythmSlash;
TEST(wxT("SetBeamStart - true"),
(rhythmSlash.SetBeamStart() && rhythmSlash.IsBeamStart()));
TEST(wxT("SetBeamStart - false"),
(rhythmSlash.SetBeamStart(false) && !rhythmSlash.IsBeamStart()));
}
// TEST CASE: SetFractionalBeam
{
RhythmSlash rhythmSlash;
TEST(wxT("SetFractionalBeam - true"),
(rhythmSlash.SetFractionalBeam() &&
rhythmSlash.HasFractionalBeam()));
TEST(wxT("SetFractionalBeam - false"),
(rhythmSlash.SetFractionalBeam(false) &&
!rhythmSlash.HasFractionalBeam()));
}
// TEST CASE: SetBeamEnd
{
RhythmSlash rhythmSlash;
TEST(wxT("SetBeamEnd - true"),
(rhythmSlash.SetBeamEnd() && rhythmSlash.IsBeamEnd()));
TEST(wxT("SetBeamEnd - false"),
(rhythmSlash.SetBeamEnd(false) && !rhythmSlash.IsBeamEnd()));
}
// TEST CASE: ClearBeam
{
RhythmSlash rhythmSlash;
rhythmSlash.SetPreviousBeamDurationType(16);
rhythmSlash.SetBeamStart();
TEST(wxT("ClearBeam - beam start"),
rhythmSlash.ClearBeam() &&
(!rhythmSlash.IsBeamStart()) &&
(rhythmSlash.GetPreviousBeamDurationType() == 0)
);
rhythmSlash.SetPreviousBeamDurationType(16);
rhythmSlash.SetFractionalBeam();
TEST(wxT("ClearBeam - fractional beam"),
rhythmSlash.ClearBeam() &&
(!rhythmSlash.HasFractionalBeam()) &&
(rhythmSlash.GetPreviousBeamDurationType() == 0)
);
rhythmSlash.SetPreviousBeamDurationType(16);
rhythmSlash.SetBeamEnd();
TEST(wxT("ClearBeam - beam end"),
rhythmSlash.ClearBeam() &&
(!rhythmSlash.IsBeamEnd()) &&
(rhythmSlash.GetPreviousBeamDurationType() == 0)
);
}
return (true);
}
/// Tests the Triplet Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseTriplet()
{
//------Last Checked------//
// - Jan 6, 2005
// TEST CASE: IsValidTripletFlag
{
const wxUint32 testValueCount = 15;
wxByte testValues[testValueCount];
testValues[0] = RhythmSlash::tripletStart;
testValues[1] = RhythmSlash::tripletMiddle;
testValues[2] = RhythmSlash::tripletEnd;
testValues[3] = (RhythmSlash::tripletStart | RhythmSlash::tripletMiddle);
testValues[4] = (RhythmSlash::tripletStart | RhythmSlash::tripletEnd);
testValues[5] = (RhythmSlash::tripletMiddle | RhythmSlash::tripletEnd);
testValues[6] = (RhythmSlash::tripletStart | RhythmSlash::tripletMiddle |
RhythmSlash::tripletEnd);
testValues[7] = 0;
testValues[8] = (RhythmSlash::tripletStart + 1);
testValues[9] = (RhythmSlash::tripletMiddle + 1);
testValues[10] = (RhythmSlash::tripletEnd + 1);
testValues[11] = (RhythmSlash::tripletStart |
RhythmSlash::tripletMiddle + 1);
testValues[12] = (RhythmSlash::tripletStart |
RhythmSlash::tripletEnd + 1);
testValues[13] = (RhythmSlash::tripletMiddle |
RhythmSlash::tripletEnd + 1);
testValues[14] = (RhythmSlash::tripletStart |
RhythmSlash::tripletMiddle | RhythmSlash::tripletEnd + 1);
wxUint32 i = 0;
for (; i < testValueCount; i++)
TEST(wxString::Format(wxT("IsValidTripletFlag - %d"), testValues[i]),
RhythmSlash::IsValidTripletFlag(testValues[i]) == (i < 7));
}
// TEST CASE: SetTripletFlag
{
RhythmSlash rhythmSlash;
TEST(wxT("SetTripletFlag - 0"), !rhythmSlash.SetTripletFlag(0));
TEST(wxT("SetTripletFlag - 1"), !rhythmSlash.SetTripletFlag(1));
TEST(wxT("SetTripletFlag - tripletStart"),
rhythmSlash.SetTripletFlag(RhythmSlash::tripletStart) &&
rhythmSlash.IsTripletFlagSet(RhythmSlash::tripletStart) &&
rhythmSlash.IsTripletStart() &&
!rhythmSlash.IsTripletMiddle() &&
!rhythmSlash.IsTripletEnd()
);
TEST(wxT("SetTripletFlag - tripletMiddle"),
rhythmSlash.SetTripletFlag(RhythmSlash::tripletMiddle) &&
rhythmSlash.IsTripletFlagSet(RhythmSlash::tripletMiddle) &&
!rhythmSlash.IsTripletStart() &&
rhythmSlash.IsTripletMiddle() &&
!rhythmSlash.IsTripletEnd()
);
TEST(wxT("SetTripletFlag - tripletEnd"),
rhythmSlash.SetTripletFlag(RhythmSlash::tripletEnd) &&
rhythmSlash.IsTripletFlagSet(RhythmSlash::tripletEnd) &&
!rhythmSlash.IsTripletStart() &&
!rhythmSlash.IsTripletMiddle() &&
rhythmSlash.IsTripletEnd()
);
}
// TEST CASE: ClearTripletFlag
{
const wxUint32 testValueCount = 5;
wxByte testValues[testValueCount];
testValues[0] = RhythmSlash::tripletStart;
testValues[1] = RhythmSlash::tripletMiddle;
testValues[2] = RhythmSlash::tripletEnd;
testValues[3] = 0;
testValues[4] = 1;
RhythmSlash rhythmSlash;
wxUint32 i = 0;
for (; i < testValueCount; i++)
{
rhythmSlash.SetTripletFlag(testValues[i]);
TEST(wxString::Format(wxT("ClearTripletFlag - %d"), i),
(rhythmSlash.ClearTripletFlag(testValues[i]) == (i < 3)) &&
(!rhythmSlash.IsTripletFlagSet(testValues[i]))
);
}
}
// TEST CASE: SetTripletStart
{
RhythmSlash rhythmSlash;
TEST(wxT("SetTripletStart - true"),
(rhythmSlash.SetTripletStart() && rhythmSlash.IsTripletStart()));
TEST(wxT("SetTripletStart - false"),
(rhythmSlash.SetTripletStart(false) &&
!rhythmSlash.IsTripletStart()));
}
// TEST CASE: SetTripletMiddle
{
RhythmSlash rhythmSlash;
TEST(wxT("SetTripletMiddle - true"),
(rhythmSlash.SetTripletMiddle() && rhythmSlash.IsTripletMiddle()));
TEST(wxT("SetTripletMiddle - false"),
(rhythmSlash.SetTripletMiddle(false) &&
!rhythmSlash.IsTripletMiddle()));
}
// TEST CASE: SetTripletEnd
{
RhythmSlash rhythmSlash;
TEST(wxT("SetTripletEnd - true"),
(rhythmSlash.SetTripletEnd() && rhythmSlash.IsTripletEnd()));
TEST(wxT("SetTripletEnd - false"),
(rhythmSlash.SetTripletEnd(false) && !rhythmSlash.IsTripletEnd()));
}
// TEST CASE: ClearTriplet
{
RhythmSlash rhythmSlash;
rhythmSlash.SetTripletStart();
TEST(wxT("ClearTriplet - triplet start"),
rhythmSlash.ClearTriplet() &&
!rhythmSlash.IsTripletStart()
);
rhythmSlash.SetTripletMiddle();
TEST(wxT("ClearTriplet - triplet middle"),
rhythmSlash.ClearTriplet() &&
!rhythmSlash.IsTripletMiddle()
);
rhythmSlash.SetTripletEnd();
TEST(wxT("ClearTriplet - triplet start"),
rhythmSlash.ClearTriplet() &&
!rhythmSlash.IsTripletEnd()
);
}
return (true);
}
/// Tests the Dotted Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseDotted()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: Dotted
{
RhythmSlash rhythmSlash;
TEST(wxT("SetDotted - true"),
(rhythmSlash.SetDotted() && rhythmSlash.IsDotted()));
TEST(wxT("SetDotted - false"),
(rhythmSlash.SetDotted(false) && !rhythmSlash.IsDotted()));
}
// TEST CASE: Double Dotted
{
RhythmSlash rhythmSlash;
TEST(wxT("SetDoubleDotted - true"),
(rhythmSlash.SetDoubleDotted() && rhythmSlash.IsDoubleDotted()));
TEST(wxT("SetDoubleDotted - false"),
(rhythmSlash.SetDoubleDotted(false) &&
!rhythmSlash.IsDoubleDotted()));
}
return (true);
}
/// Tests the Rest Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseRest()
{
//------Last Checked------//
// - Jan 7, 2005
RhythmSlash rhythmSlash;
TEST(wxT("SetRest - true"),
(rhythmSlash.SetRest() && rhythmSlash.IsRest()));
TEST(wxT("SetRest - false"),
(rhythmSlash.SetRest(false) && !rhythmSlash.IsRest()));
return (true);
}
/// Tests the Tied Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseTied()
{
//------Last Checked------//
// - Jan 7, 2005
RhythmSlash rhythmSlash;
TEST(wxT("SetTied - true"),
(rhythmSlash.SetTied() && rhythmSlash.IsTied()));
TEST(wxT("SetTied - false"),
(rhythmSlash.SetTied(false) && !rhythmSlash.IsTied()));
return (true);
}
/// Tests the Muted Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseMuted()
{
//------Last Checked------//
// - Jan 7, 2005
RhythmSlash rhythmSlash;
TEST(wxT("SetMuted - true"),
(rhythmSlash.SetMuted() && rhythmSlash.IsMuted()));
TEST(wxT("SetMuted - false"),
(rhythmSlash.SetMuted(false) && !rhythmSlash.IsMuted()));
return (true);
}
/// Tests the Staccato Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseStaccato()
{
//------Last Checked------//
// - Jan 7, 2005
RhythmSlash rhythmSlash;
TEST(wxT("SetStaccato - true"),
(rhythmSlash.SetStaccato() && rhythmSlash.IsStaccato()));
TEST(wxT("SetStaccato - false"),
(rhythmSlash.SetStaccato(false) && !rhythmSlash.IsStaccato()));
return (true);
}
/// Tests the Pick Stroke Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCasePickStroke()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: SetPickStrokeUp
{
RhythmSlash rhythmSlash;
TEST(wxT("SetPickStrokeUp - true"),
(rhythmSlash.SetPickStrokeUp() && rhythmSlash.HasPickStrokeUp()));
TEST(wxT("SetPickStrokeUp - false"),
(rhythmSlash.SetPickStrokeUp(false) &&
!rhythmSlash.HasPickStrokeUp()));
}
// TEST CASE: SetPickStrokeDown
{
RhythmSlash rhythmSlash;
TEST(wxT("SetPickStrokeDown - true"),
(rhythmSlash.SetPickStrokeDown() &&
rhythmSlash.HasPickStrokeDown()));
TEST(wxT("SetPickStrokeDown - false"),
(rhythmSlash.SetPickStrokeDown(false) &&
!rhythmSlash.HasPickStrokeDown()));
}
return (true);
}
/// Tests the Arpeggio Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseArpeggio()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: SetArpeggioDown
{
RhythmSlash rhythmSlash;
TEST(wxT("SetArpeggioDown - true"),
(rhythmSlash.SetArpeggioDown() && rhythmSlash.HasArpeggioDown()));
TEST(wxT("SetArpeggioDown - false"),
(rhythmSlash.SetArpeggioDown(false) &&
!rhythmSlash.HasArpeggioDown()));
}
// TEST CASE: SetArpeggioUp
{
RhythmSlash rhythmSlash;
TEST(wxT("SetArpeggioUp - true"),
(rhythmSlash.SetArpeggioUp() && rhythmSlash.HasArpeggioUp()));
TEST(wxT("SetArpeggioUp - false"),
(rhythmSlash.SetArpeggioUp(false) && !rhythmSlash.HasArpeggioUp()));
}
return (true);
}
/// Tests the Triplet Feel Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseTripletFeel()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: SetTripletFeel1st
{
RhythmSlash rhythmSlash;
TEST(wxT("SetTripletFeel1st - true"),
(rhythmSlash.SetTripletFeel1st() &&
rhythmSlash.IsTripletFeel1st()));
TEST(wxT("SetTripletFeel1st - false"),
(rhythmSlash.SetTripletFeel1st(false) &&
!rhythmSlash.IsTripletFeel1st()));
}
// TEST CASE: SetTripletFeel2nd
{
RhythmSlash rhythmSlash;
TEST(wxT("SetTripletFeel2nd - true"),
(rhythmSlash.SetTripletFeel2nd() &&
rhythmSlash.IsTripletFeel2nd()));
TEST(wxT("SetTripletFeel2nd - false"),
(rhythmSlash.SetTripletFeel2nd(false) &&
!rhythmSlash.IsTripletFeel2nd()));
}
return (true);
}
/// Tests the Accent Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseAccent()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: SetMarcato
{
RhythmSlash rhythmSlash;
TEST(wxT("SetMarcato - true"),
(rhythmSlash.SetMarcato() && rhythmSlash.HasMarcato()));
TEST(wxT("SetMarcato - false"),
(rhythmSlash.SetMarcato(false) && !rhythmSlash.HasMarcato()));
}
// TEST CASE: SetSforzando
{
RhythmSlash rhythmSlash;
TEST(wxT("SetSforzando - true"),
(rhythmSlash.SetSforzando() && rhythmSlash.HasSforzando()));
TEST(wxT("SetSforzando - false"),
(rhythmSlash.SetSforzando(false) && !rhythmSlash.HasSforzando()));
}
return (true);
}
/// Tests the Slide Into Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseSlideInto()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: SetSlideIntoFromAbove
{
RhythmSlash rhythmSlash;
TEST(wxT("SetSlideIntoFromAbove - true"),
(rhythmSlash.SetSlideIntoFromAbove() &&
rhythmSlash.HasSlideIntoFromAbove()));
TEST(wxT("SetSlideIntoFromAbove - false"),
(rhythmSlash.SetSlideIntoFromAbove(false) &&
!rhythmSlash.HasSlideIntoFromAbove()));
}
// TEST CASE: SetSlideIntoFromBelow
{
RhythmSlash rhythmSlash;
TEST(wxT("SetSlideIntoFromBelow - true"),
(rhythmSlash.SetSlideIntoFromBelow() &&
rhythmSlash.HasSlideIntoFromBelow()));
TEST(wxT("SetSlideIntoFromBelow - false"),
(rhythmSlash.SetSlideIntoFromBelow(false) &&
!rhythmSlash.HasSlideIntoFromBelow()));
}
return (true);
}
/// Tests the Slide Out Of Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseSlideOutOf()
{
//------Last Checked------//
// - Jan 7, 2005
// TEST CASE: SetSlideOutOfDownwards
{
RhythmSlash rhythmSlash;
TEST(wxT("SetSlideOutOfDownwards - true"),
(rhythmSlash.SetSlideOutOfDownwards() &&
rhythmSlash.HasSlideOutOfDownwards()));
TEST(wxT("SetSlideOutOfDownwards - false"),
(rhythmSlash.SetSlideOutOfDownwards(false) &&
!rhythmSlash.HasSlideOutOfDownwards()));
}
// TEST CASE: SetSlideOutOfUpwards
{
RhythmSlash rhythmSlash;
TEST(wxT("SetSlideOutOfUpwards - true"),
(rhythmSlash.SetSlideOutOfUpwards() &&
rhythmSlash.HasSlideOutOfUpwards()));
TEST(wxT("SetSlideOutOfUpwards - false"),
(rhythmSlash.SetSlideOutOfUpwards(false) &&
!rhythmSlash.HasSlideOutOfUpwards()));
}
return (true);
}
/// Tests the Single Note Data Functions
/// @return True if all tests were executed, false if not
bool RhythmSlashTestSuite::TestCaseSingleNoteData()
{
//------Last Checked------//
// - Sep 27, 2007
// TEST CASE: IsValidStringNumber
{
wxByte i = RhythmSlash::MIN_SINGLE_NOTE_STRING_NUMBER;
for (; i < (RhythmSlash::MIN_SINGLE_NOTE_STRING_NUMBER + 1); i++)
TEST(wxString::Format(wxT("IsValidStringNumber - %d"), i),
(RhythmSlash::IsValidStringNumber(i) ==
((i >= RhythmSlash::MIN_SINGLE_NOTE_STRING_NUMBER) &&
(i <= RhythmSlash::MAX_SINGLE_NOTE_STRING_NUMBER)))
);
}
// TEST CASE: IsValidFretNumber
{
wxByte i = RhythmSlash::MIN_SINGLE_NOTE_FRET_NUMBER - 1;
for (; i < (RhythmSlash::MIN_SINGLE_NOTE_FRET_NUMBER + 1); i++)
TEST(wxString::Format(wxT("IsValidFretNumber - %d"), i),
(RhythmSlash::IsValidFretNumber(i) ==
((i >= RhythmSlash::MIN_SINGLE_NOTE_FRET_NUMBER) &&
(i <= RhythmSlash::MAX_SINGLE_NOTE_FRET_NUMBER)))
);
}
// TEST CASE: SetSingleNoteData
{
RhythmSlash rhythmSlash;
TEST(wxT("SetSingleNoteData - invalid string number"),
!rhythmSlash.SetSingleNoteData(200, 1));
TEST(wxT("SetSingleNoteData - invalid fret number"),
!rhythmSlash.SetSingleNoteData(1, 200));
bool ok = rhythmSlash.SetSingleNoteData(3,5);
wxByte stringNumber = 0;
wxByte fretNumber = 0;
rhythmSlash.GetSingleNoteData(stringNumber, fretNumber);
TEST(wxT("SetSingleNoteData"), ok && (stringNumber == 3) &&
(fretNumber == 5));
}
// TEST CASE: ClearSingleNoteData
{
RhythmSlash rhythmSlash;
rhythmSlash.SetSingleNoteData(3,5);
bool ok = rhythmSlash.ClearSingleNoteData();
wxByte stringNumber = 0;
wxByte fretNumber = 0;
rhythmSlash.GetSingleNoteData(stringNumber, fretNumber);
TEST(wxT("ClearSingleNoteData"),
(ok) &&
(stringNumber == 0) &&
(fretNumber == 0)
);
}
return (true);
}
|
ed1de9e1b996c006bc1c8456d86234505e939153 | 267ca8d749ab1e79ed313696c124dde5a4930a32 | /main.cpp | c38a4ac60114f684ce6f4a0e272fe1c0e6e533d3 | [] | no_license | AlekseyPl/NIR | 93cde8dd4b217106184e3ed7f692eabab14a98ad | c3c14735dff4657b6f809758fd17fa050a01951f | refs/heads/master | 2021-02-10T01:17:20.313372 | 2020-03-27T16:00:22 | 2020-03-27T16:00:22 | 244,341,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,045 | cpp | main.cpp | #include <stdint.h>
#include <Math/IntComplex.h>
#include <Lte/Core/LteCorrelator.h>
#include <Lte/Core/Common/LteConst.h>
#include <Lte/Core/Common/LteDemConst.h>
#include "Lte/Core/LteStream.h"
#include "Lte/Core/LteOfdmDemodulator.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <assert.h>
#include <memory>
int main(int argc, char *argv[])
{
std::cout << "Start lte processing\n";
assert( argc == 2 );
std::ifstream in( argv[ 1 ], std::ifstream::binary );
assert( in.is_open( ) );
in.seekg( 0, in.end );
int32_t actualLength = in.tellg( ) / sizeof( Complex16 );
in.seekg( 0, in.beg );
size_t corrSize = 1 * ( Lte::LTEFrameLength + 2048 + 2048 );
std::vector<Complex16> corrData(corrSize);
std::shared_ptr<Lte::LteCorrelator> correlator = std::make_shared<Lte::LteCorrelator>();
assert( correlator );
in.read( reinterpret_cast<char*>(corrData.data()), corrSize * sizeof( Complex16 ) );
in.seekg( 0, in.beg );
const float corrThreshold = 0.5;
const uint32_t searchDepth = 5;
const uint32_t decimFactor = 16;
const uint32_t numChannels = 1;
correlator->SetThreshold( corrThreshold );
correlator->ConfigureSearchParams( searchDepth, decimFactor );
std::cout << "Start sync " << std::endl;
bool res = correlator->Process( corrData.data(), numChannels);
if(res) {
auto& cells = correlator->GetSyncInfo( );
int32_t sfLength = Lte::LTESubframeLength;
std::vector<Complex16> sfBuffer(sfLength);
std::shared_ptr<Lte::LteStream> stream = std::make_shared<Lte::LteStream>();
std::shared_ptr<Lte::LteOfdmDemod> demodulator = std::make_shared<Lte::LteOfdmDemod>();
std::cout << "There are " << cells.size() << " BS on syncStage " << std::endl;
for( auto& cell : cells ) {
uint32_t nCellId =cell.nCellId;
auto cp = cell.cp;
uint32_t offset = cell.framePos;
auto dp = cell.duplex;
std::cout << "Try to decode BS with nCellId " << nCellId << " Offset " << offset << " full length " << actualLength << std::endl;
int32_t length = actualLength - offset;
in.seekg( 0, in.beg );
in.seekg( offset * sizeof( Complex16 ), in.beg );
stream->InitCellProc(cell);
bool mibDecoded = false;
int32_t symCount = 0;
int32_t sfCount = length / Lte::LTESubframeLength;
if( cp == Lte::lteCP_Short ) symCount = Lte::LTESymbolsInSlotS;
else symCount = Lte::LTESymbolsInSlotL;
symCount *= Lte::LTESlotsInSubframe;
std::cout << "symCount " << symCount << "sfCount " << sfCount << std::endl;
for( uint32_t sf = Lte::PBCH_Subframe; sf < sfCount; sf += Lte::LTESubframeInFrame) {
in.read( reinterpret_cast<char*>(sfBuffer.data()), sfLength * sizeof( Complex16 ) );
in.seekg( 9 * Lte::LTESubframeLength * sizeof( Complex16 ), in.cur );
demodulator->ProcessSubframe(sfBuffer.data(), numChannels);
auto& ofdmSymbols = demodulator->GetSymbols();
auto proc = stream->ProcessSubframe(ofdmSymbols.data());
if(proc == Lte::LteStream::MIBdecoded) {
std::cout << "MIB decoded" <<std::endl;
break;
}
}
}
}
}
|
955a036cdce05e19bfb3929b76457a5f5ec095e5 | 8de319a4324969c449c7e24fde1d27004b232717 | /2601-2700/2612. Minimum Reverse Operations 605ms.cpp | c3296234aee35d0e4ebaf71f5419c15ec27c62d6 | [] | no_license | hqztrue/LeetCodeSolutions | 407cd3775c882a23531cf513d504c2b5f9a1ae6f | f837f70e5500cd92b205530d6b72ce050b2a2b1f | refs/heads/master | 2023-07-19T17:48:30.433653 | 2023-07-09T04:57:46 | 2023-07-09T04:57:46 | 186,388,726 | 401 | 48 | null | 2020-12-06T05:14:56 | 2019-05-13T09:30:01 | C++ | UTF-8 | C++ | false | false | 1,252 | cpp | 2612. Minimum Reverse Operations 605ms.cpp | typedef unsigned int uint;
const int N=100005;
int a[N],q[N]; uint even[N],odd[N];
inline void add(uint *a,int i,uint t=1){a[i/32]+=t*(1<<(i%32));}
class Solution {
public:
vector<int> minReverseOperations(int n, int p, vector<int>& b, int k) {
for (int i=0;i<n;++i)a[i]=-1,even[i]=odd[i]=0;
for (auto &x:b)a[x]=0;
int h=0,t=1; q[0]=p; a[p]=0;
for (int i=0;i<n;++i)
if (a[i]==-1)
if (i%2)add(odd,i/2);
else add(even,i/2);
while (h<t){
int x=q[h++],d=a[x],l1=max(0,x-k+1),r1=min(n-k,x),
l=l1*2+k-1-x,r=r1*2+k-1-x;
if (l>r)swap(l,r);
//for (int i=l;i<=r;i+=2)
// if (a[i]==-1)a[i]=d+1,q[t++]=i;
uint *c=l%2?odd:even;
for (;l%64>1&&l<=r;l+=2)
if (a[l]==-1)a[l]=d+1,add(c,l/2,-1),q[t++]=l;
for (;r%64<62&&r>=0&&r>=l;r-=2)
if (a[r]==-1)a[r]=d+1,add(c,r/2,-1),q[t++]=r;
if (l>r)continue;
for (int j=l/64,d0=l%2;j<=r/64;++j)
while (c[j]){
int k=__builtin_ctz(c[j]),i=(j*32+k)*2+d0;
add(c,j*32+k,-1);
a[i]=d+1,q[t++]=i;
}
}
for (auto &x:b)a[x]=-1;
vector<int> ans(a,a+n);
return ans;
}
};
|
8890c1c728be1e92a9ae0ebfc97618dd3f73817a | 25e53e283595c2c28a4cd7786274d5c4a5ceec6c | /DrawableObjects/GUI.cpp | 0b1c509daacec9f9d14e993e3c0aeb2882335e09 | [
"MIT"
] | permissive | mamoniem/TerrainEngine-OpenGL | a302058c37923295acd295993db1245ee508738e | f90eba5977c12f950f933d02125ac5b44988700b | refs/heads/master | 2020-07-20T01:54:57.621094 | 2019-04-25T11:59:38 | 2019-04-25T11:59:38 | 206,551,821 | 5 | 1 | null | 2019-09-05T11:52:14 | 2019-09-05T11:52:14 | null | UTF-8 | C++ | false | false | 2,252 | cpp | GUI.cpp | #include "GUI.h"
#include "../imgui/imgui.h"
#include "../imgui/imgui_impl_glfw.h"
#include "../imgui/imgui_impl_opengl3.h"
#include "../Engine/utils.h"
GUI::GUI(Window& window)
{
// GUI
ImGui::CreateContext();
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window.getWindow(), true);
ImGui_ImplOpenGL3_Init("#version 130");
}
void GUI::draw()
{
sceneElements& scene = *this->scene;
for (drawableObject* obj : subscribers) {
obj->setGui();
}
ImGui::Begin("Scene controls: ");
ImGui::TextColored(ImVec4(1, 1, 0, 1), "Other controls");
if (ImGui::DragFloat3("Light Position", &scene.lightDir[0], 0.01, -1.0, 1.0)) {
auto saturate = [](float v) { return std::min(std::max(v, 0.0f), 0.8f); };
scene.lightDir.y = saturate(scene.lightDir.y);
//skybox.update();
}
ImGui::InputFloat3("Camera Position", &(scene.cam->Position[0]), 7);
ImGui::ColorEdit3("Light color", (float*)&scene.lightColor);
ImGui::ColorEdit3("Fog color", (float*)&scene.fogColor);
ImGui::SliderFloat("Camera speed", &scene.cam->MovementSpeed, 0.0, SPEED*3.0);
ImGui::Checkbox("Wireframe mode", &scene.wireframe);
if (ImGui::Button("Generate seed"))
scene.seed = genRandomVec3();
//ImGui::SameLine();
//ImGui::Text("Generate a new seed");
ImGui::SameLine();
if (ImGui::Button("Use default seed"))
scene.seed = glm::vec3(0.0, 0.0, 0.0);
/*ImGui::SameLine();
if (ImGui::Button("Default Preset")) {
volumetricClouds.DefaultPreset();
lightDir.y = 0.5;
}*/
//ImGui::SameLine();
/*if (ImGui::Button("Sunset Preset 1")) {
skybox.SunsetPreset();
}
ImGui::SameLine();
if (ImGui::Button("Sunset Preset 2")) {
skybox.SunsetPreset1();
}*/
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
//actual drawing
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
void GUI::update()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
GUI & GUI::subscribe(drawableObject * subscriber)
{
subscribers.push_back(subscriber);
return *this;
}
GUI::~GUI()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
|
371daf17a30c29e1ea6d9dac34310c189d8c912d | c8a108ebc3dba13b4e051297a7bdb7d3aac2ac83 | /Sender/JoyStickController/JoyStickController/PositionTranslator.h | e6b7133cf52d2b2a79cd8494ba60bd5ddf81c3ad | [] | no_license | JonasHK/AMSProject | f24e568d88cad246c7df16ef1edb967eb376ab32 | 47427335d916bfaa9a3fd3d88abae961e1794fff | refs/heads/master | 2021-02-18T00:39:21.303659 | 2020-05-25T12:33:04 | 2020-05-25T12:33:04 | 245,141,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 616 | h | PositionTranslator.h | /*
* PositionTranslator.h
*
* Created: 19-03-2020 11:31:54
* Author: troel
*/
#include <avr/io.h>
#ifndef __POSITIONTRANSLATOR_H__
#define __POSITIONTRANSLATOR_H__
struct Vector{
float x;
float y;
};
class PositionTranslator
{
//variables
public:
protected:
private:
//functions
public:
PositionTranslator();
uint8_t Translate(uint16_t xPos, uint16_t yPos);
protected:
private:
float determinant(Vector v1, Vector v2);
Vector normalize(uint16_t x, uint16_t y);
uint8_t angleToData(Vector fromADC, Vector low, Vector high);
float length(Vector v);
}; //PositionTranslator
#endif //__POSITIONTRANSLATOR_H__
|
b4023e32252f98ebf6167237105046617b1dd2b5 | 9146d3e2d0974a3216a0a996967348ba7a21b64a | /src/goto-symex/equation_conversion_exceptions.h | ffa57abefe07b6d42e018f4bf6d32ea9f36a4d59 | [
"BSD-4-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | sonodtt/cbmc | 320c5338af567596bc0590e412802e9e3b43182b | 2dc086356a9a7c48728e8cd57136f9e04bc589b0 | refs/heads/develop | 2020-03-16T10:25:56.197239 | 2019-02-07T13:11:29 | 2019-02-07T13:11:29 | 132,635,540 | 0 | 0 | NOASSERTION | 2018-10-11T09:09:45 | 2018-05-08T16:23:07 | C++ | UTF-8 | C++ | false | false | 1,215 | h | equation_conversion_exceptions.h | /*******************************************************************\
Module: Symbolic Execution
Author: Diffblue Ltd.
\*******************************************************************/
/// \file
/// Exceptions that can be raised during the equation conversion phase
#ifndef CPROVER_GOTO_SYMEX_EQUATION_CONVERSION_EXCEPTIONS_H
#define CPROVER_GOTO_SYMEX_EQUATION_CONVERSION_EXCEPTIONS_H
#include <sstream>
#include <util/format_expr.h>
#include "symex_target_equation.h"
class equation_conversion_exceptiont : public std::runtime_error
{
public:
equation_conversion_exceptiont(
const std::string &message,
const symex_target_equationt::SSA_stept &step)
: runtime_error(message), step(step)
{
std::ostringstream error_msg;
error_msg << runtime_error::what();
error_msg << "\nSource GOTO statement: " << format(step.source.pc->code);
error_msg << "\nStep:\n";
step.output(error_msg);
error_message = error_msg.str();
}
const char *what() const optional_noexcept override
{
return error_message.c_str();
}
private:
symex_target_equationt::SSA_stept step;
std::string error_message;
};
#endif // CPROVER_GOTO_SYMEX_EQUATION_CONVERSION_EXCEPTIONS_H
|
50bc41674d1483d50c5fa6d919d70e9e32bc9403 | 97a019b52a56cfd16cd7c4dbb730e83c581d2b3e | /Archived/Research/mintos/include/mintos/math/SparseVectorTemplate.h | 9332505298030b27d70841c83ce8e24633c34d85 | [] | no_license | nalinraut/high-level-Motion-Planning | f0263dcfa344b914159b0486370bc544552ac360 | 08cd792124defba63583ba6ae6394b20329d38c0 | refs/heads/master | 2020-03-09T04:20:12.846801 | 2018-04-09T06:11:29 | 2018-04-09T06:11:29 | 128,585,159 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,032 | h | SparseVectorTemplate.h | /*****************************************************************************
*
* Copyright (c) 2013, the Trustees of Indiana University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Indiana University nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY ''AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES OF INDIANA UNIVERSITY BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
#ifndef MATH_SPARSE_VECTOR_TEMPLATE_H
#define MATH_SPARSE_VECTOR_TEMPLATE_H
#include "VectorTemplate.h"
#include "SparseArray.h"
namespace Math {
template <class T>
struct SparseVectorAccessor;
template <class T>
class SparseVectorTemplate : public SparseArray<T>
{
public:
typedef SparseVectorTemplate<T> MyT;
typedef SparseArray<T> BaseT;
typedef typename BaseT::iterator iterator;
typedef typename BaseT::const_iterator const_iterator;
typedef VectorTemplate<T> VectorT;
SparseVectorTemplate() {}
SparseVectorTemplate(size_t n):BaseT(n) {}
SparseVectorTemplate(const BaseT& v):BaseT(v) {}
void print(std::ostream&) const;
SparseVectorAccessor<T> operator() (int i);
SparseVectorAccessor<T> operator[] (int i) { return operator()(i); }
T operator() (int i) const { return get(i); }
T operator[] (int i) const { return get(i); }
T get(int i) const;
inline void set(int i,const T& t) { BaseT::insert(i,t); }
inline void setZero() { BaseT::entries.clear(); }
inline void set(const BaseT& v) { BaseT::operator = (v); }
void set(const VectorT&,T zeroTol=Zero);
void set(const T*,int n,T zeroTol=Zero);
void get(T*) const;
void get(VectorT&) const;
void inplaceNegative();
void inplaceMul(T s);
void inplaceDiv(T s);
void copy(const MyT&);
void copySubVector(int i,const MyT&);
void copySubVector(int i,const VectorT&,T zeroTol=0);
void swap(MyT&);
void add(const MyT&, const MyT&);
void sub(const MyT&, const MyT&);
void mul(const MyT&, T s);
void div(const MyT&, T s);
T dot(const VectorT&) const;
T dot(const MyT&) const;
T norm() const;
T normSquared() const;
T distance(const MyT&) const;
T distanceSquared(const MyT&) const;
inline bool isEmpty() const { return BaseT::empty(); }
inline bool hasDims(size_t _n) const { return BaseT::n==_n; }
T minElement(int* index=NULL) const;
T maxElement(int* index=NULL) const;
T minAbsElement(int* index=NULL) const;
T maxAbsElement(int* index=NULL) const;
};
template <class T>
class SparseVectorCompressed
{
public:
typedef SparseVectorCompressed<T> MyT;
typedef VectorTemplate<T> VectorT;
SparseVectorCompressed();
SparseVectorCompressed(int n, int num_entries);
SparseVectorCompressed(const MyT&);
~SparseVectorCompressed();
void init(int n, int num_entries);
void resize(int n, int num_entries);
void makeSimilar(const MyT&);
void cleanup();
void print(std::ostream&) const;
const MyT& operator =(const MyT&);
T operator() (int i) const;
void setZero();
void set(const MyT&);
void set(const VectorT&,T zeroTol=Zero);
void set(const T*,int n,T zeroTol=Zero);
void get(T*) const;
void get(VectorT&) const;
void inplaceNegative();
void inplaceMul(T s);
void inplaceDiv(T s);
void add(const MyT&, const MyT&);
void sub(const MyT&, const MyT&);
void mul(const MyT&, T s);
void div(const MyT&, T s);
T dot(const VectorT&) const;
T dot(const MyT&) const;
T norm() const;
T normSquared() const;
T distance(const MyT&) const;
T distanceSquared(const MyT&) const;
bool isValid() const;
inline bool isEmpty() const { return n == 0; }
inline bool hasDims(int _n) const { return n==_n; }
inline bool isValidIndex(int i) const { return 0<=i&&i<n; }
T minElement(int* index=NULL) const;
T maxElement(int* index=NULL) const;
T minAbsElement(int* index=NULL) const;
T maxAbsElement(int* index=NULL) const;
/***********************************************************
* Compressed vector format:
* There are num_entries nonzero entries .
* The index of entry i is indices[i] (0<=indices[i]<indices[i+1]<n)
* The value of entry i is vals[i]
**********************************************************/
int* indices;
T* vals;
int num_entries;
int n;
};
template <class T>
struct SparseVectorAccessor
{
SparseVectorAccessor(SparseVectorTemplate<T>* _vec,int _index)
:vec(_vec),index(_index)
{}
SparseVectorAccessor(const SparseVectorAccessor<T>& rhs)
:vec(rhs.vec),index(rhs.index)
{}
operator T () const
{
return vec->get(index);
}
const SparseVectorAccessor<T>& operator = (const T& rhs) {
vec->set(index,rhs);
return *this;
}
SparseVectorTemplate<T>* vec;
int index;
};
///returns true if all elements of x are finite
template <class T>
inline bool IsFinite(const SparseVectorTemplate<T>& x)
{
for(typename SparseVectorTemplate<T>::const_iterator i=x.begin();i!=x.end();i++)
if(!IsFinite(i->second)) return false;
return true;
}
///returns true if any element of x is NaN
template <class T>
inline bool HasNaN(const SparseVectorTemplate<T>& x)
{
for(typename SparseVectorTemplate<T>::const_iterator i=x.begin();i!=x.end();i++)
if(IsNaN(i->second)) return false;
return true;
}
///returns nonzero if any element of x is infininte
template <class T>
inline bool HasInf(const SparseVectorTemplate<T>& x)
{
for(typename SparseVectorTemplate<T>::const_iterator i=x.begin();i!=x.end();i++)
if(IsInf(i->second)) return IsInf(i->second);
return 0;
}
class Complex;
typedef SparseVectorTemplate<float> fSparseVector;
typedef SparseVectorTemplate<double> dSparseVector;
typedef SparseVectorTemplate<Complex> cSparseVector;
} //namespace Math
#endif
|
28c8397b64e7a818325f927159f72cc372c221f8 | a28892615bc0d4459f0c505cb462255478df8d5b | /meta-flatpak/conf/distro/include/flatpak-session.inc | 7a69c52cec33682a5b434a49dbdb543703a55b2e | [
"MIT"
] | permissive | intel/intel-iot-refkit | 4fa8829dce607e424cec670a88f871aee4773d70 | 786a4de29c30b47f885d8ad9cb2d110a08919ebd | refs/heads/master | 2023-08-16T15:26:57.401839 | 2022-08-04T22:51:00 | 2022-08-04T22:51:00 | 80,166,427 | 38 | 66 | MIT | 2018-04-05T08:25:34 | 2017-01-26T23:38:40 | Python | UTF-8 | C++ | false | false | 62 | inc | flatpak-session.inc | REFKIT_DEFAULT_DISTRO_FEATURES += " \
flatpak-session \
"
|
ac61008575e154b979e4823482dc34816477e903 | d076a96f7a7b0be760453027757f625d4674ec8d | /JunHyun_Park/BOJ/6603_로또.cpp | 798ab9983036515bc8800b32f7a60e0d0d8be4e1 | [] | no_license | Goodgaym/ProblemSolving_ | 0c0a83bbb51835b849571c14dbbd95c831dc2f72 | aba0b48f4c752626e7e74b0d2ae623c279e2a706 | refs/heads/master | 2022-12-06T03:48:45.862905 | 2022-11-22T08:11:37 | 2022-11-22T08:11:37 | 231,822,070 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | 6603_로또.cpp | #include<cstdio> // 6603_로또 [백트래킹]
int N, nl[13], s[6];
bool bl[13] ={false};
void f(int x, int y){
if(x == 6) {
for(int i=0;i<6; i++){
printf("%d ",s[i]);
}
printf("\n");
return;
}
for(int i=y; i<N; i++){
if(!bl[i]){
bl[i] = true;
s[x]=nl[i];
f(x+1, i+1);
bl[i] = false;
}
}
}
int main() {
while(1){
scanf("%d", &N);
if(N==0) break;
for(int i=0;i<N; i++)
scanf("%d", &nl[i]);
f(0, 0);
printf("\n");
}
return 0;
} |
0532077b1ad1da6a29bd76a2f92a295c6e8049d0 | 226760cea6fdde6d9ee6f846134be012aaf543b7 | /CIT284 DN Final Project/PrintDLG.h | 71611e3cae029a35e20a766924eeef56a5d54236 | [
"MIT"
] | permissive | danemo01/ServerUIMFC- | 9824a58f595cb3f29d5742a07abb4b3384dc0027 | ce7624b947d6f179f0eeef406cf1bc068d4c9649 | refs/heads/master | 2022-03-06T15:36:03.985690 | 2016-05-29T21:42:47 | 2016-05-29T21:42:47 | 59,964,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 679 | h | PrintDLG.h | #pragma once
#include "resource.h"
#include "afxwin.h"
#include <string>
using std::wstring;
// PrintDLG dialog
class PrintDLG : public CDialogEx
{
DECLARE_DYNAMIC(PrintDLG)
public:
PrintDLG(CWnd* pParent = NULL); // standard constructor
virtual ~PrintDLG();
// Dialog Data
enum { IDD = IDD_PRINT };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
CEdit printFile;
CEdit printInput;
afx_msg void OnBnClickedOk();
afx_msg void OnCbnSelchangePrintoption();
CComboBox printerOptionCBox;
CComboBox amountOfCopies;
afx_msg void OnBnClickedPrint();
wstring text;
};
|
b9d934980d2c759947ec3e270998a090ba99ecba | 53a9244661edf696808429579c282473774839e2 | /Day6(28.05.2021)/FractionalKnapsackWithMergeSort.cpp | a1538cd33962f8cde8c75b84caafd86502e1f593 | [] | no_license | biswarup55655/DSA_sem4_Practical | 84037d0fc04d731105d7db30aaa6fd01cd626199 | a3f4438335a59053ffd5bfc26628ff2db9c3a59c | refs/heads/main | 2023-07-08T07:02:30.496720 | 2021-08-04T19:04:22 | 2021-08-04T19:04:22 | 392,739,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,385 | cpp | FractionalKnapsackWithMergeSort.cpp | #include<iostream>
#include<bits/stdc++.h>
#include<fstream>
using namespace std;
struct Item{
int value;
int weight;
int ratio;
};
void display(Item arr[], int n) {
int i;
cout << "values: ";
for(i = 0; i < n; i++) {
cout << arr[i].value << "\t";
}
cout << endl << "weight: ";
for (i = 0; i < n; i++) {
cout << arr[i].weight << "\t";
}
cout << endl;
}
void merge(Item a[] , int l , int mid , int r , int n){
int i=l , j=mid+1 , k=l , t=1;
Item z[r+1];
while( i<=mid && j<=r){
if(a[i].ratio>=a[j].ratio)
z[k++]=a[i++];
else
z[k++]=a[j++];
}
while(i<=mid) z[k++]=a[i++];
while(j<=r) z[k++]=a[j++];
for(int i=l ; i<=r ; ++i)
a[i]=z[i];
}
void merge_sort(Item a[] , int l , int r , int n){
int mid ;
static int t=1;
if(l<r){
mid=(l+r)/2;
merge_sort(a , l , mid , n);
merge_sort(a , mid+1 , r , n);
merge(a , l , mid , r , n);
}
}
void fractionalKnapSack(int W,Item arr[],int n){
double x[n];
int totalweight=0;
for(int i=0;i<n;i++){
x[i]=0.0;
totalweight+=arr[i].weight;
}
int u = W;
int i;
for(i=0;i<n;i++){
if(arr[i].weight > u)break;
x[i]=1.0;
u = u - arr[i].weight;
}
if(i<=n){
x[i] = u/(double)arr[i].weight;
}
double ans=0.0;
for(int i=0;i<n;i++){
ans = ans+x[i]*arr[i].value;
}
cout << "total weight in bag " << totalweight<<endl;
cout << "Max value for "<< W <<" weight is "<< ans<<endl;
}
int main(){
int n;
int W;
fstream infile;
infile.open("fractionalKnapsack.txt" , ios::in);
if(!infile)
{
cout<<"Error on openning file"<<endl;
return 0;
}
infile>>n;
infile>>W;
Item arr[n];
for(int i=0; i<n; i++){
infile>>arr[i].value;
}
for(int i=0;i<n;i++){
infile>>arr[i].weight;
}
cout << "Entered data \n";
display(arr,n);
for(int i=0 ; i<n ; ++i)
{
arr[i].ratio=arr[i].value/arr[i].weight;
}
cout<<endl;
merge_sort(arr , 0 , n-1 , n);
cout << "After sorting: \n";
display(arr,n);
cout<<endl;
fractionalKnapSack(W,arr,n);
cout<<endl;
return 0;
}
|
f7a5a44c5282f847796a89834d93928dd1779ac4 | 8ee509ef09d2b3eeed57147de34e0cc4b1a87584 | /simpleperf/gtest_main.cpp | 599bb423a6adeb62c9d0bc135075962bf770b6af | [
"Apache-2.0"
] | permissive | LineageOS/android_system_extras | 2c0ec30966958946ed6de47e16596fe755ebb09b | 3b4b5a8d879b0eab3b587681590889718ceff85c | refs/heads/lineage-16.0 | 2023-08-16T18:57:25.255503 | 2019-07-13T16:59:49 | 2019-07-13T16:59:49 | 75,638,278 | 7 | 66 | null | 2019-05-15T17:15:13 | 2016-12-05T15:28:45 | HTML | UTF-8 | C++ | false | false | 6,930 | cpp | gtest_main.cpp | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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.
*/
#include <gtest/gtest.h>
#include <libgen.h>
#include <memory>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/test_utils.h>
#include <ziparchive/zip_archive.h>
#if defined(__ANDROID__)
#include <android-base/properties.h>
#endif
#include "command.h"
#include "environment.h"
#include "get_test_data.h"
#include "read_elf.h"
#include "test_util.h"
#include "utils.h"
#include "workload.h"
static std::string testdata_dir;
#if defined(__ANDROID__)
static const std::string testdata_section = ".testzipdata";
static bool ExtractTestDataFromElfSection() {
if (!MkdirWithParents(testdata_dir)) {
PLOG(ERROR) << "failed to create testdata_dir " << testdata_dir;
return false;
}
std::string content;
ElfStatus result = ReadSectionFromElfFile("/proc/self/exe", testdata_section, &content);
if (result != ElfStatus::NO_ERROR) {
LOG(ERROR) << "failed to read section " << testdata_section
<< ": " << result;
return false;
}
TemporaryFile tmp_file;
if (!android::base::WriteStringToFile(content, tmp_file.path)) {
PLOG(ERROR) << "failed to write file " << tmp_file.path;
return false;
}
ArchiveHelper ahelper(tmp_file.fd, tmp_file.path);
if (!ahelper) {
LOG(ERROR) << "failed to open archive " << tmp_file.path;
return false;
}
ZipArchiveHandle& handle = ahelper.archive_handle();
void* cookie;
int ret = StartIteration(handle, &cookie, nullptr, nullptr);
if (ret != 0) {
LOG(ERROR) << "failed to start iterating zip entries";
return false;
}
std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
ZipEntry entry;
ZipString name;
while (Next(cookie, &entry, &name) == 0) {
std::string entry_name(name.name, name.name + name.name_length);
std::string path = testdata_dir + entry_name;
// Skip dir.
if (path.back() == '/') {
continue;
}
if (!MkdirWithParents(path)) {
LOG(ERROR) << "failed to create dir for " << path;
return false;
}
FileHelper fhelper = FileHelper::OpenWriteOnly(path);
if (!fhelper) {
PLOG(ERROR) << "failed to create file " << path;
return false;
}
std::vector<uint8_t> data(entry.uncompressed_length);
if (ExtractToMemory(handle, &entry, data.data(), data.size()) != 0) {
LOG(ERROR) << "failed to extract entry " << entry_name;
return false;
}
if (!android::base::WriteFully(fhelper.fd(), data.data(), data.size())) {
LOG(ERROR) << "failed to write file " << path;
return false;
}
}
return true;
}
class ScopedEnablingPerf {
public:
ScopedEnablingPerf() {
prop_value_ = android::base::GetProperty("security.perf_harden", "");
SetProp("0");
}
~ScopedEnablingPerf() {
if (!prop_value_.empty()) {
SetProp(prop_value_);
}
}
private:
void SetProp(const std::string& value) {
android::base::SetProperty("security.perf_harden", value);
// Sleep one second to wait for security.perf_harden changing
// /proc/sys/kernel/perf_event_paranoid.
sleep(1);
}
std::string prop_value_;
};
class ScopedWorkloadExecutable {
public:
ScopedWorkloadExecutable() {
std::string executable_path;
if (!android::base::Readlink("/proc/self/exe", &executable_path)) {
PLOG(ERROR) << "ReadLink failed";
}
Workload::RunCmd({"run-as", GetDefaultAppPackageName(), "cp", executable_path, "workload"});
}
~ScopedWorkloadExecutable() {
Workload::RunCmd({"run-as", GetDefaultAppPackageName(), "rm", "workload"});
}
};
class ScopedTempDir {
public:
~ScopedTempDir() {
Workload::RunCmd({"rm", "-rf", dir_.path});
}
char* path() {
return dir_.path;
}
private:
TemporaryDir dir_;
};
#endif // defined(__ANDROID__)
int main(int argc, char** argv) {
android::base::InitLogging(argv, android::base::StderrLogger);
android::base::LogSeverity log_severity = android::base::WARNING;
#if defined(RUN_IN_APP_CONTEXT)
// When RUN_IN_APP_CONTEXT macro is defined, the tests running record/stat commands will
// be forced to run with '--app' option. It will copy the test binary to an Android application's
// directory, and use run-as to run the binary as simpleperf executable.
if (android::base::Basename(argv[0]) == "simpleperf") {
return RunSimpleperfCmd(argc, argv) ? 0 : 1;
} else if (android::base::Basename(argv[0]) == "workload") {
RunWorkloadFunction();
}
SetDefaultAppPackageName(RUN_IN_APP_CONTEXT);
ScopedWorkloadExecutable scoped_workload_executable;
#endif
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-t") == 0 && i + 1 < argc) {
testdata_dir = argv[i + 1];
i++;
} else if (strcmp(argv[i], "--log") == 0) {
if (i + 1 < argc) {
++i;
if (!GetLogSeverity(argv[i], &log_severity)) {
LOG(ERROR) << "Unknown log severity: " << argv[i];
return 1;
}
} else {
LOG(ERROR) << "Missing argument for --log option.\n";
return 1;
}
}
}
android::base::ScopedLogSeverity severity(log_severity);
#if defined(__ANDROID__)
// A cts test PerfEventParanoidTest.java is testing if
// /proc/sys/kernel/perf_event_paranoid is 3, so restore perf_harden
// value after current test to not break that test.
ScopedEnablingPerf scoped_enabling_perf;
std::unique_ptr<ScopedTempDir> tmp_dir;
if (!::testing::GTEST_FLAG(list_tests) && testdata_dir.empty()) {
testdata_dir = std::string(dirname(argv[0])) + "/testdata";
if (!IsDir(testdata_dir)) {
tmp_dir.reset(new ScopedTempDir);
testdata_dir = std::string(tmp_dir->path()) + "/";
if (!ExtractTestDataFromElfSection()) {
LOG(ERROR) << "failed to extract test data from elf section";
return 1;
}
}
}
#endif
testing::InitGoogleTest(&argc, argv);
if (!::testing::GTEST_FLAG(list_tests) && testdata_dir.empty()) {
printf("Usage: %s -t <testdata_dir>\n", argv[0]);
return 1;
}
if (testdata_dir.back() != '/') {
testdata_dir.push_back('/');
}
LOG(INFO) << "testdata is in " << testdata_dir;
return RUN_ALL_TESTS();
}
std::string GetTestData(const std::string& filename) {
return testdata_dir + filename;
}
const std::string& GetTestDataDir() {
return testdata_dir;
}
|
6bdfe502fee2353e3f24232f0944053d4524daaf | eae08168b61a4be2c9e4e535df229c6d67390a18 | /test/block_test.cc | 8e01a88f4b63a38fb725a7718dc35c81d4624866 | [] | no_license | bingtaoli/yodb | ce74d94188b23cb3f7f9c2688b6007d8a96ea43d | 77c23c2eca75591a3aa29fa52586b4c528ae13bf | refs/heads/master | 2020-12-31T07:33:51.446797 | 2017-04-07T16:12:11 | 2017-04-07T16:12:11 | 86,530,359 | 0 | 0 | null | 2017-03-29T02:38:47 | 2017-03-29T02:38:47 | null | UTF-8 | C++ | false | false | 990 | cc | block_test.cc | #include "util/block.h"
#include <stdint.h>
#include <gtest/gtest.h>
using namespace yodb;
TEST(Block, RW)
{
char buf[1024];
Block block(Slice(buf, 1024));
BlockWriter writer(block);
bool v = true;
uint8_t u8 = 1;
uint16_t u16 = 1000;
uint32_t u32 = 100000;
uint64_t u64 = 100000000;
writer << v << u8 << u16 << u32 << u64;
EXPECT_TRUE(writer.ok());
Slice s1("abcedf");
Slice s2("cdefgh");
Slice empty1;
writer << empty1 << s1 << s2;
EXPECT_TRUE(writer.ok());
bool rv;
uint8_t ru8;
uint16_t ru16;
uint32_t ru32;
uint64_t ru64;
BlockReader reader(block);
reader >> rv >> ru8 >> ru16 >> ru32 >> ru64;
EXPECT_TRUE(reader.ok());
EXPECT_EQ(rv, v);
EXPECT_EQ(ru8, u8);
EXPECT_EQ(ru16, u16);
EXPECT_EQ(ru32, u32);
EXPECT_EQ(ru64, u64);
Slice s3, s4, empty2;
reader >> empty2 >> s3 >> s4;
EXPECT_EQ(s1, s3);
EXPECT_EQ(s2, s4);
EXPECT_EQ(empty1, empty2);
}
|
be86733c0941a4362248a65a066fcafaceaabc1a | e56893e40447afc363a63f7fe8f6cca87325a7b5 | /Structures/nested_struct.cpp | c0ea6d55d9670badefae2cf4190d1d18dd9fd3bc | [] | no_license | ckymn/cpp | 75703223b5a479f12376d188f34ffabeaa449ac1 | 74dfe8af1a6985fd1ddfecbdbc0f3ffeb08d2b69 | refs/heads/main | 2023-03-22T19:28:14.868076 | 2021-03-11T06:10:53 | 2021-03-11T06:10:53 | 344,023,228 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | nested_struct.cpp | #include <iostream>
using namespace std;
struct Nested_Struct
{
int age;
string cityName;
};
struct Employee
{
int id;
string name;
string department;
Nested_Struct nested_struct;
};
int main()
{
Employee emp1 = {12, "muhammet cokyaman", "Yazilim", {21, "Ankara"}};
cout << "id : " << emp1.id << endl;
cout << "age : " << emp1.nested_struct.age << endl;
return 0;
} |
408f90f2c0dbecee6913475c46f817ecda4a78bd | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-privatenetworks/source/model/Network.cpp | 4ef308203f715e382d8ca9eff39aeed8a751185a | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 2,685 | cpp | Network.cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/privatenetworks/model/Network.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace PrivateNetworks
{
namespace Model
{
Network::Network() :
m_createdAtHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_networkArnHasBeenSet(false),
m_networkNameHasBeenSet(false),
m_status(NetworkStatus::NOT_SET),
m_statusHasBeenSet(false),
m_statusReasonHasBeenSet(false)
{
}
Network::Network(JsonView jsonValue) :
m_createdAtHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_networkArnHasBeenSet(false),
m_networkNameHasBeenSet(false),
m_status(NetworkStatus::NOT_SET),
m_statusHasBeenSet(false),
m_statusReasonHasBeenSet(false)
{
*this = jsonValue;
}
Network& Network::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("createdAt"))
{
m_createdAt = jsonValue.GetString("createdAt");
m_createdAtHasBeenSet = true;
}
if(jsonValue.ValueExists("description"))
{
m_description = jsonValue.GetString("description");
m_descriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("networkArn"))
{
m_networkArn = jsonValue.GetString("networkArn");
m_networkArnHasBeenSet = true;
}
if(jsonValue.ValueExists("networkName"))
{
m_networkName = jsonValue.GetString("networkName");
m_networkNameHasBeenSet = true;
}
if(jsonValue.ValueExists("status"))
{
m_status = NetworkStatusMapper::GetNetworkStatusForName(jsonValue.GetString("status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("statusReason"))
{
m_statusReason = jsonValue.GetString("statusReason");
m_statusReasonHasBeenSet = true;
}
return *this;
}
JsonValue Network::Jsonize() const
{
JsonValue payload;
if(m_createdAtHasBeenSet)
{
payload.WithString("createdAt", m_createdAt.ToGmtString(Aws::Utils::DateFormat::ISO_8601));
}
if(m_descriptionHasBeenSet)
{
payload.WithString("description", m_description);
}
if(m_networkArnHasBeenSet)
{
payload.WithString("networkArn", m_networkArn);
}
if(m_networkNameHasBeenSet)
{
payload.WithString("networkName", m_networkName);
}
if(m_statusHasBeenSet)
{
payload.WithString("status", NetworkStatusMapper::GetNameForNetworkStatus(m_status));
}
if(m_statusReasonHasBeenSet)
{
payload.WithString("statusReason", m_statusReason);
}
return payload;
}
} // namespace Model
} // namespace PrivateNetworks
} // namespace Aws
|
9696670222abc8013e5ce78b1deae2e693ed433f | 86c53a0492000693be19589ff2e14e49300a50f4 | /powerof2.cpp | caa1ad6d19f55aa89e6dae7d80cfee7997eac362 | [] | no_license | yinhaokai/Approximate-logic-optimization-for-ISFPRM-function | d4df1651a8b0d4f8482365248cd0a51a1c5bc0ba | afff381bc7f3a1a0f25ec2ec6cfc3f496fa39e37 | refs/heads/master | 2020-03-28T12:12:58.613310 | 2018-09-11T07:47:02 | 2018-09-11T07:47:02 | 148,279,119 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | cpp | powerof2.cpp | # include "header.h"
int powerof2(int x)
{
int res = 1;
for (int i = 0; i < x; i++)
res = res * 2;
return res;
} |
07f24169f4e30af51cf426266b17f165bb9a79a9 | ec45d1c385fc1f97618c7508eb0f4d03d022b438 | /Tests/Backbone/Test_Common.cpp | 7a0ba4b8ca81ba8e9dfe6aff5ebaf2a6e17c48d6 | [] | no_license | Manuzor/Backbone | 3dfef2316bb9518ab466813d3ca5d86b23d6ebf5 | 35706597466fc3668410183b0fdf84d7553fd897 | refs/heads/master | 2020-04-06T07:02:16.535616 | 2016-08-31T16:03:57 | 2016-08-31T16:03:57 | 65,106,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,337 | cpp | Test_Common.cpp | #include <Backbone/Common.hpp>
#include "catch.hpp"
static_assert(IsPOD<void>(), "Type 'void' must be considered POD.");
static_assert(IsPOD<void const>(), "Type 'void const' must be considered POD.");
static_assert(IsNaN(NaN<float>()), "NaN() or IsNaN() aren't working properly.");
static_assert(IsNaN(NaN<double>()), "NaN() or IsNaN() aren't working properly.");
TEST_CASE("Defer", "[Common]")
{
SECTION("POD")
{
int Value = 0;
Defer [&](){ REQUIRE(Value == 3); };
Defer [&](){ ++Value; };
Defer [&](){ ++Value; };
Defer [=](){ REQUIRE( Value == 0 ); };
Defer [&](){ ++Value; };
}
SECTION("Complex capture")
{
struct foo
{
int Value = 0;
foo() = default;
foo(foo const& Other) { FAIL( "Copy constructor is not supposed to be called." ); }
~foo() { REQUIRE( Value == 42 ); }
};
struct bar
{
int Value = 1337;
bar() = default;
~bar() { REQUIRE( Value == 1337 ); }
};
foo Foo;
bar Bar;
Defer [&](){ Foo.Value = 42; Bar = {}; };
Defer [Bar](){ REQUIRE( Bar.Value == 1337 ); };
Defer [&Bar](){ REQUIRE( Bar.Value == 123 ); };
Defer [=, &Foo](){ REQUIRE( Foo.Value == 3 ); REQUIRE( Bar.Value == 1337 ); };
Foo.Value = 3;
Bar.Value = 123;
}
}
TEST_CASE("Byte Sizes", "[Common]")
{
REQUIRE( ToBytes(KiB(3)) == 3 * 1024ULL );
REQUIRE( ToBytes(MiB(3)) == 3 * 1024ULL * 1024ULL );
REQUIRE( ToBytes(GiB(3)) == 3 * 1024ULL * 1024ULL * 1024ULL );
REQUIRE( ToBytes(TiB(3)) == 3 * 1024ULL * 1024ULL * 1024ULL * 1024ULL );
REQUIRE( ToBytes(KB(3)) == 3 * 1000ULL );
REQUIRE( ToBytes(MB(3)) == 3 * 1000ULL * 1000ULL );
REQUIRE( ToBytes(GB(3)) == 3 * 1000ULL * 1000ULL * 1000ULL );
REQUIRE( ToBytes(TB(3)) == 3 * 1000ULL * 1000ULL * 1000ULL * 1000ULL );
REQUIRE( ToKiB(Bytes(512)) == 0.5f );
REQUIRE( ToKiB<uint64>(Bytes(512)) == 0 );
REQUIRE( ToKiB<uint32>(Bytes(512)) == 0 );
REQUIRE( ToKiB<uint16>(Bytes(512)) == 0 );
REQUIRE( ToKiB<uint8>(Bytes(512)) == 0 );
REQUIRE( ToKiB(Bytes(2 * 1024)) == 2.0f );
REQUIRE( ToKiB<uint64>(Bytes(2 * 1024)) == 2 );
REQUIRE( ToKiB<uint32>(Bytes(2 * 1024)) == 2 );
REQUIRE( ToKiB<uint16>(Bytes(2 * 1024)) == 2 );
REQUIRE( ToKiB<uint8>(Bytes(2 * 1024)) == 2 );
}
TEST_CASE("Array Count", "[Common]")
{
SECTION("POD array")
{
int Array[42];
REQUIRE(ArrayCount(Array) == 42);
}
SECTION("String literal")
{
REQUIRE(ArrayCount("Foo") == 3 + 1);
}
}
TEST_CASE("Mem offsets", "[Common]")
{
int32 Data = 42;
auto DataOffset = (int64)&Data;
auto Foo = (int32*)&Data;
auto Bar = (void*)&Data;
SECTION("Byte offset")
{
REQUIRE(MemAddByteOffset(Foo, 2) == (int32*)( (char*)&Data + 2 ));
REQUIRE(MemAddByteOffset(Foo, -2) == (int32*)( (char*)&Data - 2 ));
REQUIRE(MemAddByteOffset(Bar, 2) == (char*)&Data + 2);
REQUIRE(MemAddByteOffset(Bar, -2) == (char*)&Data - 2);
REQUIRE(MemAddByteOffset(Foo, -DataOffset) == nullptr);
REQUIRE(MemAddByteOffset(Foo, -DataOffset - 1) == (int32*)( (char*)nullptr - 1 ));
}
SECTION("Sized offset")
{
REQUIRE(MemAddOffset(Foo, 2) == Foo + 2);
REQUIRE(MemAddOffset(Foo, -2) == Foo - 2);
REQUIRE(MemAddOffset(Bar, 2) == (char*)Bar + 2);
REQUIRE(MemAddOffset(Bar, -2) == (char*)Bar - 2);
}
}
struct CastDataInt
{
int Data = 42;
};
struct CastDataFloat
{
float Data = 0.5f;
operator CastDataInt() { return {}; }
};
namespace casts
{
int helper(int&) { return 42; }
int helper(int const&) { return 64; }
int helper(int*) { return 128; }
int helper(int const*) { return 512; }
}
TEST_CASE("Cast", "[Common]")
{
REQUIRE(Cast<float>(1) == 1.0f);
REQUIRE(Cast<CastDataInt>(CastDataFloat()).Data == 42);
}
TEST_CASE("Reinterpret", "[Common]")
{
int Data;
REQUIRE(Reinterpret<void*>(&Data) == (void*)&Data);
}
TEST_CASE("Coerce", "[Common]")
{
REQUIRE(Coerce<float>((int)42) == (float)((int)42));
}
TEST_CASE("AsConst", "[Common]")
{
int Data;
REQUIRE(casts::helper(Data) == 42);
REQUIRE(casts::helper(AsConst(Data)) == 64);
REQUIRE(casts::helper(&Data) == 128);
REQUIRE(casts::helper(AsPtrToConst(&Data)) == 512);
}
TEST_CASE("IsPowerOfTwo", "[Common]")
{
size_t Iteration = 0;
for(size_t Index = 0; Index < NumBits<size_t>(); ++Index)
{
CAPTURE( Index );
auto Integer = size_t(1) << Index;
CAPTURE( Integer );
REQUIRE( IsPowerOfTwo(Integer) );
}
auto NegativeTest = [](size_t Argument)
{
CAPTURE(Argument);
REQUIRE( !IsPowerOfTwo(Argument) );
};
NegativeTest( 3 );
NegativeTest( 5 );
NegativeTest( 6 );
NegativeTest( 12 );
NegativeTest( 1024-1 );
}
TEST_CASE("Min", "[Common]")
{
REQUIRE(Min( 0, 1) == 0);
REQUIRE(Min( 1, 0) == 0);
REQUIRE(Min(-1, 0) == -1);
REQUIRE(Min( 0, -1) == -1);
REQUIRE(Min(uint64(0), float(1)) == uint64(0));
REQUIRE(Min(uint64(1), float(0)) == uint64(0));
}
TEST_CASE("Max", "[Common]")
{
REQUIRE(Max( 0, 1) == 1);
REQUIRE(Max( 1, 0) == 1);
REQUIRE(Max(-1, 0) == 0);
REQUIRE(Max( 0, -1) == 0);
REQUIRE(Max(uint64(0), float(1)) == uint64(1));
REQUIRE(Max(uint64(1), float(0)) == uint64(1));
}
TEST_CASE("Clamp", "[Common]")
{
REQUIRE(Clamp(10, 5, 15) == 10);
REQUIRE(Clamp( 5, 5, 15) == 5);
REQUIRE(Clamp(15, 5, 15) == 15);
REQUIRE(Clamp(20, 5, 15) == 15);
REQUIRE(Clamp( 0, 5, 15) == 5);
REQUIRE(Clamp(10, 15, 5) == 10);
}
TEST_CASE("Wrap", "[Common]")
{
REQUIRE(Wrap(10, 5, 15) == 10);
REQUIRE(Wrap(15, 5, 15) == 5);
REQUIRE(Wrap(16, 5, 15) == 6);
REQUIRE(Wrap(5, 5, 15) == 5);
REQUIRE(Wrap(4, 5, 15) == 14);
REQUIRE(Wrap( 0, -10, 10) == 0);
REQUIRE(Wrap( 1, -10, 10) == 1);
REQUIRE(Wrap( 10, -10, 10) == -10);
REQUIRE(Wrap( 15, -10, 10) == -5);
REQUIRE(Wrap(-15, -10, 10) == 5);
REQUIRE(Wrap( 30, 5, 15) == 10); // 30 => 20 => 10
REQUIRE(Wrap(-10, 5, 15) == 10); // -10 => 0 => 10
}
TEST_CASE("NormalizeValue", "[Common]")
{
REQUIRE(NormalizeValue<float>(15, 10, 30) == 0.25f);
REQUIRE(NormalizeValue<float>(15, 30, 10) == 0.0f); // Invalid bounds.
}
TEST_CASE("AreNearlyEqual", "[Common]")
{
REQUIRE( AreNearlyEqual(0.9f, 1.1f, /* Epsilon: */ 0.200001f));
REQUIRE(!AreNearlyEqual(0.9f, 1.11f, /* Epsilon: */ 0.2f));
}
namespace
{
struct SomeDataCounter
{
int DefaultConstructions = 0;
int CopyConstructions = 0;
int MoveConstructions = 0;
int Destructions = 0;
};
struct SomeData
{
static SomeDataCounter* Counter;
SomeData() { Counter->DefaultConstructions++; }
SomeData(SomeData const&) { Counter->CopyConstructions++; }
SomeData(SomeData&&) { Counter->MoveConstructions++; }
~SomeData() { Counter->Destructions++; }
};
SomeDataCounter* SomeData::Counter = nullptr;
void TestCopy(SomeData Something) {}
void TestMove(SomeData&& Something) {}
}
TEST_CASE("Move", "[Common]")
{
SomeDataCounter Counter;
SomeData::Counter = &Counter;
Defer [](){ SomeData::Counter = nullptr; };
SomeData Something;
REQUIRE( Counter.DefaultConstructions == 1 );
REQUIRE( Counter.CopyConstructions == 0 );
REQUIRE( Counter.MoveConstructions == 0 );
REQUIRE( Counter.Destructions == 0 );
TestCopy(Something);
REQUIRE( Counter.DefaultConstructions == 1 );
REQUIRE( Counter.CopyConstructions == 1 );
REQUIRE( Counter.MoveConstructions == 0 );
REQUIRE( Counter.Destructions == 1 );
TestMove(Move(Something));
REQUIRE( Counter.DefaultConstructions == 1 );
REQUIRE( Counter.CopyConstructions == 1 );
REQUIRE( Counter.MoveConstructions == 0 );
REQUIRE( Counter.Destructions == 1 );
TestCopy(Move(Something));
REQUIRE( Counter.DefaultConstructions == 1 );
REQUIRE( Counter.CopyConstructions == 1 );
REQUIRE( Counter.MoveConstructions == 1 );
REQUIRE( Counter.Destructions == 2 );
TestCopy(SomeData());
REQUIRE( Counter.DefaultConstructions == 2 );
REQUIRE( Counter.CopyConstructions == 1 );
REQUIRE( Counter.MoveConstructions == 1 );
REQUIRE( Counter.Destructions == 3 );
TestMove(Move(SomeData()));
REQUIRE( Counter.DefaultConstructions == 3 );
REQUIRE( Counter.CopyConstructions == 1 );
REQUIRE( Counter.MoveConstructions == 1 );
REQUIRE( Counter.Destructions == 4 );
}
struct my_conversion
{
struct foo {};
struct bar {};
static constexpr int
Do(foo)
{
return 42;
}
static constexpr int
Do(bar)
{
return 1337;
}
};
template<> struct impl_convert<int, my_conversion::foo> : public my_conversion {};
template<> struct impl_convert<int, my_conversion::bar> : public my_conversion {};
TEST_CASE("General Conversion", "[Common]")
{
REQUIRE(Convert<int>(my_conversion::foo()) == 42);
REQUIRE(Convert<int>(my_conversion::bar()) == 1337);
}
TEST_CASE("Float UNorm SNorm Conversion", "[Common]")
{
SECTION("uint8")
{
// Note: We cast to uint32 so the output doesn't get treated as a char but
// as an integer value.
REQUIRE( (uint32)FloatToUNorm<uint8>(0.0f) == 0 );
REQUIRE( (uint32)FloatToUNorm<uint8>(1.0f) == 255 );
REQUIRE( (uint32)FloatToUNorm<uint8>(0.5f) == 128 );
REQUIRE( (uint32)FloatToUNorm<uint8>(0.2f) == 51 );
REQUIRE( (uint32)FloatToUNorm<uint8>(0.25f) == 64 );
REQUIRE( UNormToFloat(0) == 0.0f );
REQUIRE( UNormToFloat(IntMaxValue<uint8>()) == 1.0f );
REQUIRE( AreNearlyEqual(UNormToFloat<uint8>(IntMaxValue<uint8>() / 2), 0.5f, 0.005f) );
//
// Test Clamping
//
REQUIRE( (uint32)FloatToUNorm<uint8>(2.0f) == 255 );
REQUIRE( (uint32)FloatToUNorm<uint8>(-1.0f) == 0 );
}
}
TEST_CASE("Sign", "[Common]")
{
SECTION("uint8")
{
REQUIRE( Sign(uint8( 42)) == 1 );
REQUIRE( Sign(uint8( 0)) == 0 );
}
SECTION("uint16")
{
REQUIRE( Sign(uint16( 42)) == 1 );
REQUIRE( Sign(uint16( 0)) == 0 );
}
SECTION("uint32")
{
REQUIRE( Sign(uint32( 42)) == 1 );
REQUIRE( Sign(uint32( 0)) == 0 );
}
SECTION("uint64")
{
REQUIRE( Sign(uint64( 42)) == 1 );
REQUIRE( Sign(uint64( 0)) == 0 );
}
SECTION("int8")
{
REQUIRE( Sign(int8(-42)) == -1 );
REQUIRE( Sign(int8( 42)) == 1 );
REQUIRE( Sign(int8( 0)) == 0 );
}
SECTION("int16")
{
REQUIRE( Sign(int16(-42)) == -1 );
REQUIRE( Sign(int16( 42)) == 1 );
REQUIRE( Sign(int16( 0)) == 0 );
}
SECTION("int32")
{
REQUIRE( Sign(int32(-42)) == -1 );
REQUIRE( Sign(int32( 42)) == 1 );
REQUIRE( Sign(int32( 0)) == 0 );
}
SECTION("int64")
{
REQUIRE( Sign(int64(-42)) == -1 );
REQUIRE( Sign(int64( 42)) == 1 );
REQUIRE( Sign(int64( 0)) == 0 );
}
SECTION("float")
{
REQUIRE( Sign(-42.1337f) == -1 );
REQUIRE( Sign( 42.1337f) == 1 );
REQUIRE( Sign( 0.00000f) == 0 );
}
SECTION("double")
{
REQUIRE( Sign(-42.1337) == -1 );
REQUIRE( Sign( 42.1337) == 1 );
REQUIRE( Sign( 0.00000) == 0 );
}
}
TEST_CASE("Abs", "[Common]")
{
SECTION("uint8")
{
REQUIRE( Abs(uint8(1)) == 1 );
REQUIRE( Abs(IntMaxValue<uint8>()) == IntMaxValue<uint8>() );
}
SECTION("uint16")
{
REQUIRE( Abs(uint16(1)) == 1 );
REQUIRE( Abs(IntMaxValue<uint16>()) == IntMaxValue<uint16>() );
}
SECTION("uint32")
{
REQUIRE( Abs(uint32(1)) == 1 );
REQUIRE( Abs(IntMaxValue<uint32>()) == IntMaxValue<uint32>() );
}
SECTION("uint64")
{
REQUIRE( Abs(uint64(1)) == 1 );
REQUIRE( Abs(IntMaxValue<uint64>()) == IntMaxValue<uint64>() );
}
SECTION("int8")
{
REQUIRE( Abs(int8(1)) == 1 );
REQUIRE( Abs(int8(-1)) == 1 );
REQUIRE( Abs(IntMaxValue<int8>()) == IntMaxValue<int8>() );
REQUIRE( Abs(IntMinValue<int8>() + 1) == IntMaxValue<int8>() );
}
SECTION("int16")
{
REQUIRE( Abs(int16(1)) == 1 );
REQUIRE( Abs(int16(-1)) == 1 );
REQUIRE( Abs(IntMaxValue<int16>()) == IntMaxValue<int16>() );
REQUIRE( Abs(IntMinValue<int16>() + 1) == IntMaxValue<int16>() );
}
SECTION("int32")
{
REQUIRE( Abs(int32(1)) == 1 );
REQUIRE( Abs(int32(-1)) == 1 );
REQUIRE( Abs(IntMaxValue<int32>()) == IntMaxValue<int32>() );
REQUIRE( Abs(IntMinValue<int32>() + 1) == IntMaxValue<int32>() );
}
SECTION("int64")
{
REQUIRE( Abs(int64(1)) == 1 );
REQUIRE( Abs(int64(-1)) == 1 );
REQUIRE( Abs(IntMinValue<int64>() + 1) == IntMaxValue<int64>() );
REQUIRE( Abs(IntMaxValue<int64>()) == IntMaxValue<int64>() );
}
SECTION("float")
{
REQUIRE( Abs( 1.0f) == 1.0f );
REQUIRE( Abs(-1.0f) == 1.0f );
}
SECTION("double")
{
REQUIRE( Abs( 1.0) == 1.0 );
REQUIRE( Abs(-1.0) == 1.0 );
}
}
TEST_CASE("Rounding", "[Common]")
{
SECTION("RoundDown")
{
REQUIRE( RoundDown<int>( 3.40f) == 3 );
REQUIRE( RoundDown<int>( 3.50f) == 3 );
REQUIRE( RoundDown<int>( 3.60f) == 3 );
REQUIRE( RoundDown<int>(-3.40f) == -4 );
REQUIRE( RoundDown<int>(-3.50f) == -4 );
REQUIRE( RoundDown<int>(-3.60f) == -4 );
}
SECTION("RoundUp")
{
REQUIRE( RoundUp<int>( 3.40f) == 4 );
REQUIRE( RoundUp<int>( 3.50f) == 4 );
REQUIRE( RoundUp<int>( 3.60f) == 4 );
REQUIRE( RoundUp<int>(-3.40f) == -3 );
REQUIRE( RoundUp<int>(-3.50f) == -3 );
REQUIRE( RoundUp<int>(-3.60f) == -3 );
}
SECTION("RoundTowardsZero")
{
REQUIRE( RoundTowardsZero<int>( 3.40f) == 3 );
REQUIRE( RoundTowardsZero<int>( 3.50f) == 3 );
REQUIRE( RoundTowardsZero<int>( 3.60f) == 3 );
REQUIRE( RoundTowardsZero<int>(-3.40f) == -3 );
REQUIRE( RoundTowardsZero<int>(-3.50f) == -3 );
REQUIRE( RoundTowardsZero<int>(-3.60f) == -3 );
}
SECTION("RoundAwayFromZero")
{
REQUIRE( RoundAwayFromZero<int>( 3.40f) == 4 );
REQUIRE( RoundAwayFromZero<int>( 3.50f) == 4 );
REQUIRE( RoundAwayFromZero<int>( 3.60f) == 4 );
REQUIRE( RoundAwayFromZero<int>(-3.40f) == -4 );
REQUIRE( RoundAwayFromZero<int>(-3.50f) == -4 );
REQUIRE( RoundAwayFromZero<int>(-3.60f) == -4 );
}
SECTION("Round")
{
REQUIRE( Round<int>( 3.40f) == 3 );
REQUIRE( Round<int>( 3.50f) == 4 );
REQUIRE( Round<int>( 3.60f) == 4 );
REQUIRE( Round<int>(-3.40f) == -3 );
REQUIRE( Round<int>(-3.50f) == -3 );
REQUIRE( Round<int>(-3.51f) == -4 );
REQUIRE( Round<int>(-3.60f) == -4 );
}
}
|
d2410293ec06ac003c1af27a1b6884c49ca9c880 | c26d325bca488b2f071f15e7dd09a54a7bba2cf2 | /Task 4/timergalin_arthur.cpp | 3adfe379d7b470fef7ef97014f18271567affd88 | [] | no_license | devmentality/cpp-ft201-2019 | ef8388b77dbfb5dee0fab7e4ec64b22b56d11ee8 | 6529edf9ee2dfa121ab76a9e2727d1f4df71cacc | refs/heads/master | 2020-05-06T13:34:32.272691 | 2019-05-26T10:01:42 | 2019-05-26T10:01:42 | 180,143,869 | 0 | 1 | null | 2019-04-09T17:02:19 | 2019-04-08T12:25:49 | C++ | UTF-8 | C++ | false | false | 7,322 | cpp | timergalin_arthur.cpp | #include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <new>
using namespace std;
class Node{
public:
int val;
Node* left;
Node* right;
int height;
};
class AVLTree{
Node* root = 0;
size_t _getHeight(Node* node)
{
if (node == 0)
return 0;
return node->height;
}
size_t _getMaxNeighbourHeight(Node* node)
{
size_t leftHeight = _getHeight(node->left);
size_t rightHeight = _getHeight(node->right);
return (leftHeight > rightHeight)? leftHeight : rightHeight;
}
Node* _getLowestNode(Node* node)
{
Node* _temp_node = node;
while (_temp_node->left != 0)
_temp_node = _temp_node->left;
return _temp_node;
}
int _checkBalance(Node* node)
{
if (node == 0)
return 0;
return _getHeight(node->left) - _getHeight(node->right);
}
Node* _rotateLeft(Node* subroot)
{
Node* rightSubtree = subroot->right;
Node* tempSubtree = rightSubtree->left;
rightSubtree->left = subroot;
subroot->right = tempSubtree;
subroot->height = _getMaxNeighbourHeight(subroot) + 1;
rightSubtree->height = _getMaxNeighbourHeight(rightSubtree) + 1;
return rightSubtree;
}
Node* _rotateRight(Node* subroot)
{
Node* leftSubtree = subroot->left;
Node* tempSubtree = leftSubtree->right;
leftSubtree->right = subroot;
subroot->left = tempSubtree;
subroot->height = _getMaxNeighbourHeight(subroot) + 1;
leftSubtree->height = _getMaxNeighbourHeight(leftSubtree) + 1;
return leftSubtree;
}
Node* _balanceNodeAfterInsert(Node* node, int val){
int balance = _checkBalance(node);
if (balance <= 1 && balance >= -1)
return node;
if (balance > 1 && val < node->left->val)
return _rotateRight(node);
if (balance < -1 && val > node->right->val)
return _rotateLeft(node);
if (balance > 1 && val > node->left->val)
{
node->left = _rotateLeft(node->left);
return _rotateRight(node);
}
if (balance < -1 && val < node->right->val)
{
node->right = _rotateRight(node->right);
return _rotateLeft(node);
}
return node;
}
Node* _balanceNodeAfterDelete(Node* node){
int balance = _checkBalance(node);
if (balance > 1 && _checkBalance(node->left) >= 0)
return _rotateRight(node);
if (balance > 1 && _checkBalance(node->left) < 0)
{
node->left = _rotateLeft(node->left);
return _rotateRight(node);
}
if (balance < -1 && _checkBalance(node->right) <= 0)
return _rotateLeft(node);
if (balance < -1 && _checkBalance(node->right) > 0)
{
node->right = _rotateRight(node->right);
return _rotateLeft(node);
}
return node;
}
Node* _balance(Node* node){
node = _balanceNodeAfterInsert(node, node->val);
node = _balanceNodeAfterDelete(node);
return node;
}
Node* _insertNode(Node* node, size_t val)
{
if (node == 0)
{
node = new Node();
node->height = 1;
node->left = 0;
node->right = 0;
node->val = val;
return node;
}
if (val < node->val)
node->left = _insertNode(node->left, val);
else if (val > node->val)
node->right = _insertNode(node->right, val);
else
return node;
node->height = 1 + _getMaxNeighbourHeight(node);
return _balanceNodeAfterInsert(node, val);
}
Node* _deleteNode(Node* subroot, int val)
{
if (subroot == 0)
return subroot;
if (val < subroot->val)
subroot->left = _deleteNode(subroot->left, val);
else if( val > subroot->val )
subroot->right = _deleteNode(subroot->right, val);
else if(subroot->left == 0 || subroot->right == 0)
{
Node *_temp_node = subroot->left ? subroot->left : subroot->right;
if (_temp_node == 0)
{
_temp_node = subroot;
subroot = 0;
}
else
*subroot = *_temp_node;
free(_temp_node);
}
else
{
Node* temp = _getLowestNode(subroot->right);
subroot->val = temp->val;
subroot->right = _deleteNode(subroot->right, temp->val);
}
if (subroot == 0)
return subroot;
subroot->height = 1 + _getMaxNeighbourHeight(subroot);
return _balanceNodeAfterDelete(subroot);
}
void _print(Node* node, bool isInOrder){
if(node != 0){
if(!isInOrder){
_print(node->left, isInOrder);
printf("%d ", node->val);
}
else{
printf("%d ", node->val);
_print(node->left, isInOrder);
}
_print(node->right, isInOrder);
}
}
public:
AVLTree(size_t initial_value){
root = new Node();
root->height = 1;
root->left = 0;
root->right = 0;
root->val = initial_value;
}
void Insert(size_t val)
{
if(root == 0){
root = new Node();
root->height = 1;
root->left = 0;
root->right = 0;
root->val = val;
}
else
root = _insertNode(root, val);
}
void Delete(size_t val){
root = _deleteNode(root, val);
}
// баланс происходит автоматически при операциях вставки/удаления
void Balance(){
root = _balance(root);
}
void PrintBalanced(){
_print(root, false);
}
void PrintInOrder(){
_print(root, true);
}
};
int main()
{
printf("Creating tree with 1 at root...\n");
AVLTree tree = AVLTree(1);
printf("One-node tree:\n");
tree.PrintBalanced();
printf("\n\nInserting 3, 4, 5, 2...\n");
tree.Insert(3);
tree.Insert(4);
tree.Insert(5);
tree.Insert(2);
tree.Balance();
printf("Balance in tree:\n");
tree.PrintBalanced();
printf("\nOrder in tree:\n");
tree.PrintInOrder();
printf("\n\nDeleting 1, 5...\n");
tree.Delete(1);
tree.Delete(5);
tree.Balance();
printf("Balance in tree:\n");
tree.PrintBalanced();
printf("\nOrder in tree:\n");
tree.PrintInOrder();
}
|
d5db6f7a1467ad501d9ceb8842a929181b006817 | 8e5be4cd41251e2ce91de831471c06c0571a9306 | /Engine/DigDug/DigDugScene.h | 08bfcbc8026cba9a7627f60b4c580f9ca230acd0 | [] | no_license | jeeckhout/2DAE06_PROG4_Eeckhout_Jens_Engine | a9c6a1b47d3a910856095464ca190a021cf8d043 | d540a8c689ea0eb383677aa45739e643e1fb878e | refs/heads/master | 2022-02-13T06:12:53.155521 | 2019-08-27T17:34:38 | 2019-08-27T17:34:38 | 183,748,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | h | DigDugScene.h | #pragma once
#include "Scene.h"
#include "memory"
class Grid;
namespace dae
{
class GameObject;
}
class DigDugScene final : public dae::Scene
{
public:
DigDugScene(const std::string& name);
~DigDugScene();
private:
Grid* m_pGrid{};
std::shared_ptr<dae::GameObject> Player1{};
std::shared_ptr<dae::GameObject> Player2{};
bool m_HasChosenMode{false};
void Initialize() override;
void CreateCoop();
void CreateSingle();
void CreateVersus();
void DoLevelDesign();
};
|
ff99a2a9a67a4629bbfc962219eb65d1707950bf | 85a5d20a5601f1b99b8247821e2169f732abe123 | /NcursesAPI/ncurses.h | 31656a5500a5608916a9e732a0426ea7466e59d3 | [] | no_license | DSUProgrammingClub/programmingclubgame2019 | 57c1c2b07cc0f068241722bfb522b489062858e6 | 7daca4940f19dafcd1da1a36cf1c734fbcd4e148 | refs/heads/master | 2020-04-16T16:55:05.605403 | 2019-02-24T03:06:10 | 2019-02-24T03:06:10 | 165,755,165 | 1 | 7 | null | 2019-02-24T03:06:11 | 2019-01-15T00:08:23 | C++ | UTF-8 | C++ | false | false | 907 | h | ncurses.h | #include <ncurses.h>
#include <iostream>
namespace Ncurses {
void init_ncurses();
void exit_ncurses();
}
class Display {
public:
Display();
Display(int width, int height);
Display(int start_x, int start_y, int width, int height);
Display(Display &parent, int start_x, int start_y, int width, int height);
void Clear();
void DrawRectangle(int x, int y, int width, int height, char ch, int back_color, int front_color, bool filled);
void DrawRectangle(int x, int y, int width, int height, char* ch, int back_color, int front_color, bool filled);
void DrawPoint(int x, int y, char ch, int back_color, int front_color);
void DrawPoint(int x, int y, char* ch, int back_color, int front_color);
~Display();
private:
uint start_x;
uint start_y;
uint window_width;
uint window_height;
WINDOW * window;
int findColorKey(int foreground, int background);
bool contains(int x, int y);
};
|
ae6f53f8eea99bb9838f0d5661e1e1f2cc7293fb | 702ed51dce814ab86a2bb107de4a9791f7e5d442 | /src/MessageDispatch.h | 3e78f91c59297a02df408e4ea210d29fbb47c394 | [] | no_license | Keberdle/radio-observer | b6435882103bdd5bc51a2411b1c7c529b38e72f5 | 878339170296c3e153c6ea8061eec072c9017ca3 | refs/heads/master | 2021-01-17T14:50:42.689441 | 2014-10-04T13:37:55 | 2014-10-04T13:37:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | h | MessageDispatch.h | /**
* \file MessageDispatch.h
* \author Jan Milik <milikjan@fit.cvut.cz>
* \date 2014-03-17
*
* \brief Header file for the MessageDispatch class.
*/
#ifndef MESSAGEQUEUE_D3GJUHJZ
#define MESSAGEQUEUE_D3GJUHJZ
#include <cppapp/cppapp.h>
using namespace cppapp;
/**
* \brief MessageListener listens to messages sent to a \ref MessageListener.
*/
template<class T>
class MessageListener : public Object {
public:
virtual void sendMessage(const T &msg) = 0;
};
template<class T>
class FunctionMessageListener : public MessageListener<T> {
public:
typedef void (*Function)(const T &msg);
private:
Function fn_;
public:
FunctionMessageListener(Function fn) : fn_(fn) {}
virtual void sendMessage(const T &msg)
{
fn_(msg);
}
};
/**
* \brief Class dispatching messages to a collection of message listeners.
*
* \see MessageListener
*/
template<class T>
class MessageDispatch {
public:
typedef T MessageType;
private:
MessageDispatch(const MessageDispatch<T>& other);
vector<Ref<MessageListener<T> > > listeners_;
public:
/**
* Constructor.
*/
MessageDispatch() {}
/**
* Destructor.
*/
virtual ~MessageDispatch() {}
/**
* \brief Sends a message \c msg to all registered listeners.
*
* Listeners are registered by the \ref MessageDispatch::addListener method.
*/
void sendMessage(const T &msg)
{
FOR_EACH(listeners_, it) {
(*it)->sendMessage(msg);
}
}
void addListener(Ref<MessageListener<T> > listener)
{
listeners_.push_back(listener);
}
void addListener(typename FunctionMessageListener<T>::Function fn)
{
addListener(new FunctionMessageListener<T>(fn));
}
static MessageDispatch<T>& getInstance()
{
static MessageDispatch<T> instance;
return instance;
}
};
#endif /* end of include guard: MESSAGEQUEUE_D3GJUHJZ */
|
246c96102150748e70d1da609465d9aa8ed6458b | 318e452769af0188e130dbbb069a9c52657308b8 | /GameProject/include/GameProject/Scene.hpp | 39998acea3e030eaf649c0132a3c9b8d5b02ec4a | [
"MIT"
] | permissive | angkres/base-game-sfml | d479502c1cae56c2815612d8c82d829de89f6f38 | fd497c4e39d94966772604d77704f53979232d66 | refs/heads/master | 2020-04-08T16:06:01.325879 | 2018-04-22T21:00:33 | 2018-04-22T21:00:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,234 | hpp | Scene.hpp | #pragma once
#include GAMEPROJECT_PCH
#include <GameProject/Interfaces/Updatable.hpp>
#include <GameProject/Actors/Actor.hpp>
namespace gameproject
{
/// <summary>
/// Contains and manages every actor inside.
/// </summary>
class Scene
:
public sf::Drawable,
public IUpdatable
{
public:
// Enums:
/// <summary>
/// Lists the behaviour of "Scene::add" function.
/// </summary>
enum class AddPolicy
{
Unchecked, // Do not check whether actor can be properly added - assume it is not in this scene yet.
Checked // Check if actor was already in this scene.
};
// Aliases:
using ActorPtrType = std::shared_ptr< IActor >;
using ActorPoolType = std::vector< ActorPtrType >;
// Methods:
/// <summary>
/// Spawns an actor inside this scene.
/// </summary>
/// <returns>Reference to the created actor.</returns>
template <typename TActorType>
TActorType& spawn()
{
if (auto actor = std::make_shared<TActorType>())
{
this->add(actor, AddPolicy::Unchecked);
return *actor;
}
else // Something inside `make_shared` failed, most probably allocation.
throw std::runtime_error("Could not spawn actor inside the scene.");
}
/// <summary>
/// Adds the specified actor to the scene.
/// </summary>
/// <param name="actor_">The actor.</param>
/// <returns>
/// <c>true</c> if succeeded; otherwise, <c>false</c>.
/// </returns>
bool add(const ActorPtrType & actor_, const AddPolicy policy_ = AddPolicy::Checked);
/// <summary>
/// Removes the specified actor from the scene.
/// </summary>
/// <param name="actor_">The actor.</param>
/// <returns>
/// <c>true</c> if succeeded; otherwise, <c>false</c>.
/// </returns>
bool remove(const IActor& actor_);
/// <summary>
/// Determines whether scene contains the specified actor.
/// </summary>
/// <param name="actor_">The actor.</param>
/// <returns>
/// <c>true</c> if contains; otherwise, <c>false</c>.
/// </returns>
bool contains(const IActor& actor_) const;
/// <summary>
/// Returns cref to actor pool.
/// </summary>
/// <returns>const-ref to actor pool.</returns>
const ActorPoolType& getActors() const {
return m_actors;
}
// Overriden methods from IUpdatable:
/// <summary>
/// Updates this instance.
/// </summary>
/// <param name="deltaTime_">Time that passed since previous frame.</param>
/// <param name="frameTime_">The frame start time.</param>
virtual void update(const double deltaTime_, const IUpdatable::TimePoint & frameTime_) override;
protected:
// Methods:
// Overriden methods from sf::Drawable:
/// <summary>
/// Draws the entire scene on specified target.
/// </summary>
/// <param name="target_">The target.</param>
/// <param name="states_">The render states.</param>
virtual void draw(sf::RenderTarget & target_, sf::RenderStates states_) const override;
private:
// Methods:
/// <summary>
/// Finds the actor inside the pool.
/// </summary>
/// <param name="actor_">The actor.</param>
/// <returns>Iterator of the actor pool, pointing to either the actor or the end().</returns>
ActorPoolType::const_iterator findActor(const IActor& actor_) const;
// Members:
ActorPoolType m_actors; /// Every actor is stored inside this container.
};
} |
8f26b47f8e18c78bbc14ef3e863b945e44032885 | b2cba20a9900b09828894b4e8e12be0fbb420c23 | /extra/MPU6050/MPU6050Functions.ino | eac4d558c44a53fb6267fce60e48ae2f91e4318a | [] | no_license | Zarfal/MonteQuadcopter | d19227cbbaae51712d39ee30cf867d849f205745 | 511dca645fc3b99c1640b808e6d00e59b62ef0af | refs/heads/master | 2023-05-28T14:48:00.362574 | 2021-06-10T00:37:31 | 2021-06-10T00:37:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,236 | ino | MPU6050Functions.ino | void initIMU()
{
// TODO look into an option of increasing the DMP rate to 200Hz
//./MPU6050_6Axis_MotionApps20.h:305: 0x02, 0x16, 0x02, 0x00, 0x01 // D_0_22 inv_set_fifo_rate
// change last 0x01 to 0x00 to change interrupt rate from 100Hz to 200Hz,
// which might work better for quadcopter but has more noise it said..
for (int i = 0; i < 4; i++)
yprOffset[i] = 0.0;
// initialize device
// Serial.println(F("Initializing I2C devices..."));
mpu.initialize();
pinMode(INTERRUPT_PIN, INPUT);
// verify connection
// Serial.println(F("Testing device connections..."));
// Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
// wait for ready
// Serial.println(F("\nSend any character to begin DMP programming and demo: "));
while (Serial.available() && Serial.read()); // empty buffer
// while (!Serial.available()); // wait for data
// while (Serial.available() && Serial.read()); // empty buffer again
// load and configure the DMP
// Serial.println(F("Initializing DMP..."));
devStatus = mpu.dmpInitialize();
// supply your own gyro offsets here, scaled for min sensitivity
// TODO experiment with these values
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
// Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
attachAnalogueInterrupt();
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
// Serial.print(F("DMP Initialization failed (code "));
// Serial.print(devStatus);
// Serial.println(F(")"));
}
}
void processRateIMU(){
mpu.getRotation(&gx, &gy, &gz);
}
void processIMU()
{
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
Serial.println(F("FIFO overflow!"));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
#ifdef OUTPUT_READABLE_EULER
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(ypr, &q);
#endif
#ifdef OUTPUT_READABLE_YAWPITCHROLL
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
#endif
// Serial.print(ypr[1]* 180/PI);
// Serial.print(" ");
// Serial.print(ypr[2]* 180/PI);
// Serial.print(" ");
// Serial.println(filter.filter(ypr[1]* 180/PI));
// Serial.print("y=");
// Serial.print((ypr[0] - yprOffset[0]) * 180/PI);
// Serial.print(" p=");
// Serial.print((ypr[1] - yprOffset[1]) * 180/PI);
// Serial.print(" r=");
// Serial.println((ypr[2] - yprOffset[2]) * 180/PI);
// Serial.print("delay (us)= ");
//
// currTime = micros();
// Serial.println(currTime-prevTime);
// prevTime = currTime;
// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}
}
void calibrateIMU()
{
for (int i = 0; i < 4; i++)
yprOffset[i] = ypr[i];
bluetooth.println(F("Calibrated"));
}
void attachAnalogueInterrupt(){
// enable Arduino interrupt detection
// Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
// this was previously and it doesnt work on anlogue pins
// attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
// Firstly go to SoftwareSerial.cpp and comment up these lines
//#if defined(PCINT1_vect)
//ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect));
//#endif
// as they are trying to use SoftwareSerial interrupts onto Analogue pins
// howeever we dont use them anyway, we want to use them differently..
// and software serial is basically used together with bluetooth so we need it.
pinMode(INTERRUPT_PIN, INPUT_PULLUP);
attachPCINT(digitalPinToPCINT(INTERRUPT_PIN), dmpDataReady, RISING);
}
|
378c93a13cfc70f2f46e97bfae8c7aba4e1567e9 | 7340d1443bdfade13f4daa21ea5bdc804eec813a | /c++/point.h | 86b474a90c49f2165a47204372a10bf4c316bd9d | [] | no_license | sebherv/cao_project | 8e2fef1f23d992d9d46a9c7d9c1c2533861de846 | ab4436924857d1964222c14ed211108bed430f4e | refs/heads/master | 2021-09-04T11:52:17.130811 | 2018-01-18T13:14:53 | 2018-01-18T13:14:53 | 113,870,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | h | point.h | //
// Created by Sebastien Hervieu on 18/12/2017.
//
#ifndef C_POINT_H
#define C_POINT_H
class point {
private:
int m_id;
double m_x;
double m_y;
double m_f;
double m_df_dx;
double m_df_dy;
public:
point();
point(int id, double m_x, double m_y);
point(const point& other);
bool operator<(const point& other) const;
int get_id() const;
double get_x() const;
double get_y() const;
double get_f() const;
double get_df_dx() const;
double get_df_dy() const;
void set_f(double _f);
void set_df_dx(double _df_dx);
void set_df_dy(double _df_dy);
};
#endif //C_POINT_H
|
9eef84dc86703a9f2dabc88e97c600890cabe22c | e20fff5c364077852c1a9bb8b17e22936de185b9 | /A.Cheap travels.cpp | 6bb079446be62c87f2a6aee188a2b4a47b4abbda | [] | no_license | jdmoyle/CODEFORCES | b334f5087acbbafd16861d270bc451c37703fdc7 | ac84aa90fd86af863bbc8f1fc300475e8e36223b | refs/heads/main | 2023-07-04T09:04:10.308308 | 2021-08-16T20:26:39 | 2021-08-16T20:26:39 | 386,037,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | A.Cheap travels.cpp | #include <iostream>
#include<algorithm>
using namespace std;
int main() {
int n,m,a,b;
cin>>n>>m>>a>>b;
int d,j=1;
int n1=n;
for( d=1;n1>0;)
{
n1=n1-m;
if(n1>=m)
{
j++;
}
if(n1<=0)
break;
d++;
}
//cout<<d<<" "<<j<<endl;
int r1=(n-m*d);
if(r1<0)
r1=0;
int r2=n-m*j;
if(r2<0)
r2=0;
int ans1=b*d+r1*a;
int ans3=b*j+r2*a;
int ans2=n*a;
int ans=min(ans1,min(ans2,ans3));
cout<<ans<<endl;
return 0;
}
|
d49473af13f244c0a0b6f089ada72344eb1e70c7 | 4057c476345d46141e8c4f43707f2c31a237bdaa | /src/xci/geometry/Vec3.h | 60e4149442ba4cfb08e239fa03b82e3184a68d93 | [
"Apache-2.0"
] | permissive | rbrich/xcikit | 25c6895755841b9eaa8d6a5e8321e5e2fc48e8b0 | c1d7061ef0a4e8bfc88d784ae64ffc8ad5035e11 | refs/heads/master | 2023-09-04T15:20:40.477588 | 2023-08-31T20:23:15 | 2023-08-31T20:23:15 | 124,593,515 | 18 | 1 | Apache-2.0 | 2023-09-12T18:51:25 | 2018-03-09T21:09:23 | C++ | UTF-8 | C++ | false | false | 3,023 | h | Vec3.h | // Vec3.h created on 2023-03-04 as part of xcikit project
// https://github.com/rbrich/xcikit
//
// Copyright 2023 Radek Brich
// Licensed under the Apache License, Version 2.0 (see LICENSE file)
#ifndef XCI_GEOMETRY_VEC3_H
#define XCI_GEOMETRY_VEC3_H
#include <xci/compat/macros.h>
#include <ostream>
namespace xci::core {
template <typename T>
struct Vec3 {
Vec3() = default;
Vec3(T x, T y, T z) : x(x), y(y), z(z) {}
// Convert another type of vector (possibly foreign type)
template <typename TVec>
explicit Vec3(const TVec& other) : x(other.x), y(other.y), z(other.z) {}
Vec3<T>& operator +=(const Vec3<T>& rhs) {
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this;
}
Vec3<T>& operator -=(const Vec3<T>& rhs) {
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
return *this;
}
T& operator[] (unsigned i) const {
switch (i) {
case 0: return x;
case 1: return y;
case 2: return z;
}
XCI_UNREACHABLE;
}
explicit operator bool() const noexcept {
return x != T{} || y != T{} || z != T{};
}
public:
T x {};
T y {};
T z {};
};
// unary minus (opposite vector)
template <typename T>
Vec3<T> operator -(const Vec3<T>& rhs) {
return Vec3<T>(-rhs.x, -rhs.y, -rhs.z);
}
template <typename T>
Vec3<T> operator +(const Vec3<T>& lhs, const Vec3<T>& rhs) {
return Vec3<T>(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z);
}
template <typename T>
Vec3<T> operator +(const Vec3<T>& lhs, T rhs) {
return Vec3<T>(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs);
}
template <typename T>
Vec3<T> operator -(const Vec3<T>& lhs, const Vec3<T>& rhs) {
return Vec3<T>(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
}
template <typename T>
Vec3<T> operator *(const Vec3<T>& lhs, const Vec3<T>& rhs) {
return Vec3<T>(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z);
}
template <typename T>
Vec3<T> operator *(const Vec3<T>& lhs, T rhs) {
return Vec3<T>(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs);
}
template <typename T, typename U>
Vec3<T> operator *(U lhs, const Vec3<T>& rhs) {
return Vec3<T>(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z);
}
template <typename T>
Vec3<T> operator /(const Vec3<T>& lhs, const Vec3<T>& rhs) {
return Vec3<T>(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z);
}
template <typename T>
Vec3<T> operator /(const Vec3<T>& lhs, T rhs) {
return Vec3<T>(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs);
}
template <typename T>
bool operator ==(const Vec3<T>& lhs, const Vec3<T>& rhs) {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z;
}
template <typename T>
bool operator !=(const Vec3<T>& lhs, const Vec3<T>& rhs) {
return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z;
}
template <typename T>
std::ostream& operator <<(std::ostream& s, Vec3<T> v) {
return s << "{" << v.x << ", " << v.y << ", " << v.z << "}";
}
using Vec3f = Vec3<float>;
} // namespace xci::core
#endif // include guard
|
923fb8c932a3f4e75d65908a6a579024b8589faa | c7c2c85cbe71b172b6a2c3505c08c4f670997735 | /Karnaugh.cpp | cbd865ce6db0b3cc47a2d46a9f5bcb23d8540dd4 | [] | no_license | jhs951101/LCaL4 | 0f08a83d75300583324c3a5c3c00b0aa4897293f | 94053d2a65743920f663a918cfc30c9c4f59d713 | refs/heads/master | 2023-06-04T05:03:52.769298 | 2021-06-28T12:44:33 | 2021-06-28T12:44:33 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 14,607 | cpp | Karnaugh.cpp | #include "Karnaugh.h"
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int convertBinary(int* num, int size){ // 0 또는 1의 형태로 저장된 수식을 minterm으로 변환하는 함수
int decimal_n = 0; // decimal_n: minterm으로 변환된 최종 값
int k = size-1; // k: 제곱용 보조 변수
for(int i=0; i<size; i++){
decimal_n += ( num[i] * pow(2,k) ); // decimal_n에 값을 누적함으로써 minterm을 구할 수 있음
k--; // 제곱을 하기 위해 k를 1만큼 감소시킴
}
return decimal_n; // 최종적으로 계산된 minterm을 return함
}
void ZeroAndOne(int* num, int* arr ,int& cnt, int a, int b, int c){ // 0 또는 1의 형태를 여러 가지 케이스로 나누는 함수 (Overloading)
// (보이지 않는 문자가 3개인 경우)
/* a, b, c: 보이지 않는 문자의 자리 (w:0, x:1, y:2, z:3) */
/* ex) w: x,y,z가 보이지 않으므로 a,b,c의 값은 1,2,3 */
for(int i=1; i<=2; i++){
if(i == 1) num[a] = 0; // 처음에 a자리를 0으로 가정
else num[a] = 1; // 다음 a자리를 1로 가정
for(int j=1; j<=4; j++){
if(j == 1){ // 첫째, b,c자리를 모두 0으로 가정
num[b] = 0;
num[c] = 0;
}
else if(j == 2){ // 둘째, b자리는 1, c자리는 0으로 가정
num[b] = 1;
num[c] = 0;
}
else if(j == 3){ // 셋째, b자리는 0, c자리는 1으로 가정
num[b] = 0;
num[c] = 1;
}
else{ // 넷째, b,c자리를 모두 1으로 가정
num[b] = 1;
num[c] = 1;
}
arr[cnt] = convertBinary(num, 4); // minterm으로 변환된 값을 배열에 넣어줌
cnt++; // 원소의 갯수: +1
}
}
}
void ZeroAndOne(int* num, int* arr ,int& cnt, int a, int b){ // 0 또는 1의 형태를 여러 가지 케이스로 나누는 함수 (Overloading)
// (보이지 않는 문자가 2개인 경우)
/* a, b: 보이지 않는 문자의 자리 (w:0, x:1, y:2, z:3) */
/* ex) wz: x,y가 보이지 않으므로 a,b의 값은 1,2 */
for(int j=1; j<=4; j++){
if(j == 1){ // 첫째, a,b자리를 모두 0으로 가정
num[a] = 0;
num[b] = 0;
}
else if(j == 2){ // 둘째, a자리는 1, b자리는 0으로 가정
num[a] = 1;
num[b] = 0;
}
else if(j == 3){ // 셋째, a자리는 0, b자리는 1로 가정
num[a] = 0;
num[b] = 1;
}
else{ // 넷째, a,b자리를 모두 1로 가정
num[a] = 1;
num[b] = 1;
}
arr[cnt] = convertBinary(num, 4); // minterm으로 변환된 값을 배열에 넣어줌
cnt++; // 원소의 갯수: +1
// 2진수로 변환된 숫자를 배열에 넣음
}
}
void ZeroAndOne(int* num, int* arr ,int& cnt, int a){ // 0 또는 1의 형태를 여러 가지 케이스로 나누는 함수 (Overloading)
// (보이지 않는 문자가 1개인 경우)
/* a: 보이지 않는 문자의 자리 (w:0, x:1, y:2, z:3) */
/* ex) wxz: y가 보이지 않으므로 a의 값은 2 */
for(int j=1; j<=2; j++){
if(j == 1)
num[a] = 0; // 첫째, a자리를 0으로 가정
else
num[a] = 1; // 둘째, a자리를 1로 가정
arr[cnt] = convertBinary(num, 4); // minterm으로 변환된 값을 배열에 넣어줌
cnt++; // 원소의 갯수: +1
// 2진수로 변환된 숫자를 배열에 넣음
}
}
void Karnaugh::insert(string s){
poly = s; // 입력받은 식을 저장함
}
void Karnaugh::devide(){
int len = poly.length()-1; // len: 입력받은 식 전체의 길이
int point = 0; // point: 지점을 저장 (식 전체를 나누는 데에 사용)
int count = 0; // count: 갯수를 저장 (식 전체를 나누는 데에 사용)
int a = 0; // a: 수식의 갯수
for(int i=0; i<=len; i++){
if(i == len){ // 식에서 제일 끝 문자에 도달했을 경우
terms[a] = poly.substr(point,count+1); // 구역을 지정해서 배열에 저장함
a++; // 수식의 갯수: +1
term_num = a; // 수식의 갯수를 class 변수로 넘겨줌
}
if(poly.at(i) == '+'){
terms[a] = poly.substr(point,count); // 구역을 지정해서 배열에 저장함
point = i+1; // 지점을 '+'에서 한 칸 앞쪽으로 지정함
count = 0; // 구역을 재지정하기위해 count를 0으로 함
a++; // 수식의 갯수: +1
}
else{
count++; // 구역을 지정하기 위해 count를 +1 해나감
}
}
}
void Karnaugh::minterm(){
for(int i=0; i<4; i++)
for(int j=0; j<100; j++)
tempTerm[i][j] = -1; // 배열 값을 모두 -1로 세팅함
for(int n=0; n<=term_num-1; n++){
string str = terms[n]; // str: 수식들이 저장된 배열로부터 값을 받는 변수
char arr1[8]; // arr[]: 수식을 나누어 저장하는 배열
for(int j=0; j<8; j++)
arr1[j] = ' '; // 배열 값을 모두 ' '으로 세팅함
for(int j=0; j<=str.length()-1; j++)
arr1[j] = str.at(j); // 수식에서 문자 하나하나를 배열에 저장함 ( "w`x`yz" -> w, `, x, `, y, z )
if( (arr1[0] >= 119 && arr1[0] <= 122) && arr1[1] == ' ' ){ // 문자가 단 하나만 존재하고 알파벳인 경우
int pos = arr1[0] - 119; // 숫자가 들어갈 자리를 지정함
tempTerm[pos][n] = 1; // 지정된 자리에 숫자를 넣음
}
else{
for(int j=0; j<=str.length()-2; j++){
if( (arr1[j] >= 119 && arr1[j] <= 122) && (arr1[j+1] >= 119 && arr1[j+1] <= 122) ){
// 왼쪽 값과 오른쪽 값 모두 알파벳일 경우, 왼쪽 값은 확실히 1임
int pos = arr1[j] - 119; // 숫자가 들어갈 자리를 지정함
tempTerm[pos][n] = 1; // 지정된 자리에 숫자를 넣음
}
else if( (arr1[j] >= 119 && arr1[j] <= 122) && arr1[j+1] == '`' ){
// 왼쪽 값이 알파벳이고 오른쪽 값이 '`'이면, 왼쪽 값은 0
int pos = arr1[j] - 119; // 숫자가 들어갈 자리를 지정함
tempTerm[pos][n] = 0; // 지정된 자리에 숫자를 넣음
}
}
if( arr1[str.length()-1] >= 119 && arr1[str.length()-1] <= 122 ){ // 제일 끝 문자가 알파벳일 경우 1
int pos = arr1[str.length()-1] - 119; // 숫자가 들어갈 자리를 지정함
tempTerm[pos][n] = 1; // 지정된 자리에 숫자를 넣음
}
}
}
}
void Karnaugh::kmap(){
int arrDecimal[100]; // arrDecimal[]: 수식들의 minterm을 저장
int sup = 0; // sup: 'arrDecimal[]'의 원소의 갯수
int temArr[4]; // temArr[]: 'tempTerm[k][n]' 2차원 배열에서 한 행씩 저장
for(int i=0; i<=3; i++)
temArr[i] = 0; // 배열을 모두 0으로 세팅함
for(int n=0; n<=term_num-1; n++){
if(tempTerm[0][n] == -1) // 'w'의 값이 없다면
{
if(tempTerm[1][n] == -1) // 'x'의 값이 없다면
{
if(tempTerm[2][n] == -1) // 'y'의 값이 없다면
{
// z (-1, -1, -1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 0, 1, 2); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else
{
if(tempTerm[3][n] == -1) // 'z'의 값이 없다면
{
// y (-1, -1, 1, -1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 0, 1, 3); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else // 'z'의 값이 있으면
{
// yz (-1, -1, 1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 0, 1); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
}
}
else // 'x'의 값이 있으면
{
if(tempTerm[2][n] == -1) // 'y'의 값이 없다면
{
if(tempTerm[3][n] == -1) // 'z'의 값이 없다면
{
// x (-1, 1, -1, -1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 0, 2, 3); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else // 'z'의 값이 있으면
{
// xz (-1, 1, -1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 0, 2); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
}
else
{
if(tempTerm[3][n] == -1) // 'y'의 값이 없다면
{
// xy (-1, 1, 1, -1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 0, 3); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else // 'z'의 값이 있으면
{
// xyz (-1, 1, 1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 0); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
}
}
}
else // 'w'의 값이 있으면
{
if(tempTerm[1][n] == -1) // 'x'의 값이 없다면
{
if(tempTerm[2][n] == -1) // 'y'의 값이 없다면
{
if(tempTerm[3][n] == -1) // 'z'의 값이 없다면
{
// w (1, -1, -1, -1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 1, 2, 3); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else // 'z'의 값이 있으면
{
// wz (1, -1, -1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 1, 2); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
}
else // 'y'의 값이 있으면
{
if(tempTerm[3][n] == -1) // 'z'의 값이 없다면
{
// wy (1, -1, 1, -1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 1, 3); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else // 'z'의 값이 있으면
{
// wyz (1, -1, 1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 1); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
}
}
else // 'x'의 값이 있으면
{
if(tempTerm[2][n] == -1) // 'y'의 값이 없다면
{
if(tempTerm[3][n] == -1) // 'z'의 값이 없다면
{
// wx(1, 1, -1, -1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 2, 3); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else // 'z'의 값이 있으면
{
// wxz (1, 1, -1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 2); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
}
else // 'y'의 값이 있으면
{
if(tempTerm[3][n] == -1) // 'z'의 값이 없다면
{
// wxy (1, 1, 1, -1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
ZeroAndOne(temArr, arrDecimal, sup, 3); // 0 또는 1의 형태로 변환하고 minterm을 계산함
}
else // 'z'의 값이 있으면
{
// wxyz (1, 1, 1, 1)
for(int k=0; k<=3; k++)
temArr[k] = tempTerm[k][n]; // 2차원 배열에서 해당 행을 저장
arrDecimal[sup] = convertBinary(temArr, 4); // 2진수로 변환된 숫자를 배열에 넣음
sup++; // 원소의 갯수: +1
}
}
}
}
}
for(int i=sup-1; i>=1; i--) // 원소들을 오름차순으로 정렬하는 부분
for(int j=0; j<i; j++){
if(arrDecimal[j] > arrDecimal[j+1]){ // 왼쪽 값이 오른쪽 값보다 클 경우 서로 맞바꿈
int swap = arrDecimal[j+1]; // 맞바꾸기 Step1
arrDecimal[j+1] = arrDecimal[j]; // 맞바꾸기 Step2
arrDecimal[j] = swap; // 맞바꾸기 Step3
}
}
int kmap[4][4] = { 0, 1, 3, 2, 4, 5, 7, 6, 12, 13, 15, 14, 8, 9, 11, 10 };
// kmap[][]: Karnaugh Map
int showing[4][4]; // showing[][]: 입력받은 식에 따른 카르노 맵
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
showing[i][j] = 0; // 배열 값을 모두 0으로 세팅함
// 중복값 제거
int arrDecimal_cleaned[100]; // arrDecimal_cleaned[]: 수식들의 minterm을 저장하는 배열 (중복 값 제거)
int sup2 = 0; // sup2: 'arrDecimal_cleaned[]'의 원소의 갯수
for(int i=0; i<sup; i++){
bool isDuplicate = false; // isDuplicate: 중복된 값일 경우 true, 아니면 false
int num = arrDecimal[i]; // num: minterm이 저장된 배열로부터 숫자를 받음
for(int j=0; j<sup2; j++){
if(num == arrDecimal_cleaned[j]) // 중복된 값을 발견했을 경우 true로 변경
isDuplicate = true; // bool 변수를 true로 변경
}
if(isDuplicate == false){ // 해당 값이 중복된 값이 아닐 경우
arrDecimal_cleaned[sup2] = num; // minterm을 배열에 저장함
sup2++; // 원소의 갯수: +1
}
}
int k = sup2-1; // k: 'arrDecimal_cleaned[]'의 보조 변수
while(k >= 0){
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
if(kmap[i][j] == arrDecimal_cleaned[k]){ // minterm이 들어갈 k-map의 위치를 찾았을 경우
showing[i][j] = 1; // 해당 위치를 1로 지정함
break; // 끝내고 다음 minterm이 들어갈 위치를 찾음
}
k--; // 배열에서 값을 계속 빼내기 위해 1만큼 감소시킴
}
cout << "Minterm : "; // 선 출력문
for(int i=0; i<sup2; i++)
cout << arrDecimal_cleaned[i] << " "; // minterm 값을 출력함
cout << endl;
cout << "K-map : " << endl; // 선 출력문
for(int i=0; i<4; i++){
for(int j=0; j<4; j++)
cout << showing[i][j]; // k-map을 출력함
cout << endl;
}
} |
db1e35098b36b17e415d25685ae500b100fb60ce | da13476293be1a3f3fe011b64d0c22fe22053930 | /搬寝室DP.cpp | e73d116ce4e8c387e5e400542dbda87f9a289329 | [] | no_license | dongZheX/Coding | 4138bccbc3683329f7571b2cac56180f8d8399b3 | 6be5f801876b28b5abd574d98995b893e39e3279 | refs/heads/master | 2020-07-11T18:40:45.172457 | 2019-08-27T04:02:58 | 2019-08-27T04:02:58 | 204,617,001 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 934 | cpp | 搬寝室DP.cpp | #include<cstdio>
#include<algorithm>
using namespace std;
int dp[1001][2002];
int main() {
int k;
int n;
int i;
int j;
int list[2002];
while(scanf("%d%d", &n, &k) != EOF) {
for (i = 1;i <= n;i++)
scanf("%d", &list[i]);
for (i = 0;i <= n;i++)
dp[0][i] = 0;
sort(list+1, list + n + 1);
for (i = 1;i <= k;i++) {
for (j = 2 * i;j <= n;j++) {
//dp[i][j]表示前j物品搬i对的最小疲劳度
if (j == 2 * i) {
dp[i][j] = dp[i - 1][j - 2] + (list[j] - list[j - 1])*(list[j] - list[j - 1]);
}
else {
int x = dp[i][j - 1];
int y = dp[i - 1][j - 2] + (list[j] - list[j - 1])*(list[j] - list[j - 1]);
//看新加入的j的影响,而且他必须跟他前面的配对,所以状态方程就是比较j-1个物品和前j个物品且用了倒数两个的情况 或者直接可以说第j个用还是不用
dp[i][j] = x > y ? y : x;
}
}
}
printf("%d\n", dp[k][n]);
}
} |
e7528da69a40c2707a4a97e4f810d5e715d1ca4a | 6eefc187a14b7b390f32313d2f8ff91a667feba1 | /1312【例3.4】昆虫繁殖.cpp | 1faca5172088bfb5e3b5f871a5b652d06538e384 | [] | no_license | yuhy916/Olympic | b8bbaff7b9a566d2a6ca40b47a7c31a11d19f8f3 | a0356f9f23bfa40aeea235e75505fa8652f6219e | refs/heads/master | 2021-05-12T14:18:42.923868 | 2018-02-07T16:41:11 | 2018-02-07T16:41:11 | 116,955,184 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 856 | cpp | 1312【例3.4】昆虫繁殖.cpp | /*
【题目描述】
科学家在热带森林中发现了一种特殊的昆虫,这种昆虫的繁殖能力很强。每对成虫过x个月产y对卵,每对卵要过两个月长成成虫。假设每个成虫不死,第一个月只有一对成虫,且卵长成成虫后的第一个月不产卵(过X个月产卵),问过Z个月以后,共有成虫多少对?0≤X≤20,1≤Y≤20,X≤Z≤50。
【输入】
x,y,z的数值。
【输出】
过Z个月以后,共有成虫对数。
【输入样例】
1 2 8
【输出样例】
37
*/
#include <iostream>
using namespace std;
int main()
{
int x, y, z;
while (cin >> x >> y >> z)
{
long long a[101] = {0}, b[101] = {0};
for (int i = 1; i <= x; i++)
a[i] = 1;
for (int i = x+1; i <= z+1; i++)
{
b[i] = y * a[i-x];
a[i] = a[i-1] + b[i-2];
}
cout << a[z+1] << endl;
}
return 0;
}
|
cda8f049346df21d58af4bd6752ca6600657048a | 7b302026e0cf51e916c88cb0c44cc868815e3f6c | /Веселый Зомби Фермер/Node.cpp | 0b3197ed75b6bc54b3b763fcbac33f170f6f837a | [] | no_license | iam1mPerec/ZombieFarm | d590ef420b9af8af77ac56de66d4202fb2850ccd | c302d5641ac021d52ac2e9b9be71766c58c478fe | refs/heads/master | 2023-01-27T11:52:26.962930 | 2020-12-12T17:53:36 | 2020-12-12T17:53:36 | 312,341,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | Node.cpp | #include "Node.h"
#include <iostream>
using namespace std;
node::node(char* pName, int pValue):
PropName(pName),
PropValue(pValue)
{
}
node::node(char* pName):
PropName(pName),
PropValue(0)
{
} |
512053ccca3b02e947b0ac99b0f74152d6ee34e7 | 929bfc7f53782bc9555193a794ef60ca2bff7854 | /drug.cpp | 39fddf32ef49fd68edf68d923dad79a6d63619f1 | [] | no_license | 15831944/MFC-Login | c603f0867587a94dba162901d479b1e2bbfebd4b | 521128266c8cf072318cc4c74547fc295ea3a099 | refs/heads/master | 2023-03-17T10:21:10.461718 | 2017-12-26T01:12:06 | 2017-12-26T01:12:06 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 435 | cpp | drug.cpp | // drug.cpp : 实现文件
//
#include "stdafx.h"
#include "LoginTest.h"
#include "drug.h"
#include "afxdialogex.h"
// drug 对话框
IMPLEMENT_DYNAMIC(drug, CDialogEx)
drug::drug(CWnd* pParent /*=NULL*/)
: CDialogEx(drug::IDD, pParent)
{
}
drug::~drug()
{
}
void drug::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(drug, CDialogEx)
END_MESSAGE_MAP()
// drug 消息处理程序
|
112d402536c3b48c95199b160d69f6a1bbdf3eca | 1c055a1a6e7d1fee1cb5ad9953ba7b8db5f30d35 | /Robot/Main.cpp | ea8bd455555cfe85fe359aa40234e5295fbd6e2a | [] | no_license | ABP1718/Code | 37d372b202130b1976f7a9678350d842624b7317 | c4d5b436510518f21238c4415693f9f43ae783a9 | refs/heads/master | 2021-09-04T03:31:46.409413 | 2018-01-15T10:09:33 | 2018-01-15T10:09:33 | 109,837,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | cpp | Main.cpp | //#include "UR3_Lib.h"
#include "UR_Control.h"
int main()
{
unsigned int usecs = 1000000; //1sec = 1.000.000 usec
//UR3* test = new UR3();
Binzone* zone = new Binzone();
Control* robot = new Control(0.0001,3.0, zone);
cout << "Starting in 2 seconds" << endl;
usleep(2000000);
/*
std::thread safety(&Control::safetyTest, robot_);
cout << "Safety Thread Started" << endl;
std::thread binpicking(&Control::Demo, robot_);
cout << "Started Bin Picking Thread" << endl;
safety.join();
binpicking.join();*/
robot->Demo();
cout << "Done, shutting down" << endl;
return 0;
}
//Control* robot2_ = new Control(0.0001,3.0, zone);
/*while(true){
cout << "Starting in 2 seconds" << endl;
usleep(2000000);
//robot_->Demo(3.0); //ADD SLEEP!
robot_->Demo();
//robot_->robot_->IO_test();
}*/
//c++ UR3_Lib.cpp robot_state.cpp robot_state_RT.cpp ur_realtime_communication.cpp ur_communication.cpp UR_Control.cpp Main.cpp -o test -pthread -std=c++11
|
e47e8072e95f27d84b2a001c0d631969282b3bc2 | 66349a1614e3d2ec7489d445b7892daf475cd700 | /Core/nuMutex.h | 405a99ebdc5069ac749cc6ead709f9f5c095f26e | [] | no_license | SaintNus/nuDE | 81724fca78585103d3bdf7b649ea563acf60cd09 | 41e16c63800a7d856ab86308b45297179103582b | refs/heads/master | 2021-01-19T07:38:42.947937 | 2012-06-16T16:32:43 | 2012-06-16T16:32:43 | 2,604,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | h | nuMutex.h | /*!
* \file nuMutex.h
* \brief Mutex.
* \author Nus
* \date 2011/11/26 22:36
*/
#ifndef __NUMUTEX_H__
#define __NUMUTEX_H__
#include "nuObject.h"
namespace nude
{
template< class T >
class Mutex : public nuObject
{
public:
class Autolock {
Mutex& mMutex;
Autolock();
public:
Autolock(Mutex& mutex)
: mMutex(mutex)
{
mMutex.lock();
}
~Autolock() {
mMutex.unlock();
}
};
Mutex() {}
~Mutex() {}
void lock(void) {
mMutexHandler.lock();
}
void unlock(void) {
mMutexHandler.unlock();
}
bool trylock(void) {
return mMutexHandler.trylock();
}
private:
T mMutexHandler;
};
}
#endif
|
1af2e5145974886540f2f9d84f43c8806d173b8b | eceae66751dd55401f5d241bb55f70761a37ef61 | /ImplementationPhase/Model/ParsingPackage/include/EvenNotEvenDatasetParser.hpp | 2ebaccb1b0dfb83dadfc1d969e5ee5493eaf364e | [] | no_license | JohannesHaering/PSE | 541ec622a35915bd2fbc397f6184fea6391ed965 | 0b068c37925c99dcba25ae178db4376dc47601ba | refs/heads/master | 2022-04-16T23:43:34.421768 | 2020-03-13T10:05:24 | 2020-03-13T10:05:24 | 220,481,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | hpp | EvenNotEvenDatasetParser.hpp | #ifndef EVEN_NOT_EVEN_DATASET_PARSER_H_
#define EVEN_NOT_EVEN_DATASET_PARSER_H_
#include <opencv2/opencv.hpp>
#include <vector>
class EvenNotEvenDatasetParser
{
public:
std::vector<cv::Mat> parseDataset(int numbBits);
std::vector<std::vector<float>> parseDatasetLabel(int numbBits);
private:
cv::Mat parseToMat(std::vector<int> bitst);
};
#endif
|
d8a5472908e9c679b034b4117564593c75de405e | 384e2e93f39d2e800883bba66dfb15014a8d4da6 | /src/ros_utils/tf_transform_broadcaster.cc | a36ed104be0fd1143cc4426b79e3604e7b31f124 | [] | no_license | lisilin013/common | 8ca90b882e2d950fdd6106f0940c48f254565ee2 | e05efb089cd25b8885df14c7af7236ca3f0db3db | refs/heads/master | 2023-02-16T15:49:09.692179 | 2021-01-17T11:30:06 | 2021-01-17T11:30:06 | 321,511,828 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,547 | cc | tf_transform_broadcaster.cc | // Copyright (c) 2020. All rights reserved.
// Author: lisilin013@163.com(Silin Li) on 20-8-31.
#include "common/ros_utils/tf_transform_broadcaster.h"
#include "minkindr_conversions/kindr_msg.h"
#include "minkindr_conversions/kindr_tf.h"
namespace ros_utils {
TfTransformBroadcaster::TfTransformBroadcaster(const std::string &frame_id,
const std::string &child_frame_id)
: frame_id_(frame_id), child_frame_id_(child_frame_id) {
tf_tb_ = std::make_unique<tf::TransformBroadcaster>();
}
void TfTransformBroadcaster::Publish(const kindr::minimal::QuatTransformation &quat_transform,
const ros::Time &stamp) {
tf::Transform transform;
minkindr_conversions::transformKindrToTF(quat_transform, &transform);
tf_tb_->sendTransform(tf::StampedTransform(transform, stamp, frame_id_, child_frame_id_));
}
void TfTransformBroadcaster::Publish(const tf::Transform &transform, const ros::Time &stamp) {
tf_tb_->sendTransform(tf::StampedTransform(transform, stamp, frame_id_, child_frame_id_));
}
void TfTransformBroadcaster::Publish(const nav_msgs::Odometry &odometry) {
tf::Transform transform;
transform.setOrigin(tf::Vector3(odometry.pose.pose.position.x, odometry.pose.pose.position.y,
odometry.pose.pose.position.z));
tf::Quaternion q(odometry.pose.pose.orientation.x, odometry.pose.pose.orientation.y,
odometry.pose.pose.orientation.z, odometry.pose.pose.orientation.w);
transform.setRotation(q);
tf_tb_->sendTransform(
tf::StampedTransform(transform, odometry.header.stamp, frame_id_, child_frame_id_));
}
TfStaticTransformBroadcaster::TfStaticTransformBroadcaster(
const kindr::minimal::QuatTransformation &quat_transform, const std::string &frame_id,
const std::string &child_frame_id)
: transform_(quat_transform), frame_id_(frame_id), child_frame_id_(child_frame_id) {
static_broadcaster_ = std::make_unique<tf2_ros::StaticTransformBroadcaster>();
static_transformStamped_ = std::make_unique<geometry_msgs::TransformStamped>();
}
void TfStaticTransformBroadcaster::Publish(const ros::Time &stamp) {
static_transformStamped_->header.stamp = stamp;
static_transformStamped_->header.frame_id = frame_id_;
static_transformStamped_->child_frame_id = child_frame_id_;
minkindr_conversions::transformKindrToMsg(transform_, &static_transformStamped_->transform);
static_broadcaster_->sendTransform(*static_transformStamped_);
}
} // namespace ros_utils
|
ee9c22cd7ee10d99f515c95826ad863704e2f578 | 616a11240d405214ebca576a66d42d12c2b61a07 | /ProjectAzur/ProjectAzur/MainGame/DrawTask/paDrawTask.h | a6115181726f10a2884363029ef2bbcada18597c | [] | no_license | Sharoku-haga/ProjectAzur | 730f8c540a522be24562cfb6fa75a92c8d92deba | 6ffaa7ee93e689748814d7736de959947ccca372 | refs/heads/master | 2021-09-12T21:15:17.249155 | 2018-01-28T13:57:51 | 2018-01-28T13:57:51 | 108,383,434 | 3 | 0 | null | 2018-01-30T17:27:29 | 2017-10-26T08:29:59 | C++ | UTF-8 | C++ | false | false | 2,279 | h | paDrawTask.h | //==================================================================================================================================//
//!< @file paDrawTask.h
//!< @brief pa::DrawTaskクラスのヘッダ
//!< @author T.Haga
//!< @data 作成日時:2017//11/20 更新履歴:2017//11/29
//==================================================================================================================================//
#ifndef PA_DRAW_TASK_H
#define PA_DRAW_TASK_H
#include <functional>
namespace pa
{
//===================================================================================//
//!< 描画のタスククラス
//===================================================================================//
class DrawTask final
{
public:
/**
* Constructor
* Manager登録もここで行う
* @param[in] priority タスクの優先度. 低い値が優先される
* @param[in] func タスクに登録する描画関数のポインタ
*/
DrawTask(int priority
, std::function<void()> func);
/** Destructor */
~DrawTask();
/** タスク実行関数 */
void Run();
/** タスクをアクティブにする関数 */
void Activate();
/** タスクを非アクティブにする関数 */
void Deactivate();
/** タスクの現在の優先度を元の優先度に戻す関数 */
void ReturnOriginalPriority();
/**
* 現在のタスクの優先度を変更する関数
* @param[in] priority 設定したい優先度
*/
void ChangeCurrentPriority(int priority);
/**
* Getter
* @return このタスクの現在の優先度
*/
inline int GetCurrentPriority() { return m_CurrentPriority; }
private:
int m_OriginalPriority; //!< インスタンス化したときに設定した優先度
int m_CurrentPriority; //!< 現在の優先度
std::function<void()> m_CurrentFunc; //!< 現在のタスク関数
std::function<void()> m_DrawFunc; //!< 描画関数
}; // class DrawTask
} // namespace pa
#endif // PA_DRAW_TASK_H
//==================================================================================================================================//
// END OF FILE
//==================================================================================================================================//
|
b61ff4c944362a6732e13eebf1e7778df5ce2285 | ab68fed73e190c98eebf5e558226d67da860a631 | /Source/TwoColours/Private/TCCharacter.cpp | 64a555f3642bdfc5c674bd15d82df32ce3cab766 | [] | no_license | rohitrtk/UE4_TwoColours | fc1a581a728673b3aa38bd444ca8820f631c5a42 | ac930c2224733c5c9d35b885323023dd191b4bd3 | refs/heads/master | 2020-05-22T08:49:38.026639 | 2019-06-19T19:42:22 | 2019-06-19T19:42:22 | 186,287,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,685 | cpp | TCCharacter.cpp | #include "TCCharacter.h"
#include "GameFramework/SpringArmComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "Components/InputComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/ArrowComponent.h"
#include "Camera/CameraComponent.h"
#include "PaperFlipbookComponent.h"
#include "Blueprint/UserWidget.h"
#include "TimerManager.h"
#include "Kismet/GameplayStatics.h"
#include "TCPlayerController.h"
#include "TCHealthComponent.h"
#include "TCColourComponent.h"
#include "TCProjectile.h"
#include "Materials/MaterialInterface.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "Math/Color.h"
#include "TwoColoursGameModeBase.h"
#include "TwoColours.h"
#include "Sound/SoundBase.h"
ATCCharacter::ATCCharacter()
{
this->GetCapsuleComponent()->SetCapsuleHalfHeight(10.f);
this->GetCapsuleComponent()->SetCapsuleRadius(8.f);
this->GetSprite()->SetRelativeLocation(FVector(0.f, 0.f, -12.f));
this->GetCharacterMovement()->JumpZVelocity = 250.f;
this->GetCharacterMovement()->AirControl = 2.f;
this->GetCharacterMovement()->MaxWalkSpeed = 275.f;
this->GetCharacterMovement()->MaxStepHeight = 12.f;
this->GetCharacterMovement()->SetWalkableFloorAngle(60.f);
this->CameraStartingDistance = 300.f;
this->ZoomHelper.ZoomInterval = 200.f;
this->ZoomHelper.MinOrthoWidth = 280.f;
this->ZoomHelper.MaxOrthoWidth = 1000.f;
this->SpringArmComponent = CreateDefaultSubobject<USpringArmComponent>(TEXT("Spring Arm Component"));
this->SpringArmComponent->SetupAttachment(this->RootComponent);
this->SpringArmComponent->bAbsoluteRotation = true;
this->SpringArmComponent->bDoCollisionTest = false;
this->SpringArmComponent->TargetArmLength = this->CameraStartingDistance;
this->SpringArmComponent->RelativeRotation = FRotator(0.f, -90.f, 0.f);
this->CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera Component"));
this->CameraComponent->bAutoActivate = true;
this->CameraComponent->bUsePawnControlRotation = false;
this->CameraComponent->SetProjectionMode(ECameraProjectionMode::Orthographic);
this->CameraComponent->SetOrthoWidth(348.f);
this->CameraComponent->SetupAttachment(this->SpringArmComponent);
this->PSpawnArrow = CreateDefaultSubobject<UArrowComponent>(TEXT("Projectile Spawn Arrow"));
this->PSpawnArrow->SetupAttachment(RootComponent);
this->HealthComponent = CreateDefaultSubobject<UTCHealthComponent>(TEXT("Health Component"));
this->ColourComponent = CreateDefaultSubobject<UTCColourComponent>(TEXT("Colour Component"));
this->FireTimerHandle.RateOfFire = 120.f;
this->DamageImmuneTime = 2.f;
this->bIsJumping = false;
this->bIsShooting = false;
this->facingRight = 0;
this->respawnTime = 3.f;
}
void ATCCharacter::BeginPlay()
{
Super::BeginPlay();
this->HealthComponent->OnHealthChanged.AddDynamic(this, &ATCCharacter::HandleTakeDamage);
this->GetCapsuleComponent()->OnComponentBeginOverlap.AddDynamic(this, &ATCCharacter::HandleOverlap);
FireTimerHandle.TimeBetweenShots = 60.f / FireTimerHandle.RateOfFire;
}
void ATCCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveRight", this, &ATCCharacter::MoveRight);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ATCCharacter::Jump);
PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &ATCCharacter::StartFire);
PlayerInputComponent->BindAction("Fire", IE_Released, this, &ATCCharacter::StopFire);
PlayerInputComponent->BindAction("ZoomIn", IE_Pressed, this, &ATCCharacter::CameraZoomIn);
PlayerInputComponent->BindAction("ZoomOut", IE_Pressed, this, &ATCCharacter::CameraZoomOut);
}
void ATCCharacter::MoveRight(float delta)
{
AddMovementInput(FVector(1.f, 0.f, 0.f), delta);
}
void ATCCharacter::Jump()
{
if (bIsJumping) return;
Super::Jump();
if (JumpSound)
{
UGameplayStatics::PlaySound2D(GetWorld(), JumpSound, .5f);
}
bIsJumping = true;
}
void ATCCharacter::Landed(const FHitResult& Hit)
{
Super::Landed(Hit);
if (bTookHit)
{
bKnockedDown = true;
}
bIsJumping = false;
}
void ATCCharacter::Tick(float delta)
{
Super::Tick(delta);
ManageAnimations();
}
void ATCCharacter::StartFire()
{
if (!ProjectileClass || bIsJumping || CurrentCharacterState == ECharacterStates::CS_Running)
{
return;
}
float delay = FMath::Max(FireTimerHandle.LastFireTime + FireTimerHandle.TimeBetweenShots - GetWorld()->TimeSeconds, 0.f);
GetWorldTimerManager().SetTimer(FireTimerHandle.TimerHandle_Handler, this, &ATCCharacter::Fire, FireTimerHandle.TimeBetweenShots, true, delay);
}
void ATCCharacter::Fire()
{
if (bIsJumping || CurrentCharacterState == ECharacterStates::CS_Running) return;
bIsShooting = true;
if (ShootSound)
{
UGameplayStatics::PlaySound2D(GetWorld(), ShootSound, .5f);
}
GetCharacterMovement()->StopMovementImmediately();
UE_LOG(LogTemp, Log, TEXT("%s firing Projectile"), *this->GetHumanReadableName());
UArrowComponent* arrowComponent = GetArrowComponent();
if (!arrowComponent) return;
FActorSpawnParameters spawnParameters;
spawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
spawnParameters.Owner = this;
ATCProjectile* projectile =
GetWorld()->SpawnActor<ATCProjectile>(ProjectileClass, PSpawnArrow->GetComponentTransform(), spawnParameters);
FireTimerHandle.LastFireTime = GetWorld()->TimeSeconds;
}
void ATCCharacter::StopFire()
{
bIsShooting = false;
GetWorldTimerManager().ClearTimer(FireTimerHandle.TimerHandle_Handler);
}
void ATCCharacter::CameraZoomIn()
{
CameraZoom(-1);
}
void ATCCharacter::CameraZoomOut()
{
CameraZoom(1);
}
void ATCCharacter::CameraZoom(int zoom)
{
UE_LOG(LogTemp, Log, TEXT("Camera Zoom"));
float newOrthoWidth = this->CameraComponent->OrthoWidth + (zoom * ZoomHelper.ZoomInterval);
this->CameraComponent->OrthoWidth = FMath::LerpStable(this->CameraComponent->OrthoWidth, newOrthoWidth, 0.2f);
CameraComponent->OrthoWidth = FMath::Clamp(CameraComponent->OrthoWidth, ZoomHelper.MinOrthoWidth, ZoomHelper.MaxOrthoWidth);
}
void ATCCharacter::ManageAnimations()
{
FVector playerVelocity = this->GetVelocity();
float playerVelocitySq = playerVelocity.SizeSquared();
if (HealthComponent->GetIsDead())
{
CurrentCharacterState = ECharacterStates::CS_Death;
}
else if (bKnockedDown)
{
CurrentCharacterState = ECharacterStates::CS_KnockDown;
}
else if (bTookHit)
{
CurrentCharacterState = ECharacterStates::CS_Hit;
}
else if (bIsJumping)
{
CurrentCharacterState = ECharacterStates::CS_Jumping;
}
else if (playerVelocitySq > 0.f)
{
CurrentCharacterState = ECharacterStates::CS_Running;
}
else if (bIsShooting)
{
CurrentCharacterState = ECharacterStates::CS_Shoot;
}
else
{
CurrentCharacterState = ECharacterStates::CS_Idle;
}
UpdateAnimations();
float playerDirection = playerVelocity.X;
if (playerDirection > 0.f)
{
Controller->SetControlRotation(FRotator(0.f, 0.f, 0.f));
this->facingRight = 1;
}
else if (playerDirection < 0.f)
{
Controller->SetControlRotation(FRotator(0.f, 180.f, 0.f));
this->facingRight = -1;
}
}
void ATCCharacter::UpdateAnimations()
{
UPaperFlipbook* animation = nullptr;
switch (CurrentCharacterState)
{
case ECharacterStates::CS_Death:
animation = DeathAnimation;
break;
case ECharacterStates::CS_Hit:
animation = HitAnimation;
break;
case ECharacterStates::CS_KnockDown:
animation = KnockedDownAnimation;
break;
case ECharacterStates::CS_Shoot:
animation = ShootingAnimation;
break;
case ECharacterStates::CS_Jumping:
animation = JumpAnimation;
break;
case ECharacterStates::CS_Running:
animation = RunningAnimation;
break;
case ECharacterStates::CS_Idle:
animation = IdleAnimation;
break;
default:
UE_LOG(LogTemp, Warning, TEXT("Character was unable to identify animation!"));
break;
}
if (animation && GetSprite()->GetFlipbook() != animation)
{
GetSprite()->SetFlipbook(animation);
}
}
void ATCCharacter::StartBlink()
{
UE_LOG(LogTemp, Log, TEXT("Starting blink"))
this->HealthComponent->SetCanTakeDamage(false);
GetWorldTimerManager().SetTimer(TimerHandle_Blink, this, &ATCCharacter::Blink, 0.1f, true);
GetWorldTimerManager().SetTimer(TimerHandle_BlinkClear, this, &ATCCharacter::StopBlink, DamageImmuneTime, false);
}
void ATCCharacter::StopBlink()
{
UE_LOG(LogTemp, Log, TEXT("Stopping blink"))
GetWorldTimerManager().ClearTimer(TimerHandle_Blink);
GetWorldTimerManager().ClearTimer(TimerHandle_BlinkClear);
if (!GetSprite()->IsVisible()) GetSprite()->ToggleVisibility();
this->HealthComponent->SetCanTakeDamage(true);
}
void ATCCharacter::Blink()
{
GetSprite()->ToggleVisibility();
}
void ATCCharacter::ManageDeath()
{
ATwoColoursGameModeBase* gameMode = Cast<ATwoColoursGameModeBase>(GetWorld()->GetAuthGameMode());
if (gameMode)
{
UE_LOG(LogTemp, Log, TEXT("Attempting to respawn players through MangeDeath."));
DetachFromControllerPendingDestroy();
gameMode->RespawnPlayers();
}
Destroy();
}
void ATCCharacter::TakeHit()
{
bTookHit = true;
if (HitSound)
{
UGameplayStatics::PlaySound2D(GetWorld(), HitSound, .5f);
}
GetCharacterMovement()->Launch(FVector(-1 * facingRight * 200.f, 0.f, 200.f));
GetWorldTimerManager().SetTimer(TimerHandle_EnableControlAfterHit, this, &ATCCharacter::EnableControl, DamageImmuneTime, false);
}
void ATCCharacter::EnableControl()
{
APlayerController* playerController = Cast<APlayerController>(GetController());
this->EnableInput(playerController);
bTookHit = false;
bKnockedDown = false;
GetWorldTimerManager().ClearTimer(TimerHandle_EnableControlAfterHit);
}
void ATCCharacter::HandleTakeDamage(class UTCHealthComponent* HealthComp, int Lives, const class UDamageType* DamageType,
class AController* InstigatedBy, AActor* DamageCauser)
{
UE_LOG(LogTemp, Log, TEXT("Number of Lives: %d"), Lives);
APlayerController* playerController = Cast<APlayerController>(GetController());
this->DisableInput(playerController);
if (Lives <= 0)
{
this->HealthComponent->SetIsDead(true);
if (DieSound)
{
UGameplayStatics::PlaySound2D(GetWorld(), DieSound, .5f);
}
GetMovementComponent()->StopMovementImmediately();
GetWorldTimerManager().SetTimer(TimerHandle_Death, this, &ATCCharacter::ManageDeath, respawnTime, false);
return;
}
TakeHit();
StartBlink();
}
void ATCCharacter::HandleOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
UE_LOG(LogTemp, Log, TEXT("Character is colliding"));
}
|
443f75141158226a174325d5b6cba05b6b8acfc6 | f993f4944836f06f37916c009c8c1a1cfa729bd3 | /CircularBuffer.h | e478f4af93419a48ec4f7fcb48870710fc60133a | [] | no_license | ccc321q/CppDataStructures | a211c0c5fbc8a834d996a2f05bf6d28f1e4c7f1b | 3669ee0f4204cb54f1f4010ff3a445d9458b62aa | refs/heads/master | 2022-11-05T15:29:47.036501 | 2017-06-28T12:30:01 | 2017-06-28T12:30:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | h | CircularBuffer.h |
#ifndef _CIRCULARBUFFER_H_
#define _CIRCULARBUFFER_H_
template <class T>
class CircularBuffer
{
public:
CircularBuffer()
{
// init the buffer head, tail and count to 0
this->head = 0;
this->tail = 0;
this->count = 0;
};
void pushBack(T value)
{
char t;
if(this->count < BUFFERLEN) // there is room for our value
{
// add value to tail
this->buffer[this->tail] = value;
// increment tail and count
t = this->tail;
if(++t >= BUFFERLEN)
t=0;
this->count++;
this->tail = t;
return; // success
}
};
T popFront()
{
T returnVal;
char t;
if((this->count != 0)) // something is in there
{
this->count--;
// get the return value
returnVal = this->buffer[this->head];
// increment head
t = this->head;
if(++t >= BUFFERLEN)
t=0;
this->head = t;
}
return returnVal;
};
bool isEmpty()
{
return (count == 0);
};
unsigned int itemCount()
{
return count;
};
private:
static const unsigned int BUFFERLEN = 32;
unsigned int head; // head index
unsigned int tail; // tail index
unsigned int count; // number of items in buffer
T buffer[BUFFERLEN]; // the actual buffer contents
};
#endif // _CIRCULARBUFFER_H_
|
1b43edc66ae1f257249503c330d6bd5f3edbaac6 | df05713bb78cf039445e0c5e207a3d32c2f0e1e4 | /undoTest/undo/undocommand.h | c84afe63d5ad0a12cbbf69b06ef9c1c0247ab433 | [] | no_license | haipengyu1013/undoDemo | 21ed4bd1cb92c6658af446e5e39e2fbb03f9f3bb | 79e250e78a5c129ce752a1e1ede55781848048ba | refs/heads/main | 2023-06-05T16:15:25.467542 | 2021-06-29T03:38:34 | 2021-06-29T03:38:34 | 381,229,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | h | undocommand.h | #ifndef UNDOCOMMAND_H
#define UNDOCOMMAND_H
#include <QObject>
#include "undo_global.h"
QT_BEGIN_NAMESPACE
class UndoCommandPrivate;
class UndoCommand : public QObject
//class Q_UNDO_EXPORT UndoCommand : public QObject
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
public:
explicit UndoCommand(UndoCommand *parent = nullptr);
explicit UndoCommand(const QString &text, UndoCommand *parent = nullptr);
virtual ~UndoCommand();
virtual void undo();
virtual void redo();
QString text() const;
QString actionText() const;
void setText(const QString &text);
virtual int id() const;
virtual bool mergeWith(const UndoCommand *other);
int childCount() const;
const UndoCommand *child(int index) const;
Q_SIGNALS:
void textChanged();
private:
Q_DISABLE_COPY(UndoCommand)
Q_DECLARE_PRIVATE(UndoCommand)
friend class UndoStack;
};
QT_END_NAMESPACE
#endif // UNDOCOMMAND_H
|
e129b07594fa33151f8ebab3089242e3d4a7e5c1 | 948aa574a33161c92988fd5795cc7d831a532d8c | /Engine/Utility/Code/Management.cpp | 09ee3160945301487788e38e2a5c70b349c4214b | [] | no_license | eststar/TIGL3D_SR_Forked | d907a7645528f108b378653abc49271a510beb0b | 459687f9e78302d1836692f30b142ec03a77752f | refs/heads/main | 2023-04-02T02:41:39.598795 | 2021-04-04T12:28:50 | 2021-04-04T12:28:50 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,580 | cpp | Management.cpp | #include "Export_Utility.h"
#include "Management.h"
USING(Engine)
IMPLEMENT_SINGLETON(CManagement)
Engine::CManagement::CManagement()
:m_pScene(nullptr)
{
}
Engine::CManagement::~CManagement()
{
Free();
}
Engine::CComponent* CManagement::Get_Component(LAYERID eLayerID, const _int& iIndex, const _tchar* pObjTag, const _tchar* pComponentTag, COMPONENTID eType)
{
if (nullptr == m_pScene)
return nullptr;
return m_pScene->Get_Component(eLayerID, iIndex, pObjTag, pComponentTag, eType);
}
HRESULT Engine::CManagement::Add_GameObject(LAYERID eLayerID, const _int & iIndex, CGameObject * pGameObject)
{
if (nullptr == m_pScene)
return E_FAIL;
if (FAILED(m_pScene->Add_GameObject(eLayerID, iIndex, pGameObject)))
return E_FAIL;
return S_OK;
}
HRESULT Engine::CManagement::SetUp_Scene(CScene* pScene)
{
if (nullptr != m_pScene)
Safe_Release(m_pScene);
Engine::Clear_RenderGroup(); // 씬을 교체하면서 전에 그리던 오브젝트들을 모두 지운다.
m_pScene = pScene;
return S_OK;
}
Engine::_int Engine::CManagement::Update_Scene(const _float& fTimeDelta)
{
if (nullptr == m_pScene)
return -1;
m_pScene->Update_Scene(fTimeDelta);
return 0;
}
void CManagement::LateUpdate_Scene(const _float & fTimeDelta)
{
if (nullptr == m_pScene)
return;
m_pScene->LateUpdate_Scene(fTimeDelta);
}
void Engine::CManagement::Render_Scene(LPDIRECT3DDEVICE9& pGraphicDev)
{
Engine::Render_GameObject(pGraphicDev);
if (nullptr == m_pScene)
return;
m_pScene->Render_Scene();
}
void Engine::CManagement::Free()
{
Safe_Release(m_pScene);
}
|
7a514b0be8d6ce14895c571664a9370cf1dd6191 | 7c92cb901551f1962c1599e670d78a1485f19ca7 | /src/CentralTaxis.h | 9de33cb4447d294fbd2dbf56f8e1d4bb68f1e642 | [] | no_license | anaezes/TaxiCentral | 97672262b4f9436036e6a92ae523f6ac83dc8905 | 1c20a5d1447bd7011bb4916231aeab69dfa895c6 | refs/heads/master | 2021-01-12T17:46:20.743135 | 2016-11-28T10:54:52 | 2016-11-28T10:54:52 | 71,643,643 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,945 | h | CentralTaxis.h | /*
* CentralTaxis.h
*
*/
#pragma once
#include "Customer.h"
#include "PrivateCustomer.h"
#include "CompanyCustomer.h"
#include "Service.h"
#include "Route.h"
#include "Voucher.h"
#include "Date.h"
#include "utilities.h"
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <utility>
#include <math.h>
#include <map>
class Service;
using namespace std;
class CentralTaxis
{
private:
string name;
string customersFile;
string servicesFile;
string routesFile;
string vouchersFile;
map<int,Voucher*> mapVouchers;
vector<Customer*> customers;
vector<Service*> services;
vector<Route*> routes;
public:
CentralTaxis(string name, string vouchersFile, string customersFile, string servicesFile, string routesFile);
~CentralTaxis();
void loadVouchers(map<int,Voucher*>&);
vector<Customer*> getCustomers() const;
vector<Service*> getServices() const;
vector<Route*> getRoutes() const;
string getCustomersFileName() const;
string getServicesFileName() const;
void editCustomerName();
void editCustomerAddress();
void editCustomerPhoneNumber();
void removeCustomer();
Customer* insertNewCustomer();
void saveCustomers();
void removeRoute();
void insertNewRoute();
Route* insertNewRoute(string, string);
void saveRoutes();
void insertNewService();
Customer* processCustomerNewService();
Route* findRoute(string, string);
Route* processRouteNewService();
int processTimeService();
string processTypeOfPayment(Customer*);
void processExtraRateService(double&, string);
bool useDiscount(Customer*, float);
bool offerVoucher(CompanyCustomer*);
void saveServices();
void saveVouchers();
bool readFile(const string&, vector<string>&);
bool readVouchersFile(map<int, Voucher*>&);
bool readCustomersFile(const map<int, Voucher*> &);
bool readServicesFile();
bool readRoutesFile();
void printVoucherTable();
void showDiscounts();
};
|
c6993fbf3eb3ef114ee45ffe626d68f0e0e51954 | cd470ad61c4dbbd37ff004785fd6d75980987fe9 | /Luogu/1341 无序字母对/DFS,欧拉路/std.cpp | d6b1892cba155ba2253a0736e19ea725a1081c71 | [] | no_license | AutumnKite/Codes | d67c3770687f3d68f17a06775c79285edc59a96d | 31b7fc457bf8858424172bc3580389badab62269 | refs/heads/master | 2023-02-17T21:33:04.604104 | 2023-02-17T05:38:57 | 2023-02-17T05:38:57 | 202,944,952 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 754 | cpp | std.cpp | #include <cstdio>
#include <cctype>
#define For(i,a,b) for(register int i=(int)(a);i<=(int)(b);++i)
#define Fod(i,a,b) for(register int i=(int)(a);i>=(int)(b);--i)
using namespace std;
int n,e[55][55],d[55],s,u,m,ans[3005];
inline void dfs(int u){
For(v,1,52) e[u][v]?e[u][v]=e[v][u]=0,dfs(v),0:0;
ans[++m]=u;
}
int main(){
scanf("%d",&n);
For(i,1,n){
char a,b;
while(!isalpha(a=getchar()));
b=getchar(),a=isupper(a)?a-64:a-70,b=isupper(b)?b-64:b-70;
e[a][b]=e[b][a]=1,d[a]++,d[b]++;
}
For(i,1,52) d[i]&1?++s,!u?u=i:0:0;
if(s>2) return printf("No Solution"),0;
if(!u) For(i,1,52) !u&&d[i]?u=i:0;
dfs(u);
Fod(i,m,1) putchar(ans[i]<=26?ans[i]+64:ans[i]+70);
}
|
42d0da244141266c250e625cbc32ade50da87aae | cd3eb264a9e1f61f69a692ed12bdafa476ad5cf4 | /src/mahjongCore/Perspective.h | 817cd4632da43db52360346c7bf34a01d5929f42 | [
"MIT"
] | permissive | nerds-odd-e/mahjong | be5b63077ba6347e92f14dea0ee9e4a2eb6ed1f6 | e4fa21cc68b869394d123e0fa0957d0c7e4d70aa | refs/heads/master | 2022-12-23T19:56:14.877008 | 2019-12-02T09:12:57 | 2019-12-02T09:12:57 | 218,472,201 | 6 | 0 | NOASSERTION | 2022-12-13T05:58:22 | 2019-10-30T07:55:24 | C++ | UTF-8 | C++ | false | false | 1,099 | h | Perspective.h | #ifndef PLAYER_H_
#define PLAYER_H_
#include "tile.h"
#include "PlayerActionRequest.h"
#include "Settings.h"
class Player {
public:
Player(Settings & settings) : currentActionRequest_(NO_ACTION, NO_TILE), settings_{settings} {}
virtual ~Player(){}
virtual void deal(const Tile tiles[], int n, int distance)=0;
virtual void pick(Tile tile, int distance)=0;
virtual void pong(Tile tile, int distance)=0;
virtual int chow(Tile tile, Tile with, int distance)=0;
virtual void win(int score, int distance)=0;
virtual void discard(Tile tile, int distance)=0;
virtual PlayerActionRequest takeActionRequest(){
PlayerActionRequest saved = currentActionRequest_;
currentActionRequest_.action_ = NO_ACTION;
return saved;
}
virtual PlayerActionRequest* takeActionRequest1(){
return ¤tActionRequest_;
}
virtual void pushActionRequest(PlayerActionRequest *actionRequest)=0;
protected:
void UserWon() {settings_.GetGameLevel().Won();}
void UserLost() {settings_.GetGameLevel().Lost();}
PlayerActionRequest currentActionRequest_;
Settings & settings_;
};
#endif /* PLAYER_H_ */
|
6f68e506e91e2c3a1526da8a53f40e7f55666f92 | b30d612758b4661363fff1a8e73900466821bb74 | /Engine/Math/vec2.cpp | 8431ee44f495ed2be1426d229b8134d6e3b444b6 | [] | no_license | Richy321/Engine | 7e3e9668d5b04671e8fa99c567eb0180aa0c82fa | 9f0e7c637a260f729f5a34264b4548d94838dd90 | refs/heads/master | 2020-04-15T15:22:27.956280 | 2016-06-01T00:58:37 | 2016-06-01T00:58:37 | 43,676,989 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,976 | cpp | vec2.cpp | #include "vec2.h"
using namespace Math;
vec2 vec2::Zero(0, 0);
#pragma region Construction/Destruction
vec2::vec2()
{
}
vec2::vec2(float nx, float ny) : x(nx), y(ny)
{
}
Math::vec2::vec2(vec2 &rhs) : x(rhs.x), y(rhs.y)
{
}
vec2::~vec2()
{
}
#pragma endregion
vec2& Math::vec2::operator=(const vec2 &rhs)
{
x = rhs.x;
y = rhs.y;
return *this;
}
bool Math::vec2::operator==(const vec2 & rhs)
{
return x == rhs.x && y == rhs.y;
}
float vec2::Length() const
{
return sqrt(x*x + y*y);
}
#pragma region Unary operations
//Unary minus returns negative of the vector
vec2 Math::vec2::operator-() const
{
return vec2(-x, -y);
}
#pragma endregion
#pragma region scalar operations
vec2 Math::vec2::operator+=(const float s) const
{
return vec2(x + s, y + s);
}
vec2 Math::vec2::operator-=(const float s) const
{
return vec2(x - s, y - s);
}
vec2 Math::vec2::operator*=(const float s) const
{
return vec2(x*s, y*s);
}
vec2 Math::vec2::operator/=(const float s) const
{
float recip = 1.0f / s; // one div by s and multiplying by recip*3 is faster than div by s
return vec2(x*recip, y*recip);
}
vec2 &Math::vec2::operator+=(const float s)
{
x += s;
y += s;
return *this;
}
vec2 &Math::vec2::operator-=(const float s)
{
x -= s;
y -= s;
return *this;
}
vec2 & Math::vec2::operator/=(const float s)
{
float recip = 1.0f / s;
x /= recip;
y /= recip;
return *this;
}
vec2 & Math::vec2::operator*=(const float s)
{
x *= s;
y *= s;
return *this;
}
#pragma endregion
#pragma region vector operations
vec2 Math::vec2::operator+(const vec2 rhs) const
{
return vec2(x + rhs.x, y + rhs.y);
}
vec2 Math::vec2::operator-(const vec2 rhs) const
{
return vec2(x - rhs.x, y - rhs.y);
}
void Math::vec2::normalize()
{
float magnitudeSquared = x*x + y*y;
if (magnitudeSquared > 0)
{
float magRecip = 1.0f / magnitudeSquared;
x *= magRecip;
y *= magRecip;
}
}
float Math::vec2::dot(const vec2 rhs) const
{
return x*rhs.x + y*rhs.y;
}
#pragma endregion |
25435723b03f574bf354d94e15e65bd982a1e384 | a15950e54e6775e6f7f7004bb90a5585405eade7 | /chrome/browser/ui/infobar_container_delegate.cc | 9009035803ae0c0db9bcc50038786b32e8084203 | [
"BSD-3-Clause"
] | permissive | whycoding126/chromium | 19f6b44d0ec3e4f1b5ef61cc083cae587de3df73 | 9191e417b00328d59a7060fa6bbef061a3fe4ce4 | refs/heads/master | 2023-02-26T22:57:28.582142 | 2018-04-09T11:12:57 | 2018-04-09T11:12:57 | 128,760,157 | 1 | 0 | null | 2018-04-09T11:17:03 | 2018-04-09T11:17:03 | null | UTF-8 | C++ | false | false | 525 | cc | infobar_container_delegate.cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/infobar_container_delegate.h"
#if defined(TOOLKIT_VIEWS)
#include "ui/views/window/non_client_view.h"
#endif
// static
#if defined(OS_MACOSX)
const int InfoBarContainerDelegate::kSeparatorLineHeight = 1;
#else
const int InfoBarContainerDelegate::kSeparatorLineHeight =
views::NonClientFrameView::kClientEdgeThickness;
#endif
|
77f432cb2ea826af0992e85f69f89e8ccab99713 | de675fc694cc6851145ef4705c6bd4f90e2d532b | /llrb-test.cpp | b1dee38a23d82c6e575972343433765cdb61fc4b | [
"Apache-2.0"
] | permissive | baiger/LLRB-demo | 96212cc580e06930b8a80a4fdbfd045685b02dc0 | dce249e3932095093e6b709a3b24a822b2488f47 | refs/heads/master | 2016-08-12T02:34:43.127542 | 2015-11-27T22:58:31 | 2015-11-27T22:58:31 | 47,002,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | cpp | llrb-test.cpp | #include "llrb.h"
#include <iostream>
int main(int argc, char *argv[])
{
LLRB tree;
std::string command;
std::cin >> command;
while (command != "exit") {
if (command == "insert") {
int key;
std::cin >> key;
tree.insert(key);
} else if (command == "print") {
std::cout << tree;
}
std::cin >> command;
}
return 0;
}
|
afe47962ef06826a6df25128413135de07275f8b | 08df76546448792c53c26770e4ccc2bf7644542d | /LINKED_LIST/PalindromeList.cpp | c52ffb0a558ded9309a7f6b0c388d432e0f85c83 | [] | no_license | HarshitaSonkar/InterviewBit | 8e8a11972e3058eca81f69649b4c9da41c0f1a96 | bf19104e5a4ae5b45ca37d197030d7b9d4e8b1ea | refs/heads/master | 2022-11-15T19:33:43.339116 | 2020-07-16T17:44:03 | 2020-07-16T17:44:03 | 237,727,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | PalindromeList.cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int Solution::lPalin(ListNode* A) {
ListNode *temp=A;
stack<ListNode*> s;
while(temp!=NULL)
{
s.push(temp);
temp=temp->next;
}
while(!s.empty())
{
if(s.top()->val!=A->val)
{
return 0;
}
s.pop();
A=A->next;
}
return 1;
}
|
a2cc2fea4a772ebd43188149412d908b29a57a19 | f8ba9a974ad2e39a8c4f4ee3e495ac86029f6167 | /HashTable.h | 3186b258d5adde3e51d0acd2b439939ee82df82e | [] | no_license | froprintoai/HashTable | 7d485520d57cbb39e9bbe9acde8a02341ecbb3fe | d77ec520214db25354167c3449f84c3fbea9efc1 | refs/heads/master | 2020-12-22T18:58:59.946004 | 2020-01-29T04:12:23 | 2020-01-29T04:12:23 | 236,899,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,222 | h | HashTable.h | #ifndef HASHTABLE_H_
#define HASHTABLE_H_
#include "prime.h"
#include <vector>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
template <typename valueType, typename keyType>
class HTEntry
{
public:
HTEntry()
{}
HTEntry(
const valueType& value,
keyType key
)
:m_value(value), m_key(key) {}
HTEntry(const HTEntry<valueType, keyType>& copySource)
{
m_key = copySource.m_key;
m_value = copySource.m_value;
}
HTEntry<valueType, keyType>& operator=(const HTEntry<valueType, keyType>& left)
{
m_key = left.m_key;
m_value = left.m_value;
}
keyType GetKey() const
{
return m_key;
}
const valueType& GetValue() const
{
return m_value;
}
void SetKey(const keyType& key)
{
m_key = key;
}
void SetValue(const valueType& value)
{
m_value = value;
}
private:
keyType m_key;
valueType m_value;
};
/*
template <typename valueType>
class HTOpenAddressing
{
public:
//Constructor
//assumption : dynEntryArray doesn't have a pair of elements whose keys are the same
HTOpenAddressing(double loadFactor, const vector<HTEntry<valueType, unsigned int>>& dynEntryArray)
:m_numElements(0)
{
if (loadFactor > 0 && loadFactor < 1)
m_loadFactor = loadFactor;
else
m_loadFactor = 0.1;
m_numSlot = GetPrimeLargerThan(dynEntryArray.size() / m_loadFactor);
m_empty = m_numSlot + 1;
m_hashTable = vector<HTEntry<valueType, unsigned int>>(m_numSlot);
//Initialize all elements to have m_empty value
for_each (m_hashTable.begin(),
m_hashTable.end(),
[this] (auto& element) {
element.SetKey(this->m_empty);
});
for_each (dynEntryArray.cbegin(),
dynEntryArray.cend(),
[this](auto& element) {
this->Insert(element);
});
m_loadFactor = m_numElements / double(m_numSlot);
}
double GetLoadFactor()
{
return m_loadFactor;
}
void Insert(const HTEntry<valueType, unsigned int>& entry)
{
int insertedIndex = 0;
unsigned int key = entry.GetKey();
int i = 0;
for (; i < m_numSlot; i++)
{
insertedIndex = doubleHashing(key, i);
if (m_hashTable[insertedIndex].GetKey() == m_empty)
{
m_hashTable[insertedIndex] = entry;
m_numElements++;
break;
}
}
if (i == m_numSlot)
cout << "Insertion Failed" << endl;
}
unsigned int Search(unsigned int key)
{
unsigned int returnIndex = m_empty;
unsigned int workingIndex = 0;
for (int i = 0; i < m_numSlot; i++)
{
workingIndex = doubleHashing(key, i);
unsigned int foundKey = m_hashTable[workingIndex].GetKey();
if (foundKey == key)
{
returnIndex = workingIndex;
break;
}
else if (foundKey == m_empty || i == (m_numSlot - 1))
{
cout << "not found" << endl;
break;
}
}
return returnIndex;
}
void Show() const
{
cout << "load factor :" << m_loadFactor << endl;
cout << "number of slot : " << m_numSlot << endl;
cout << "number of elements :" << m_numElements << endl;
cout << "EMPTY_VALUE : " << m_empty << endl;
int index = 0;
for_each(m_hashTable.cbegin(),
m_hashTable.cend(),
[this, index] (auto& element) mutable {
cout << index++ << " : ";
if (element.GetKey() == this->m_empty)
cout << "empty" << endl;
else
cout << element.GetKey() << endl;
});
}
private:
unsigned int doubleHashing(unsigned int key, unsigned int i)
{
return (h1(key) + i * h2(key)) % m_numSlot;
}
unsigned int h1(unsigned int key)
{
return key % m_numSlot;
}
unsigned int h2(unsigned int key)
{
return key % (m_numSlot - 1) + 1;
}
vector<HTEntry<valueType, unsigned int>> m_hashTable;
double m_loadFactor;
unsigned int m_numSlot;
unsigned int m_numElements;
unsigned int m_empty;
};
*/
//This version implements deletion
template <typename valueType>
class HTOpenAddressing
{
public:
HTOpenAddressing()
:m_loadFactor(0),
m_numSlot(0),
m_numElements(0),
m_empty(0),
m_deleted(0)
{}
//Constructor
//assumption : dynEntryArray doesn't have a pair of elements whose keys are the same
HTOpenAddressing(double loadFactor, const vector<HTEntry<valueType, unsigned int>>& dynEntryArray)
:m_numElements(0)
{
if (loadFactor > 0 && loadFactor < 1)
m_loadFactor = loadFactor;
else
m_loadFactor = 0.1;
m_numSlot = GetPrimeLargerThan(dynEntryArray.size() / m_loadFactor);
m_empty = m_numSlot + 1;
m_deleted = m_numSlot + 2;
m_hashTable = vector<HTEntry<valueType, unsigned int>>(m_numSlot);
//Initialize all elements to have m_empty value
for_each (m_hashTable.begin(),
m_hashTable.end(),
[this] (auto& element) {
element.SetKey(this->m_empty);
});
for_each (dynEntryArray.cbegin(),
dynEntryArray.cend(),
[this](auto& element) {
this->Insert(element);
});
m_loadFactor = m_numElements / double(m_numSlot);
}
//Constructor
HTOpenAddressing(unsigned int numSlot)
{
m_numElements = 0;
m_loadFactor = 0;
m_numSlot = GetPrimeLargerThan(numSlot);
m_empty = m_numSlot + 1;
m_deleted = m_numSlot + 2;
m_hashTable = vector<HTEntry<valueType, unsigned int>>(m_numSlot);
//Initialize all elements to have m_empty value
for_each (m_hashTable.begin(),
m_hashTable.end(),
[this] (auto& element) {
element.SetKey(this->m_empty);
});
}
HTOpenAddressing(const HTOpenAddressing<valueType>& source)
{
m_hashTable = source.m_hashTable;
m_loadFactor = source.m_loadFactor;
m_numSlot = source.m_numSlot;
m_numElements = source.m_numElements;
m_empty = source.m_empty;
m_deleted = source.m_deleted;
m_emptyEntry = source.m_emptyEntry;
}
HTOpenAddressing<valueType>& operator=(const HTOpenAddressing<valueType> rightSource)
{
m_hashTable = rightSource.m_hashTable;
m_loadFactor = rightSource.m_loadFactor;
m_numSlot = rightSource.m_numSlot;
m_numElements = rightSource.m_numElements;
m_empty = rightSource.m_empty;
m_deleted = rightSource.m_deleted;
m_emptyEntry = rightSource.m_emptyEntry;
}
double GetLoadFactor()
{
m_loadFactor = m_numElements / (double)m_numSlot;
return m_loadFactor;
}
void Insert(const HTEntry<valueType, unsigned int>& entry)
{
int insertedIndex = 0;
unsigned int key = entry.GetKey();
int i = 0;
for (; i < m_numSlot; i++)
{
insertedIndex = doubleHashing(key, i);
if (m_hashTable[insertedIndex].GetKey() == m_empty || m_hashTable[insertedIndex].GetKey() == m_deleted)
{
m_hashTable[insertedIndex] = entry;
m_numElements++;
break;
}
}
if (i == m_numSlot)
cout << "Insertion Failed" << endl;
}
unsigned int Search(unsigned int key)
{
unsigned int returnIndex = m_empty;
unsigned int workingIndex = 0;
for (int i = 0; i < m_numSlot; i++)
{
workingIndex = doubleHashing(key, i);
unsigned int foundKey = m_hashTable[workingIndex].GetKey();
if (foundKey == key)
{
returnIndex = workingIndex;
break;
}
else if (foundKey == m_empty || i == (m_numSlot - 1))
{
cout << "not found" << endl;
break;
}
}
return returnIndex;
}
void Delete(unsigned int key)
{
unsigned int workingIndex = 0;
for (int i = 0; i < m_numSlot; i++)
{
workingIndex = doubleHashing(key, i);
unsigned int foundKey = m_hashTable[workingIndex].GetKey();
if (foundKey == key)
{
m_hashTable[workingIndex].SetKey(m_deleted);
m_numElements--;
cout << "deleted" << endl;
break;
}
else if (foundKey == m_empty || i == (m_numSlot - 1))
{
cout << "not found to be deleted" << endl;
break;
}
}
}
HTEntry<valueType, unsigned int>& operator[] (const unsigned int key)
{
unsigned int foundIndex = Search(key);
if (foundIndex == m_empty || foundIndex == m_deleted)
{
return m_emptyEntry;
}
else
{
return m_hashTable[foundIndex];
}
}
void Show() const
{
cout << "load factor :" << m_loadFactor << endl;
cout << "number of slot : " << m_numSlot << endl;
cout << "number of elements :" << m_numElements << endl;
cout << "EMPTY_VALUE : " << m_empty << endl;
int index = 0;
for_each(m_hashTable.cbegin(),
m_hashTable.cend(),
[this, index] (auto& element) mutable {
cout << index++ << " : ";
if (element.GetKey() == this->m_empty)
cout << "empty" << endl;
else if (element.GetKey() == this->m_deleted)
cout << "deleted" << endl;
else
cout << element.GetKey() << endl;
});
}
unsigned int GetEmptyKey()
{
return m_empty;
}
private:
unsigned int doubleHashing(unsigned int key, unsigned int i)
{
return (h1(key) + i * h2(key)) % m_numSlot;
}
unsigned int h1(unsigned int key)
{
return key % m_numSlot;
}
unsigned int h2(unsigned int key)
{
return key % (m_numSlot - 1) + 1;
}
vector<HTEntry<valueType, unsigned int>> m_hashTable;
double m_loadFactor;
unsigned int m_numSlot;
unsigned int m_numElements;
unsigned int m_empty;
unsigned int m_deleted;
HTEntry<valueType, unsigned int> m_emptyEntry;
};
struct AB
{
AB()
:m_a(0), m_b(0), m_key(0) {}
AB(unsigned int a, unsigned int b, unsigned int key)
:m_a(a), m_b(b), m_key(key) {}
unsigned int m_a;
unsigned int m_b;
unsigned int m_key;
};
//valueType must have default constructor
//Universal Hashing and Chaining
template <typename valueType>
class HTUnivChaining
{
public:
//constructor
//assumption : dynEntryArray doesn't have a pair of elements whose keys are the same
//maxKey is a key value which is must be the possible maximum value the keys could be
//maxNumElements is an expected max number of elements which will be stored in the future
HTUnivChaining(unsigned int numSlot,
const vector<HTEntry<valueType, unsigned int>>& dynEntryArray,
unsigned int maxKey,
unsigned int maxNumElements)
:m_numSlot(numSlot)
{
m_prime = GetPrimeLargerThan(maxKey);
m_hashTable.resize(numSlot);
HTOpenAddressing<AB> abHashTable(maxNumElements);
m_abHashTable = abHashTable;
for_each(dynEntryArray.cbegin(),
dynEntryArray.cend(),
[this] (auto& element)
{
this->Insert(element);
});
m_loadFactor = m_numElements / m_numSlot;
}
void Insert(const HTEntry<valueType, unsigned int>& entry)
{
unsigned int key = entry.GetKey();
//pick a and b randomly
unsigned int a = GetRandomValue(m_prime - 1) + 1;
unsigned int b = GetRandomValue(m_prime);
//calculate slot number using universal hashing
unsigned int slot = universalHash(a, b, key);
//insert entry into m_hashTable
m_hashTable[slot].push_back(entry);
//record a and b with key value into m_abHashTable
HTEntry<AB, unsigned int> abEntry(AB(a, b, key), key);
m_abHashTable.Insert(abEntry);
m_numElements++;
}
const valueType& Search(unsigned int key)
{
//get a & b value from m_abHashTable
if (m_abHashTable[key].GetKey() == m_abHashTable.GetEmptyKey())
{
cout << "Not Found" << endl;
return m_emptyValue;
}
else
{
AB ab = m_abHashTable[key].GetValue();
//calculate slot using a b and key by universalHash
unsigned int slot = universalHash(ab.m_a, ab.m_b, key);
//list<HTEntry<valueType, unsigned int>>::iterator ite;
auto ite = m_hashTable[slot].cbegin();
for (; ite != m_hashTable[slot].cend(); ite++)
{
if ((*ite).GetKey() == key)
break;
}
if (ite == m_hashTable[slot].cend())
{
//not found
cout << "not found from HTUnivChaining::Search" << endl;
return m_emptyValue;
}
else
{
return (*ite).GetValue();
}
}
}
void Delete(unsigned int key)
{
if (m_abHashTable[key].GetKey() == m_abHashTable.GetEmptyKey())
{
cout << "Not Found" << endl;
}
else
{
AB ab = m_abHashTable[key].GetValue();
//calculate slot using a b and key by universalHash
unsigned int slot = universalHash(ab.m_a, ab.m_b, key);
auto ite = m_hashTable[slot].begin();
for (; ite != m_hashTable[slot].end(); ite++)
{
if ((*ite).GetKey() == key)
break;
}
if (ite == m_hashTable[slot].cend())
{
//not found
cout << "not found from HTUnivChaining::Delete" << endl;
}
else
{
m_hashTable[slot].erase(ite);
}
}
}
void Show()
{
int index = 0;
for_each(m_hashTable.cbegin(),
m_hashTable.cend(),
[&index] (auto& element) mutable {
cout << index++ << " : ";
for_each(element.cbegin(),
element.cend(),
[] (auto& e){
cout << " --> " << e.GetKey();
});
cout << endl;
});
}
private:
unsigned int universalHash(unsigned int a, unsigned int b, unsigned int key)
{
return ((a * key + b) % m_prime) % m_numSlot;
}
unsigned int m_numSlot;
unsigned int m_prime;
vector<list<HTEntry<valueType, unsigned int>>> m_hashTable;
HTOpenAddressing<AB> m_abHashTable;
unsigned int m_numElements;
unsigned int m_loadFactor;
valueType m_emptyValue;
};
#endif |
38d7192b3b3266ea1d20af65c110200a2b571eaf | cc2b07d9e4266efcc830451adfb69b925ec10867 | /RenderSystems/GL3Plus/include/OgreGL3PlusHardwareOcclusionQuery.h | a5fe9f5029a244b4f75fe9d10b7ad4706a24e4af | [
"MIT"
] | permissive | OGRECave/ogre | 74c9c318d95010a3e5fba9709ffebc7e781f27a2 | 15631ca2dd44bd0c925e33411bee05ccac95fc55 | refs/heads/master | 2023-09-04T21:08:30.326815 | 2023-09-02T10:49:34 | 2023-09-02T10:49:34 | 47,069,819 | 3,716 | 1,178 | MIT | 2023-09-14T05:33:08 | 2015-11-29T15:57:03 | C++ | UTF-8 | C++ | false | false | 3,398 | h | OgreGL3PlusHardwareOcclusionQuery.h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
/*
The nVidia occlusion query extension is defined in glext.h so you don't
need anything else. You do need to look up the function, we provide a
GL3PlusSupport class to do this, which has platform implementations for
getProcAddress. Check the way that extensions like glActiveTextureARB are
initialised and used in glRenderSystem and copy what is done there.
To do: fix so dx7 and DX9 checks and flags if HW Occlusion is supported
See the openGl dito for ideas what to do.
*/
#ifndef __GL3PlusHARDWAREOCCLUSIONQUERY_H__
#define __GL3PlusHARDWAREOCCLUSIONQUERY_H__
#include "OgreGL3PlusPrerequisites.h"
#include "OgreHardwareOcclusionQuery.h"
namespace Ogre {
// If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered
// if the first pass result has too few pixels visible.
// Be sure to render all occluder first and whats out so the RenderQue don't switch places on
// the occluding objects and the tested objects because it thinks it's more effective..
/**
* This is a class that is the base class of the query class for
* hardware occlusion.
*
* @author Lee Sandberg email: lee@abcmedia.se
* Updated on 13/9/2005 by Tuan Kuranes email: tuan.kuranes@free.fr
*/
class _OgreGL3PlusExport GL3PlusHardwareOcclusionQuery : public HardwareOcclusionQuery
{
//----------------------------------------------------------------------
// Public methods
//--
public:
/**
* Default object constructor
*
*/
GL3PlusHardwareOcclusionQuery();
/**
* Object destructor
*/
~GL3PlusHardwareOcclusionQuery();
//------------------------------------------------------------------
// Occlusion query functions (see base class documentation for this)
//--
void beginOcclusionQuery() override;
void endOcclusionQuery() override;
bool pullOcclusionQuery(unsigned int* NumOfFragments) override;
bool isStillOutstanding(void) override;
private:
GLuint mQueryID;
};
}
#endif
|
0ff617656058a4126e91b1889e16a615462a4685 | 82be91341698a16e1da63d3e89482dfd32bd7594 | /Source/AGGPlugin/Classes/AGGContext.h | 78aef8a0a9344bd667c8203acd34717821625813 | [
"MIT"
] | permissive | richmondx/AGGPlugin | 21eca3d943c5265a4dfb20caaa3d3bb402eab1e6 | 308b0a65ce1ddf9b7c92ac23e0b207b4d844c0b0 | refs/heads/master | 2020-03-28T23:59:04.826181 | 2018-02-17T04:36:41 | 2018-02-17T04:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,223 | h | AGGContext.h | //
#pragma once
#include "CoreUObject.h"
#include "SharedPointer.h"
#include "Engine/Texture2D.h"
#include "AGGTypes.h"
#include "AGGPathController.h"
#include "AGGContext.generated.h"
UCLASS(Abstract)
class AGGPLUGIN_API UAGGContext : public UObject
{
GENERATED_BODY()
public:
// BEGIN UObject Interface
virtual void PostInitProperties() override
{
Super::PostInitProperties();
InitContext();
}
virtual void BeginDestroy() override
{
ClearContext();
Super::BeginDestroy();
}
// END UObject Interface
// BEGIN UAGGContext Interface
// Called by CDO, must not be pure virtual
virtual void InitContext() { }
// Called by CDO, must not be pure virtual
virtual void ClearContext() { }
virtual void InitBuffer(int32 w, int32 h, int32 c, bool bSq)
PURE_VIRTUAL(UAGGContext::InitBuffer, );
virtual void ClearBuffer(uint8 ClearVal)
PURE_VIRTUAL(UAGGContext::ClearBuffer, );
UFUNCTION(BlueprintCallable, Category = "AGG")
virtual void RenderContext()
PURE_VIRTUAL(UAGGContext::RenderContext, );
virtual IAGGRenderBuffer* GetBuffer()
PURE_VIRTUAL(UAGGContext::GetBuffer, return nullptr;);
virtual const IAGGRenderBuffer* GetBuffer() const
PURE_VIRTUAL(UAGGContext::GetBuffer, return nullptr;);
virtual EPixelFormat GetPixelFormat()
PURE_VIRTUAL(
UAGGContext::GetPixelFormat,
return EPixelFormat::PF_Unknown;
);
virtual void SetColor(const FColor& Color) { }
virtual void SetColorByte(uint8 Color) { }
FORCEINLINE bool HasValidBuffer() const
{
if (const IAGGRenderBuffer* b = GetBuffer())
{
return b->IsValid();
}
return false;
}
uint8 GetByteAt(int32 X, int32 Y) const
{
if (HasValidBuffer())
{
return GetBuffer()->GetByteAt(X, Y);
}
return 0;
}
UFUNCTION(BlueprintCallable, Category = "AGG")
uint8 GetByteAtUnsafe(int32 X, int32 Y) const
{
return GetBuffer()->GetByteAt(X, Y);
}
// END UAGGContext Interface
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "AGG")
UAGGPathController* GetPathController()
{
return PathController;
}
UFUNCTION(BlueprintCallable, Category = "AGG")
void ClearPath()
{
if (PathController)
PathController->Clear();
}
UFUNCTION(BlueprintCallable, Category = "AGG")
bool Blueprint_HasValidBuffer() const
{
return HasValidBuffer();
}
UFUNCTION(BlueprintCallable, Category = "AGG")
uint8 Blueprint_GetByteAt(int32 X, int32 Y) const
{
return GetByteAt(X, Y);
}
UFUNCTION(BlueprintCallable, Category = "AGG")
uint8 Blueprint_GetByteAtUnsafe(int32 X, int32 Y) const
{
return GetByteAtUnsafe(X, Y);
}
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "AGG")
const TArray<uint8>& GetByteBuffer() const
{
return GetBuffer()->GetByteBuffer();
}
UFUNCTION(BlueprintCallable, Category = "AGG")
void ConstructBuffer(int32 InBufferW, int32 InBufferH, uint8 InClearVal = 0, bool bSquareSize = false)
{
InitBuffer(InBufferW, InBufferH, InClearVal, bSquareSize);
}
UFUNCTION(BlueprintCallable, Category = "AGG")
void ClearBuffer()
{
ClearBuffer(0);
}
UFUNCTION(BlueprintCallable, Category = "AGG")
UTexture2D* CreateTexture(bool bSRGB = false)
{
if (! HasValidBuffer())
{
return nullptr;
}
IAGGRenderBuffer& Buffer( *GetBuffer() );
// Generates transient texture
UTexture2D* texture = Buffer.CreateTransientTexture( GetPixelFormat() );
texture->MipGenSettings = TextureMipGenSettings::TMGS_NoMipmaps;
texture->SRGB = bSRGB ? 1 : 0;
// Flush buffer data
Buffer.CopyTo(texture);
// Update texture resource
texture->UpdateResource();
return texture;
}
UFUNCTION(BlueprintCallable, Category = "AGG")
void CopyFromTexture(UTexture2D* Texture)
{
if (Texture && HasValidBuffer())
{
GetBuffer()->CopyFrom(Texture);
}
}
UFUNCTION(BlueprintCallable, Category = "AGG")
void CopyToTexture(UTexture2D* Texture)
{
if (Texture && HasValidBuffer())
{
GetBuffer()->CopyTo(Texture);
Texture->UpdateResource();
}
}
//FORCEINLINE IAGGRenderBuffer::TRawBuffer GetRawBuffer()
//{
// return GetBuffer()->GetRawBuffer();
//}
FORCEINLINE int32 GetBufferSize()
{
return GetBuffer()->GetBufferSize();
}
FORCEINLINE int32 GetBufferTypeSize()
{
return GetBuffer()->GetTypeSize();
}
//FORCEINLINE bool FlushBuffer(IAGGRenderBuffer::TRawBuffer OutBuffer)
//{
// return GetBuffer()->Flush( OutBuffer );
//}
//FORCEINLINE bool CopyBuffer(IAGGRenderBuffer::TRawBuffer OutBuffer)
//{
// return GetBuffer()->CopyTo( OutBuffer );
//}
protected:
UPROPERTY(Transient)
UAGGPathController* PathController;
};
|
f3bbd3fb994e2cbb1fc5e9366e49b1740e0e2f76 | 4872af1781a6f86b62810d0ce2e45a704a4e4d6a | /Codeforces Rounds/Round #716 Div. 2/tempCodeRunnerFile.cpp | 67277315effa87c97ffdc7dc7081aa053d4ff9da | [] | no_license | JoseJuanSE/Problems | ab63f089bfcdefda028fa7cac9b8e825d03a14dc | ccf4728a2dd0cc20e156d9414a2e9676d036c2ba | refs/heads/master | 2023-05-03T23:58:15.232430 | 2021-05-22T03:03:12 | 2021-05-22T03:03:12 | 308,523,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18 | cpp | tempCodeRunnerFile.cpp |
}while(m!=1); |
827e204bbb1843fbc0c8f2d1ee979eb756c33264 | e50db54265c01bfee67e035942e944bd0c28251a | /register_types.cpp | 150cc33a214545504526a7ba980a1fc33a25ac2c | [
"MIT"
] | permissive | Schroedi/autocomplete_service | cdaf8eead7b56fc0a0aff7d44f7bdb61c11537ff | 107418568acb2d10c81c00dfa061c26492f846cb | refs/heads/master | 2020-04-09T04:43:40.016924 | 2018-12-02T06:23:40 | 2018-12-02T06:23:40 | 160,034,131 | 0 | 0 | MIT | 2018-12-02T10:00:37 | 2018-12-02T10:00:36 | null | UTF-8 | C++ | false | false | 408 | cpp | register_types.cpp | /* register_types.cpp */
#include "register_types.h"
#if defined(TOOLS_ENABLED) && defined(TOOLS_ENABLED)
#define AUTOCOMPLETE_SERVICE
#endif
#ifdef AUTOCOMPLETE_SERVICE
#include "completion_service_plugin.h"
#endif
void register_autocomplete_service_types() {
#ifdef AUTOCOMPLETE_SERVICE
EditorPlugins::add_by_type<CompletionServicePlugin>();
#endif
}
void unregister_autocomplete_service_types() {
}
|
86eba0607f4e9b5767c515280937e10a10454bfd | 85fe031ad1b7ba918fd2de0ccc68185b0e19439e | /source-code/ZigZag_Conversion.cpp | 80bfce43f3770acc77c6ef2294d2c8c7c956e4fc | [] | no_license | Mogileeswaran/LeetCode_problems_solution | e7bbe0387bd98fed115ba4c73ea549270aa7a7bd | f31032c69fcb0d549797023584aa131507e7471e | refs/heads/master | 2021-01-09T00:21:28.139841 | 2019-01-13T07:00:39 | 2019-01-13T07:00:39 | 242,186,579 | 1 | 0 | null | 2020-02-21T16:46:29 | 2020-02-21T16:46:28 | null | UTF-8 | C++ | false | false | 730 | cpp | ZigZag_Conversion.cpp | class Solution {
public:
string convert(string s, int nRows) {
if(s.empty()) return s;
string str[nRows + 1];
int j = 0, flip = 0, len = s.length();
while(j < len) {
flip ^= 1;
if(flip) {
for(int i = 0; i < nRows; ++i) {
if(j < len) str[i] += s[j++];
else break;
}
} else {
for(int i = nRows - 2; i > 0; --i) {
if(j < len) str[i] += s[j++];
else break;
}
}
}
string result;
for(int i = 0; i < nRows; ++i) result += str[i];
return result;
}
}; |
d79b9e1dcf4686505d1670926a4cc8be78154698 | d9f78cc6722c2c6d1af2af9e2aff0d9a78f5e7f3 | /Cookie/AlgorithmShortcuts.h | ffe681d4a645be0e7fa386a4a697c4e6e63da8a3 | [] | no_license | MaximeWYZUJ/2019-CppNoEngine-SuperRacingGalaxy | 74d0cd2b46f69b6c58c9ef52ab6bbfc23df592c6 | c26fa7806bc54593ce74382743068dc3cc1dd847 | refs/heads/master | 2020-12-06T11:27:15.450156 | 2019-12-21T14:58:12 | 2019-12-21T14:58:12 | 232,447,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 483 | h | AlgorithmShortcuts.h | #pragma once
#include <algorithm>
namespace Cookie
{
namespace Algo
{
template<class TContainer, class TVal>
typename TContainer::iterator Find(TContainer const& container, TVal const& val)
{
return std::find(std::begin(container), std::end(container), val);
}
template<class TContainer, class TVal>
bool Exists(TContainer const& container, TVal const& val)
{
return std::find(std::begin(container), std::end(container), val) != std::end(container);
}
}
} |
f1cfc4e70f33f7dff345224f8d098016753bfbbd | fda79f408b120ab0a12acc146fc8179dd64e1ab3 | /FieldGame/FieldGame/Field.hpp | 6db167ca33f5ac7c0fe92bb537722c2c5708b6d3 | [] | no_license | TmPhantom/FieldGame | 7be7a1648a092289ea2fd7764dcb9381645e6a97 | 7a26c8ca51f64d72102cfa7810920b75c8ef5476 | refs/heads/master | 2021-05-08T10:11:49.632035 | 2018-02-02T10:01:43 | 2018-02-02T10:01:43 | 119,832,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | hpp | Field.hpp | #pragma once
#include <string>
class Field {
private:
std::string name;
public:
// status declare the status of a field
// if free: the field isnt occupied, if busy: the field is occupied
// if hit: The field was occupied and is hited now, if besides: The field wasn't occupied
enum State { FREE = 1, BUSY = 2, HIT = 3, BESIDES = 4 } myState;
Field();
void setState(State status);
Field::State getState();
}; |
ccd610a8714e0b8afe7e1a3a0e0e042ca6d5b094 | 6693c202f4aa960b05d7dfd0ac8e19a0d1199a16 | /COJ/eliogovea-cojAC/eliogovea-p1396-Accepted-s688831.cpp | 9da6c69814b77d99363fb7851a0485f31fef791f | [] | no_license | eliogovea/solutions_cp | 001cf73566ee819990065ea054e5f110d3187777 | 088e45dc48bfb4d06be8a03f4b38e9211a5039df | refs/heads/master | 2020-09-11T11:13:47.691359 | 2019-11-17T19:30:57 | 2019-11-17T19:30:57 | 222,045,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | eliogovea-p1396-Accepted-s688831.cpp | #include <iostream>
using namespace std;
typedef unsigned long long LL;
int tc, n, k;
LL dp[101][101][101];
LL solve(LL n, LL k) {
if ((n & 1LL) || (k == 0)) return 0;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
for (int l = 0; l < k; l++)
dp[i][j][l] = 0;
dp[0][0][0] = 1LL;
for (LL i = 0; i < n; i++)
for (LL j = 0; j <= n / 2; j++) {
for (LL l = 0; l < k; l++) {
dp[i + 1][j + 1][(l + (1LL << i) % k) % k] += dp[i][j][l];
if (i != n - 1) dp[i + 1][j][l] += dp[i][j][l];
}
}
return dp[n][n / 2][0];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> tc;
for (int i = 1; i <= tc; i++) {
cin >> n >> k;
cout << "Case " << i << ": " << solve(n, k) << "\n";
}
}
|
cf3f39fe32cb620baf6fa7d6dd6a38ace59b64fc | e334a56a1bbd361dd6df1abbae34d4382558e6df | /Joc_QT/Dialog.h | 16b4f4e8b09119e05e0dbea2d0248e55c4df1cc1 | [] | no_license | CoroamaDianaMihaela/OOP_Game | bb08ef593339afc8fdde363b5d3c8a5d1a4d33c7 | c5e8ac9beec5716aeac93aeef11edb33fe71db17 | refs/heads/main | 2023-03-14T21:16:12.381758 | 2021-03-12T10:04:31 | 2021-03-12T10:04:31 | 347,020,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,092 | h | Dialog.h | #pragma once
#include <QDialog>
#include <QApplication>
#include <QtWidgets/qlabel.h>
#include <QtWidgets/qpushbutton.h>
#include <QtWidgets/qboxlayout.h>
#include <QtWidgets/qformlayout.h>
#include <QtWidgets/qlistwidget.h>
#include <QtWidgets/qlineedit.h>
#include <QtWidgets/qtablewidget.h>
#include <QtWidgets/qmessagebox.h>
#include <QtWidgets/qstyle.h>
#include <vector>
#include <string>
#include "Controller.h"
using std::vector;
using std::string;
class Dialog : public QDialog
{
private:
QHBoxLayout *main_layout=new QHBoxLayout{};
QListWidget* ly= new QListWidget;
QPushButton* btnStart= new QPushButton{"&Start"};
public:
Dialog()
{
initStart();
initConnect();
}
~Dialog()
{
delete main_layout;
delete ly;
delete btnStart;
}
void initStart()
{
this->setLayout(main_layout);
QPixmap image("C:\\Users\\GEMENELE\\Pictures\\barci_2.jpg");
QLabel *imageLabel = new QLabel();
imageLabel->setPixmap(image);
QVBoxLayout *img_ly= new QVBoxLayout{};
img_ly->addWidget(imageLabel);
img_ly->addWidget(btnStart);
btnStart->setStyleSheet( "background-color: rgb(135,206,250)");
main_layout->addLayout(img_ly);
}
void initConnect()
{
QObject::connect(btnStart,&QPushButton::clicked,[&](){
close();
Controller* contr= new Controller{};
contr->show();
});
}
// void loadData()
// {
// vector<string> listProducts={"prod1","prod2","prod3","prod4","prod5","prod6"};
// for(string word : listProducts)
// {
// ly->addItem(QString::fromStdString(word));
// }
// }
// void initGUI(){
// main_layout->addWidget(ly);
// QHBoxLayout *secondary_layout= new QHBoxLayout{};
// secondary_layout->addWidget(new QLabel{"Wassap"});
// secondary_layout->addWidget(new QLineEdit);
// main_layout->addLayout(secondary_layout);
//// VBoxLayout
// QVBoxLayout *third_ly= new QVBoxLayout{};
// third_ly->addWidget(new QLabel{"Wassap"});
// third_ly->addWidget(new QLabel{"Sup"});
// third_ly->addWidget(new QLabel{"was"});
// third_ly->addWidget(new QLabel{"Yahoink"});
// main_layout->addLayout(third_ly);
// //form Layout
// auto addLy= new QVBoxLayout{};
// auto formLy= new QFormLayout{};
// formLy->addRow("Nume",new QLineEdit);
// formLy->addRow("Prenume",new QLineEdit);
// formLy->addRow("Varsta",new QLineEdit);
// formLy->addRow("Badassery",new QLineEdit);
// addLy->addLayout(formLy);
// auto lyBtn = new QHBoxLayout{};
// lyBtn->addWidget(new QPushButton{"&Adauga"});
// lyBtn->addWidget(new QPushButton{"&Sterge"});
// lyBtn->addWidget(new QPushButton{"&Modifica"});
// lyBtn->addWidget(btnExit);
// addLy->addLayout(lyBtn);
// main_layout->addLayout(addLy);
//};
};
|
0c704c3e07db694baace91364c0aed0e9feb9176 | 708a133bc81953e14f29d5da8aa8a94cb19f7ebd | /src/graphics/gl_shader.h | b1914df6cf3e67b03331d59ab28a964d3b127dcc | [
"MIT"
] | permissive | uzername/Yukkuri | b8e94bc8edb0094143eded81e6eb917f8ee493c6 | 1feac46e1bc3e9a9a60ed9a68accc38b86b72988 | refs/heads/master | 2021-01-20T21:25:56.008039 | 2012-08-07T07:29:24 | 2012-08-07T07:29:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | h | gl_shader.h | /*
* gl_shader.h
*
* Created on: 24.05.2012
*
* Want a shader? Create and manage it yourself.
*
*/
#ifndef GL_SHADER_H_
#define GL_SHADER_H_
#include <string>
#include "graphics/GraphicsTypes.h"
namespace Shaders {
GLuint getProgram( std::string filename );
}
#endif /* GL_SHADER_H_ */
|
959edbd09c14a42f7dd95913dff60a8ea0090bb9 | ae913a8843f9f1f5ce1d8b14b4f4a958ca00530e | /gloop.hpp | 1fc325035f59baf5031476c61ff886be8a796af8 | [
"MIT"
] | permissive | practisebody/gloop | aeacdff10db59d23722a1958052703cd31d86185 | ff34fb821fc8d35b29d831ba2fcce430b09095f8 | refs/heads/master | 2020-05-19T04:18:50.282279 | 2019-05-03T21:30:11 | 2019-05-03T21:36:18 | 184,822,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,529 | hpp | gloop.hpp | #pragma once
#define GL_OOP
// io
#include <string>
#include <fstream>
// data structure
#include <any>
#include <array>
#include <map>
#include <optional>
#include <stack>
#include <variant>
#include <vector>
// utility
#include <numeric>
#include <memory>
#include <functional>
#include <type_traits>
#ifndef _LIB
#ifndef GL_TRUE
#error "Include OpenGL loader first! See https://www.khronos.org/opengl/wiki/OpenGL_Loading_Library for how to."
#endif
#else
#if _WIN32
#include <Windows.h>
#endif
#include <gl/gl.h>
#define GL_GLEXT_PROTOTYPES
#include <gl/glext.h>
#endif
// glm
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "macro.h"
// Desgin choices:
// 1. Returning raw pointer (for most objects)
// a) Why not void
// - Want to have function chaining.
// b) Why not smart pointer
// C++ requires covariant return type.
// 1) Why not name hiding (not use virtual functions)?
// - It's not c++ style
// 2) Why not curiously recurring template pattern (CRTP)?
// - Multilevel inheritance requires abstract base class
// 3) Why not use an abstract base class?
// - Need virtual inheritance, which comlicates things
// - However, we actually use this for some class with the help
// from class GL::Shared
// c) Why not reference
// - Need to seperate variable declaration from function calls.
// - Though it is possible to have a container of reference via
// reference_wrapper, it makes things unnecessary complicated
// 2. Why factory class Make? (why not constructor?)
// - Keep constructor simple
// - Let Data() do actual work, no need to overload constructor again
// Note:
// Need call functions in order of from derived to base class
// TODO
// 1) perfect capture for lambda function, currently still copying
// 2) string, starts_with
// 3) if constexpr in lambda function
// 4) PmxObjObject
// base
#include "Enum.hpp"
#include "Unique.hpp"
#include "Attribute.hpp"
#include "IDObject.hpp"
#include "Shared.hpp"
// OpenGL objects
#include "GLObject.hpp"
// Standard OpenGL objects
// https://www.khronos.org/opengl/wiki/OpenGL_Object
#include "GLStandardObject.hpp"
// 0. GLSL objects
#include "GLSL.hpp"
// 1. regular objects
#include "GLRegular.hpp"
// 2. container objects
#include "GLContainer.hpp"
// Non-standard objects
// 3. other objects
#include "GLExtraObject.hpp"
// utility
#include "Traits.hpp"
#include "Utility.hpp"
#include "Initializer.hpp"
#include "Make.hpp"
// 1.1 buffer objects
// https://www.khronos.org/opengl/wiki/Buffer_Object
#include "Buffer.hpp"
#include "Buffer2D.hpp"
#include "VBO.hpp"
#include "IBO.hpp"
// 1.5 texture objects
// https://www.khronos.org/opengl/wiki/Texture
#include "Texture.hpp"
#include "Texture1D.hpp"
#include "Texture2D.hpp"
// 3.1 Program Attribute objects
#include "ProgramAttribute.hpp"
// 3.1.1 matrix
#include "Matrix.hpp"
#include "ProjMatrix.hpp"
#include "ViewMatrix.hpp"
#include "ModelMatrix.hpp"
// https://www.khronos.org/opengl/wiki/GLSL_Object
// 0.2 Shader objects (Note: it's not an attribute!)
#include "Shader.hpp"
// 0.1 Program objects
#include "Program.hpp"
// 3.1.2 Color
#include "Color3.hpp"
#include "Color4.hpp"
// Renderable objects
#include "Object.hpp"
#include "Group.hpp"
#include "World.hpp"
// 2.1 framebuffer objects
// https://www.khronos.org/opengl/wiki/Framebuffer_Object
#include "FBO.hpp"
// 2.4 vertex array objects
// https://www.khronos.org/opengl/wiki/Vertex_Specification#Vertex_Array_Object
#include "VAO.hpp"
#include "helper.h" |
7950902dc74edb0628485ae246985328100b935a | 19ebf115ad64c00b6e202afc5568a2c45d31ed80 | /P3/luzdireccional.cc | 25d81e0663fa413ec76cea9dd5aa964557d59c19 | [] | no_license | Agumeri/IG-2020 | 7665851a13f01df7984e3af0407f39f1c900d19f | 7145a4c9b5dd04ce83feabb5c583334c67ccd4a7 | refs/heads/main | 2023-03-09T13:19:21.088165 | 2021-02-25T17:14:08 | 2021-02-25T17:14:08 | 303,163,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | cc | luzdireccional.cc | #include "aux.h"
#include "luz.h"
#include "luzdireccional.h"
#include "math.h"
LuzDireccional::LuzDireccional(const Tupla2f & orientacion){
// Primero lo obtenemos en grados
alpha = orientacion[0];
beta = orientacion[1];
// Lo pasamos a radianes, y calculamos el angulo z (ganma)
alpha = sin(alpha*M_PI/180);
beta = cos(beta*M_PI/180);
float ganma = sin(alpha) * cos(beta);
// Asignamos cada angulo a su posicion correspondiente;
this->posicion[0] = alpha;
this->posicion[1] = beta;
this->posicion[2] = ganma;
this->posicion[3] = 0.0;
}
LuzDireccional::LuzDireccional(Tupla2f direccion, GLenum idLuzOpenGL, Tupla4f colorAmbiente, Tupla4f colorEspecular, Tupla4f colorDifuso){
//Asignamos los valores por parametro a su correspondiente lugar
// Primero lo obtenemos en grados
alpha = direccion[0];
beta = direccion[1];
// Lo pasamos a radianes, y calculamos el angulo z (ganma)
alpha = sin(alpha*M_PI/180);
beta = cos(beta*M_PI/180);
float ganma = sin(alpha) * cos(beta);
// Asignamos cada angulo a su posicion correspondiente;
this->posicion[0] = alpha;
this->posicion[1] = beta;
this->posicion[2] = ganma;
this->posicion[3] = 0.0;
// IdLuz
id = idLuzOpenGL;
// Colores
this->colorAmbiente = colorAmbiente;
this->colorDifuso = colorDifuso;
this->colorEspecular = colorEspecular;
}
void LuzDireccional::variarAnguloAlpha(float incremento){
alpha += incremento;
alpha = sin(alpha*M_PI/180);
float ganma = sin(alpha) * cos(beta);
this->posicion[0] = alpha;
this->posicion[2] = ganma;
}
void LuzDireccional::variarAnguloBeta(float incremento){
beta += incremento;
beta = cos(beta*M_PI/180);
float ganma = sin(alpha) * cos(beta);
this->posicion[1] = beta;
this->posicion[2] = ganma;
} |
77cad6f4463855554d1709ddcf5bc3224d7ae83f | 936abcf5c18e3c5818037f90d4954b59dab700fe | /Table/Table/Table.cpp | f3da131264762ca9a0633486210d3e95c2aa270d | [] | no_license | whistlinwilly/SMAART | 9b540214455ba06ab700c4ccf41455008e884f70 | 8014c40361b2dad2a2624cbb059d87d4b701d0fa | refs/heads/master | 2021-01-02T23:13:27.685974 | 2013-04-13T23:35:20 | 2013-04-13T23:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | cpp | Table.cpp | // Table.cpp : Defines the entry point for the console application.
//
#include "Initialization.h"
#include "Table.h"
Table::Table(char* ip, int port, int camNum){
sn = new ServerNetwork(ip, port);
tCam.initFastCam(camNum);
recvbuf = (char*)malloc(MAX_REC_BUF*sizeof(char));
tableBGsub = new BackgroundSubtractorMOG2(0, 400, true);
projectorsConnected = 0;
}
void Table::initialize(){
Initialization* tableInit = new Initialization();
//connect all the projectors
tableInit->connectToProjectors(sn);
//make camera shit perfect and receive a cameraperspective
cp = tableInit->camRotation(tCam);
//set background subtractor
frame = tCam.grabFrameWithPerspective(cp);
tableBGsub->operator()(frame, foreground, 0.001);
//read init pattern for each projector
for (int i=0; i<NUM_PROJECTORS; i++){
tableInit->readInitPattern(i, tableBGsub, tCam, sn);
tableInit->computePerspective(i, sn);
sn->sendToAll("0", 5, i);
sn->receiveData(i, recvbuf);
}
//send every projector their perspectives
tableInit->sendPerspectives(sn);
sn->sendToAll("4",5,0);
sn->receiveData(0, recvbuf);
sn->sendToAll("4",5,1);
sn->receiveData(1,recvbuf);
}
void Table::run(){
}
|
beb8e5a38f8a4666bf5ce6ac143a86a91a795bcd | 375cf87e30b5f480fb22f739a3b862ceb16c4fcf | /include/AI/TreeNode.hh | 158c35c815e7099491039ba65965f2b2c4be3d4c | [] | no_license | drouarb/Gomoku | b960ca8866175886c37bc13da1547195d4fd79ff | 06f869f268b87b4045adaa0c81dc561b26640bc9 | refs/heads/master | 2021-08-24T02:25:08.591875 | 2017-12-07T16:42:56 | 2017-12-07T16:42:56 | 113,475,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,319 | hh | TreeNode.hh | //
// Created by drouar_b on 11/25/16.
//
#ifndef GOMOKU_TREENODE_HH
#define GOMOKU_TREENODE_HH
#include <vector>
#include <Core/Referee.hpp>
#include <mutex>
namespace AI {
class TreeNode {
public:
TreeNode(Core::IReferee *gameState, Team team, TreeNode *parent = NULL);
TreeNode(Core::IReferee *gameState, Team team, TreeNode *parent, std::vector<std::pair<boardPos_t, weight_t>> *moves);
~TreeNode();
TreeNode *getSimulationNode();
TreeNode *getBestChild();
int getBestAction() const;
bool hasWinningChild() const;
void backPropagate(int result, Team winner);
int getMove() const;
double getPlays() const;
double getBlackWins() const;
double getWhiteWins() const;
void setParent(TreeNode *parent);
TreeNode *getParent() const;
Core::IReferee *getReferee() const;
std::vector<TreeNode *> &getChilds();
private:
Team aiTeam;
Core::IReferee *referee;
unsigned int plays;
unsigned int blackWins;
unsigned int whiteWins;
TreeNode *parent;
std::vector<TreeNode *> childs;
int move;
std::vector<std::pair<boardPos_t, weight_t>> *moves;
std::mutex mutex;
};
}
#endif //GOMOKU_TREENODE_HH
|
9262aed14abc57fe9999ef4c6350be4d3aec355f | 8cb1290022972445dcbf7368c1a688dae25e840f | /20180726/9_1080.cc | 37aa4693c0353ed29e04385d6c9a1917e75856bf | [] | no_license | connorhzp/PAT | 2612c41e3d14ba517ecc1f037b7b445322f51f4d | 4b814bfe24d934070ff47b8d4faebb55fcc2a62a | refs/heads/master | 2020-03-25T13:43:41.558357 | 2018-08-07T07:56:19 | 2018-08-07T07:56:19 | 143,839,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,294 | cc | 9_1080.cc | ///
/// @file 9_1080.cc
/// @author hzp(haozhipeng2018@163.com)
/// @date 2018-07-16 21:06:24
///
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using std::cout;
using std::endl;
struct Student {
int id;
int gradeE;
int gradeI;
int totalGrade;
vector<int> prefer;
};
bool cmp(Student a, Student b) {
if(a.totalGrade != b.totalGrade)
return a.totalGrade > b.totalGrade;
else
return a.gradeE > b.gradeE;
}
int main() {
int nstu, nschool, nprefer;
scanf("%d%d%d", &nstu, &nschool, &nprefer);
int quota[nschool];
for(int i = 0; i < nschool; i++) {
scanf("%d", quota + i);
};
vector<Student> stu;
for(int i = 0; i < nstu; i++) {
stu[i].id = i;
scanf("%d%d", &stu[i].gradeE, &stu[i].gradeI);
stu[i].totalGrade = stu[i].gradeE + stu[i].gradeI;
for(int j = 0; j < nprefer; j++) {
scanf("%d", &stu[i].prefer[j]);
}
}
sort(&stu[0], &stu[nstu - 1] + 1, cmp);
int stuAdmitted[nschool][10010];
int preferIdx = 0, stuAdmIdx = 0;
for(int i = 0; i < nstu; i++) {
for(int j = 0; j < nprefer; j++) {
if(quota[stu[i].prefer[preferIdx]] != 0) {
stuAdmitted[stu[i].prefer[preferIdx++]][stuAdmIdx++] = stu[i].id;
quota[stu[i].prefer[preferIdx - 1]]--;
break;
} else if();
}
}
}
return 0;
}
|
7c4e7e7ca4a09bc4e70cc28176b3df2807414a8f | 396791c5f5d928e3f82a7a193e22bcb3a5f222dc | /src/mesh.cpp | 3f9f52eed50ab19f1489229fecc4b638b8f746dc | [
"BSD-3-Clause"
] | permissive | certik/hermes1d | be0287f8b3407c876509be2e92111308dd6f532c | a8b84a99b012818ce201c1b5c9265be1751e05bd | refs/heads/master | 2016-09-06T04:30:02.726879 | 2010-07-06T20:29:03 | 2010-07-06T20:29:03 | 53,871 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 49,399 | cpp | mesh.cpp | // Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Distributed under the terms of the BSD license (see the LICENSE
// file for the exact terms).
// Email: hermes1d@googlegroups.com, home page: http://hpfem.org/
#include "mesh.h"
#include "iterator.h"
#include "adapt.h"
#include "transforms.h"
#include "linearizer.h"
// debug - prints element dof arrays in assign_dofs()
int DEBUG_ELEM_DOF = 0;
Element::Element()
{
x1 = x2 = 0;
p = 0;
for (int j=0; j < MAX_EQN_NUM; j++) {
for (int k=0; k < MAX_P + 1; k++) {
dof[j][k] = 0;
for (int sln=0; sln < MAX_SLN_NUM; sln++) {
coeffs[sln][j][k] = 0;
}
}
}
sons[0] = sons[1] = NULL;
active = 1;
level = 0;
marker = -1;
id = -1;
n_eq = 0;
n_sln = 0;
}
Element::Element(double x_left, double x_right, int level, int deg, int n_eq, int n_sln, int marker)
{
x1 = x_left;
x2 = x_right;
p = deg;
this->n_eq = n_eq;
this->n_sln = n_sln;
if (dof == NULL) error("Not enough memory in Element().");
sons[0] = sons[1] = NULL;
active = 1;
this->level = level;
this->marker = marker;
id = -1;
}
unsigned Element::is_active()
{
return this->active;
}
// Refines an element. In case of p-refinement, only the
// poly degree is increased. In case of hp-refinement,
// two sons are created and the solution is moved into
// them.
// NOTE: dof[] arrays become invalid because they are global.
// assign_dof() must be run after the refinement is completed.
void Element::refine(int type, int p_left, int p_right)
{
if(type == 0) { // p-refinement
this->p = p_left;
}
else {
double x1 = this->x1;
double x2 = this->x2;
double midpoint = (x1 + x2)/2.;
this->sons[0] = new Element(x1, midpoint, this->level + 1, p_left, this->n_eq, this->n_sln, this->marker);
this->sons[1] = new Element(midpoint, x2, this->level + 1,
p_right, this->n_eq, this->n_sln, this->marker);
// Copy Dirichtel boundary conditions to sons
for(int c=0; c<this->n_eq; c++) {
if (this->dof[c][0] < 0) {
this->sons[0]->dof[c][0] = this->dof[c][0];
for(int sln=0; sln<this->n_sln; sln++) {
this->sons[0]->coeffs[sln][c][0] = this->coeffs[sln][c][0];
}
}
if (this->dof[c][1] < 0) {
this->sons[1]->dof[c][1] = this->dof[c][1];
for(int sln=0; sln<this->n_sln; sln++) {
this->sons[1]->coeffs[sln][c][1] = this->coeffs[sln][c][1];
}
}
}
// Transfer solution to sons
for(int c=0; c<this->n_eq; c++) {
transform_element_refined_forward(c, this, this->sons[0], this->sons[1]);
}
this->active = 0;
}
}
void Element::refine(int3 cand)
{
this->refine(cand[0], cand[1], cand[2]);
}
// initialize element and allocate dof and coeffs
// arrays for all solution components
void Element::init(double x1, double x2, int p_init,
int id, int active, int level, int n_eq, int n_sln, int marker)
{
this->x1 = x1;
this->x2 = x2;
this->p = p_init;
this->id = id;
this->active = active;
this->level = level;
this->marker = marker;
this->n_eq = n_eq;
this->n_sln = n_sln;
}
// Copies coefficients from the solution vector into element.
// Assumes that Dirichlet boundary conditions have been set.
void Element::get_coeffs_from_vector(double *y, int sln)
{
if (!this->is_active()) error("Internal in get_coeffs_from_vector().");
for(int c=0; c<this->n_eq; c++) {
for (int j=0; j < this->p + 1; j++) {
if (this->dof[c][j] != -1) this->coeffs[sln][c][j] = y[this->dof[c][j]];
}
}
}
// Copies coefficients from element coeffs arrays to the solution vector.
// Assumes that Dirichlet boundary conditions have been set.
void Element::copy_coeffs_to_vector(double *y, int sln)
{
if (!this->is_active()) error("Internal in copy_coeffs_to_vector().");
for(int c=0; c<this->n_eq; c++) {
for (int j=0; j < this->p + 1; j++) {
if (this->dof[c][j] != -1) y[this->dof[c][j]] = this->coeffs[sln][c][j];
}
}
}
void Element::copy_dofs(int sln_src, int sln_trg)
{
for (int c = 0; c < this -> n_eq; c++) { // loop over solution components
for (int i = 0; i < this -> p + 1; i++) { // loop over coefficients
if (this->dof[c][i] >= 0) {
coeffs[sln_trg][c][i] = coeffs[sln_src][c][i];
}
}
}
}
// Evaluate solution and its derivatives in Gauss quadrature points
// of order 'quad_order' in the element.
void Element::get_solution_quad(int flag, int quad_order,
double val_phys[MAX_EQN_NUM][MAX_QUAD_PTS_NUM],
double der_phys[MAX_EQN_NUM][MAX_QUAD_PTS_NUM], int sln)
{
double phys_x[MAX_QUAD_PTS_NUM]; // quad points
double phys_w[MAX_QUAD_PTS_NUM]; // quad weights
int pts_num;
create_phys_element_quadrature(this->x1, this->x2,
quad_order, phys_x, phys_w,
&pts_num);
double jac = (this->x2 - this->x1)/2.; // Jacobian of reference map
int p = this->p;
double x_ref[MAX_QUAD_PTS_NUM];
// filling the values and derivatives
if (flag == 0) { // integration points in the whole element
for(int c=0; c<this->n_eq; c++) {
for (int i=0 ; i < pts_num; i++) {
der_phys[c][i] = val_phys[c][i] = 0;
for(int j=0; j<=p; j++) {
val_phys[c][i] += this->coeffs[sln][c][j]*lobatto_val_ref_tab[quad_order][i][j];
der_phys[c][i] += this->coeffs[sln][c][j]*lobatto_der_ref_tab[quad_order][i][j];
}
der_phys[c][i] /= jac;
}
}
}
if (flag == -1) { // integration points in the left half of element
for(int c=0; c<this->n_eq; c++) {
for (int i=0 ; i < pts_num; i++) {
der_phys[c][i] = val_phys[c][i] = 0;
for(int j=0; j<=p; j++) {
val_phys[c][i] += this->coeffs[sln][c][j]*lobatto_val_ref_tab_left[quad_order][i][j];
der_phys[c][i] += this->coeffs[sln][c][j]*lobatto_der_ref_tab_left[quad_order][i][j];
}
der_phys[c][i] /= jac;
}
}
}
if (flag == 1) { // integration points in the right half of element
for(int c=0; c<this->n_eq; c++) {
for (int i=0 ; i < pts_num; i++) {
der_phys[c][i] = val_phys[c][i] = 0;
for(int j=0; j<=p; j++) {
val_phys[c][i] += this->coeffs[sln][c][j]*lobatto_val_ref_tab_right[quad_order][i][j];
der_phys[c][i] += this->coeffs[sln][c][j]*lobatto_der_ref_tab_right[quad_order][i][j];
}
der_phys[c][i] /= jac;
}
}
}
}
// Evaluate solution and its derivatives in plotting points 'x_phys'
// in the element.
void Element::get_solution_plot(double x_phys[MAX_PLOT_PTS_NUM], int pts_num,
double val_phys[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
double der_phys[MAX_EQN_NUM][MAX_PLOT_PTS_NUM], int sln)
{
double x1 = this->x1;
double x2 = this->x2;
double jac = (x2-x1)/2.; // Jacobian of reference map
int p = this->p;
double x_ref[MAX_PLOT_PTS_NUM];
// transforming points to (-1, 1)
for (int i=0 ; i < pts_num; i++) x_ref[i] = inverse_map(x1, x2, x_phys[i]);
// filling the values and derivatives
for(int c=0; c<this->n_eq; c++) {
for (int i=0 ; i < pts_num; i++) {
der_phys[c][i] = val_phys[c][i] = 0;
for(int j=0; j<=p; j++) {
val_phys[c][i] += this->coeffs[sln][c][j]*lobatto_val_ref(x_ref[i], j);
der_phys[c][i] += this->coeffs[sln][c][j]*lobatto_der_ref(x_ref[i], j);
}
der_phys[c][i] /= jac;
}
}
}
// Calculates square of the L2 or H1 norm of the solution in element
double Element::calc_elem_norm_squared(int norm)
{
double val_phys[MAX_EQN_NUM][MAX_QUAD_PTS_NUM];
double der_phys[MAX_EQN_NUM][MAX_QUAD_PTS_NUM];
int pts_num;
int order = 2*this->p;
this->get_solution_quad(0, order, val_phys, der_phys);
double phys_x[MAX_QUAD_PTS_NUM];
double phys_weights[MAX_QUAD_PTS_NUM];
create_phys_element_quadrature(this->x1, this->x2, order, phys_x, phys_weights,
&pts_num);
// integrate square over (-1, 1)
int n_eq = this->n_eq;
double norm_squared[MAX_EQN_NUM];
for (int c=0; c<n_eq; c++) {
norm_squared[c] = 0;
for (int i=0; i<pts_num; i++) {
double val = val_phys[c][i];
if (norm == 1) {
double der;
der = der_phys[c][i];
norm_squared[c] += (val*val + der*der) * phys_weights[i];
}
else norm_squared[c] += val*val * phys_weights[i];
}
}
double elem_norm_squared = 0;
for (int c=0; c<n_eq; c++)
elem_norm_squared += norm_squared[c];
return elem_norm_squared;
}
// Evaluate solution and its derivative at point x_phys.
void Element::get_solution_point(double x_phys,
double val[MAX_EQN_NUM],
double der[MAX_EQN_NUM], int sln)
{
double x1 = this->x1;
double x2 = this->x2;
double jac = (x2-x1)/2.;
int p = this->p;
// transforming point x_phys to (-1, 1)
double x_ref = inverse_map(x1, x2, x_phys);
for(int c=0; c < this->n_eq; c++) {
der[c] = val[c] = 0;
for(int j=0; j<=p; j++) {
val[c] += this->coeffs[sln][c][j]*lobatto_val_ref(x_ref, j);
der[c] += this->coeffs[sln][c][j]*lobatto_der_ref(x_ref, j);
}
der[c] /= jac;
}
}
// Copying elements including all their variables, dof arrays, but not
// refinement trees. Does not care about sons.
void Element::copy_into(Element *e_trg)
{
// copy all variables of Element class
e_trg->init(this->x1, this->x2, this->p, this->id,
this->active, this->level, this->n_eq, this->n_sln, this->marker);
// copy dof arrays for all solution components
for(int c=0; c < this->n_eq; c++) {
for(int i=0; i < MAX_P + 1; i++) {
e_trg->dof[c][i] = this->dof[c][i];
for(int sln=0; sln < this->n_sln; sln++) {
e_trg->coeffs[sln][c][i] = this->coeffs[sln][c][i];
}
}
}
}
// Copying elements including all their variables, dof and coeffs
// arrays, and refinement trees,
// FIXME - the recursive version is slow and should be improved.
void Element::copy_recursively_into(Element *e_trg)
{
this->copy_into(e_trg); // copy all variables of Element class but sons
// replicate sons if relevant
if(this->sons[0] != NULL) { // element was split in space (sons will be replicated)
e_trg->sons[0] = new Element();
e_trg->sons[1] = new Element();
// left son
this->sons[0]->copy_recursively_into(e_trg->sons[0]);
// right son
this->sons[1]->copy_recursively_into(e_trg->sons[1]);
}
else { // element was split in space (sons are NULL)
e_trg->sons[0] = NULL;
e_trg->sons[1] = NULL;
}
}
// gets physical coordinate of a reference point x_ref \in [-1,1]
double Element::get_x_phys(double x_ref)
{
double a = this->x1;
double b = this->x2;
return (a+b)/2. + x_ref*(b-a)/2.;
}
Mesh::Mesh() {
n_eq = 0;
n_sln = 0;
n_base_elem = 0;
n_active_elem = 0;
n_dof = 0;
base_elems = NULL;
}
// Creates equidistant mesh with uniform polynomial degree of elements.
// All elements will have the same (zero) marker.
Mesh::Mesh(double a, double b, int n_base_elem, int p_init, int n_eq, int n_sln)
{
// print the banner (only once)
static int n_calls = 0;
n_calls++;
if (n_calls == 1) intro();
// check maximum number of equations
if(n_eq > MAX_EQN_NUM)
error("Maximum number of equations exceeded (set in common.h)");
// all Mesh class variables
this->left_endpoint = a;
this->right_endpoint = b;
this->n_base_elem = n_base_elem;
this->n_eq = n_eq;
this->n_sln = n_sln;
this->n_active_elem = n_base_elem;
// allocate element array
this->base_elems = new Element[this->n_base_elem];
if (base_elems == NULL) error("Not enough memory in Mesh::create().");
if (p_init > MAX_P)
error("Max element order exceeded (set in common.h).");
// element length
double h = (b - a)/this->n_base_elem;
int marker_default = 0;
// fill initial element array
for(int i=0; i<this->n_base_elem; i++) {
int id = i;
int active = 1;
int level = 0;
this->base_elems[i].init(a + i*h, a + i*h + h, p_init,
id, active, level, n_eq, n_sln, marker_default);
}
}
// Creates a general mesh (used, e.g., in example "neutronics").
// n_macro_elem... number of macro elements
// pts_array[]... array of macroelement grid points
// p_array[]... array of macroelement poly degrees
// m_array[]... array of macroelement material markers
// div_array[]... array of macroelement equidistant divisions
Mesh::Mesh(int n_macro_elem, double *pts_array, int *p_array, int *m_array, int *div_array, int n_eq, int n_sln)
{
// print the banner (only once)
static int n_calls = 0;
n_calls++;
if (n_calls == 1) intro();
// check maximum number of equations
if(n_eq > MAX_EQN_NUM)
error("Maximum number of equations exceeded (set in common.h)");
// calculate n_base_elem
int n_base_elem = 0;
for (int i=0; i < n_macro_elem; i++) {
if(div_array[i] <= 0) error("Inadmissible macroelement subdivision.");
if(p_array[i] <= 0) error("Inadmissible macroelement poly degree.");
if (p_array[i] > MAX_P) error("Max element order exceeded (set in common.h).");
if(m_array[i] < 0) error("Inadmissible macroelement material marker.");
if(pts_array[i] >= pts_array[i+1]) error("Inadmissible macroelement grid point.");
n_base_elem += div_array[i];
}
printf("Number of elements: %d\n", n_base_elem);
// define all Mesh class variables
this->left_endpoint = pts_array[0];
this->right_endpoint = pts_array[n_macro_elem];
this->n_base_elem = n_base_elem;
this->n_eq = n_eq;
this->n_sln = n_sln;
this->n_active_elem = n_base_elem;
// allocate base element array
this->base_elems = new Element[this->n_base_elem];
if (base_elems == NULL) error("Not enough memory for base element array in Mesh::create().");
// initialize element array
int count = 0;
for(int i=0; i < n_macro_elem; i++) {
double length = (pts_array[i+1] - pts_array[i])/div_array[i];
for(int j=0; j < div_array[i]; j++) {
int id = count;
int active = 1;
int level = 0;
double x_left = pts_array[i] + length * j;
double x_right = x_left + length;
this->base_elems[count].init(x_left, x_right, p_array[i], id, active, level, n_eq, n_sln, m_array[i]);
count++;
}
}
}
// CAUTION - this is expensive (traverses the entire tree
// from the beginning until the element is found)
void Mesh::refine_single_elem(int id, int3 cand)
{
Iterator I(this);
Element *e;
while ((e = I.next_active_element()) != NULL) {
printf("%d %d\n", e->id, id);
if (e->id == id) {
e->refine(cand);
if (cand[0] == 1) this->n_active_elem++; // hp-refinement
return;
}
}
error("refine_single_elem: Element not found.");
}
// performs mesh refinement using a list of elements to be
// refined and a list of corresponding polynomial degree
// pairs for the sons
void Mesh::refine_elems(int elem_num, int *id_array, int3 *cand_array)
{
Iterator *I = new Iterator(this);
Element *e;
int count = 0;
while ((e = I->next_active_element()) != NULL) {
if (e->id == id_array[count]) {
if (count >= elem_num)
error("refine_multi_elems: not enough elems specified");
e->refine(cand_array[count]);
if (cand_array[count][0] == 1) this->n_active_elem++;
count++;
}
}
}
// Splits the indicated elements and
// increases poly degree in sons by one.
// Solution is transfered to new elements.
void Mesh::reference_refinement(int start_elem_id, int elem_num)
{
Iterator *I = new Iterator(this);
Element *e;
int count = 0;
while ((e = I->next_active_element()) != NULL) {
if (e->id >= start_elem_id && e->id < start_elem_id + elem_num) {
if (count >= elem_num) return;
int3 cand = {1, e->p + 1, e->p + 1};
e->refine(cand);
if (cand[0] == 1) this->n_active_elem++; // if hp-refinement
count++;
}
}
this->assign_dofs();
}
void Mesh::set_bc_left_dirichlet(int eqn, double val)
{
// deactivate the corresponding dof for the left-most
// element and all his descendants adjacent to the
// left boundary, and fill the coeffs array entry
Element *e = this->base_elems + 0;
do {
e->dof[eqn][0] = -1;
for (int sln=0; sln < this->n_sln; sln++) {
e->coeffs[sln][eqn][0] = val;
}
e = e->sons[0];
} while (e != NULL);
}
void Mesh::set_bc_right_dirichlet(int eqn, double val)
{
// deactivate the corresponding dof for the right-most
// element and all his descendants adjacent to the
// right boundary, and fill the coeffs array entry
Element *e = this->base_elems + this->n_base_elem - 1;
do {
e->dof[eqn][1] = -1;
for (int sln=0; sln < this->n_sln; sln++) {
e->coeffs[sln][eqn][1] = val;
}
e = e->sons[1];
} while (e != NULL);
}
// define element connectivities (dof arrays)
int Mesh::assign_dofs()
{
Iterator *I = new Iterator(this);
// (1) enumerate vertex dofs
int count_dof = 0;
// loop over solution components
for(int c=0; c<this->n_eq; c++) {
Element *e;
I->reset();
while ((e = I->next_active_element()) != NULL) {
if (e->dof[c][0] != -1) e->dof[c][0] = count_dof++;
if (e->dof[c][1] != -1) e->dof[c][1] = count_dof;
else count_dof--;
}
count_dof++;
// (2) enumerate bubble dofs
I->reset();
while ((e = I->next_active_element()) != NULL) {
for(int j=2; j <= e->p; j++) {
e->dof[c][j] = count_dof;
count_dof++;
}
}
}
this->n_dof = count_dof;
// enumerate elements
this->assign_elem_ids();
// print element connectivities
if(DEBUG_ELEM_DOF) {
printf("Printing element DOF arrays:\n");
printf("Elements = %d\n", this->n_base_elem);
printf("DOF = %d", this->n_dof);
for(int c = 0; c<this->n_eq; c++) {
I->reset();
Element *e;
while ((e = I->next_active_element()) != NULL) {
printf("\nElement (%g, %g), id = %d, p = %d\n ",
e->x1, e->x2, e->id, e->p);
for(int j = 0; j<e->p + 1; j++) {
printf("dof[%d][%d] = %d\n ", c, j, e->dof[c][j]);
}
}
}
printf("\n");
}
delete I;
return this->n_dof;
}
int Mesh::assign_elem_ids()
{
Iterator *I = new Iterator(this);
int count_id = 0;
Element *e;
I->reset();
while ((e = I->next_active_element()) != NULL) {
e->id = count_id;
count_id++;
}
delete I;
}
Element* Mesh::first_active_element()
{
Element *e = base_elems;
while(!e->is_active()) {
e = e->sons[0];
}
return e;
}
Element* Mesh::last_active_element()
{
Element *e = base_elems + n_base_elem - 1;
while(!e->is_active()) {
e = e->sons[1];
}
return e;
}
// defining macro to check whether hp candidates are admissible
#define add_hp_candidate_if_ok(new_p_left, new_p_right) \
candidate_ok = 1; \
if (new_p_left >= MAX_P) candidate_ok = 0; \
if (new_p_right >= MAX_P) candidate_ok = 0; \
if (ref_solution_p_refined) { \
if (new_p_left >= p_ref && new_p_right >= p_ref) \
candidate_ok = 0; \
} else { \
if (new_p_left == p_ref_left && new_p_right == p_ref_right) \
candidate_ok = 0; \
if (new_p_left > p_ref_left || new_p_right > p_ref_right) \
candidate_ok = 0; \
} \
if (candidate_ok) { \
cand_list[counter][0] = 1; \
cand_list[counter][1] = new_p_left; \
cand_list[counter][2] = new_p_right; \
counter++; \
}
// defining macro to check whether p candidates are admissible
#define add_p_candidate_if_ok(new_p) \
candidate_ok = 1; \
if (new_p >= MAX_P) candidate_ok = 0; \
if (ref_solution_p_refined) \
if (new_p >= p_ref) \
candidate_ok = 0; \
if (candidate_ok) { \
cand_list[counter][0] = 0; \
cand_list[counter][1] = new_p; \
cand_list[counter][2] = -1; \
counter++; \
} \
/*
p_ref_left and p_ref_right are the polynomial orders of the reference
solution (left and right refinement). If p_ref_right is -1, then the
reference solution is only "p" refined.
adapt_type = 0 ... hp-adaptivity (full list of candidates)
adapt_type = 1 ... h-adaptivity (h-candidates only)
*/
int Element::create_cand_list(int adapt_type, int p_ref_left,
int p_ref_right, int3 *cand_list)
{
int ref_solution_p_refined = (p_ref_right == -1);
int p_ref = p_ref_left; // use only if ref_solution_p_refined == 1
int counter = 0;
int candidate_ok;
if (adapt_type == 0) {
// p-adaptivity candidates:
add_p_candidate_if_ok(this->p + 1);
add_p_candidate_if_ok(this->p + 2);
// hp-adaptivity candidates:
// we first divide the poly degree by two
int base_p = this->p / 2;
if (base_p < 1) base_p = 1;
add_hp_candidate_if_ok(base_p, base_p); // p -> (p/2, p/2)
add_hp_candidate_if_ok(base_p + 1, base_p); // p -> (p/2+1, p/2)
add_hp_candidate_if_ok(base_p, base_p + 1); // p -> (p/2, p/2+1)
add_hp_candidate_if_ok(base_p + 1, base_p + 1); // p -> (p/2+1, p/2+1)
add_hp_candidate_if_ok(base_p + 2, base_p); // p -> (p/2+2, p/2)
add_hp_candidate_if_ok(base_p, base_p + 2); // p -> (p/2, p/2+2)
add_hp_candidate_if_ok(base_p + 1, base_p + 2); // p -> (p/2+1, p/2+2)
add_hp_candidate_if_ok(base_p + 2, base_p + 1); // p -> (p/2+2, p/2+1)
add_hp_candidate_if_ok(base_p + 2, base_p + 2); // p -> (p/2+2, p/2+2)
}
if (adapt_type == 1) {
add_hp_candidate_if_ok(this->p, this->p); // p -> (p, p)
}
if (adapt_type == 2) {
add_p_candidate_if_ok(this->p + 1);
add_p_candidate_if_ok(this->p + 2);
}
return counter;
}
void Element::print_cand_list(int num_cand, int3 *cand_list)
{
printf("Element (%g, %g): refinement candidates:\n", this->x1, this->x2);
for (int i=0; i < num_cand; i++) {
printf("%d %d %d\n", cand_list[i][0], cand_list[i][1], cand_list[i][2]);
}
}
// transformation of k-th shape function defined on Gauss points
// corresponding to 'order' to physical interval (a,b)
void element_shapefn(double a, double b,
int k, int order, double *val, double *der) {
//double2 *ref_tab = g_quad_1d_std.get_points(order);
int pts_num = g_quad_1d_std.get_num_points(order);
double jac = (b-a)/2.;
for (int i=0 ; i < pts_num; i++) {
// change function values and derivatives to interval (a, b)
//val[i] = lobatto_val_ref(ref_tab[i][0], k);
val[i] = lobatto_val_ref_tab[order][i][k];
//der[i] = lobatto_der_ref(ref_tab[i][0], k) / jac;
der[i] = lobatto_der_ref_tab[order][i][k]/jac;
}
};
// transformation of k-th shape function at the reference
// point x_ref to physical interval (a,b).
void element_shapefn_point(double x_ref, double a, double b,
int k, double &val, double &der) {
// change function values and derivatives to interval (a, b)
val = lobatto_val_ref(x_ref, k);
double jac = (b-a)/2.;
der = lobatto_der_ref(x_ref, k) / jac;
}
// Replicate mesh including dof arrays in all elements
Mesh *Mesh::replicate()
{
// copy base mesh element array, use dummy poly degree first
// (poly degrees in base mesh may have changed since initialization)
int p_dummy = -1;
Mesh *mesh_new = new Mesh(this->left_endpoint, this->right_endpoint,
this->n_base_elem, p_dummy, this->n_eq, this->n_sln);
// copy all Mesh class variables
mesh_new->set_n_eq(this->n_eq);
mesh_new->set_n_base_elem(this->n_base_elem);
mesh_new->set_n_active_elem(this->n_active_elem);
mesh_new->set_left_endpoint(this->left_endpoint);
mesh_new->set_right_endpoint(this->right_endpoint);
mesh_new->set_n_dof(this->n_dof);
// replicate all base mesh elements including all their
// variables, dof arrays, and tree-structure
Element *base_elems_new = mesh_new->get_base_elems();
for(int i=0; i<this->n_base_elem; i++) {
Element *e_src = this->base_elems + i;
Element *e_trg = base_elems_new + i;
e_src->copy_recursively_into(e_trg);
}
return mesh_new;
}
void Mesh::plot(const char* filename)
{
FILE *f = fopen(filename, "wb");
if(f == NULL) error("problem opening file in Mesh::plot().");
Iterator I(this);
Element *e;
while ((e = I.next_active_element()) != NULL) {
fprintf(f, "%g %d\n", e->x1, 0);
fprintf(f, "%g %d\n", e->x1, e->p);
fprintf(f, "%g %d\n", e->x2, e->p);
fprintf(f, "%g %d\n\n", e->x2, 0);
}
fclose(f);
printf("Mesh written to %s.\n", filename);
}
// Plots the error between the reference and coarse mesh solutions
// if the reference refinement was p-refinement
void Mesh::plot_element_error_p(int norm, FILE *f, Element *e, Element *e_ref,
int subdivision)
{
int n_eq = this->get_n_eq();
int pts_num = subdivision + 1;
if (pts_num > MAX_PLOT_PTS_NUM) {
printf("Try to increase MAX_PLOT_PTS_NUM in common.h\n");
error("MAX_PLOT_PTS_NUM exceeded in plot_element_error_p().");
}
double x1 = e->x1;
double x2 = e->x2;
// calculate point array
double x_phys[MAX_PLOT_PTS_NUM];
double h = (x2 - x1)/subdivision;
for (int i=0; i < pts_num; i++) {
x_phys[i] = x1 + i*h;
}
// get coarse mesh solution values and derivatives
double phys_u[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
phys_dudx[MAX_EQN_NUM][MAX_PLOT_PTS_NUM];
e->get_solution_plot(x_phys, pts_num, phys_u, phys_dudx);
// get fine mesh solution values and derivatives
double phys_u_ref[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
phys_dudx_ref[MAX_EQN_NUM][MAX_PLOT_PTS_NUM];
e_ref->get_solution_plot(x_phys, pts_num, phys_u_ref, phys_dudx_ref);
for (int i=0; i < pts_num; i++) {
double diff_squared_pt = 0;
for (int c=0; c < n_eq; c++) {
double val = phys_u_ref[c][i] - phys_u[c][i];
double der = phys_dudx_ref[c][i] - phys_dudx[c][i];
diff_squared_pt += val*val;
if (norm == 1) diff_squared_pt += der*der;
}
fprintf(f, "%g %g\n", x_phys[i], sqrt(diff_squared_pt));
}
fprintf(f, "\n");
}
// Plots the error between the reference and coarse mesh solutions
// if the reference refinement was hp-refinement
void Mesh::plot_element_error_hp(int norm, FILE *f, Element *e,
Element *e_ref_left,
Element *e_ref_right,
int subdivision)
{
// We will be plotting the error separately in the
// elements e_ref_left (left half of 'e') and
// e_ref_right (right half of 'e').
subdivision /= 2;
int pts_num = subdivision + 1;
if (pts_num > MAX_PLOT_PTS_NUM) {
printf("Try to increase MAX_PLOT_PTS_NUM in common.h\n");
error("MAX_PLOT_PTS_NUM exceeded in plot_element_error_hp().");
}
// First: element e_ref_left
double x1 = e_ref_left->x1;
double x2 = e_ref_left->x2;
// calculate array of x-coordinates
double x_phys_left[MAX_PLOT_PTS_NUM];
double h = (x2 - x1)/subdivision;
for (int i=0; i < pts_num; i++) {
x_phys_left[i] = x1 + i*h;
}
// get coarse mesh solution values and derivatives
double phys_u_left[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
phys_dudx_left[MAX_EQN_NUM][MAX_PLOT_PTS_NUM];
e->get_solution_plot(x_phys_left, pts_num, phys_u_left, phys_dudx_left);
// get fine mesh solution values and derivatives
double phys_u_ref_left[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
phys_dudx_ref_left[MAX_EQN_NUM][MAX_PLOT_PTS_NUM];
e_ref_left->get_solution_plot(x_phys_left, pts_num, phys_u_ref_left,
phys_dudx_ref_left);
for (int i=0; i < pts_num; i++) {
double diff_squared_pt = 0;
for (int c=0; c < n_eq; c++) {
double val = phys_u_ref_left[c][i] - phys_u_left[c][i];
double der = phys_dudx_ref_left[c][i] - phys_dudx_left[c][i];
diff_squared_pt += val*val;
if (norm == 1) diff_squared_pt += der*der;
}
fprintf(f, "%g %g\n", x_phys_left[i], sqrt(diff_squared_pt));
fprintf(f, "\n");
}
// Second: element e_ref_right
x1 = e_ref_right->x1;
x2 = e_ref_right->x2;
// calculate array of x-coordinates
double x_phys_right[MAX_PLOT_PTS_NUM];
h = (x2 - x1)/subdivision;
for (int i=0; i < pts_num; i++) {
x_phys_right[i] = x1 + i*h;
}
// get coarse mesh solution values and derivatives
double phys_u_right[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
phys_dudx_right[MAX_EQN_NUM][MAX_PLOT_PTS_NUM];
e->get_solution_plot(x_phys_right, pts_num, phys_u_right, phys_dudx_right);
// get fine mesh solution values and derivatives
double phys_u_ref_right[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
phys_dudx_ref_right[MAX_EQN_NUM][MAX_PLOT_PTS_NUM];
e_ref_right->get_solution_plot(x_phys_right, pts_num, phys_u_ref_right,
phys_dudx_ref_right);
for (int i=0; i < pts_num; i++) {
double diff_squared_pt = 0;
for (int c=0; c < n_eq; c++) {
double val = phys_u_ref_right[c][i] - phys_u_right[c][i];
double der = phys_dudx_ref_right[c][i] - phys_dudx_right[c][i];
diff_squared_pt += val*val;
if (norm == 1) diff_squared_pt += der*der;
}
fprintf(f, "%g %g\n", x_phys_right[i], sqrt(diff_squared_pt));
fprintf(f, "\n");
}
}
// Plots the error wrt. the exact solution (if available)
void Mesh::plot_element_error_exact(int norm, FILE *f, Element *e,
exact_sol_type exact_sol, int subdivision)
{
int pts_num = subdivision + 1;
double x1 = e->x1;
double x2 = e->x2;
// calculate array of x-coordinates
double x_phys[MAX_PLOT_PTS_NUM];
double h = (x2 - x1)/subdivision;
for (int i=0; i < pts_num; i++) {
x_phys[i] = x1 + i*h;
}
// get coarse mesh solution values and derivatives
double phys_u[MAX_EQN_NUM][MAX_PLOT_PTS_NUM],
phys_dudx[MAX_EQN_NUM][MAX_PLOT_PTS_NUM];
e->get_solution_plot(x_phys, pts_num, phys_u, phys_dudx);
for (int i=0; i < pts_num; i++) {
double exact_sol_point[MAX_EQN_NUM];
double exact_der_point[MAX_EQN_NUM];
exact_sol(x_phys[i], exact_sol_point, exact_der_point);
double diff_squared_pt = 0;
for (int c=0; c < n_eq; c++) {
double val = exact_sol_point[c] - phys_u[c][i];
double der = exact_der_point[c] - phys_dudx[c][i];
diff_squared_pt += val*val;
if (norm == 1) diff_squared_pt += der*der;
}
fprintf(f, "%g %g\n", x_phys[i], sqrt(diff_squared_pt));
}
fprintf(f, "\n");
}
// Plots the error between the reference and coarse mesh solutions
void Mesh::plot_error_estimate(int norm, Mesh* mesh_ref, const char *filename,
int subdivision)
{
char final_filename[MAX_STRING_LENGTH];
sprintf(final_filename, "%s", filename);
FILE *f = fopen(final_filename, "wb");
if(f == NULL) error("problem opening file in plot_error_estimate().");
// simultaneous traversal of 'this' and 'mesh_ref'
Element *e;
Iterator *I = new Iterator(this);
Iterator *I_ref = new Iterator(mesh_ref);
while ((e = I->next_active_element()) != NULL) {
Element *e_ref = I_ref->next_active_element();
if (e->level == e_ref->level) { // element 'e' was not refined in space
// for reference solution
if (e_ref->p >= MAX_P) {
printf("Try to increase MAX_P in common.h.\n");
error("Max poly degree exceeded in plot_error_estimate().");
}
plot_element_error_p(norm, f, e, e_ref, subdivision);
}
else { // element 'e' was refined in space for reference solution
Element* e_ref_left = e_ref;
Element* e_ref_right = I_ref->next_active_element();
if (e_ref_left->p >= MAX_P || e_ref_right->p >= MAX_P) {
printf("Try to increase MAX_P in common.h.\n");
error("Max poly degree exceeded in plot_error_estimate().");
}
plot_element_error_hp(norm, f, e, e_ref_left, e_ref_right,
subdivision);
}
}
fclose(f);
printf("Error function written to %s.\n", final_filename);
}
// Plots the error between the coarse mesh solution
// and the solution stored in the elem_ref_pairs[] array
void Mesh::plot_error_estimate(int norm, ElemPtr2* elem_ref_pairs,
const char *filename,
int subdivision)
{
char final_filename[MAX_STRING_LENGTH];
sprintf(final_filename, "%s", filename);
FILE *f = fopen(final_filename, "wb");
if(f == NULL) error("problem opening file in plot_error_estimate().");
// simultaneous traversal of 'this' and the elem_ref_pairs[] array
Element *e;
Iterator *I = new Iterator(this);
while ((e = I->next_active_element()) != NULL) {
Element* e_ref = elem_ref_pairs[e->id][0];
if (e->level == e_ref->level) { // element 'e' was not refined in space
// for reference solution
if (e_ref->p >= MAX_P) {
printf("Try to increase MAX_P in common.h.\n");
error("Max poly degree exceeded in plot_error_estimate().");
}
plot_element_error_p(norm, f, e, e_ref, subdivision);
}
else { // element 'e' was refined in space for reference solution
Element* e_ref_left = e_ref;
Element* e_ref_right = elem_ref_pairs[e->id][1];
if (e_ref_left->p >= MAX_P || e_ref_right->p >= MAX_P) {
printf("Try to increase MAX_P in common.h.\n");
error("Max poly degree exceeded in plot_error_estimate().");
}
plot_element_error_hp(norm, f, e, e_ref_left, e_ref_right,
subdivision);
}
}
fclose(f);
printf("Error function written to %s.\n", final_filename);
}
// Plots the error wrt. the exact solution (if available)
void Mesh::plot_error_exact(int norm, exact_sol_type exact_sol,
const char *filename,
int subdivision)
{
char final_filename[MAX_STRING_LENGTH];
sprintf(final_filename, "%s", filename);
FILE *f = fopen(final_filename, "wb");
if(f == NULL) error("problem opening file in plot_error_exact().");
// traversal of 'this'
Element *e;
Iterator *I = new Iterator(this);
while ((e = I->next_active_element()) != NULL) {
if (e->p >= MAX_P) {
printf("Try to increase MAX_P in common.h.\n");
error("Max poly degree exceeded in plot_error_exact().");
}
plot_element_error_exact(norm, f, e, exact_sol, subdivision);
}
fclose(f);
printf("Exact solution error written to %s.\n", final_filename);
}
// Use the err_array[] and threshold to create a list of
// elements to be refined.
void create_ref_index_array(double threshold, double *err_array,
int n_elem, int *adapt_list, int &num_to_adapt)
{
// debug
//printf("num_to_adapt = %d\n", num_to_adapt);
//for (int i=0; i < n_elem; i++) printf("err_array[%d] = %g\n", i, err_array[i]);
// Find element with largest error
double max_elem_error = 0;
for(int i=0; i < n_elem; i++) {
if (err_array[i] > max_elem_error) {
max_elem_error = err_array[i];
}
}
// Create auxiliary array of element indices
int id_array[MAX_ELEM_NUM];
for(int i=0; i < n_elem; i++) {
if(err_array[i] < threshold*max_elem_error) id_array[i] = -1;
else id_array[i] = i;
}
/*
// Debug:
// Print elements to be refined
printf("Elements to be refined:\n");
for (int i=0; i < n_elem; i++) {
if (id_array[i] >= 0) printf("Elem[%d], error = %g\n", id_array[i],
err_array[i]);
}
*/
// Create list of elements to be refined, in increasing order
num_to_adapt = 0;
for (int i=0; i < n_elem; i++) {
if (id_array[i] >= 0) {
adapt_list[num_to_adapt] = id_array[i];
num_to_adapt++;
}
}
/*
// Debug: Printing list of elements to be refined
printf("Elements to be refined: ");
for (int i=0; i<num_to_adapt; i++) printf("%d ", adapt_list[i]);
printf("\n");
*/
}
// Returns updated coarse and reference meshes, with the last
// coarse and reference mesh solutions on them, respectively.
// The coefficient vectors and numbers of degrees of freedom
// on both meshes are also updated.
void adapt(int norm, int adapt_type, double threshold,
double *err_array,
Mesh* &mesh, Mesh* &mesh_ref)
{
int n_elem = mesh->get_n_active_elem();
// Use the err_array[] and threshold to create a list of
// elements to be refined.
int adapt_list[MAX_ELEM_NUM];
int num_to_adapt;
create_ref_index_array(threshold, err_array, n_elem, adapt_list, num_to_adapt);
// Replicate the coarse and fine meshes. The original meshes become
// backup and refinements will only be done in the new ones.
Mesh *mesh_new = mesh->replicate();
Mesh *mesh_ref_new = mesh_ref->replicate();
// Simultaneous traversal of all meshes.
// For each element in 'mesh_new', create a list of refinement
// candidates and select the one that best resembles the reference
// solution on 'mesh_ref_new'. While elements in 'mesh_new' are refined,
// corresponding refinements are also done in 'mesh_ref_new'.
Iterator *I = new Iterator(mesh);
Iterator *I_new = new Iterator(mesh_new);
Iterator *I_ref = new Iterator(mesh_ref);
Iterator *I_ref_new = new Iterator(mesh_ref_new);
Element *e = I->next_active_element();
Element *e_new = I_new->next_active_element();
Element *e_ref = I_ref->next_active_element();
Element *e_ref_new = I_ref_new->next_active_element();
int counter = 0;
while (counter != num_to_adapt) {
if (e->id == adapt_list[counter]) {
counter++;
int choice = 0;
// Every refinement candidate consists of three
// and then either one or two polynomial degrees
int3 cand_list[MAX_CAND_NUM];
Element* e_ref_left;
Element* e_ref_right;
Element* e_ref_new_left;
Element* e_ref_new_right;
// Element 'e' was not refined in space
// for reference solution.
if (e->level == e_ref->level) {
e_ref_left = e_ref;
e_ref_new_left = e_ref_new;
e_ref_right = NULL;
e_ref_new_right = NULL;
int num_cand = e->create_cand_list(adapt_type, e_ref->p, -1, cand_list);
// debug:
//e->print_cand_list(num_cand, cand_list);
// reference element was p-refined
choice = select_hp_refinement(e, e_ref, NULL, num_cand, cand_list,
0, norm);
}
// Element 'e' was refined in space for reference solution.
else {
e_ref_left = e_ref;
e_ref_new_left = e_ref_new;
e_ref_right = I_ref->next_active_element();
e_ref_new_right = I_ref_new->next_active_element();
int num_cand = e->create_cand_list(adapt_type, e_ref_left->p,
e_ref_right->p, cand_list);
choice = select_hp_refinement(e, e_ref_left, e_ref_right,
num_cand, cand_list, 1, norm);
}
// Next we perform the refinement defined by cand_list[choice]
// e_new_last... element in mesh_new that will be refined,
// e_ref_left... corresponding element in fine mesh (if reference
// refinement was p-refinement). In this case
// e_ref_right == NULL
// e_ref_left, e_ref_right... corresponding pair of elements
// in the fine mesh if reference refinement was hp-refinement
Element *e_new_last = e_new;
// moving pointers 'e' and 'e_new' to the next position in coarse meshes
// and 'e_ref' and 'e_ref_new' to the next position in fine meshes
e = I->next_active_element();
e_new = I_new->next_active_element();
e_ref = I_ref->next_active_element();
e_ref_new = I_ref_new->next_active_element();
// perform the refinement of element e_new_last
e_new_last->refine(cand_list[choice]);
//printf(" Refined element (%g, %g), cand = (%d %d %d)\n",
// e_new_last->x1, e_new_last->x2, cand_list[choice][0],
// cand_list[choice][1], cand_list[choice][2]);
if(cand_list[choice][0] == 1) mesh_new->n_active_elem++;
// perform corresponding refinement(s) in the new fine mesh
if (e_new_last->level == e_ref_left->level) { // ref. refinement of 'e_last' was
// p-refinement so also future ref.
// refinements will be p-refinements
if (cand_list[choice][0] == 0) { // e_last is being p-refined, thus also
// e_ref_new_left needs to be p-refined
int new_p = cand_list[choice][1];
e_ref_new_left->refine(0, new_p + 1, -1);
}
else { // e_new_last is being split, thus e_ref_new_left needs to be
// split as well
int new_p_left = cand_list[choice][1];
int new_p_right = cand_list[choice][2];
e_ref_new_left->refine(1, new_p_left + 1, new_p_right + 1);
mesh_ref_new->n_active_elem++;
}
}
else { // ref. refinement was hp-refinement, so also future
// ref. refinements will be hp-refinements
if (cand_list[choice][0] == 0) { // e_new_last is being p-refined, thus also
// e_ref_new_left and e_ref_new_right
// will just be p-refined
int new_p = cand_list[choice][1];
e_ref_new_left->refine(0, new_p + 1, -1);
e_ref_new_right->refine(0, new_p + 1, -1);
}
else { // e_new_last is being hp-refined, so we need to
// split both e_ref_new_left and e_ref_new_right
int new_p_left = cand_list[choice][1];
int new_p_right = cand_list[choice][2];
e_ref_new_left->refine(1, new_p_left + 1, new_p_left + 1);
mesh_ref_new->n_active_elem++;
e_ref_new_right->refine(1, new_p_right + 1, new_p_right + 1);
mesh_ref_new->n_active_elem++;
}
}
}
else {
e = I->next_active_element();
e_new = I_new->next_active_element();
e_ref = I_ref->next_active_element();
e_ref_new = I_ref_new->next_active_element();
if (e->level != e_ref->level) {
e_ref = I_ref->next_active_element();
e_ref_new = I_ref_new->next_active_element();
}
}
}
// enumerate dofs in both new meshes
int n_dof_new = mesh_new->assign_dofs();
int n_dof_ref_new = mesh_ref_new->assign_dofs();
printf("Coarse mesh refined (%d elem, %d DOF)\n",
mesh_new->get_n_active_elem(), n_dof_new);
printf("Fine mesh refined (%d elem, %d DOF)\n",
mesh_ref_new->get_n_active_elem(), n_dof_ref_new);
// Delete old meshes and copy the new ones in place of them
delete mesh;
delete mesh_ref;
mesh = mesh_new;
mesh_ref = mesh_ref_new;
// Last adjust the number of dofs in each mesh
mesh->set_n_dof(n_dof_new);
mesh_ref->set_n_dof(n_dof_ref_new);
}
// Returns updated coarse mesh, with the last
// coarse solution on it.
// The coefficient vector and number of degrees of freedom
// also is updated.
void adapt(int norm, int adapt_type, double threshold,
double *err_array,
Mesh* &mesh, ElemPtr2 *ref_elem_pairs)
{
int n_elem = mesh->get_n_active_elem();
// Use the err_array[] and threshold to create a list of
// elements to be refined.
int adapt_list[MAX_ELEM_NUM];
int num_to_adapt;
create_ref_index_array(threshold, err_array, n_elem, adapt_list, num_to_adapt);
// Replicate the coarse mesh. The original coarse mesh becomes
// backup and refinements will only be done in the new one.
Mesh *mesh_new = mesh->replicate();
// Simultaneous traversal of mesh_new and the ref_elem_pairs[] array.
// For each element in mesh_new create a list of refinement
// candidates and select the one that best resembles the reference
// solution in ref_elem_pairs[].
Iterator *I = new Iterator(mesh);
Iterator *I_new = new Iterator(mesh_new);
Element *e = I->next_active_element();
Element *e_new = I_new->next_active_element();
int counter_adapt = 0;
while (counter_adapt != num_to_adapt) {
if (e->id == adapt_list[counter_adapt]) {
counter_adapt++;
int choice = 0;
// Every refinement candidate consists of three
// and then either one or two polynomial degrees
int3 cand_list[MAX_CAND_NUM];
Element* e_ref = ref_elem_pairs[e->id][0];
Element* e_ref_left;
Element* e_ref_right;
// Element 'e' was not refined in space
// for reference solution.
if (e->level == e_ref->level) {
e_ref_left = e_ref;
e_ref_right = NULL;
int num_cand = e->create_cand_list(adapt_type, e_ref->p, -1, cand_list);
// debug:
//e->print_cand_list(num_cand, cand_list);
// reference element was p-refined
choice = select_hp_refinement(e, e_ref, NULL, num_cand, cand_list,
0, norm);
}
// Element 'e' was refined in space for reference solution.
else {
e_ref_left = e_ref;
e_ref_right = ref_elem_pairs[e->id][1];
int num_cand = e->create_cand_list(adapt_type, e_ref_left->p,
e_ref_right->p, cand_list);
choice = select_hp_refinement(e, e_ref_left, e_ref_right,
num_cand, cand_list, 1, norm);
}
// Next we perform the refinement defined by cand_list[choice]
// e_new_last... element in mesh_new that will be refined,
// e_ref_left... corresponding element in ref_elem_pairs[] (if reference
// refinement was p-refinement). In this case
// e_ref_right == NULL
// e_ref_left, e_ref_right... corresponding pair of elements
// in ref_elem_pairs[] (if reference refinement was hp-refinement)
Element *e_new_last = e_new;
// moving pointers 'e' and 'e_new' to the next position in coarse meshes
e = I->next_active_element();
e_new = I_new->next_active_element();
// perform the refinement of element e_new_last
e_new_last->refine(cand_list[choice]);
printf(" Refined element (%g, %g), cand = (%d %d %d)\n",
e_new_last->x1, e_new_last->x2, cand_list[choice][0],
cand_list[choice][1], cand_list[choice][2]);
if(cand_list[choice][0] == 1) mesh_new->n_active_elem++;
}
else {
e = I->next_active_element();
e_new = I_new->next_active_element();
}
}
// enumerate dofs in both new meshes
int n_dof_new = mesh_new->assign_dofs();
printf("New mesh has %d elements.\n",
mesh_new->get_n_active_elem(), n_dof_new);
// Delete old coarse mesh
delete mesh;
mesh = mesh_new;
// check on DOF overflow
if (n_dof_new > MAX_N_DOF) error("MAX_N_DOF exceeded in adapt().");
// Adjust the number of dofs
mesh->set_n_dof(n_dof_new);
}
void adapt_plotting(Mesh *mesh, Mesh *mesh_ref,
int norm, int exact_sol_provided,
exact_sol_type exact_sol)
{
// Plot the coarse mesh solution
Linearizer l(mesh);
l.plot_solution("solution.gp");
// Plot the fine mesh solution
Linearizer l_ref(mesh_ref);
l_ref.plot_solution("solution_ref.gp");
// Plot the coarse and fine meshes
mesh->plot("mesh.gp");
mesh_ref->plot("mesh_ref.gp");
// Plot the error estimate (difference between
// coarse and fine mesh solutions)
mesh->plot_error_estimate(norm, mesh_ref, "error_est.gp");
// Plot error wrt. exact solution (if available)
if (exact_sol_provided) {
mesh->plot_error_exact(norm, exact_sol, "error_exact.gp");
}
}
void adapt_plotting(Mesh *mesh, ElemPtr2 *ref_elem_pairs,
int norm, int exact_sol_provided,
exact_sol_type exact_sol)
{
// Plot the coarse mesh solution.
Linearizer l(mesh);
l.plot_solution("solution.gp");
// Plot solution stored in the ref_elem_pairs[] array.
Linearizer l_ref(mesh);
l_ref.plot_ref_elem_pairs(ref_elem_pairs, "solution_ref.gp");
// Plot the mesh
mesh->plot("mesh.gp");
// Plot the difference between the coarse mesh solution
// and the solution stored in the ref_elem_pairs[] array.
mesh->plot_error_estimate(norm, ref_elem_pairs, "error_est.gp");
// Plot error wrt. exact solution (if available).
if (exact_sol_provided) {
mesh->plot_error_exact(norm, exact_sol, "error_exact.gp");
}
}
void copy_mesh_to_vector(Mesh *mesh, double *y, int sln) {
Element *e;
Iterator *I = new Iterator(mesh);
while ((e = I->next_active_element()) != NULL) {
e->copy_coeffs_to_vector(y, sln);
}
delete I;
}
void copy_vector_to_mesh(double *y, Mesh *mesh, int sln)
{
Element *e;
Iterator *I = new Iterator(mesh);
while ((e = I->next_active_element()) != NULL) {
e->get_coeffs_from_vector(y, sln);
}
delete I;
}
|
42464df414b38d98d75120c0b156ec276c122dc5 | dddea9f57189af8e26a7a0da95ef57116d9a0a37 | /application/include/Link.h | 07cc54d494b9e3606e831933ec87e02642c36647 | [] | no_license | sunnybouorm/Task_Tracker | ecb09f81d5c001f91f7c0449f9ea3b7255f612ff | c4b2a7ee7e56b80bba422f2b67f5c64e11474858 | refs/heads/master | 2016-09-05T18:14:10.363717 | 2015-01-29T07:00:59 | 2015-01-29T07:00:59 | 28,864,357 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 745 | h | Link.h | /* Date Created : 19/12/2014
* Author : Sultan Bou Orm
* Description :
* Links connect to two nodes, pointing to two regions in memory with a unique
* LID used to identify the link.
*/
#ifndef LINK_H
#define LINK_H
#include<vector>
#include "stdint.h"
#include "Task.h"
#include "Category.h"
class Link{
friend class Link_Manager;
private :
uint16_t LID;//link ID
std::pair<Task*, Category*> nodes;
std::pair<std::string, std::string> nodeTypes;
Link(Task *tp, Category *cp, const uint16_t &IDval);
void set_LID(uint16_t &val){LID=val;};
void print(void);
public:
Link(){LID=0;};
uint16_t get_LID(void){return LID;};
std::pair<Task*, Category*> get_pair() {return nodes;};
};
#endif // LINK_H
|
4820fdc444098afecceb23061f3ae6af053675e8 | bda65138aff4a6cc0e84ddc51acec7ea0fff7ba3 | /Program 1 CSSE 1430/1430Program.cpp | c77507fc68784d8feb39b788e9bef9ad55ba6158 | [] | no_license | schultzder/C-programs-and-assignments | 44d5f799b6bc6619cb430ceffec03ae8d969a139 | 1927eb2daeb63048f92bac484647489cf58a51fa | refs/heads/master | 2020-03-31T23:48:48.571327 | 2018-10-12T00:14:27 | 2018-10-12T00:14:27 | 152,670,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,374 | cpp | 1430Program.cpp | //------------------------------------------------------------------------
//
// Name: Derek Schultz
//
// Course: CS 1430, Section 2
//
// Purpose: Wtrie a program to calculate the GPA for four courses.
//
// Input: The program will accept inputs in the form of integers for the credits and grades.
// grades - as an int
// credits - as an int
// Output: The program will provide the semester summary for a given student, including:
// Total creidts: Whether or not it was a full load
// GPA: Whether or not the student made the honors list
//------------------------------------------------------------------------
//
// TODO1: Right-click to the right of the last dash above, select
// Guidelines, and then select Add Guideline. This will place a
// Guideline at the end of column 74. Do not go past it!
// You can also change the color of the Guideline by right-clicking.
// TODO2: To reformat, click Edit -> Advanced -> Format Document.
// This will clean up the formatting if you have issues.
// Then recheck to make sure line lengths are inside the Guidelines.
// The above TODO's assume templates were properly installed as per
// Step 4 of the Visual_Studio_2015_Installation document at:
// K:\Academic\CSSE\Software\VisualStudo2015_Installation
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int fullLoad = 12;
const float honorList = 3.5;
int main()
{
// Input Variables //
int course1_credits;
int course2_creidts;
int course3_credits;
int course4_credits;
int course1_grade;
int course2_grade;
int course3_grade;
int course4_grade;
int totalCredits;
int gradePoints;
float GPA;
string lastname;
// Prompt: Enter last name //
cout << "Enter last name: " << endl;
cin >> lastname;
// Prompts: Enter credits and grades //
cout << "Enter the credits for Course 1: " << endl;
cin >> course1_credits;
cout << "Enter the grade for Course 1, where F=0, A=4: " << endl;
cin >> course1_grade;
cout << "Enter the credits for Course 2: " << endl;
cin >> course2_creidts;
cout << "Enter the grade for Course 2, where F=0, A=4: " << endl;
cin >> course2_grade;
cout << "Enter the credits for Course 3: " << endl;
cin >> course3_credits;
cout << "Enter the grade for Course 3, where F=0, A=4: " << endl;
cin >> course3_grade;
cout << "Enter the credits for Course 4: " << endl;
cin >> course4_credits;
cout << "Enter the grade for Course 4, where F=0, A=4: " << endl;
cin >> course4_grade;
// Calculations //
totalCredits = course1_credits + course2_creidts + course3_credits
+ course4_credits;
gradePoints = (course1_credits * course1_grade) +
(course2_creidts * course2_grade) +
(course3_credits * course3_grade) +
(course4_credits * course4_grade);
GPA = float(float(gradePoints) / float(totalCredits));
// Final Output //
cout << "Semester summary for "; cout << lastname << endl;
cout << " Credits: "; cout << totalCredits << endl;
if (totalCredits >= fullLoad) cout << " Full Credit Load " << endl;
cout << " GPA: "; cout << GPA << endl;
if (GPA >= 3.5) cout << " Honors List " << endl;
cout << "Normal Termination of Program 1." << endl;
return 0;
} |
f8d6f4233283fa9840c813f31b8e83e77fd20951 | 7cb110accee977bfcb6bd72ce1347df9d5158640 | /src/worker_task.cpp | 530cfbb72956d2ed899e4f13dc1a97e405a40422 | [] | no_license | Towerism/csce-313-mp5 | 31857790d95de1658c39b6f5773131ef9320464d | f05036c6659b724f890c29bebb9b137aa30e297e | refs/heads/master | 2021-04-27T09:08:13.259395 | 2015-05-05T01:54:46 | 2015-05-05T01:54:46 | 122,508,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | worker_task.cpp | #include <string>
#include <cstring>
#include <unistd.h>
#include "worker_task.h"
#include "bounded_buffer.h"
#include "util.h"
Worker_task::Worker_task(Bounded_buffer<Data>* buf, Buffer_filter& out_bufs, NetworkRequestChannel& ctrl) : buffer(buf), out_buffers(out_bufs) {
std::cout << "" << std::endl;
std::string chan_handle = ctrl.send_request("newthread");
channel = new NetworkRequestChannel(chan_handle, NetworkRequestChannel::CLIENT_SIDE, ctrl.get_hostname(), ctrl.get_port());
}
void Worker_task::run() {
while (!cancelled) {
Data d = buffer->dequeue();
std::string response = channel->send_request("data");
// make sure the response is a number before putting it in out_buffers
if (is_number(response)) {
out_buffers.push(Data(d.request_origin, response));
}
}
}
|
89d0c2e56ea436735f96027926c99ae726a3522a | e7d550d4dbda4e0e0471f15acc34578f7311e3d6 | /abc044/b.cpp | 862774e82aae23e63476f46ad2292e94ebcb8e11 | [] | no_license | amrk0320/atcorder-cpp | bf74e26e810b2c130db8cab3441b72f22b5e2cd4 | dae9d6060426150620f6a145991a88df6dcf5309 | refs/heads/master | 2023-02-09T23:11:02.381020 | 2021-01-05T11:32:17 | 2021-01-05T11:32:17 | 286,736,637 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | cpp | b.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
string s;
cin >> s;
map<char, int> pat;
for (int i = 0; i < s.size(); i++){
pat[s.at(i)]++;
}
for (char i = 'a'; i <= 'z'; i++){
if (pat.count(i)) {
if (pat.at(i) %2 != 0 ) {
cout << "No" << endl;
return 0;
}
}
}
cout << "Yes" << endl;
}
|
a765ecbafea67ab34f58655b70c87ca4ae6d248e | be93b9ffb49ec6f73d2558cedd02cd50a4060858 | /Online judge solutions/Spoj/BYTESM2.cpp | 3dc4c032be130d1d6d5aeeaae0f394d68f83fb81 | [] | no_license | salonimohta/competitive-programming | ceec3c2c87eb8078b051166654c3faac5ce27d0b | 2639a14acf4beb453bb9277779ad5d705c6fa97a | refs/heads/master | 2020-08-09T02:12:27.005619 | 2019-10-14T08:07:46 | 2019-10-14T08:07:46 | 213,975,049 | 2 | 0 | null | 2019-10-09T16:59:36 | 2019-10-09T16:59:36 | null | UTF-8 | C++ | false | false | 876 | cpp | BYTESM2.cpp | #include<cmath>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef double lf;
typedef long long ll;
typedef long double LF;
typedef unsigned long long ull;
using namespace std;
int ans(int h,int w,int *s,int *sum,int i,int j){
if(i<0 || i>=h || j<0 || j>=w) return 0;
if( *(sum+i*w+j) ) return *(sum+i*w+j);
*(sum+i*w+j) = max( ans(h,w,s,sum,i-1,j) , max( ans(h,w,s,sum,i-1,j-1) , ans(h,w,s,sum,i-1,j+1) ) ) + *(s+i*w+j);
return *(sum+i*w+j);
}
int main(){
int t;
cin >> t;
while(t--){
int h,w;
cin >> h >> w;
int s[h][w],sum[h][w];
memset(sum,0,h*w*sizeof(int));
for(int i=0 ; i<h ; i++){
for(int j=0 ; j<w ; j++){
cin >> s[i][j];
}
}
int maximum = INT_MIN;
for(int j=w-1 ; j>=0 ; j--){
maximum=max(maximum,ans(h,w,(int*)s,(int*)sum,h-1,j));
}
cout << maximum << "\n";
}
return 0;
}
|
a35a217855aafa347d2993b1047b61d9267a2846 | 70d59e29be5357c06e642691bd57a65fe3832289 | /include/BoundingBox.h | 0d2badb205dadb48a73c4348833a0bf0ed555acf | [] | no_license | hdaMagi/opengl_rain | 370c3461e6aa4323a918b124465b4a7d54b5fde2 | 590c4c1308fa09a47d302c9c4452aac6acdc55de | refs/heads/master | 2021-01-12T12:23:04.364745 | 2017-01-10T13:04:26 | 2017-01-10T13:04:26 | 72,480,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | BoundingBox.h | /*
* BoundingBox.h
*
* Created on: 22.12.2016
* Author: jannis
*/
#ifndef BOUNDINGBOX_H_
#define BOUNDINGBOX_H_
#include <vector>
#include "MassPoint.h"
#include "Globals.h"
class BoundingBox {
public:
BoundingBox();
BoundingBox(std::vector<MassPoint> vecMassPoints);
void update(std::vector<MassPoint> vecMassPoints);
point2d pAC;
point2d pAF;
point2d p1;
point2d p2;
virtual ~BoundingBox();
};
#endif /* BOUNDINGBOX_H_ */
|
6543342a06bb71d22e56f951b4fa68efbb999fb9 | 11faa02f6258d6710f5a87b9476859e23aeafff4 | /simulation/17144.cpp | 5f7ac9b529e8dd66ff7f13621308abf16ca0e51f | [] | no_license | brorica/Algorithm | 46480876ea47232b92f4b2577ff1f3d38ca3cb6d | 748e9662794f8a19bff1a5037ee1afc9ce39d163 | refs/heads/main | 2023-08-17T19:58:58.406251 | 2021-10-01T14:18:44 | 2021-10-01T14:18:44 | 326,300,128 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,496 | cpp | 17144.cpp | #include <iostream>
#include <cstring>
using namespace std;
int r, c, t;
int room[52][52] = { 0, }, roomTemp[52][52] = { 0, }, cleaner[2];
int dx[4] = { 0,0,1,-1 }, dy[4] = { 1,-1,0,0, };
int spread()
{
int avg;
int thereX, thereY;
memcpy(roomTemp, room, sizeof(room));
for (int i = 1; i <= c; i++)
{
for (int j = 1; j <= r; j++)
{
if (room[i][j] == -1)
continue;
avg = room[i][j] / 5;
for (int k = 0; k < 4; k++)
{
thereX = j + dx[k];
thereY = i + dy[k];
if (thereX < 1 || thereX > r || thereY < 1 || thereY > c || room[thereY][thereX] == -1)
continue;
roomTemp[i][j] -= avg;
roomTemp[thereY][thereX] += avg;
}
}
}
memcpy(room, roomTemp, sizeof(room));
return 0;
}
int topMove()
{
int top = cleaner[0];
int prevTemp, currentTemp;
prevTemp = room[top][2];
room[top][2] = 0;
for (int i = 2 + 1; i <= r; i++)
{
currentTemp = room[top][i];
room[top][i] = prevTemp;
prevTemp = currentTemp;
}
for (int i = top - 1; i >= 1; i--)
{
currentTemp = room[i][r];
room[i][r] = prevTemp;
prevTemp = currentTemp;
}
for (int i = r - 1; i >= 1; i--)
{
currentTemp = room[1][i];
room[1][i] = prevTemp;
prevTemp = currentTemp;
}
for (int i = 1 + 1; i < top; i++)
{
currentTemp = room[i][1];
room[i][1] = prevTemp;
prevTemp = currentTemp;
}
return 0;
}
int bottomMove()
{
int bottom = cleaner[1];
int prevTemp, currentTemp;
prevTemp = room[bottom][2];
room[bottom][2] = 0;
for (int i = 2 + 1; i <= r; i++)
{
currentTemp = room[bottom][i];
room[bottom][i] = prevTemp;
prevTemp = currentTemp;
}
for (int i = bottom + 1; i <= c; i++)
{
currentTemp = room[i][r];
room[i][r] = prevTemp;
prevTemp = currentTemp;
}
for (int i = r - 1; i >= 1; i--)
{
currentTemp = room[c][i];
room[c][i] = prevTemp;
prevTemp = currentTemp;
}
for (int i = c - 1; i > bottom; i--)
{
currentTemp = room[i][1];
room[i][1] = prevTemp;
prevTemp = currentTemp;
}
return 0;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int cleanerIndex = 0;
cin >> c >> r >> t;
// r : Çà c : ¿
for (int i = 1; i <= c; i++)
{
for (int j = 1; j <= r; j++)
{
cin >> room[i][j];
if (room[i][j] == -1)
cleaner[cleanerIndex++] = i;
}
}
while (t--)
{
spread();
topMove();
bottomMove();
}
int ans = 0;
for (int i = 1; i <= c; i++)
{
for (int j = 1; j <= r; j++)
{
if (room[i][j] != -1)
ans += room[i][j];
}
}
cout << ans;
return 0;
}
|
19e8388a86716b76ee57c853a2a8910a3c113a72 | 1885ce333f6980ab6aad764b3f8caf42094d9f7d | /test/e2e/test_input/wxWidgets/include/wx/gtk/private/image.h | ed5e7091bc4b1b4cc46e4d071019e59f8ba0440c | [
"MIT"
] | permissive | satya-das/cppparser | 1dbccdeed4287c36c61edc30190c82de447e415b | f9a4cfac1a3af7286332056d7c661d86b6c35eb3 | refs/heads/master | 2023-07-06T00:55:23.382303 | 2022-10-03T19:40:05 | 2022-10-03T19:40:05 | 16,642,636 | 194 | 26 | MIT | 2023-06-26T13:44:32 | 2014-02-08T12:20:01 | C++ | UTF-8 | C++ | false | false | 1,025 | h | image.h | ///////////////////////////////////////////////////////////////////////////////
// Name: wx/gtk/private/image.h
// Author: Paul Cornett
// Copyright: (c) 2020 Paul Cornett
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// Class that can be used in place of GtkImage, to allow drawing of alternate
// bitmaps, such as HiDPI or disabled.
class wxGtkImage: GtkImage
{
public:
struct BitmapProvider
{
virtual ~BitmapProvider() { }
virtual wxBitmap Get() const = 0;
virtual void Set(const wxBitmap&) { }
};
static GType Type();
static GtkWidget* New(BitmapProvider* provider);
static GtkWidget* New(wxWindow* win = NULL);
void Set(const wxBitmap& bitmap);
BitmapProvider* m_provider;
wxDECLARE_NO_COPY_CLASS(wxGtkImage);
wxGtkImage() wxMEMBER_DELETE;
~wxGtkImage() wxMEMBER_DELETE;
};
#define WX_GTK_IMAGE(obj) G_TYPE_CHECK_INSTANCE_CAST(obj, wxGtkImage::Type(), wxGtkImage)
|
46cb21cdc13dd0cf02103d192a2fc251dc2719dc | 639b07558de6dcdb9b428c29b251736c55d4c6eb | /Programming For Graphics/Assignment 2/Flipbook Texture Animations/TestApp/Camera.h | 44662eabac8c935a8729a4fed721df562335c93f | [] | no_license | Danbob-Airsoft/Programming-for-Graphics | f85cc676df844683604bbc419ad74117e320f3d7 | 0cf6dd00569b698bd45ace83b62bb12cab2811d4 | refs/heads/master | 2021-03-29T23:49:19.653411 | 2020-12-27T14:30:16 | 2020-12-27T14:30:16 | 247,995,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | h | Camera.h | #pragma once
#include "Transform.h"
#include "glm/glm.hpp"
#include "glm/gtx/transform.hpp"
class Camera
{
public:
Transform* CameraTransform = new Transform();
glm::vec3 ForwardVec;
glm::vec3 UpVec;
glm::vec3 RightVec;
float fov = 120.0f;
float aspect = 800.0f / 800.0f;
float znear = 0.1f;
float zfar = 100.0f;
void UpdateVectors();
mat4 m_PerspectiveProjection;
mat4 CalculateViewMatrix();
Camera(glm::vec3 _pos)
{
CameraTransform->SetPosition(_pos);
m_PerspectiveProjection = glm::perspective(glm::radians(fov), aspect, znear, zfar);
}
mat4 GetPerspective()
{
return m_PerspectiveProjection;
}
};
|
837302f641024e846144e9ce88705dc3e8b69962 | 685c659628c34e42144ee87a467d55a02d11df71 | /numerical_analysis/gaussian_elimimination_with_pivoting.cc | a22aab8d4ed55e7dfa9f9cd5679036cbe0c79823 | [] | no_license | tshita/algorithm | 9959bee5ce7b69f4e51243203062c321e3060a87 | df1181c12041779b406ae0ac121d7fb0a7b11132 | refs/heads/master | 2022-12-24T14:04:54.191621 | 2019-07-07T23:10:35 | 2019-07-07T23:10:35 | 61,629,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,044 | cc | gaussian_elimimination_with_pivoting.cc | /*
Gaussian Elimination With Pivoting
枢軸選択付きガウスの消去法
==================================
# Problem
Input: n x n 正方行列 A, n 次元列ベクトル b
Output: Ax = b を満たす n 次元列ベクトル x
# Complexity
- Time: O(n^3) (前進消去でほぼ n^3 / 3 回,後進代入でほぼ n^2 / 2 回)
# Usage
- Vector GaussianElimination(A, b): A と b を入力として x を返す
(A が正則行列でないとき空ベクトルを返す)
# Description
ガウスの消去法(gaussian elimination)または掃き出し法(row reduction)とは
連立一次方程式を解く直接法のアルゴリズム.前進消去で上三角行列にして,後進代入で x の値を求める.
枢軸(pivot)は絶対値が最大となるものを選択している.ただし,EPS よりも小さいときは 0 とみなしている.
A が正則であることと A のランクが n であることは必要十分なので,枢軸として 0 のものがあるときは
解なしとして空ベクトルを返す.
# Note
- 引数の A と b は値渡しで内部で破壊される
- 誤差が大きいので注意(求めた Ax の値と b を比較すると 100 * EPS よりも大きい場合がある)
# References
- [数値解析(松尾) 配付資料]
(http://www.sr3.t.u-tokyo.ac.jp/~matsuo/lecture/12suchi/shiryo2.pdf)
# Verified
*/
#include <iostream>
#include <vector>
#include <cassert>
// -------------8<------- start of library -------8<------------------------
using Number = double;
using Vector = std::vector<Number>;
using Matrix = std::vector<Vector>;
constexpr Number EPS = 1e-12;
Vector GaussianElimination(Matrix A, Vector b) {
const size_t N = A.size();
assert(0 < N && N == A[0].size() && N == b.size());
// 前進消去
for (size_t k = 0; k + 1 < N; ++k) {
size_t pivot = k;
for (size_t i = k + 1; i < N; ++i)
if (std::abs(A[pivot][k]) < std::abs(A[i][k])) pivot = i;
if (std::abs(A[pivot][k]) <= EPS) return Vector{};
std::swap(A[k], A[pivot]); std::swap(b[k], b[pivot]);
for (size_t i = k + 1; i < N; ++i) {
A[i][k] = A[i][k] / A[k][k];
for (size_t j = k + 1; j < N; ++j)
A[i][j] -= A[i][k] * A[k][j];
b[i] -= A[i][k] * b[k];
}
}
// 後退代入
for (int i = N - 1; 0 <= i; --i) {
Number sum = 0;
for (size_t j = i + 1; j < N; ++j) sum += A[i][j] * b[j];
b[i] = (b[i] - sum) / A[i][i];
}
return b;
}
// -------------8<------- end of library ---------8-------------------------
int main() {
std::cin.tie(0); std::ios::sync_with_stdio(false);
Matrix A = {{1, 0}, {0, 1}};
Vector b = {1, 2};
Vector x = GaussianElimination(A, b);
for (const auto &e : x) std::cout << e << std::endl;
return 0;
}
|
fb558ee8a7242582be0acdfebffd5cc3d450630b | af7c1052e88457de6226ee59e810075b167af571 | /Projects_2010VS/Linguamatics/Linguamatics/TextInputFile.h | f7c5a9f181cd646916128403549f803dea120c44 | [] | no_license | peter-tang2015/cplusplus | 350140edb6b635b294262fe9a45fc6335598ab26 | 86de487c75cfb4549d46e4e9ff1fc64cd35a80d8 | refs/heads/master | 2021-01-12T15:02:02.654795 | 2016-10-02T11:51:42 | 2016-10-02T11:51:42 | 69,789,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | h | TextInputFile.h | #pragma once
#ifndef TEXT_INPUT_FILE_H
#define TEXT_INPUT_FILE_H
#include "TextFile.h"
namespace Linguamatics {
namespace TextHighlight {
class TextInputFile :
public TextFile
{
public:
TextInputFile(const std::string &fileName);
~TextInputFile(void);
void GetTextString(std::string &text);
private:
std::ifstream m_IFileStream;
};
}
}
#endif |
60d2136c473242aab1b7d8205a6366e229e42eaf | 20371ffc4d2989cf52d4785ba91f65253911a360 | /16章/ex16_16_VecTest.cpp | 34b76d9bea1bf38b8e557c139d92d76474dd2e83 | [] | no_license | jhxu1/Cpp-Primer | abafa1f46fae971f404ec5c3e1a735b6e762317b | 27fed29ea1c6f018088bf53a9043fe18d92402e7 | refs/heads/master | 2021-07-09T00:54:45.989614 | 2017-10-09T08:19:08 | 2017-10-09T08:19:08 | 103,544,202 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 151 | cpp | ex16_16_VecTest.cpp | #include "ex16_16_Vec.h"
using namespace std;
int main()
{
Vec<string> S1 = { "a","b","c" };
cout << S1[2] << endl;
system("pause");
return 0;
}
|
07c3fc1ad77a36f409113081a0b97e81d1c0e230 | 957204df3398e8f03206dc62f12132afea5ca3a8 | /include/chapter-5/hire_assistant_randomize_in_place/swap_randomized_hire_assistant.hpp | d9a51880186ed4480c0d2b9f639a8bca1953c085 | [
"MIT"
] | permissive | zero4drift/CLRS_Cpp_Implementations | 080d4d358e9c8f1bed8f8950c38dead75b7c6621 | efafbb34fb9f83dedecdcf01395def27fd64a33a | refs/heads/master | 2020-03-27T18:02:32.220877 | 2019-01-09T09:05:21 | 2019-01-09T09:05:21 | 146,894,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | hpp | swap_randomized_hire_assistant.hpp | #ifndef SWAP_RANDOMIZED_HIRE_ASSISTANT_H
#define SWAP_RANDOMIZED_HIRE_ASSISTANT_H
#include <utility>
#include "randomize_in_place.hpp"
namespace CLRS
{
template <typename T, std::size_t n>
void swap_randomized_hire_assistant(T (&a)[n], T *choose)
{
randomize_in_place(a);
*choose = 0;
for(std::size_t i = 0; i != n; ++i)
{
if(a[i] > *choose)
*choose = a[i];
}
}
}
#endif
|
9230f2caa2d470878cd3e9ad3378129182e61c46 | 80cedb653bc8327cde6c6aa1f88891c6bc36b5bd | /src/MainMenu.cpp | 758331a21b8efbb2d3c2b70e244870bc11058f7d | [] | no_license | AaronCur/MadtingRacing-GroupProject | 2d524b8d4d5c4b47cdd5507d2c5551b3ad4bb164 | 5a53072d70ecf46320e25019954740f27850992a | refs/heads/master | 2021-06-27T20:01:17.846173 | 2017-09-17T16:03:06 | 2017-09-17T16:03:06 | 103,837,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,721 | cpp | MainMenu.cpp | #include "MainMenu.h"
#include <iostream>
MainMenu::MainMenu(Game & game, sf::Font font) :
m_game(&game),
m_font(font),
m_play("Play", m_font),
m_upgrades("Upgrades", m_font),
m_options("Options", m_font),
m_exit("Exit", m_font),
m_mainMenuTxt("Main Menu", m_meatLoaf, 70)
{
if (!m_mainMenuTexture.loadFromFile("./resources/images/button.png"))
{
std::string main("Error Loading Texture");
throw std::exception(main.c_str());
}
if (!m_selectTex.loadFromFile("./resources/images/select.png"))
{
std::string main("Error Loading Texture");
throw std::exception(main.c_str());
}
if (!m_backgroundTexture.loadFromFile("./resources/images/background.png"))
{
std::string main("Error Loading Texture");
throw std::exception(main.c_str());
}
m_meatLoaf.loadFromFile("./resources/images/Meatloaf.ttf");
m_backgroundSprite.setTexture(m_backgroundTexture);
m_mainMenuTxt.setPosition(740, -10);
if (!buffer.loadFromFile("./resources/images/button.wav"))
{
std::string main("Error Loading sound");
throw std::exception(main.c_str());
}
buttonPress.setBuffer(buffer);
m_backgroundSprite.setPosition(0, 0);
m_select.setTexture(m_selectTex);
m_select.setPosition(-11, 50);
m_selectUpgrade.setTexture(m_selectTex);
m_selectUpgrade.setPosition(381, 200);
m_selectOptions.setTexture(m_selectTex);
m_selectOptions.setPosition(421, 350);
m_selectExit.setTexture(m_selectTex);
m_selectExit.setPosition(461, 500);
m_mainMenuSprite.setTexture(m_mainMenuTexture);
m_mainMenuSprite.setPosition(-10, 30);
m_mainMenuSpriteTwo.setTexture(m_mainMenuTexture);
m_mainMenuSpriteTwo.setPosition(590, 180);
m_mainMenuSpriteThree.setTexture(m_mainMenuTexture);
m_mainMenuSpriteThree.setPosition(-10, 330);
m_mainMenuSpriteFour.setTexture(m_mainMenuTexture);
m_mainMenuSpriteFour.setPosition(590, 480);
//m_play.setPosition(320, 55);
m_play.setColor(sf::Color::White);
m_options.setScale(0.7, 1);
m_upgrades.setScale(0.6, 1);
m_blankTexture.loadFromFile("./resources/images/blank.png");
m_blankSprite.setTexture(m_blankTexture);
if (!m_shader.loadFromFile("firstShader.txt", sf::Shader::Fragment))
{
std::cout << "Shader is not available" << std::endl;
}
m_shader.setParameter("time", 0);
m_shader.setParameter("resolution", 1000, 650);
m_blankSprite.setPosition(0, 0);
}
MainMenu::~MainMenu()
{
std::cout << "destructing Splash" << std::endl;
}
void MainMenu::update(sf::Time deltaTime, Xbox360Controller& controller)
{
time += deltaTime;
updateShader = time.asSeconds();
m_shader.setParameter("time", updateShader);
if (buttonCounter == 1)
{
buttonOneSelected = true;
buttonTwoSelected = false;
buttonThreeSelected = false;
buttonFourSelected = false;
}
if (buttonCounter == 2)
{
buttonOneSelected = false;
buttonTwoSelected = true;
buttonThreeSelected = false;
buttonFourSelected = false;
}
if (buttonCounter == 3)
{
buttonOneSelected = false;
buttonTwoSelected = false;
buttonThreeSelected = true;
buttonFourSelected = false;
}
if (buttonCounter == 4)
{
buttonOneSelected = false;
buttonTwoSelected = false;
buttonThreeSelected = false;
buttonFourSelected = true;
}
if (buttonOneSelected == true)
{
if (controller.m_currentState.A&& controller.m_previousState.A == false && buttonOneSelected)
{
buttonPress.play();
m_game->setGameState(GameState::CarSelect);
}
}
if (buttonTwoSelected == true)
{
if (controller.m_currentState.A)
{
buttonPress.play();
m_game->setGameState(GameState::Upgrade);
}
}
if (buttonThreeSelected == true)
{
if (controller.m_currentState.A)
{
buttonPress.play();
m_game->setGameState(GameState::Options);
}
}
if (buttonFourSelected == true)
{
if (controller.m_previousState.A)
{
buttonPress.play();
close = true;
}
}
/*if (buttonOneSelected == false)
{
m_playGame.setColor(sf::Color::Blue);
}
if (buttonTwoSelected == false)
{
m_options.setColor(sf::Color::Green);
}
if (buttonThreeSelected == false)
{
m_exit.setColor(sf::Color::Red);
}*/
// Set position of text so it moves with button
m_play.setPosition(m_mainMenuSprite.getPosition().x + 130, 55);
m_upgrades.setPosition(m_mainMenuSpriteTwo.getPosition().x + 120, 205);
m_options.setPosition(m_mainMenuSpriteThree.getPosition().x + 120, 355);
m_exit.setPosition(m_mainMenuSpriteFour.getPosition().x + 140, 505);
if (controller.m_currentState.DpadDown == false && controller.m_currentState.DpadUp == false)
{
pressed = false;
}
if (controller.m_currentState.DpadDown && pressed == false)
{
buttonCounter = buttonCounter + 1;
if (buttonCounter == 5)
{
buttonCounter = 1;
}
pressed = true;
}
if (controller.m_currentState.DpadUp && pressed == false)
{
buttonCounter = buttonCounter - 1;
if (buttonCounter == 0)
{
buttonCounter = 4;
}
if (buttonCounter == -1)
{
buttonCounter = 4;
}
pressed = true;
}
if (buttonCounter == 1 && alphaCount == true)
{
alpha += 5;
m_play.setColor(sf::Color(255, 255, 255, alpha));
}
else
{
m_play.setColor(sf::Color(255, 255, 255, 255));
}
if (buttonCounter == 2)
{
alpha += 5;
m_upgrades.setColor(sf::Color(255, 255, 255, alpha));
}
else
{
m_upgrades.setColor(sf::Color(255, 255, 255, 255));
}
if (buttonCounter == 3)
{
alpha += 5;
m_options.setColor(sf::Color(255, 255, 255, alpha));
}
else
{
m_options.setColor(sf::Color(255, 255, 255, 255));
}
if (buttonCounter == 4)
{
alpha += 5;
m_exit.setColor(sf::Color(255, 255, 255, alpha));
}
else
{
m_exit.setColor(sf::Color(255, 255, 255, 255));
}
if (m_mainMenuSprite.getPosition().x > -11)
{
if (m_mainMenuSprite.getPosition().x <= 300)
{
//moving in from the right
m_mainMenuSprite.move(10, 0); //PLAY
m_select.move(11, 0);//OPTIONS
m_mainMenuSpriteThree.move(12.5, 0);
//moving in from the left
m_mainMenuSpriteTwo.move(-7.5, 0);//UP
m_mainMenuSpriteFour.move(-5, 0);//EXIT
}
}
//Check to see what button is pressed
}
void MainMenu::render(sf::RenderWindow & window)
{
window.draw(m_backgroundSprite);
window.draw(m_blankSprite, &m_shader);
window.draw(m_carOne);
window.draw(m_carTwo);
window.draw(m_mainMenuSprite);
window.draw(m_mainMenuSpriteTwo);
window.draw(m_mainMenuSpriteThree);
window.draw(m_mainMenuSpriteFour);
window.draw(m_mainMenuTxt);
if(buttonCounter == 1)
{
window.draw(m_select);
}
if (buttonCounter == 2)
{
window.draw(m_selectUpgrade);
}
if (buttonCounter == 3)
{
window.draw(m_selectOptions);
}
if (buttonCounter == 4)
{
window.draw(m_selectExit);
}
window.draw(m_play);
window.draw(m_upgrades);
window.draw(m_options);
window.draw(m_exit);
}
|
db41a88aa61bf75ac21178774fabae26b4b7f735 | a4cafdae890bbbc0b5efb1ffd8a4f1fd4267dcc1 | /views/View/View_charSelect.cpp | 371496238383c0d63a2a4a128152b2ca5909f718 | [] | no_license | tomiir/taller-marvel-capcom | 5aa8047350e67b2702d3d1a5ffa370c99f1ce5d0 | fcfea6e474d50d273bcdf16f6f329992fea7e78a | refs/heads/master | 2020-04-28T19:53:31.238073 | 2019-06-29T20:24:17 | 2019-06-29T20:24:17 | 175,525,464 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,843 | cpp | View_charSelect.cpp | //
// Created by arielpm on 12/05/19.
//
#include "View_charSelect.h"
#include <algorithm>
View_charSelect::View_charSelect(SDL_Renderer *renderer_, int screenWidth_, int screenHeight_): View(renderer_){
screenWidth = screenWidth_;
screenHeight = screenHeight_;
int aux_y = (screenHeight - 600)/2;
int aux_x = (screenWidth - 800)/2;
squarePosition["CaptainAmerica"] = {233 + aux_x,291 + aux_y,165,127}; // FALTA AGREGAR LAS POSICIONES
squarePosition["SpiderMan"] = {400 + aux_x,291 + aux_y,165,127}; // FALTA AGREGAR LAS POSICIONES
squarePosition["ChunLi"] = {234 + aux_x,417 + aux_y,165,127}; // FALTA AGREGAR LAS POSICIONES
squarePosition["Venom"] = {399 + aux_x,417 + aux_y,165,127}; // FALTA AGREGAR LAS POSICIONES
std::vector<int> aux_1 = {497 + aux_x,0 + aux_y,303,300};// arriba a la derecha
std::vector<int> aux_2 = {497 + aux_x,300 + aux_y,303,300};// abajo a la derecha
std::vector<int> aux_3 = {0 + aux_x,0 + aux_y,303,300};// arriba a la izquierda
std::vector<int> aux_4 = {0 + aux_x,300 + aux_y,303,300};// abajo a la izquierda
posc_side_1 = {aux_1 , aux_2};
posc_side_2 = {aux_3, aux_4};
}
void View_charSelect::addGameObject_square(GameObject_charSelect* square, int team){
if (team == 1 ){
square_team1 = square;
}
else {
square_team2 = square;
}
}
void View_charSelect::addGameObject_square_gray(GameObject_charSelect* square){
greySquare[square->getName()] = square;
}
void View_charSelect::updateView() {
this->clearWindow();
background->render();
renderVector(this->getGreysSquares());
renderVector(this->getSelectionSquares());
renderVector(this->getSides());
//LO PRESENTO EN EL RENDER
SDL_RenderPresent(renderer);
}
void View_charSelect::addGameObject_background(GameObject_charSelect *background){
this->background = background;
}
void View_charSelect:: addGameObject_character(GameObject_charSelect* gameObject, int team){
if (team == 1 ){
team_1[gameObject->getName()] = gameObject;
}
else{
team_2[gameObject->getName()] = gameObject;
}
}
void View_charSelect:: addGameObject_character_selected(GameObject_charSelect* gameObject, int team){
if (team == 1 ){
team_1_selected[gameObject->getName()] = gameObject;
}
else{
team_2_selected[gameObject->getName()] = gameObject;
}
}
bool View_charSelect:: end(){
return selected.size() == 4;
}
View_charSelect::~View_charSelect() {
}
string View_charSelect::getNextView() {
return "fight";
}
std::vector<GameObject_charSelect *> View_charSelect::getSides() {
// LOGICA DE LATERALES. to_render es un vector que tiene los laterales a renderizar.
std::vector<GameObject_charSelect *> to_render;
if (selected_1.empty()) {
itr_team_1 = team_1.find((preselectedT1));
(itr_team_1->second)->setPosc(posc_side_1[0]);
to_render.push_back(itr_team_1->second);
}
if (selected_2.empty()) {
itr_team_2 = team_2.find((preselectedT2));
vector<int> posc_prueba = posc_side_2[0];
(itr_team_2->second)->setPosc(posc_prueba);
to_render.push_back(itr_team_2->second);
}
if (selected_1.size() == 1) {
itr_team_1_selected = team_1_selected.find(selected_1[0]);
(itr_team_1_selected->second)->setPosc(posc_side_1[0]);
to_render.push_back(itr_team_1_selected->second);
itr_team_1 = team_1.find(preselectedT1);
(itr_team_1->second)->setPosc(posc_side_1[1]);
to_render.push_back(itr_team_1->second);
}
if (selected_2.size() == 1) {
itr_team_2_selected = team_2_selected.find(selected_2[0]);
(itr_team_2_selected->second)->setPosc(posc_side_2[0]);
to_render.push_back(itr_team_2_selected->second);
itr_team_2 = team_2.find(preselectedT2);
(itr_team_2->second)->setPosc(posc_side_2[1]);
to_render.push_back(itr_team_2->second);
}
if (selected_1.size() == 2) {
itr_team_1_selected = team_1_selected.find(selected_1[0]);
(itr_team_1_selected->second)->setPosc(posc_side_1[0]);
to_render.push_back(itr_team_1_selected->second);
itr_team_1_selected = team_1_selected.find(selected_1[1]);
(itr_team_1_selected->second)->setPosc(posc_side_1[1]);
to_render.push_back(itr_team_1_selected->second);
}
if (selected_2.size() == 2) {
itr_team_2_selected = team_2_selected.find(selected_2[0]);
(itr_team_2_selected->second)->setPosc(posc_side_2[0]);
to_render.push_back(itr_team_2_selected->second);
itr_team_2_selected = team_2_selected.find(selected_2[1]);
(itr_team_2_selected->second)->setPosc(posc_side_2[1]);
to_render.push_back(itr_team_2_selected->second);
}
return to_render;
}
std::vector<GameObject_charSelect *> View_charSelect::getGreysSquares() {
std::vector<GameObject_charSelect *> to_render;
std::vector<string>::iterator itr_selected = selected.begin();
for (itr_selected; itr_selected != selected.end(); ++itr_selected){
itr_greySquare= greySquare.find(*itr_selected);
to_render.push_back(itr_greySquare->second);
}
return to_render;
}
std::vector<GameObject_charSelect *> View_charSelect::getSelectionSquares() {
std::vector<GameObject_charSelect*> to_render;
itr_squarePosition = squarePosition.find(preselectedT1);
square_team1->setPosc((itr_squarePosition->second));
to_render.push_back(square_team1);
itr_squarePosition = squarePosition.find(preselectedT2);
square_team2->setPosc((itr_squarePosition->second));
to_render.push_back(square_team2);
return to_render;
}
void View_charSelect::renderVector(std::vector<GameObject_charSelect*> to_render) {
std::vector<GameObject_charSelect*>::iterator itr_to_render = to_render.begin();
for (itr_to_render; itr_to_render != to_render.end(); ++itr_to_render){
(*itr_to_render)->render();
}
}
std::vector<string> View_charSelect::getTeam1() {
return selected_1;
}
std::vector<string> View_charSelect::getTeam2() {
return selected_2;
}
bool View_charSelect::selectedNotContains(string name){
std::vector<string>::iterator itr_selected = selected.begin();
for (itr_selected; itr_selected != selected.end(); ++itr_selected){
if (*itr_selected == name) return false;
}
return true;
}
void View_charSelect::updateGreySquares(char* greySquares ) {
if (greySquares[0] == '1' and selectedNotContains("CaptainAmerica")) selected.push_back("CaptainAmerica");
if (greySquares[1] == '1' and selectedNotContains("SpiderMan")) selected.push_back("SpiderMan");
if (greySquares[2] == '1' and selectedNotContains("ChunLi")) selected.push_back("ChunLi");
if (greySquares[3] == '1' and selectedNotContains("Venom")) selected.push_back("Venom");
}
void View_charSelect::updateSelects(char *selectT1, char *selectT2) {
if (strcmp(selectT1, "00") == 0){
preselectedT1 = "CaptainAmerica";
} else if(strcmp(selectT1, "01") == 0){
preselectedT1 = "SpiderMan";
} else if(strcmp(selectT1, "10") == 0) {
preselectedT1 = "ChunLi";
} else preselectedT1 = "Venom";
if (strcmp(selectT2, "00") == 0){
preselectedT2 = "CaptainAmerica";
} else if(strcmp(selectT2, "01") == 0){
preselectedT2 = "SpiderMan";
} else if(strcmp(selectT2, "10") == 0) {
preselectedT2 = "ChunLi";
} else preselectedT2 = "Venom";
}
string getCharacter(char name){
if (name == 'C') return "CaptainAmerica";
else if (name == 'S') return "SpiderMan";
else if (name == 'H') return "ChunLi";
else if (name == 'V') return "Venom";
else {
cout << "Error recibir personajes seleccionados view CharSelect" << endl;
return nullptr;
}
}
void View_charSelect::updateCharacterImages(char *selected_1_, char *selected_2_) {
if (selected_1_[0] != '0'){
string pj = getCharacter(selected_1_[0]);
if (selectedNotContains(pj)) this->selected_1.push_back(pj);
}
if (selected_1_[1] != '0'){
string pj = getCharacter(selected_1_[1]);
if (selectedNotContains(pj)) this->selected_1.push_back(pj);
}
if (selected_2_[0] != '0'){
string pj = getCharacter(selected_2_[0]);
if (selectedNotContains(pj)) this->selected_2.push_back(pj);
}
if (selected_2_[1] != '0'){
string pj = getCharacter(selected_2_[1]);
if (selectedNotContains(pj)) this->selected_2.push_back(pj);
}
}
void View_charSelect::renderDisconnected() {
disconnected->render();
SDL_RenderPresent(renderer);
}
void View_charSelect::addGameObject_disconnected(GameObject *disconnected_) {
disconnected = disconnected_;
}
|
48b82786b02d0739f5b4ec7d5789d8e0451896bb | de7e771699065ec21a340ada1060a3cf0bec3091 | /analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseIterationMarkCharFilter.cpp | b0e9c0c1507cdd3c190b625a66785bd920ed39b3 | [] | no_license | sraihan73/Lucene- | 0d7290bacba05c33b8d5762e0a2a30c1ec8cf110 | 1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3 | refs/heads/master | 2020-03-31T07:23:46.505891 | 2018-12-08T14:57:54 | 2018-12-08T14:57:54 | 152,020,180 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,294 | cpp | TestJapaneseIterationMarkCharFilter.cpp | using namespace std;
#include "TestJapaneseIterationMarkCharFilter.h"
#include "../../../../../../../../../core/src/java/org/apache/lucene/analysis/CharFilter.h"
#include "../../../../../../../../../core/src/java/org/apache/lucene/analysis/Tokenizer.h"
#include "../../../../../../../../../core/src/java/org/apache/lucene/util/IOUtils.h"
#include "../../../../../../../../../test-framework/src/java/org/apache/lucene/analysis/MockTokenizer.h"
#include "../../../../../../java/org/apache/lucene/analysis/ja/JapaneseIterationMarkCharFilter.h"
#include "../../../../../../java/org/apache/lucene/analysis/ja/JapaneseTokenizer.h"
namespace org::apache::lucene::analysis::ja
{
using Analyzer = org::apache::lucene::analysis::Analyzer;
using BaseTokenStreamTestCase =
org::apache::lucene::analysis::BaseTokenStreamTestCase;
using CharFilter = org::apache::lucene::analysis::CharFilter;
using MockTokenizer = org::apache::lucene::analysis::MockTokenizer;
using Tokenizer = org::apache::lucene::analysis::Tokenizer;
using IOUtils = org::apache::lucene::util::IOUtils;
void TestJapaneseIterationMarkCharFilter::setUp()
{
BaseTokenStreamTestCase::setUp();
keywordAnalyzer =
make_shared<AnalyzerAnonymousInnerClass>(shared_from_this());
japaneseAnalyzer =
make_shared<AnalyzerAnonymousInnerClass2>(shared_from_this());
}
TestJapaneseIterationMarkCharFilter::AnalyzerAnonymousInnerClass::
AnalyzerAnonymousInnerClass(
shared_ptr<TestJapaneseIterationMarkCharFilter> outerInstance)
{
this->outerInstance = outerInstance;
}
shared_ptr<Analyzer::TokenStreamComponents>
TestJapaneseIterationMarkCharFilter::AnalyzerAnonymousInnerClass::
createComponents(const wstring &fieldName)
{
shared_ptr<Tokenizer> tokenizer =
make_shared<MockTokenizer>(MockTokenizer::KEYWORD, false);
return make_shared<Analyzer::TokenStreamComponents>(tokenizer, tokenizer);
}
shared_ptr<Reader>
TestJapaneseIterationMarkCharFilter::AnalyzerAnonymousInnerClass::initReader(
const wstring &fieldName, shared_ptr<Reader> reader)
{
return make_shared<JapaneseIterationMarkCharFilter>(reader);
}
TestJapaneseIterationMarkCharFilter::AnalyzerAnonymousInnerClass2::
AnalyzerAnonymousInnerClass2(
shared_ptr<TestJapaneseIterationMarkCharFilter> outerInstance)
{
this->outerInstance = outerInstance;
}
shared_ptr<Analyzer::TokenStreamComponents>
TestJapaneseIterationMarkCharFilter::AnalyzerAnonymousInnerClass2::
createComponents(const wstring &fieldName)
{
shared_ptr<Tokenizer> tokenizer = make_shared<JapaneseTokenizer>(
BaseTokenStreamTestCase::newAttributeFactory(), nullptr, false,
JapaneseTokenizer::Mode::SEARCH);
return make_shared<Analyzer::TokenStreamComponents>(tokenizer, tokenizer);
}
shared_ptr<Reader>
TestJapaneseIterationMarkCharFilter::AnalyzerAnonymousInnerClass2::initReader(
const wstring &fieldName, shared_ptr<Reader> reader)
{
return make_shared<JapaneseIterationMarkCharFilter>(reader);
}
void TestJapaneseIterationMarkCharFilter::tearDown()
{
IOUtils::close({keywordAnalyzer, japaneseAnalyzer});
BaseTokenStreamTestCase::tearDown();
}
void TestJapaneseIterationMarkCharFilter::testKanji()
{
// Test single repetition
assertAnalyzesTo(keywordAnalyzer, L"時々", std::deque<wstring>{L"時時"});
assertAnalyzesTo(japaneseAnalyzer, L"時々", std::deque<wstring>{L"時時"});
// Test multiple repetitions
assertAnalyzesTo(keywordAnalyzer, L"馬鹿々々しい",
std::deque<wstring>{L"馬鹿馬鹿しい"});
assertAnalyzesTo(japaneseAnalyzer, L"馬鹿々々しい",
std::deque<wstring>{L"馬鹿馬鹿しい"});
}
void TestJapaneseIterationMarkCharFilter::testKatakana()
{
// Test single repetition
assertAnalyzesTo(keywordAnalyzer, L"ミスヾ", std::deque<wstring>{L"ミスズ"});
assertAnalyzesTo(japaneseAnalyzer, L"ミスヾ",
std::deque<wstring>{L"ミ", L"スズ"}); // Side effect
}
void TestJapaneseIterationMarkCharFilter::testHiragana()
{
// Test single unvoiced iteration
assertAnalyzesTo(keywordAnalyzer, L"おゝの", std::deque<wstring>{L"おおの"});
assertAnalyzesTo(japaneseAnalyzer, L"おゝの",
std::deque<wstring>{L"お", L"おの"}); // Side effect
// Test single voiced iteration
assertAnalyzesTo(keywordAnalyzer, L"みすゞ", std::deque<wstring>{L"みすず"});
assertAnalyzesTo(japaneseAnalyzer, L"みすゞ",
std::deque<wstring>{L"みすず"});
// Test single voiced iteration
assertAnalyzesTo(keywordAnalyzer, L"じゞ", std::deque<wstring>{L"じじ"});
assertAnalyzesTo(japaneseAnalyzer, L"じゞ", std::deque<wstring>{L"じじ"});
// Test single unvoiced iteration with voiced iteration
assertAnalyzesTo(keywordAnalyzer, L"じゝ", std::deque<wstring>{L"じし"});
assertAnalyzesTo(japaneseAnalyzer, L"じゝ", std::deque<wstring>{L"じし"});
// Test multiple repetitions with voiced iteration
assertAnalyzesTo(keywordAnalyzer, L"ところゞゝゝ",
std::deque<wstring>{L"ところどころ"});
assertAnalyzesTo(japaneseAnalyzer, L"ところゞゝゝ",
std::deque<wstring>{L"ところどころ"});
}
void TestJapaneseIterationMarkCharFilter::testMalformed()
{
// We can't iterate c here, so emit as it is
assertAnalyzesTo(keywordAnalyzer, L"abcところゝゝゝゝ",
std::deque<wstring>{L"abcところcところ"});
// We can't iterate c (with dakuten change) here, so emit it as-is
assertAnalyzesTo(keywordAnalyzer, L"abcところゞゝゝゝ",
std::deque<wstring>{L"abcところcところ"});
// We can't iterate before beginning of stream, so emit characters as-is
assertAnalyzesTo(keywordAnalyzer, L"ところゞゝゝゞゝゞ",
std::deque<wstring>{L"ところどころゞゝゞ"});
// We can't iterate an iteration mark only, so emit as-is
assertAnalyzesTo(keywordAnalyzer, L"々", std::deque<wstring>{L"々"});
assertAnalyzesTo(keywordAnalyzer, L"ゞ", std::deque<wstring>{L"ゞ"});
assertAnalyzesTo(keywordAnalyzer, L"ゞゝ", std::deque<wstring>{L"ゞゝ"});
// We can't iterate a full stop punctuation mark (because we use it as a flush
// marker)
assertAnalyzesTo(keywordAnalyzer, L"。ゝ", std::deque<wstring>{L"。ゝ"});
assertAnalyzesTo(keywordAnalyzer, L"。。ゝゝ",
std::deque<wstring>{L"。。ゝゝ"});
// We can iterate other punctuation marks
assertAnalyzesTo(keywordAnalyzer, L"?ゝ", std::deque<wstring>{L"??"});
// We can not get a dakuten variant of ぽ -- this is also a corner case test
// for inside()
assertAnalyzesTo(keywordAnalyzer, L"ねやぽゞつむぴ",
std::deque<wstring>{L"ねやぽぽつむぴ"});
assertAnalyzesTo(keywordAnalyzer, L"ねやぽゝつむぴ",
std::deque<wstring>{L"ねやぽぽつむぴ"});
}
void TestJapaneseIterationMarkCharFilter::testEmpty()
{
// Empty input stays empty
assertAnalyzesTo(keywordAnalyzer, L"", std::deque<wstring>(0));
assertAnalyzesTo(japaneseAnalyzer, L"", std::deque<wstring>(0));
}
void TestJapaneseIterationMarkCharFilter::testFullStop()
{
// Test full stops
assertAnalyzesTo(keywordAnalyzer, L"。", std::deque<wstring>{L"。"});
assertAnalyzesTo(keywordAnalyzer, L"。。", std::deque<wstring>{L"。。"});
assertAnalyzesTo(keywordAnalyzer, L"。。。", std::deque<wstring>{L"。。。"});
}
void TestJapaneseIterationMarkCharFilter::testKanjiOnly()
{
// Test kanji only repetition marks
shared_ptr<CharFilter> filter = make_shared<JapaneseIterationMarkCharFilter>(
make_shared<StringReader>(
L"時々、おゝのさんと一緒にお寿司が食べたいです。abcところゞゝゝ。"),
true, false);
assertCharFilterEquals(
filter,
L"時時、おゝのさんと一緒にお寿司が食べたいです。abcところゞゝゝ。");
}
void TestJapaneseIterationMarkCharFilter::testKanaOnly()
{
// Test kana only repetition marks
shared_ptr<CharFilter> filter = make_shared<JapaneseIterationMarkCharFilter>(
make_shared<StringReader>(
L"時々、おゝのさんと一緒にお寿司が食べたいです。abcところゞゝゝ。"),
false, true);
assertCharFilterEquals(
filter,
L"時々、おおのさんと一緒にお寿司が食べたいです。abcところどころ。");
}
void TestJapaneseIterationMarkCharFilter::testNone()
{
// Test no repetition marks
shared_ptr<CharFilter> filter = make_shared<JapaneseIterationMarkCharFilter>(
make_shared<StringReader>(
L"時々、おゝのさんと一緒にお寿司が食べたいです。abcところゞゝゝ。"),
false, false);
assertCharFilterEquals(
filter,
L"時々、おゝのさんと一緒にお寿司が食べたいです。abcところゞゝゝ。");
}
void TestJapaneseIterationMarkCharFilter::testCombinations()
{
assertAnalyzesTo(keywordAnalyzer,
L"時々、おゝのさんと一緒にお寿司を食べに行きます。",
std::deque<wstring>{
L"時時、おおのさんと一緒にお寿司を食べに行きます。"});
}
void TestJapaneseIterationMarkCharFilter::testHiraganaCoverage() throw(
IOException)
{
// Test all hiragana iteration variants
wstring source = L"かゝがゝきゝぎゝくゝぐゝけゝげゝこゝごゝさゝざゝしゝじゝす"
L"ゝずゝせゝぜゝそゝぞゝたゝだゝちゝぢゝつゝづゝてゝでゝとゝ"
L"どゝはゝばゝひゝびゝふゝぶゝへゝべゝほゝぼゝ";
wstring target = L"かかがかききぎきくくぐくけけげけここごこささざさししじしす"
L"すずすせせぜせそそぞそたただたちちぢちつつづつててでてとと"
L"どとははばはひひびひふふぶふへへべへほほぼほ";
assertAnalyzesTo(keywordAnalyzer, source, std::deque<wstring>{target});
// Test all hiragana iteration variants with dakuten
source = L"かゞがゞきゞぎゞくゞぐゞけゞげゞこゞごゞさゞざゞしゞじゞすゞずゞせ"
L"ゞぜゞそゞぞゞたゞだゞちゞぢゞつゞづゞてゞでゞとゞどゞはゞばゞひゞ"
L"びゞふゞぶゞへゞべゞほゞぼゞ";
target = L"かがががきぎぎぎくぐぐぐけげげげこごごごさざざざしじじじすずずずせ"
L"ぜぜぜそぞぞぞただだだちぢぢぢつづづづてでででとどどどはばばばひび"
L"びびふぶぶぶへべべべほぼぼぼ";
assertAnalyzesTo(keywordAnalyzer, source, std::deque<wstring>{target});
}
void TestJapaneseIterationMarkCharFilter::testKatakanaCoverage() throw(
IOException)
{
// Test all katakana iteration variants
wstring source = L"カヽガヽキヽギヽクヽグヽケヽゲヽコヽゴヽサヽザヽシヽジヽス"
L"ヽズヽセヽゼヽソヽゾヽタヽダヽチヽヂヽツヽヅヽテヽデヽトヽ"
L"ドヽハヽバヽヒヽビヽフヽブヽヘヽベヽホヽボヽ";
wstring target = L"カカガカキキギキククグクケケゲケココゴコササザサシシジシス"
L"スズスセセゼセソソゾソタタダタチチヂチツツヅツテテデテトト"
L"ドトハハバハヒヒビヒフフブフヘヘベヘホホボホ";
assertAnalyzesTo(keywordAnalyzer, source, std::deque<wstring>{target});
// Test all katakana iteration variants with dakuten
source = L"カヾガヾキヾギヾクヾグヾケヾゲヾコヾゴヾサヾザヾシヾジヾスヾズヾセ"
L"ヾゼヾソヾゾヾタヾダヾチヾヂヾツヾヅヾテヾデヾトヾドヾハヾバヾヒヾ"
L"ビヾフヾブヾヘヾベヾホヾボヾ";
target = L"カガガガキギギギクグググケゲゲゲコゴゴゴサザザザシジジジスズズズセ"
L"ゼゼゼソゾゾゾタダダダチヂヂヂツヅヅヅテデデデトドドドハバババヒビ"
L"ビビフブブブヘベベベホボボボ";
assertAnalyzesTo(keywordAnalyzer, source, std::deque<wstring>{target});
}
void TestJapaneseIterationMarkCharFilter::testRandomStrings() throw(
runtime_error)
{
// Blast some random strings through
checkRandomData(random(), keywordAnalyzer, 1000 * RANDOM_MULTIPLIER);
}
void TestJapaneseIterationMarkCharFilter::testRandomHugeStrings() throw(
runtime_error)
{
// Blast some random strings through
checkRandomData(random(), keywordAnalyzer, 100 * RANDOM_MULTIPLIER, 8192);
}
void TestJapaneseIterationMarkCharFilter::assertCharFilterEquals(
shared_ptr<CharFilter> filter, const wstring &expected)
{
wstring actual = readFully(filter);
assertEquals(expected, actual);
}
wstring TestJapaneseIterationMarkCharFilter::readFully(
shared_ptr<Reader> stream)
{
shared_ptr<StringBuilder> buffer = make_shared<StringBuilder>();
int ch;
while ((ch = stream->read()) != -1) {
buffer->append(static_cast<wchar_t>(ch));
}
return buffer->toString();
}
} // namespace org::apache::lucene::analysis::ja |
9cb079c7d974b42975d553968159971d09b8af44 | cc3fd3a55992b7c59d2148c16f05db5ca884bfbf | /Codesignal/core/15.willYou.cpp | 34fb54a97c1016afef89e06066edd1be8b506030 | [] | no_license | karlsmarx/Challenges | 541b0b608d440afdd4ef1e1757e1df2f8b70fe7d | b24adcc466d9ad2b2ce8b52d1301c932b27e5af3 | refs/heads/master | 2021-06-18T06:15:42.231961 | 2021-03-16T10:20:25 | 2021-03-16T10:20:25 | 176,175,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | cpp | 15.willYou.cpp | bool willYou(bool young, bool beautiful, bool loved) {
// If one of then is false, then loved must be false to
// assert conceptions, otherwise loved must be true
bool beatAndYoung = young && beautiful;
return beatAndYoung ? !loved : loved;
}
|
499bdee8ec95d51e17c07885a1ee50f6f5e5a0f5 | f890418376a8aa142cad598fc3add9d53a5f1343 | /rosabridge_arduino/sketchbook/libraries/ros_lib/rosabridge_msgs/RequestOdometryCovariances.h | f6da3d5d3e45d68cac8ba1cfeba9dddb82957106 | [
"BSD-3-Clause"
] | permissive | ecostech/rosabridge | 90372201a971c0007b3b9a4c71ce61770faf78b8 | a52d375412ab8e758b2556af1c4b620a44b37ce8 | refs/heads/master | 2021-05-14T12:52:28.501085 | 2021-04-07T17:13:00 | 2021-04-07T17:13:00 | 116,420,431 | 7 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | h | RequestOdometryCovariances.h | #ifndef _ROS_SERVICE_RequestOdometryCovariances_h
#define _ROS_SERVICE_RequestOdometryCovariances_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "std_msgs/Empty.h"
#include "rosabridge_msgs/OdometryCovariances.h"
namespace rosabridge_msgs
{
static const char REQUESTODOMETRYCOVARIANCES[] = "rosabridge_msgs/RequestOdometryCovariances";
class RequestOdometryCovariancesRequest : public ros::Msg
{
public:
std_msgs::Empty empty;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->empty.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->empty.deserialize(inbuffer + offset);
return offset;
}
const char * getType(){ return REQUESTODOMETRYCOVARIANCES; };
const char * getMD5(){ return "6aac6c697d5414bc0fcede8c33981d0e"; };
};
class RequestOdometryCovariancesResponse : public ros::Msg
{
public:
rosabridge_msgs::OdometryCovariances odometry_covariances;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->odometry_covariances.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->odometry_covariances.deserialize(inbuffer + offset);
return offset;
}
const char * getType(){ return REQUESTODOMETRYCOVARIANCES; };
const char * getMD5(){ return "560766e7723436a6430cd33a6d8796bb"; };
};
class RequestOdometryCovariances {
public:
typedef RequestOdometryCovariancesRequest Request;
typedef RequestOdometryCovariancesResponse Response;
};
}
#endif
|
120b0f0b08aaee6d982a2f558f0e0421269401e5 | c475cd8531a94ffae69cc92371d41531dbbddb6c | /Projects/bullet3-2.89/examples/TinyAudio/RtAudio.cpp | 882a478b1966360eeed11feef36740700c3375f7 | [
"Zlib",
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | WolfireGames/overgrowth | 72d3dd29cbd7254337265c29f8de3e5c32400114 | 594a2a4f9da0855304ee8cd5335d042f8e954ce1 | refs/heads/main | 2023-08-15T19:36:56.156578 | 2023-05-17T08:17:53 | 2023-05-17T08:20:36 | 467,448,492 | 2,264 | 245 | Apache-2.0 | 2023-05-09T07:29:58 | 2022-03-08T09:38:54 | C++ | IBM852 | C++ | false | false | 335,239 | cpp | RtAudio.cpp | /************************************************************************/
/*! \class RtAudio
\brief Realtime audio i/o C++ classes.
RtAudio provides a common API (Application Programming Interface)
for realtime audio input/output across Linux (native ALSA, Jack,
and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
(DirectSound, ASIO and WASAPI) operating systems.
RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
RtAudio: realtime audio i/o C++ classes
Copyright (c) 2001-2016 Gary P. Scavone
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
Any person wishing to distribute modifications to the Software is
asked to send the modifications to the original developer so that
they can be incorporated into the canonical version. This is,
however, not a binding provision of this license.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/************************************************************************/
// RtAudio: Version 4.1.2
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <algorithm>
// Static variable definitions.
const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
const unsigned int RtApi::SAMPLE_RATES[] = {
4000, 5512, 8000, 9600, 11025, 16000, 22050,
32000, 44100, 48000, 88200, 96000, 176400, 192000};
#if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
#define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
#define MUTEX_DESTROY(A) DeleteCriticalSection(A)
#define MUTEX_LOCK(A) EnterCriticalSection(A)
#define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
#include "tchar.h"
static std::string convertCharPointerToStdString(const char *text)
{
return std::string(text);
}
static std::string convertCharPointerToStdString(const wchar_t *text)
{
int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);
std::string s(length - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);
return s;
}
#elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
// pthread API
#define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
#define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
#define MUTEX_LOCK(A) pthread_mutex_lock(A)
#define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
#else
#define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions
#define MUTEX_DESTROY(A) abs(*A) // dummy definitions
#endif
// *************************************************** //
//
// RtAudio definitions.
//
// *************************************************** //
std::string RtAudio ::getVersion(void) throw()
{
return RTAUDIO_VERSION;
}
void RtAudio ::getCompiledApi(std::vector<RtAudio::Api> &apis) throw()
{
apis.clear();
// The order here will control the order of RtAudio's API search in
// the constructor.
#if defined(__UNIX_JACK__)
apis.push_back(UNIX_JACK);
#endif
#if defined(__LINUX_ALSA__)
apis.push_back(LINUX_ALSA);
#endif
#if defined(__LINUX_PULSE__)
apis.push_back(LINUX_PULSE);
#endif
#if defined(__LINUX_OSS__)
apis.push_back(LINUX_OSS);
#endif
#if defined(__WINDOWS_ASIO__)
apis.push_back(WINDOWS_ASIO);
#endif
#if defined(__WINDOWS_WASAPI__)
apis.push_back(WINDOWS_WASAPI);
#endif
#if defined(__WINDOWS_DS__)
apis.push_back(WINDOWS_DS);
#endif
#if defined(__MACOSX_CORE__)
apis.push_back(MACOSX_CORE);
#endif
#if defined(__RTAUDIO_DUMMY__)
apis.push_back(RTAUDIO_DUMMY);
#endif
}
void RtAudio ::openRtApi(RtAudio::Api api)
{
if (rtapi_)
delete rtapi_;
rtapi_ = 0;
#if defined(__UNIX_JACK__)
if (api == UNIX_JACK)
rtapi_ = new RtApiJack();
#endif
#if defined(__LINUX_ALSA__)
if (api == LINUX_ALSA)
rtapi_ = new RtApiAlsa();
#endif
#if defined(__LINUX_PULSE__)
if (api == LINUX_PULSE)
rtapi_ = new RtApiPulse();
#endif
#if defined(__LINUX_OSS__)
if (api == LINUX_OSS)
rtapi_ = new RtApiOss();
#endif
#if defined(__WINDOWS_ASIO__)
if (api == WINDOWS_ASIO)
rtapi_ = new RtApiAsio();
#endif
#if defined(__WINDOWS_WASAPI__)
if (api == WINDOWS_WASAPI)
rtapi_ = new RtApiWasapi();
#endif
#if defined(__WINDOWS_DS__)
if (api == WINDOWS_DS)
rtapi_ = new RtApiDs();
#endif
#if defined(__MACOSX_CORE__)
if (api == MACOSX_CORE)
rtapi_ = new RtApiCore();
#endif
#if defined(__RTAUDIO_DUMMY__)
if (api == RTAUDIO_DUMMY)
rtapi_ = new RtApiDummy();
#endif
}
RtAudio ::RtAudio(RtAudio::Api api)
{
rtapi_ = 0;
if (api != UNSPECIFIED)
{
// Attempt to open the specified API.
openRtApi(api);
if (rtapi_) return;
// No compiled support for specified API value. Issue a debug
// warning and continue as if no API was specified.
std::cerr << "\nRtAudio: no compiled support for specified API argument!\n"
<< std::endl;
}
// Iterate through the compiled APIs and return as soon as we find
// one with at least one device or we reach the end of the list.
std::vector<RtAudio::Api> apis;
getCompiledApi(apis);
for (unsigned int i = 0; i < apis.size(); i++)
{
openRtApi(apis[i]);
if (rtapi_ && rtapi_->getDeviceCount()) break;
}
if (rtapi_) return;
// It should not be possible to get here because the preprocessor
// definition __RTAUDIO_DUMMY__ is automatically defined if no
// API-specific definitions are passed to the compiler. But just in
// case something weird happens, we'll thow an error.
std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";
throw(RtAudioError(errorText, RtAudioError::UNSPECIFIED));
}
RtAudio ::~RtAudio() throw()
{
if (rtapi_)
delete rtapi_;
}
void RtAudio ::openStream(RtAudio::StreamParameters *outputParameters,
RtAudio::StreamParameters *inputParameters,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options,
RtAudioErrorCallback errorCallback)
{
return rtapi_->openStream(outputParameters, inputParameters, format,
sampleRate, bufferFrames, callback,
userData, options, errorCallback);
}
// *************************************************** //
//
// Public RtApi definitions (see end of file for
// private or protected utility functions).
//
// *************************************************** //
RtApi ::RtApi()
{
stream_.state = STREAM_CLOSED;
stream_.mode = UNINITIALIZED;
stream_.apiHandle = 0;
stream_.userBuffer[0] = 0;
stream_.userBuffer[1] = 0;
MUTEX_INITIALIZE(&stream_.mutex);
showWarnings_ = true;
firstErrorOccurred_ = false;
}
RtApi ::~RtApi()
{
MUTEX_DESTROY(&stream_.mutex);
}
void RtApi ::openStream(RtAudio::StreamParameters *oParams,
RtAudio::StreamParameters *iParams,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options,
RtAudioErrorCallback errorCallback)
{
if (stream_.state != STREAM_CLOSED)
{
errorText_ = "RtApi::openStream: a stream is already open!";
error(RtAudioError::INVALID_USE);
return;
}
// Clear stream information potentially left from a previously open stream.
clearStreamInfo();
if (oParams && oParams->nChannels < 1)
{
errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
error(RtAudioError::INVALID_USE);
return;
}
if (iParams && iParams->nChannels < 1)
{
errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
error(RtAudioError::INVALID_USE);
return;
}
if (oParams == NULL && iParams == NULL)
{
errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
error(RtAudioError::INVALID_USE);
return;
}
if (formatBytes(format) == 0)
{
errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
error(RtAudioError::INVALID_USE);
return;
}
unsigned int nDevices = getDeviceCount();
unsigned int oChannels = 0;
if (oParams)
{
oChannels = oParams->nChannels;
if (oParams->deviceId >= nDevices)
{
errorText_ = "RtApi::openStream: output device parameter value is invalid.";
error(RtAudioError::INVALID_USE);
return;
}
}
unsigned int iChannels = 0;
if (iParams)
{
iChannels = iParams->nChannels;
if (iParams->deviceId >= nDevices)
{
errorText_ = "RtApi::openStream: input device parameter value is invalid.";
error(RtAudioError::INVALID_USE);
return;
}
}
bool result;
if (oChannels > 0)
{
result = probeDeviceOpen(oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
sampleRate, format, bufferFrames, options);
if (result == false)
{
error(RtAudioError::SYSTEM_ERROR);
return;
}
}
if (iChannels > 0)
{
result = probeDeviceOpen(iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
sampleRate, format, bufferFrames, options);
if (result == false)
{
if (oChannels > 0) closeStream();
error(RtAudioError::SYSTEM_ERROR);
return;
}
}
stream_.callbackInfo.callback = (void *)callback;
stream_.callbackInfo.userData = userData;
stream_.callbackInfo.errorCallback = (void *)errorCallback;
if (options) options->numberOfBuffers = stream_.nBuffers;
stream_.state = STREAM_STOPPED;
}
unsigned int RtApi ::getDefaultInputDevice(void)
{
// Should be implemented in subclasses if possible.
return 0;
}
unsigned int RtApi ::getDefaultOutputDevice(void)
{
// Should be implemented in subclasses if possible.
return 0;
}
void RtApi ::closeStream(void)
{
// MUST be implemented in subclasses!
return;
}
bool RtApi ::probeDeviceOpen(unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
RtAudio::StreamOptions * /*options*/)
{
// MUST be implemented in subclasses!
return FAILURE;
}
void RtApi ::tickStreamTime(void)
{
// Subclasses that do not provide their own implementation of
// getStreamTime should call this function once per buffer I/O to
// provide basic stream time support.
stream_.streamTime += (stream_.bufferSize * 1.0 / stream_.sampleRate);
#if defined(HAVE_GETTIMEOFDAY)
gettimeofday(&stream_.lastTickTimestamp, NULL);
#endif
}
long RtApi ::getStreamLatency(void)
{
verifyStream();
long totalLatency = 0;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
totalLatency = stream_.latency[0];
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
totalLatency += stream_.latency[1];
return totalLatency;
}
double RtApi ::getStreamTime(void)
{
verifyStream();
#if defined(HAVE_GETTIMEOFDAY)
// Return a very accurate estimate of the stream time by
// adding in the elapsed time since the last tick.
struct timeval then;
struct timeval now;
if (stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0)
return stream_.streamTime;
gettimeofday(&now, NULL);
then = stream_.lastTickTimestamp;
return stream_.streamTime +
((now.tv_sec + 0.000001 * now.tv_usec) -
(then.tv_sec + 0.000001 * then.tv_usec));
#else
return stream_.streamTime;
#endif
}
void RtApi ::setStreamTime(double time)
{
verifyStream();
if (time >= 0.0)
stream_.streamTime = time;
}
unsigned int RtApi ::getStreamSampleRate(void)
{
verifyStream();
return stream_.sampleRate;
}
// *************************************************** //
//
// OS/API-specific methods.
//
// *************************************************** //
#if defined(__MACOSX_CORE__)
// The OS X CoreAudio API is designed to use a separate callback
// procedure for each of its audio devices. A single RtAudio duplex
// stream using two different devices is supported here, though it
// cannot be guaranteed to always behave correctly because we cannot
// synchronize these two callbacks.
//
// A property listener is installed for over/underrun information.
// However, no functionality is currently provided to allow property
// listeners to trigger user handlers because it is unclear what could
// be done if a critical stream parameter (buffer size, sample rate,
// device disconnect) notification arrived. The listeners entail
// quite a bit of extra code and most likely, a user program wouldn't
// be prepared for the result anyway. However, we do provide a flag
// to the client callback function to inform of an over/underrun.
// A structure to hold various information related to the CoreAudio API
// implementation.
struct CoreHandle
{
AudioDeviceID id[2]; // device ids
#if defined(MAC_OS_X_VERSION_10_5) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
AudioDeviceIOProcID procId[2];
#endif
UInt32 iStream[2]; // device stream index (or first if using multiple)
UInt32 nStreams[2]; // number of streams to use
bool xrun[2];
char *deviceBuffer;
pthread_cond_t condition;
int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
CoreHandle()
: deviceBuffer(0), drainCounter(0), internalDrain(false)
{
nStreams[0] = 1;
nStreams[1] = 1;
id[0] = 0;
id[1] = 0;
xrun[0] = false;
xrun[1] = false;
}
};
RtApiCore::RtApiCore()
{
#if defined(AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER)
// This is a largely undocumented but absolutely necessary
// requirement starting with OS-X 10.6. If not called, queries and
// updates to various audio device properties are not handled
// correctly.
CFRunLoopRef theRunLoop = NULL;
AudioObjectPropertyAddress property = {kAudioHardwarePropertyRunLoop,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
OSStatus result = AudioObjectSetPropertyData(kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
if (result != noErr)
{
errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
error(RtAudioError::WARNING);
}
#endif
}
RtApiCore ::~RtApiCore()
{
// The subclass destructor gets called before the base class
// destructor, so close an existing stream before deallocating
// apiDeviceId memory.
if (stream_.state != STREAM_CLOSED) closeStream();
}
unsigned int RtApiCore ::getDeviceCount(void)
{
// Find out how many audio devices there are, if any.
UInt32 dataSize;
AudioObjectPropertyAddress propertyAddress = {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
OSStatus result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize);
if (result != noErr)
{
errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
error(RtAudioError::WARNING);
return 0;
}
return dataSize / sizeof(AudioDeviceID);
}
unsigned int RtApiCore ::getDefaultInputDevice(void)
{
unsigned int nDevices = getDeviceCount();
if (nDevices <= 1) return 0;
AudioDeviceID id;
UInt32 dataSize = sizeof(AudioDeviceID);
AudioObjectPropertyAddress property = {kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id);
if (result != noErr)
{
errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
error(RtAudioError::WARNING);
return 0;
}
dataSize *= nDevices;
AudioDeviceID deviceList[nDevices];
property.mSelector = kAudioHardwarePropertyDevices;
result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *)&deviceList);
if (result != noErr)
{
errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
error(RtAudioError::WARNING);
return 0;
}
for (unsigned int i = 0; i < nDevices; i++)
if (id == deviceList[i]) return i;
errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
error(RtAudioError::WARNING);
return 0;
}
unsigned int RtApiCore ::getDefaultOutputDevice(void)
{
unsigned int nDevices = getDeviceCount();
if (nDevices <= 1) return 0;
AudioDeviceID id;
UInt32 dataSize = sizeof(AudioDeviceID);
AudioObjectPropertyAddress property = {kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id);
if (result != noErr)
{
errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
error(RtAudioError::WARNING);
return 0;
}
dataSize = sizeof(AudioDeviceID) * nDevices;
AudioDeviceID deviceList[nDevices];
property.mSelector = kAudioHardwarePropertyDevices;
result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *)&deviceList);
if (result != noErr)
{
errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
error(RtAudioError::WARNING);
return 0;
}
for (unsigned int i = 0; i < nDevices; i++)
if (id == deviceList[i]) return i;
errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
error(RtAudioError::WARNING);
return 0;
}
RtAudio::DeviceInfo RtApiCore ::getDeviceInfo(unsigned int device)
{
RtAudio::DeviceInfo info;
info.probed = false;
// Get device ID
unsigned int nDevices = getDeviceCount();
if (nDevices == 0)
{
errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
error(RtAudioError::INVALID_USE);
return info;
}
if (device >= nDevices)
{
errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
error(RtAudioError::INVALID_USE);
return info;
}
AudioDeviceID deviceList[nDevices];
UInt32 dataSize = sizeof(AudioDeviceID) * nDevices;
AudioObjectPropertyAddress property = {kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property,
0, NULL, &dataSize, (void *)&deviceList);
if (result != noErr)
{
errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
error(RtAudioError::WARNING);
return info;
}
AudioDeviceID id = deviceList[device];
// Get the device name.
info.name.erase();
CFStringRef cfname;
dataSize = sizeof(CFStringRef);
property.mSelector = kAudioObjectPropertyManufacturer;
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &cfname);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode(result) << ") getting device manufacturer.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
//const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
int length = CFStringGetLength(cfname);
char *mname = (char *)malloc(length * 3 + 1);
#if defined(UNICODE) || defined(_UNICODE)
CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
#else
CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
#endif
info.name.append((const char *)mname, strlen(mname));
info.name.append(": ");
CFRelease(cfname);
free(mname);
property.mSelector = kAudioObjectPropertyName;
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &cfname);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode(result) << ") getting device name.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
//const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
length = CFStringGetLength(cfname);
char *name = (char *)malloc(length * 3 + 1);
#if defined(UNICODE) || defined(_UNICODE)
CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
#else
CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
#endif
info.name.append((const char *)name, strlen(name));
CFRelease(cfname);
free(name);
// Get the output stream "configuration".
AudioBufferList *bufferList = nil;
property.mSelector = kAudioDevicePropertyStreamConfiguration;
property.mScope = kAudioDevicePropertyScopeOutput;
// property.mElement = kAudioObjectPropertyElementWildcard;
dataSize = 0;
result = AudioObjectGetPropertyDataSize(id, &property, 0, NULL, &dataSize);
if (result != noErr || dataSize == 0)
{
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode(result) << ") getting output stream configuration info for device (" << device << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *)malloc(dataSize);
if (bufferList == NULL)
{
errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
error(RtAudioError::WARNING);
return info;
}
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, bufferList);
if (result != noErr || dataSize == 0)
{
free(bufferList);
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode(result) << ") getting output stream configuration for device (" << device << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Get output channel information.
unsigned int i, nStreams = bufferList->mNumberBuffers;
for (i = 0; i < nStreams; i++)
info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
free(bufferList);
// Get the input stream "configuration".
property.mScope = kAudioDevicePropertyScopeInput;
result = AudioObjectGetPropertyDataSize(id, &property, 0, NULL, &dataSize);
if (result != noErr || dataSize == 0)
{
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode(result) << ") getting input stream configuration info for device (" << device << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *)malloc(dataSize);
if (bufferList == NULL)
{
errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
error(RtAudioError::WARNING);
return info;
}
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, bufferList);
if (result != noErr || dataSize == 0)
{
free(bufferList);
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode(result) << ") getting input stream configuration for device (" << device << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Get input channel information.
nStreams = bufferList->mNumberBuffers;
for (i = 0; i < nStreams; i++)
info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
free(bufferList);
// If device opens for both playback and capture, we determine the channels.
if (info.outputChannels > 0 && info.inputChannels > 0)
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// Probe the device sample rates.
bool isInput = false;
if (info.outputChannels == 0) isInput = true;
// Determine the supported sample rates.
property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
if (isInput == false) property.mScope = kAudioDevicePropertyScopeOutput;
result = AudioObjectGetPropertyDataSize(id, &property, 0, NULL, &dataSize);
if (result != kAudioHardwareNoError || dataSize == 0)
{
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode(result) << ") getting sample rate info.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
UInt32 nRanges = dataSize / sizeof(AudioValueRange);
AudioValueRange rangeList[nRanges];
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &rangeList);
if (result != kAudioHardwareNoError)
{
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode(result) << ") getting sample rates.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// The sample rate reporting mechanism is a bit of a mystery. It
// seems that it can either return individual rates or a range of
// rates. I assume that if the min / max range values are the same,
// then that represents a single supported rate and if the min / max
// range values are different, the device supports an arbitrary
// range of values (though there might be multiple ranges, so we'll
// use the most conservative range).
Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
bool haveValueRange = false;
info.sampleRates.clear();
for (UInt32 i = 0; i < nRanges; i++)
{
if (rangeList[i].mMinimum == rangeList[i].mMaximum)
{
unsigned int tmpSr = (unsigned int)rangeList[i].mMinimum;
info.sampleRates.push_back(tmpSr);
if (!info.preferredSampleRate || (tmpSr <= 48000 && tmpSr > info.preferredSampleRate))
info.preferredSampleRate = tmpSr;
}
else
{
haveValueRange = true;
if (rangeList[i].mMinimum > minimumRate) minimumRate = rangeList[i].mMinimum;
if (rangeList[i].mMaximum < maximumRate) maximumRate = rangeList[i].mMaximum;
}
}
if (haveValueRange)
{
for (unsigned int k = 0; k < MAX_SAMPLE_RATES; k++)
{
if (SAMPLE_RATES[k] >= (unsigned int)minimumRate && SAMPLE_RATES[k] <= (unsigned int)maximumRate)
{
info.sampleRates.push_back(SAMPLE_RATES[k]);
if (!info.preferredSampleRate || (SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate))
info.preferredSampleRate = SAMPLE_RATES[k];
}
}
}
// Sort and remove any redundant values
std::sort(info.sampleRates.begin(), info.sampleRates.end());
info.sampleRates.erase(unique(info.sampleRates.begin(), info.sampleRates.end()), info.sampleRates.end());
if (info.sampleRates.size() == 0)
{
errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// CoreAudio always uses 32-bit floating point data for PCM streams.
// Thus, any other "physical" formats supported by the device are of
// no interest to the client.
info.nativeFormats = RTAUDIO_FLOAT32;
if (info.outputChannels > 0)
if (getDefaultOutputDevice() == device) info.isDefaultOutput = true;
if (info.inputChannels > 0)
if (getDefaultInputDevice() == device) info.isDefaultInput = true;
info.probed = true;
return info;
}
static OSStatus callbackHandler(AudioDeviceID inDevice,
const AudioTimeStamp * /*inNow*/,
const AudioBufferList *inInputData,
const AudioTimeStamp * /*inInputTime*/,
AudioBufferList *outOutputData,
const AudioTimeStamp * /*inOutputTime*/,
void *infoPointer)
{
CallbackInfo *info = (CallbackInfo *)infoPointer;
RtApiCore *object = (RtApiCore *)info->object;
if (object->callbackEvent(inDevice, inInputData, outOutputData) == false)
return kAudioHardwareUnspecifiedError;
else
return kAudioHardwareNoError;
}
static OSStatus xrunListener(AudioObjectID /*inDevice*/,
UInt32 nAddresses,
const AudioObjectPropertyAddress properties[],
void *handlePointer)
{
CoreHandle *handle = (CoreHandle *)handlePointer;
for (UInt32 i = 0; i < nAddresses; i++)
{
if (properties[i].mSelector == kAudioDeviceProcessorOverload)
{
if (properties[i].mScope == kAudioDevicePropertyScopeInput)
handle->xrun[1] = true;
else
handle->xrun[0] = true;
}
}
return kAudioHardwareNoError;
}
static OSStatus rateListener(AudioObjectID inDevice,
UInt32 /*nAddresses*/,
const AudioObjectPropertyAddress /*properties*/[],
void *ratePointer)
{
Float64 *rate = (Float64 *)ratePointer;
UInt32 dataSize = sizeof(Float64);
AudioObjectPropertyAddress property = {kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
AudioObjectGetPropertyData(inDevice, &property, 0, NULL, &dataSize, rate);
return kAudioHardwareNoError;
}
bool RtApiCore ::probeDeviceOpen(unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options)
{
// Get device ID
unsigned int nDevices = getDeviceCount();
if (nDevices == 0)
{
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
return FAILURE;
}
if (device >= nDevices)
{
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
AudioDeviceID deviceList[nDevices];
UInt32 dataSize = sizeof(AudioDeviceID) * nDevices;
AudioObjectPropertyAddress property = {kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property,
0, NULL, &dataSize, (void *)&deviceList);
if (result != noErr)
{
errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
return FAILURE;
}
AudioDeviceID id = deviceList[device];
// Setup for stream mode.
bool isInput = false;
if (mode == INPUT)
{
isInput = true;
property.mScope = kAudioDevicePropertyScopeInput;
}
else
property.mScope = kAudioDevicePropertyScopeOutput;
// Get the stream "configuration".
AudioBufferList *bufferList = nil;
dataSize = 0;
property.mSelector = kAudioDevicePropertyStreamConfiguration;
result = AudioObjectGetPropertyDataSize(id, &property, 0, NULL, &dataSize);
if (result != noErr || dataSize == 0)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting stream configuration info for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *)malloc(dataSize);
if (bufferList == NULL)
{
errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
return FAILURE;
}
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, bufferList);
if (result != noErr || dataSize == 0)
{
free(bufferList);
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting stream configuration for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Search for one or more streams that contain the desired number of
// channels. CoreAudio devices can have an arbitrary number of
// streams and each stream can have an arbitrary number of channels.
// For each stream, a single buffer of interleaved samples is
// provided. RtAudio prefers the use of one stream of interleaved
// data or multiple consecutive single-channel streams. However, we
// now support multiple consecutive multi-channel streams of
// interleaved data as well.
UInt32 iStream, offsetCounter = firstChannel;
UInt32 nStreams = bufferList->mNumberBuffers;
bool monoMode = false;
bool foundStream = false;
// First check that the device supports the requested number of
// channels.
UInt32 deviceChannels = 0;
for (iStream = 0; iStream < nStreams; iStream++)
deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
if (deviceChannels < (channels + firstChannel))
{
free(bufferList);
errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Look for a single stream meeting our needs.
UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;
for (iStream = 0; iStream < nStreams; iStream++)
{
streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
if (streamChannels >= channels + offsetCounter)
{
firstStream = iStream;
channelOffset = offsetCounter;
foundStream = true;
break;
}
if (streamChannels > offsetCounter) break;
offsetCounter -= streamChannels;
}
// If we didn't find a single stream above, then we should be able
// to meet the channel specification with multiple streams.
if (foundStream == false)
{
monoMode = true;
offsetCounter = firstChannel;
for (iStream = 0; iStream < nStreams; iStream++)
{
streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
if (streamChannels > offsetCounter) break;
offsetCounter -= streamChannels;
}
firstStream = iStream;
channelOffset = offsetCounter;
Int32 channelCounter = channels + offsetCounter - streamChannels;
if (streamChannels > 1) monoMode = false;
while (channelCounter > 0)
{
streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
if (streamChannels > 1) monoMode = false;
channelCounter -= streamChannels;
streamCount++;
}
}
free(bufferList);
// Determine the buffer size.
AudioValueRange bufferRange;
dataSize = sizeof(AudioValueRange);
property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &bufferRange);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting buffer size range for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
if (bufferRange.mMinimum > *bufferSize)
*bufferSize = (unsigned long)bufferRange.mMinimum;
else if (bufferRange.mMaximum < *bufferSize)
*bufferSize = (unsigned long)bufferRange.mMaximum;
if (options && options->flags & RTAUDIO_MINIMIZE_LATENCY) *bufferSize = (unsigned long)bufferRange.mMinimum;
// Set the buffer size. For multiple streams, I'm assuming we only
// need to make this setting for the master channel.
UInt32 theSize = (UInt32)*bufferSize;
dataSize = sizeof(UInt32);
property.mSelector = kAudioDevicePropertyBufferFrameSize;
result = AudioObjectSetPropertyData(id, &property, 0, NULL, dataSize, &theSize);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") setting the buffer size for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// If attempting to setup a duplex stream, the bufferSize parameter
// MUST be the same in both directions!
*bufferSize = theSize;
if (stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.bufferSize = *bufferSize;
stream_.nBuffers = 1;
// Try to set "hog" mode ... it's not clear to me this is working.
if (options && options->flags & RTAUDIO_HOG_DEVICE)
{
pid_t hog_pid;
dataSize = sizeof(hog_pid);
property.mSelector = kAudioDevicePropertyHogMode;
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &hog_pid);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting 'hog' state!";
errorText_ = errorStream_.str();
return FAILURE;
}
if (hog_pid != getpid())
{
hog_pid = getpid();
result = AudioObjectSetPropertyData(id, &property, 0, NULL, dataSize, &hog_pid);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") setting 'hog' state!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
}
// Check and if necessary, change the sample rate for the device.
Float64 nominalRate;
dataSize = sizeof(Float64);
property.mSelector = kAudioDevicePropertyNominalSampleRate;
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &nominalRate);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting current sample rate.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Only change the sample rate if off by more than 1 Hz.
if (fabs(nominalRate - (double)sampleRate) > 1.0)
{
// Set a property listener for the sample rate change
Float64 reportedRate = 0.0;
AudioObjectPropertyAddress tmp = {kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
result = AudioObjectAddPropertyListener(id, &tmp, rateListener, (void *)&reportedRate);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") setting sample rate property listener for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
nominalRate = (Float64)sampleRate;
result = AudioObjectSetPropertyData(id, &property, 0, NULL, dataSize, &nominalRate);
if (result != noErr)
{
AudioObjectRemovePropertyListener(id, &tmp, rateListener, (void *)&reportedRate);
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") setting sample rate for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Now wait until the reported nominal rate is what we just set.
UInt32 microCounter = 0;
while (reportedRate != nominalRate)
{
microCounter += 5000;
if (microCounter > 5000000) break;
usleep(5000);
}
// Remove the property listener.
AudioObjectRemovePropertyListener(id, &tmp, rateListener, (void *)&reportedRate);
if (microCounter > 5000000)
{
errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Now set the stream format for all streams. Also, check the
// physical format of the device and change that if necessary.
AudioStreamBasicDescription description;
dataSize = sizeof(AudioStreamBasicDescription);
property.mSelector = kAudioStreamPropertyVirtualFormat;
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &description);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting stream format for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the sample rate and data format id. However, only make the
// change if the sample rate is not within 1.0 of the desired
// rate and the format is not linear pcm.
bool updateFormat = false;
if (fabs(description.mSampleRate - (Float64)sampleRate) > 1.0)
{
description.mSampleRate = (Float64)sampleRate;
updateFormat = true;
}
if (description.mFormatID != kAudioFormatLinearPCM)
{
description.mFormatID = kAudioFormatLinearPCM;
updateFormat = true;
}
if (updateFormat)
{
result = AudioObjectSetPropertyData(id, &property, 0, NULL, dataSize, &description);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") setting sample rate or data format for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Now check the physical format.
property.mSelector = kAudioStreamPropertyPhysicalFormat;
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &description);
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting stream physical format for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
//std::cout << "Current physical stream format:" << std::endl;
//std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl;
//std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
//std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl;
//std::cout << " sample rate = " << description.mSampleRate << std::endl;
if (description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16)
{
description.mFormatID = kAudioFormatLinearPCM;
//description.mSampleRate = (Float64) sampleRate;
AudioStreamBasicDescription testDescription = description;
UInt32 formatFlags;
// We'll try higher bit rates first and then work our way down.
std::vector<std::pair<UInt32, UInt32> > physicalFormats;
formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;
physicalFormats.push_back(std::pair<Float32, UInt32>(32, formatFlags));
formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
physicalFormats.push_back(std::pair<Float32, UInt32>(32, formatFlags));
physicalFormats.push_back(std::pair<Float32, UInt32>(24, formatFlags)); // 24-bit packed
formatFlags &= ~(kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh);
physicalFormats.push_back(std::pair<Float32, UInt32>(24.2, formatFlags)); // 24-bit in 4 bytes, aligned low
formatFlags |= kAudioFormatFlagIsAlignedHigh;
physicalFormats.push_back(std::pair<Float32, UInt32>(24.4, formatFlags)); // 24-bit in 4 bytes, aligned high
formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
physicalFormats.push_back(std::pair<Float32, UInt32>(16, formatFlags));
physicalFormats.push_back(std::pair<Float32, UInt32>(8, formatFlags));
bool setPhysicalFormat = false;
for (unsigned int i = 0; i < physicalFormats.size(); i++)
{
testDescription = description;
testDescription.mBitsPerChannel = (UInt32)physicalFormats[i].first;
testDescription.mFormatFlags = physicalFormats[i].second;
if ((24 == (UInt32)physicalFormats[i].first) && ~(physicalFormats[i].second & kAudioFormatFlagIsPacked))
testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame;
else
testDescription.mBytesPerFrame = testDescription.mBitsPerChannel / 8 * testDescription.mChannelsPerFrame;
testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;
result = AudioObjectSetPropertyData(id, &property, 0, NULL, dataSize, &testDescription);
if (result == noErr)
{
setPhysicalFormat = true;
//std::cout << "Updated physical stream format:" << std::endl;
//std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;
//std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
//std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;
//std::cout << " sample rate = " << testDescription.mSampleRate << std::endl;
break;
}
}
if (!setPhysicalFormat)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") setting physical data format for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
} // done setting virtual/physical formats.
// Get the stream / device latency.
UInt32 latency;
dataSize = sizeof(UInt32);
property.mSelector = kAudioDevicePropertyLatency;
if (AudioObjectHasProperty(id, &property) == true)
{
result = AudioObjectGetPropertyData(id, &property, 0, NULL, &dataSize, &latency);
if (result == kAudioHardwareNoError)
stream_.latency[mode] = latency;
else
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode(result) << ") getting device latency for device (" << device << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
}
}
// Byte-swapping: According to AudioHardware.h, the stream data will
// always be presented in native-endian format, so we should never
// need to byte swap.
stream_.doByteSwap[mode] = false;
// From the CoreAudio documentation, PCM data must be supplied as
// 32-bit floats.
stream_.userFormat = format;
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
if (streamCount == 1)
stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
else // multiple streams
stream_.nDeviceChannels[mode] = channels;
stream_.nUserChannels[mode] = channels;
stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
stream_.userInterleaved = false;
else
stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
if (monoMode == true) stream_.deviceInterleaved[mode] = false;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode])
stream_.doConvertBuffer[mode] = true;
if (streamCount == 1)
{
if (stream_.nUserChannels[mode] > 1 &&
stream_.userInterleaved != stream_.deviceInterleaved[mode])
stream_.doConvertBuffer[mode] = true;
}
else if (monoMode && stream_.userInterleaved)
stream_.doConvertBuffer[mode] = true;
// Allocate our CoreHandle structure for the stream.
CoreHandle *handle = 0;
if (stream_.apiHandle == 0)
{
try
{
handle = new CoreHandle;
}
catch (std::bad_alloc &)
{
errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
goto error;
}
if (pthread_cond_init(&handle->condition, NULL))
{
errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *)handle;
}
else
handle = (CoreHandle *)stream_.apiHandle;
handle->iStream[mode] = firstStream;
handle->nStreams[mode] = streamCount;
handle->id[mode] = id;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes(stream_.userFormat);
// stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
stream_.userBuffer[mode] = (char *)malloc(bufferBytes * sizeof(char));
memset(stream_.userBuffer[mode], 0, bufferBytes * sizeof(char));
if (stream_.userBuffer[mode] == NULL)
{
errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
// If possible, we will make use of the CoreAudio stream buffers as
// "device buffers". However, we can't do this if using multiple
// streams.
if (stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1)
{
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes(stream_.deviceFormat[mode]);
if (mode == INPUT)
{
if (stream_.mode == OUTPUT && stream_.deviceBuffer)
{
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if (bufferBytes <= bytesOut) makeBuffer = false;
}
}
if (makeBuffer)
{
bufferBytes *= *bufferSize;
if (stream_.deviceBuffer) free(stream_.deviceBuffer);
stream_.deviceBuffer = (char *)calloc(bufferBytes, 1);
if (stream_.deviceBuffer == NULL)
{
errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.sampleRate = sampleRate;
stream_.device[mode] = device;
stream_.state = STREAM_STOPPED;
stream_.callbackInfo.object = (void *)this;
// Setup the buffer conversion information structure.
if (stream_.doConvertBuffer[mode])
{
if (streamCount > 1)
setConvertInfo(mode, 0);
else
setConvertInfo(mode, channelOffset);
}
if (mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device)
// Only one callback procedure per device.
stream_.mode = DUPLEX;
else
{
#if defined(MAC_OS_X_VERSION_10_5) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
result = AudioDeviceCreateIOProcID(id, callbackHandler, (void *)&stream_.callbackInfo, &handle->procId[mode]);
#else
// deprecated in favor of AudioDeviceCreateIOProcID()
result = AudioDeviceAddIOProc(id, callbackHandler, (void *)&stream_.callbackInfo);
#endif
if (result != noErr)
{
errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";
errorText_ = errorStream_.str();
goto error;
}
if (stream_.mode == OUTPUT && mode == INPUT)
stream_.mode = DUPLEX;
else
stream_.mode = mode;
}
// Setup the device property listener for over/underload.
property.mSelector = kAudioDeviceProcessorOverload;
property.mScope = kAudioObjectPropertyScopeGlobal;
result = AudioObjectAddPropertyListener(id, &property, xrunListener, (void *)handle);
return SUCCESS;
error:
if (handle)
{
pthread_cond_destroy(&handle->condition);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.state = STREAM_CLOSED;
return FAILURE;
}
void RtApiCore ::closeStream(void)
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiCore::closeStream(): no open stream to close!";
error(RtAudioError::WARNING);
return;
}
CoreHandle *handle = (CoreHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (handle)
{
AudioObjectPropertyAddress property = {kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
property.mSelector = kAudioDeviceProcessorOverload;
property.mScope = kAudioObjectPropertyScopeGlobal;
if (AudioObjectRemovePropertyListener(handle->id[0], &property, xrunListener, (void *)handle) != noErr)
{
errorText_ = "RtApiCore::closeStream(): error removing property listener!";
error(RtAudioError::WARNING);
}
}
if (stream_.state == STREAM_RUNNING)
AudioDeviceStop(handle->id[0], callbackHandler);
#if defined(MAC_OS_X_VERSION_10_5) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
AudioDeviceDestroyIOProcID(handle->id[0], handle->procId[0]);
#else
// deprecated in favor of AudioDeviceDestroyIOProcID()
AudioDeviceRemoveIOProc(handle->id[0], callbackHandler);
#endif
}
if (stream_.mode == INPUT || (stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1]))
{
if (handle)
{
AudioObjectPropertyAddress property = {kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
property.mSelector = kAudioDeviceProcessorOverload;
property.mScope = kAudioObjectPropertyScopeGlobal;
if (AudioObjectRemovePropertyListener(handle->id[1], &property, xrunListener, (void *)handle) != noErr)
{
errorText_ = "RtApiCore::closeStream(): error removing property listener!";
error(RtAudioError::WARNING);
}
}
if (stream_.state == STREAM_RUNNING)
AudioDeviceStop(handle->id[1], callbackHandler);
#if defined(MAC_OS_X_VERSION_10_5) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
AudioDeviceDestroyIOProcID(handle->id[1], handle->procId[1]);
#else
// deprecated in favor of AudioDeviceDestroyIOProcID()
AudioDeviceRemoveIOProc(handle->id[1], callbackHandler);
#endif
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
// Destroy pthread condition variable.
pthread_cond_destroy(&handle->condition);
delete handle;
stream_.apiHandle = 0;
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
}
void RtApiCore ::startStream(void)
{
verifyStream();
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiCore::startStream(): the stream is already running!";
error(RtAudioError::WARNING);
return;
}
OSStatus result = noErr;
CoreHandle *handle = (CoreHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
result = AudioDeviceStart(handle->id[0], callbackHandler);
if (result != noErr)
{
errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode(result) << ") starting callback procedure on device (" << stream_.device[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
if (stream_.mode == INPUT ||
(stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1]))
{
result = AudioDeviceStart(handle->id[1], callbackHandler);
if (result != noErr)
{
errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
handle->drainCounter = 0;
handle->internalDrain = false;
stream_.state = STREAM_RUNNING;
unlock:
if (result == noErr) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiCore ::stopStream(void)
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
OSStatus result = noErr;
CoreHandle *handle = (CoreHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (handle->drainCounter == 0)
{
handle->drainCounter = 2;
pthread_cond_wait(&handle->condition, &stream_.mutex); // block until signaled
}
result = AudioDeviceStop(handle->id[0], callbackHandler);
if (result != noErr)
{
errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode(result) << ") stopping callback procedure on device (" << stream_.device[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
if (stream_.mode == INPUT || (stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1]))
{
result = AudioDeviceStop(handle->id[1], callbackHandler);
if (result != noErr)
{
errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode(result) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
stream_.state = STREAM_STOPPED;
unlock:
if (result == noErr) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiCore ::abortStream(void)
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
CoreHandle *handle = (CoreHandle *)stream_.apiHandle;
handle->drainCounter = 2;
stopStream();
}
// This function will be called by a spawned thread when the user
// callback function signals that the stream should be stopped or
// aborted. It is better to handle it this way because the
// callbackEvent() function probably should return before the AudioDeviceStop()
// function is called.
static void *coreStopStream(void *ptr)
{
CallbackInfo *info = (CallbackInfo *)ptr;
RtApiCore *object = (RtApiCore *)info->object;
object->stopStream();
pthread_exit(NULL);
}
bool RtApiCore ::callbackEvent(AudioDeviceID deviceId,
const AudioBufferList *inBufferList,
const AudioBufferList *outBufferList)
{
if (stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING) return SUCCESS;
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
error(RtAudioError::WARNING);
return FAILURE;
}
CallbackInfo *info = (CallbackInfo *)&stream_.callbackInfo;
CoreHandle *handle = (CoreHandle *)stream_.apiHandle;
// Check if we were draining the stream and signal is finished.
if (handle->drainCounter > 3)
{
ThreadHandle threadId;
stream_.state = STREAM_STOPPING;
if (handle->internalDrain == true)
pthread_create(&threadId, NULL, coreStopStream, info);
else // external call to stopStream()
pthread_cond_signal(&handle->condition);
return SUCCESS;
}
AudioDeviceID outputDevice = handle->id[0];
// Invoke user callback to get fresh output data UNLESS we are
// draining stream or duplex mode AND the input/output devices are
// different AND this function is called for the input device.
if (handle->drainCounter == 0 && (stream_.mode != DUPLEX || deviceId == outputDevice))
{
RtAudioCallback callback = (RtAudioCallback)info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if (stream_.mode != INPUT && handle->xrun[0] == true)
{
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if (stream_.mode != OUTPUT && handle->xrun[1] == true)
{
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
int cbReturnValue = callback(stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData);
if (cbReturnValue == 2)
{
stream_.state = STREAM_STOPPING;
handle->drainCounter = 2;
abortStream();
return SUCCESS;
}
else if (cbReturnValue == 1)
{
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
if (stream_.mode == OUTPUT || (stream_.mode == DUPLEX && deviceId == outputDevice))
{
if (handle->drainCounter > 1)
{ // write zeros to the output stream
if (handle->nStreams[0] == 1)
{
memset(outBufferList->mBuffers[handle->iStream[0]].mData,
0,
outBufferList->mBuffers[handle->iStream[0]].mDataByteSize);
}
else
{ // fill multiple streams with zeros
for (unsigned int i = 0; i < handle->nStreams[0]; i++)
{
memset(outBufferList->mBuffers[handle->iStream[0] + i].mData,
0,
outBufferList->mBuffers[handle->iStream[0] + i].mDataByteSize);
}
}
}
else if (handle->nStreams[0] == 1)
{
if (stream_.doConvertBuffer[0])
{ // convert directly to CoreAudio stream buffer
convertBuffer((char *)outBufferList->mBuffers[handle->iStream[0]].mData,
stream_.userBuffer[0], stream_.convertInfo[0]);
}
else
{ // copy from user buffer
memcpy(outBufferList->mBuffers[handle->iStream[0]].mData,
stream_.userBuffer[0],
outBufferList->mBuffers[handle->iStream[0]].mDataByteSize);
}
}
else
{ // fill multiple streams
Float32 *inBuffer = (Float32 *)stream_.userBuffer[0];
if (stream_.doConvertBuffer[0])
{
convertBuffer(stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0]);
inBuffer = (Float32 *)stream_.deviceBuffer;
}
if (stream_.deviceInterleaved[0] == false)
{ // mono mode
UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
for (unsigned int i = 0; i < stream_.nUserChannels[0]; i++)
{
memcpy(outBufferList->mBuffers[handle->iStream[0] + i].mData,
(void *)&inBuffer[i * stream_.bufferSize], bufferBytes);
}
}
else
{ // fill multiple multi-channel streams with interleaved data
UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
Float32 *out, *in;
bool inInterleaved = (stream_.userInterleaved) ? true : false;
UInt32 inChannels = stream_.nUserChannels[0];
if (stream_.doConvertBuffer[0])
{
inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
inChannels = stream_.nDeviceChannels[0];
}
if (inInterleaved)
inOffset = 1;
else
inOffset = stream_.bufferSize;
channelsLeft = inChannels;
for (unsigned int i = 0; i < handle->nStreams[0]; i++)
{
in = inBuffer;
out = (Float32 *)outBufferList->mBuffers[handle->iStream[0] + i].mData;
streamChannels = outBufferList->mBuffers[handle->iStream[0] + i].mNumberChannels;
outJump = 0;
// Account for possible channel offset in first stream
if (i == 0 && stream_.channelOffset[0] > 0)
{
streamChannels -= stream_.channelOffset[0];
outJump = stream_.channelOffset[0];
out += outJump;
}
// Account for possible unfilled channels at end of the last stream
if (streamChannels > channelsLeft)
{
outJump = streamChannels - channelsLeft;
streamChannels = channelsLeft;
}
// Determine input buffer offsets and skips
if (inInterleaved)
{
inJump = inChannels;
in += inChannels - channelsLeft;
}
else
{
inJump = 1;
in += (inChannels - channelsLeft) * inOffset;
}
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (unsigned int j = 0; j < streamChannels; j++)
{
*out++ = in[j * inOffset];
}
out += outJump;
in += inJump;
}
channelsLeft -= streamChannels;
}
}
}
}
// Don't bother draining input
if (handle->drainCounter)
{
handle->drainCounter++;
goto unlock;
}
AudioDeviceID inputDevice;
inputDevice = handle->id[1];
if (stream_.mode == INPUT || (stream_.mode == DUPLEX && deviceId == inputDevice))
{
if (handle->nStreams[1] == 1)
{
if (stream_.doConvertBuffer[1])
{ // convert directly from CoreAudio stream buffer
convertBuffer(stream_.userBuffer[1],
(char *)inBufferList->mBuffers[handle->iStream[1]].mData,
stream_.convertInfo[1]);
}
else
{ // copy to user buffer
memcpy(stream_.userBuffer[1],
inBufferList->mBuffers[handle->iStream[1]].mData,
inBufferList->mBuffers[handle->iStream[1]].mDataByteSize);
}
}
else
{ // read from multiple streams
Float32 *outBuffer = (Float32 *)stream_.userBuffer[1];
if (stream_.doConvertBuffer[1]) outBuffer = (Float32 *)stream_.deviceBuffer;
if (stream_.deviceInterleaved[1] == false)
{ // mono mode
UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
for (unsigned int i = 0; i < stream_.nUserChannels[1]; i++)
{
memcpy((void *)&outBuffer[i * stream_.bufferSize],
inBufferList->mBuffers[handle->iStream[1] + i].mData, bufferBytes);
}
}
else
{ // read from multiple multi-channel streams
UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
Float32 *out, *in;
bool outInterleaved = (stream_.userInterleaved) ? true : false;
UInt32 outChannels = stream_.nUserChannels[1];
if (stream_.doConvertBuffer[1])
{
outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
outChannels = stream_.nDeviceChannels[1];
}
if (outInterleaved)
outOffset = 1;
else
outOffset = stream_.bufferSize;
channelsLeft = outChannels;
for (unsigned int i = 0; i < handle->nStreams[1]; i++)
{
out = outBuffer;
in = (Float32 *)inBufferList->mBuffers[handle->iStream[1] + i].mData;
streamChannels = inBufferList->mBuffers[handle->iStream[1] + i].mNumberChannels;
inJump = 0;
// Account for possible channel offset in first stream
if (i == 0 && stream_.channelOffset[1] > 0)
{
streamChannels -= stream_.channelOffset[1];
inJump = stream_.channelOffset[1];
in += inJump;
}
// Account for possible unread channels at end of the last stream
if (streamChannels > channelsLeft)
{
inJump = streamChannels - channelsLeft;
streamChannels = channelsLeft;
}
// Determine output buffer offsets and skips
if (outInterleaved)
{
outJump = outChannels;
out += outChannels - channelsLeft;
}
else
{
outJump = 1;
out += (outChannels - channelsLeft) * outOffset;
}
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (unsigned int j = 0; j < streamChannels; j++)
{
out[j * outOffset] = *in++;
}
out += outJump;
in += inJump;
}
channelsLeft -= streamChannels;
}
}
if (stream_.doConvertBuffer[1])
{ // convert from our internal "device" buffer
convertBuffer(stream_.userBuffer[1],
stream_.deviceBuffer,
stream_.convertInfo[1]);
}
}
}
unlock:
//MUTEX_UNLOCK( &stream_.mutex );
RtApi::tickStreamTime();
return SUCCESS;
}
const char *RtApiCore ::getErrorCode(OSStatus code)
{
switch (code)
{
case kAudioHardwareNotRunningError:
return "kAudioHardwareNotRunningError";
case kAudioHardwareUnspecifiedError:
return "kAudioHardwareUnspecifiedError";
case kAudioHardwareUnknownPropertyError:
return "kAudioHardwareUnknownPropertyError";
case kAudioHardwareBadPropertySizeError:
return "kAudioHardwareBadPropertySizeError";
case kAudioHardwareIllegalOperationError:
return "kAudioHardwareIllegalOperationError";
case kAudioHardwareBadObjectError:
return "kAudioHardwareBadObjectError";
case kAudioHardwareBadDeviceError:
return "kAudioHardwareBadDeviceError";
case kAudioHardwareBadStreamError:
return "kAudioHardwareBadStreamError";
case kAudioHardwareUnsupportedOperationError:
return "kAudioHardwareUnsupportedOperationError";
case kAudioDeviceUnsupportedFormatError:
return "kAudioDeviceUnsupportedFormatError";
case kAudioDevicePermissionsError:
return "kAudioDevicePermissionsError";
default:
return "CoreAudio unknown error";
}
}
//******************** End of __MACOSX_CORE__ *********************//
#endif
#if defined(__UNIX_JACK__)
// JACK is a low-latency audio server, originally written for the
// GNU/Linux operating system and now also ported to OS-X. It can
// connect a number of different applications to an audio device, as
// well as allowing them to share audio between themselves.
//
// When using JACK with RtAudio, "devices" refer to JACK clients that
// have ports connected to the server. The JACK server is typically
// started in a terminal as follows:
//
// .jackd -d alsa -d hw:0
//
// or through an interface program such as qjackctl. Many of the
// parameters normally set for a stream are fixed by the JACK server
// and can be specified when the JACK server is started. In
// particular,
//
// .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
//
// specifies a sample rate of 44100 Hz, a buffer size of 512 sample
// frames, and number of buffers = 4. Once the server is running, it
// is not possible to override these values. If the values are not
// specified in the command-line, the JACK server uses default values.
//
// The JACK server does not have to be running when an instance of
// RtApiJack is created, though the function getDeviceCount() will
// report 0 devices found until JACK has been started. When no
// devices are available (i.e., the JACK server is not running), a
// stream cannot be opened.
#include <jack/jack.h>
#include <unistd.h>
#include <cstdio>
// A structure to hold various information related to the Jack API
// implementation.
struct JackHandle
{
jack_client_t *client;
jack_port_t **ports[2];
std::string deviceName[2];
bool xrun[2];
pthread_cond_t condition;
int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
JackHandle()
: client(0), drainCounter(0), internalDrain(false)
{
ports[0] = 0;
ports[1] = 0;
xrun[0] = false;
xrun[1] = false;
}
};
static void jackSilentError(const char *){};
RtApiJack ::RtApiJack()
{
// Nothing to do here.
#if !defined(__RTAUDIO_DEBUG__)
// Turn off Jack's internal error reporting.
jack_set_error_function(&jackSilentError);
#endif
}
RtApiJack ::~RtApiJack()
{
if (stream_.state != STREAM_CLOSED) closeStream();
}
unsigned int RtApiJack ::getDeviceCount(void)
{
// See if we can become a jack client.
jack_options_t options = (jack_options_t)(JackNoStartServer); //JackNullOption;
jack_status_t *status = NULL;
jack_client_t *client = jack_client_open("RtApiJackCount", options, status);
if (client == 0) return 0;
const char **ports;
std::string port, previousPort;
unsigned int nChannels = 0, nDevices = 0;
ports = jack_get_ports(client, NULL, NULL, 0);
if (ports)
{
// Parse the port names up to the first colon (:).
size_t iColon = 0;
do
{
port = (char *)ports[nChannels];
iColon = port.find(":");
if (iColon != std::string::npos)
{
port = port.substr(0, iColon + 1);
if (port != previousPort)
{
nDevices++;
previousPort = port;
}
}
} while (ports[++nChannels]);
free(ports);
}
jack_client_close(client);
return nDevices;
}
RtAudio::DeviceInfo RtApiJack ::getDeviceInfo(unsigned int device)
{
RtAudio::DeviceInfo info;
info.probed = false;
jack_options_t options = (jack_options_t)(JackNoStartServer); //JackNullOption
jack_status_t *status = NULL;
jack_client_t *client = jack_client_open("RtApiJackInfo", options, status);
if (client == 0)
{
errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
error(RtAudioError::WARNING);
return info;
}
const char **ports;
std::string port, previousPort;
unsigned int nPorts = 0, nDevices = 0;
ports = jack_get_ports(client, NULL, NULL, 0);
if (ports)
{
// Parse the port names up to the first colon (:).
size_t iColon = 0;
do
{
port = (char *)ports[nPorts];
iColon = port.find(":");
if (iColon != std::string::npos)
{
port = port.substr(0, iColon);
if (port != previousPort)
{
if (nDevices == device) info.name = port;
nDevices++;
previousPort = port;
}
}
} while (ports[++nPorts]);
free(ports);
}
if (device >= nDevices)
{
jack_client_close(client);
errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
error(RtAudioError::INVALID_USE);
return info;
}
// Get the current jack server sample rate.
info.sampleRates.clear();
info.preferredSampleRate = jack_get_sample_rate(client);
info.sampleRates.push_back(info.preferredSampleRate);
// Count the available ports containing the client name as device
// channels. Jack "input ports" equal RtAudio output channels.
unsigned int nChannels = 0;
ports = jack_get_ports(client, info.name.c_str(), NULL, JackPortIsInput);
if (ports)
{
while (ports[nChannels]) nChannels++;
free(ports);
info.outputChannels = nChannels;
}
// Jack "output ports" equal RtAudio input channels.
nChannels = 0;
ports = jack_get_ports(client, info.name.c_str(), NULL, JackPortIsOutput);
if (ports)
{
while (ports[nChannels]) nChannels++;
free(ports);
info.inputChannels = nChannels;
}
if (info.outputChannels == 0 && info.inputChannels == 0)
{
jack_client_close(client);
errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
error(RtAudioError::WARNING);
return info;
}
// If device opens for both playback and capture, we determine the channels.
if (info.outputChannels > 0 && info.inputChannels > 0)
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// Jack always uses 32-bit floats.
info.nativeFormats = RTAUDIO_FLOAT32;
// Jack doesn't provide default devices so we'll use the first available one.
if (device == 0 && info.outputChannels > 0)
info.isDefaultOutput = true;
if (device == 0 && info.inputChannels > 0)
info.isDefaultInput = true;
jack_client_close(client);
info.probed = true;
return info;
}
static int jackCallbackHandler(jack_nframes_t nframes, void *infoPointer)
{
CallbackInfo *info = (CallbackInfo *)infoPointer;
RtApiJack *object = (RtApiJack *)info->object;
if (object->callbackEvent((unsigned long)nframes) == false) return 1;
return 0;
}
// This function will be called by a spawned thread when the Jack
// server signals that it is shutting down. It is necessary to handle
// it this way because the jackShutdown() function must return before
// the jack_deactivate() function (in closeStream()) will return.
static void *jackCloseStream(void *ptr)
{
CallbackInfo *info = (CallbackInfo *)ptr;
RtApiJack *object = (RtApiJack *)info->object;
object->closeStream();
pthread_exit(NULL);
}
static void jackShutdown(void *infoPointer)
{
CallbackInfo *info = (CallbackInfo *)infoPointer;
RtApiJack *object = (RtApiJack *)info->object;
// Check current stream state. If stopped, then we'll assume this
// was called as a result of a call to RtApiJack::stopStream (the
// deactivation of a client handle causes this function to be called).
// If not, we'll assume the Jack server is shutting down or some
// other problem occurred and we should close the stream.
if (object->isStreamRunning() == false) return;
ThreadHandle threadId;
pthread_create(&threadId, NULL, jackCloseStream, info);
std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n"
<< std::endl;
}
static int jackXrun(void *infoPointer)
{
JackHandle *handle = (JackHandle *)infoPointer;
if (handle->ports[0]) handle->xrun[0] = true;
if (handle->ports[1]) handle->xrun[1] = true;
return 0;
}
bool RtApiJack ::probeDeviceOpen(unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options)
{
JackHandle *handle = (JackHandle *)stream_.apiHandle;
// Look for jack server and try to become a client (only do once per stream).
jack_client_t *client = 0;
if (mode == OUTPUT || (mode == INPUT && stream_.mode != OUTPUT))
{
jack_options_t jackoptions = (jack_options_t)(JackNoStartServer); //JackNullOption;
jack_status_t *status = NULL;
if (options && !options->streamName.empty())
client = jack_client_open(options->streamName.c_str(), jackoptions, status);
else
client = jack_client_open("RtApiJack", jackoptions, status);
if (client == 0)
{
errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
error(RtAudioError::WARNING);
return FAILURE;
}
}
else
{
// The handle must have been created on an earlier pass.
client = handle->client;
}
const char **ports;
std::string port, previousPort, deviceName;
unsigned int nPorts = 0, nDevices = 0;
ports = jack_get_ports(client, NULL, NULL, 0);
if (ports)
{
// Parse the port names up to the first colon (:).
size_t iColon = 0;
do
{
port = (char *)ports[nPorts];
iColon = port.find(":");
if (iColon != std::string::npos)
{
port = port.substr(0, iColon);
if (port != previousPort)
{
if (nDevices == device) deviceName = port;
nDevices++;
previousPort = port;
}
}
} while (ports[++nPorts]);
free(ports);
}
if (device >= nDevices)
{
errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
// Count the available ports containing the client name as device
// channels. Jack "input ports" equal RtAudio output channels.
unsigned int nChannels = 0;
unsigned long flag = JackPortIsInput;
if (mode == INPUT) flag = JackPortIsOutput;
ports = jack_get_ports(client, deviceName.c_str(), NULL, flag);
if (ports)
{
while (ports[nChannels]) nChannels++;
free(ports);
}
// Compare the jack ports for specified client to the requested number of channels.
if (nChannels < (channels + firstChannel))
{
errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check the jack server sample rate.
unsigned int jackRate = jack_get_sample_rate(client);
if (sampleRate != jackRate)
{
jack_client_close(client);
errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.sampleRate = jackRate;
// Get the latency of the JACK port.
ports = jack_get_ports(client, deviceName.c_str(), NULL, flag);
if (ports[firstChannel])
{
// Added by Ge Wang
jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
// the range (usually the min and max are equal)
jack_latency_range_t latrange;
latrange.min = latrange.max = 0;
// get the latency range
jack_port_get_latency_range(jack_port_by_name(client, ports[firstChannel]), cbmode, &latrange);
// be optimistic, use the min!
stream_.latency[mode] = latrange.min;
//stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
}
free(ports);
// The jack server always uses 32-bit floating-point data.
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
stream_.userFormat = format;
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
stream_.userInterleaved = false;
else
stream_.userInterleaved = true;
// Jack always uses non-interleaved buffers.
stream_.deviceInterleaved[mode] = false;
// Jack always provides host byte-ordered data.
stream_.doByteSwap[mode] = false;
// Get the buffer size. The buffer size and number of buffers
// (periods) is set when the jack server is started.
stream_.bufferSize = (int)jack_get_buffer_size(client);
*bufferSize = stream_.bufferSize;
stream_.nDeviceChannels[mode] = channels;
stream_.nUserChannels[mode] = channels;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1)
stream_.doConvertBuffer[mode] = true;
// Allocate our JackHandle structure for the stream.
if (handle == 0)
{
try
{
handle = new JackHandle;
}
catch (std::bad_alloc &)
{
errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
goto error;
}
if (pthread_cond_init(&handle->condition, NULL))
{
errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *)handle;
handle->client = client;
}
handle->deviceName[mode] = deviceName;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes(stream_.userFormat);
stream_.userBuffer[mode] = (char *)calloc(bufferBytes, 1);
if (stream_.userBuffer[mode] == NULL)
{
errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if (stream_.doConvertBuffer[mode])
{
bool makeBuffer = true;
if (mode == OUTPUT)
bufferBytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
else
{ // mode == INPUT
bufferBytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
if (stream_.mode == OUTPUT && stream_.deviceBuffer)
{
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if (bufferBytes < bytesOut) makeBuffer = false;
}
}
if (makeBuffer)
{
bufferBytes *= *bufferSize;
if (stream_.deviceBuffer) free(stream_.deviceBuffer);
stream_.deviceBuffer = (char *)calloc(bufferBytes, 1);
if (stream_.deviceBuffer == NULL)
{
errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
// Allocate memory for the Jack ports (channels) identifiers.
handle->ports[mode] = (jack_port_t **)malloc(sizeof(jack_port_t *) * channels);
if (handle->ports[mode] == NULL)
{
errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
goto error;
}
stream_.device[mode] = device;
stream_.channelOffset[mode] = firstChannel;
stream_.state = STREAM_STOPPED;
stream_.callbackInfo.object = (void *)this;
if (stream_.mode == OUTPUT && mode == INPUT)
// We had already set up the stream for output.
stream_.mode = DUPLEX;
else
{
stream_.mode = mode;
jack_set_process_callback(handle->client, jackCallbackHandler, (void *)&stream_.callbackInfo);
jack_set_xrun_callback(handle->client, jackXrun, (void *)&handle);
jack_on_shutdown(handle->client, jackShutdown, (void *)&stream_.callbackInfo);
}
// Register our ports.
char label[64];
if (mode == OUTPUT)
{
for (unsigned int i = 0; i < stream_.nUserChannels[0]; i++)
{
snprintf(label, 64, "outport %d", i);
handle->ports[0][i] = jack_port_register(handle->client, (const char *)label,
JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
}
}
else
{
for (unsigned int i = 0; i < stream_.nUserChannels[1]; i++)
{
snprintf(label, 64, "inport %d", i);
handle->ports[1][i] = jack_port_register(handle->client, (const char *)label,
JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
}
}
// Setup the buffer conversion information structure. We don't use
// buffers to do channel offsets, so we override that parameter
// here.
if (stream_.doConvertBuffer[mode]) setConvertInfo(mode, 0);
return SUCCESS;
error:
if (handle)
{
pthread_cond_destroy(&handle->condition);
jack_client_close(handle->client);
if (handle->ports[0]) free(handle->ports[0]);
if (handle->ports[1]) free(handle->ports[1]);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
return FAILURE;
}
void RtApiJack ::closeStream(void)
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiJack::closeStream(): no open stream to close!";
error(RtAudioError::WARNING);
return;
}
JackHandle *handle = (JackHandle *)stream_.apiHandle;
if (handle)
{
if (stream_.state == STREAM_RUNNING)
jack_deactivate(handle->client);
jack_client_close(handle->client);
}
if (handle)
{
if (handle->ports[0]) free(handle->ports[0]);
if (handle->ports[1]) free(handle->ports[1]);
pthread_cond_destroy(&handle->condition);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
}
void RtApiJack ::startStream(void)
{
verifyStream();
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiJack::startStream(): the stream is already running!";
error(RtAudioError::WARNING);
return;
}
JackHandle *handle = (JackHandle *)stream_.apiHandle;
int result = jack_activate(handle->client);
if (result)
{
errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
goto unlock;
}
const char **ports;
// Get the list of available ports.
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
result = 1;
ports = jack_get_ports(handle->client, handle->deviceName[0].c_str(), NULL, JackPortIsInput);
if (ports == NULL)
{
errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
goto unlock;
}
// Now make the port connections. Since RtAudio wasn't designed to
// allow the user to select particular channels of a device, we'll
// just open the first "nChannels" ports with offset.
for (unsigned int i = 0; i < stream_.nUserChannels[0]; i++)
{
result = 1;
if (ports[stream_.channelOffset[0] + i])
result = jack_connect(handle->client, jack_port_name(handle->ports[0][i]), ports[stream_.channelOffset[0] + i]);
if (result)
{
free(ports);
errorText_ = "RtApiJack::startStream(): error connecting output ports!";
goto unlock;
}
}
free(ports);
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
result = 1;
ports = jack_get_ports(handle->client, handle->deviceName[1].c_str(), NULL, JackPortIsOutput);
if (ports == NULL)
{
errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
goto unlock;
}
// Now make the port connections. See note above.
for (unsigned int i = 0; i < stream_.nUserChannels[1]; i++)
{
result = 1;
if (ports[stream_.channelOffset[1] + i])
result = jack_connect(handle->client, ports[stream_.channelOffset[1] + i], jack_port_name(handle->ports[1][i]));
if (result)
{
free(ports);
errorText_ = "RtApiJack::startStream(): error connecting input ports!";
goto unlock;
}
}
free(ports);
}
handle->drainCounter = 0;
handle->internalDrain = false;
stream_.state = STREAM_RUNNING;
unlock:
if (result == 0) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiJack ::stopStream(void)
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
JackHandle *handle = (JackHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (handle->drainCounter == 0)
{
handle->drainCounter = 2;
pthread_cond_wait(&handle->condition, &stream_.mutex); // block until signaled
}
}
jack_deactivate(handle->client);
stream_.state = STREAM_STOPPED;
}
void RtApiJack ::abortStream(void)
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
JackHandle *handle = (JackHandle *)stream_.apiHandle;
handle->drainCounter = 2;
stopStream();
}
// This function will be called by a spawned thread when the user
// callback function signals that the stream should be stopped or
// aborted. It is necessary to handle it this way because the
// callbackEvent() function must return before the jack_deactivate()
// function will return.
static void *jackStopStream(void *ptr)
{
CallbackInfo *info = (CallbackInfo *)ptr;
RtApiJack *object = (RtApiJack *)info->object;
object->stopStream();
pthread_exit(NULL);
}
bool RtApiJack ::callbackEvent(unsigned long nframes)
{
if (stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING) return SUCCESS;
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
error(RtAudioError::WARNING);
return FAILURE;
}
if (stream_.bufferSize != nframes)
{
errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
error(RtAudioError::WARNING);
return FAILURE;
}
CallbackInfo *info = (CallbackInfo *)&stream_.callbackInfo;
JackHandle *handle = (JackHandle *)stream_.apiHandle;
// Check if we were draining the stream and signal is finished.
if (handle->drainCounter > 3)
{
ThreadHandle threadId;
stream_.state = STREAM_STOPPING;
if (handle->internalDrain == true)
pthread_create(&threadId, NULL, jackStopStream, info);
else
pthread_cond_signal(&handle->condition);
return SUCCESS;
}
// Invoke user callback first, to get fresh output data.
if (handle->drainCounter == 0)
{
RtAudioCallback callback = (RtAudioCallback)info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if (stream_.mode != INPUT && handle->xrun[0] == true)
{
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if (stream_.mode != OUTPUT && handle->xrun[1] == true)
{
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
int cbReturnValue = callback(stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData);
if (cbReturnValue == 2)
{
stream_.state = STREAM_STOPPING;
handle->drainCounter = 2;
ThreadHandle id;
pthread_create(&id, NULL, jackStopStream, info);
return SUCCESS;
}
else if (cbReturnValue == 1)
{
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
jack_default_audio_sample_t *jackbuffer;
unsigned long bufferBytes = nframes * sizeof(jack_default_audio_sample_t);
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (handle->drainCounter > 1)
{ // write zeros to the output stream
for (unsigned int i = 0; i < stream_.nDeviceChannels[0]; i++)
{
jackbuffer = (jack_default_audio_sample_t *)jack_port_get_buffer(handle->ports[0][i], (jack_nframes_t)nframes);
memset(jackbuffer, 0, bufferBytes);
}
}
else if (stream_.doConvertBuffer[0])
{
convertBuffer(stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0]);
for (unsigned int i = 0; i < stream_.nDeviceChannels[0]; i++)
{
jackbuffer = (jack_default_audio_sample_t *)jack_port_get_buffer(handle->ports[0][i], (jack_nframes_t)nframes);
memcpy(jackbuffer, &stream_.deviceBuffer[i * bufferBytes], bufferBytes);
}
}
else
{ // no buffer conversion
for (unsigned int i = 0; i < stream_.nUserChannels[0]; i++)
{
jackbuffer = (jack_default_audio_sample_t *)jack_port_get_buffer(handle->ports[0][i], (jack_nframes_t)nframes);
memcpy(jackbuffer, &stream_.userBuffer[0][i * bufferBytes], bufferBytes);
}
}
}
// Don't bother draining input
if (handle->drainCounter)
{
handle->drainCounter++;
goto unlock;
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
if (stream_.doConvertBuffer[1])
{
for (unsigned int i = 0; i < stream_.nDeviceChannels[1]; i++)
{
jackbuffer = (jack_default_audio_sample_t *)jack_port_get_buffer(handle->ports[1][i], (jack_nframes_t)nframes);
memcpy(&stream_.deviceBuffer[i * bufferBytes], jackbuffer, bufferBytes);
}
convertBuffer(stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1]);
}
else
{ // no buffer conversion
for (unsigned int i = 0; i < stream_.nUserChannels[1]; i++)
{
jackbuffer = (jack_default_audio_sample_t *)jack_port_get_buffer(handle->ports[1][i], (jack_nframes_t)nframes);
memcpy(&stream_.userBuffer[1][i * bufferBytes], jackbuffer, bufferBytes);
}
}
}
unlock:
RtApi::tickStreamTime();
return SUCCESS;
}
//******************** End of __UNIX_JACK__ *********************//
#endif
#if defined(__WINDOWS_ASIO__) // ASIO API on Windows
// The ASIO API is designed around a callback scheme, so this
// implementation is similar to that used for OS-X CoreAudio and Linux
// Jack. The primary constraint with ASIO is that it only allows
// access to a single driver at a time. Thus, it is not possible to
// have more than one simultaneous RtAudio stream.
//
// This implementation also requires a number of external ASIO files
// and a few global variables. The ASIO callback scheme does not
// allow for the passing of user data, so we must create a global
// pointer to our callbackInfo structure.
//
// On unix systems, we make use of a pthread condition variable.
// Since there is no equivalent in Windows, I hacked something based
// on information found in
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
#include "asiosys.h"
#include "asio.h"
#include "iasiothiscallresolver.h"
#include "asiodrivers.h"
#include <cmath>
static AsioDrivers drivers;
static ASIOCallbacks asioCallbacks;
static ASIODriverInfo driverInfo;
static CallbackInfo *asioCallbackInfo;
static bool asioXRun;
struct AsioHandle
{
int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
ASIOBufferInfo *bufferInfos;
HANDLE condition;
AsioHandle()
: drainCounter(0), internalDrain(false), bufferInfos(0) {}
};
// Function declarations (definitions at end of section)
static const char *getAsioErrorString(ASIOError result);
static void sampleRateChanged(ASIOSampleRate sRate);
static long asioMessages(long selector, long value, void *message, double *opt);
RtApiAsio ::RtApiAsio()
{
// ASIO cannot run on a multi-threaded appartment. You can call
// CoInitialize beforehand, but it must be for appartment threading
// (in which case, CoInitilialize will return S_FALSE here).
coInitialized_ = false;
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
{
errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
error(RtAudioError::WARNING);
}
coInitialized_ = true;
drivers.removeCurrentDriver();
driverInfo.asioVersion = 2;
// See note in DirectSound implementation about GetDesktopWindow().
driverInfo.sysRef = GetForegroundWindow();
}
RtApiAsio ::~RtApiAsio()
{
if (stream_.state != STREAM_CLOSED) closeStream();
if (coInitialized_) CoUninitialize();
}
unsigned int RtApiAsio ::getDeviceCount(void)
{
return (unsigned int)drivers.asioGetNumDev();
}
RtAudio::DeviceInfo RtApiAsio ::getDeviceInfo(unsigned int device)
{
RtAudio::DeviceInfo info;
info.probed = false;
// Get device ID
unsigned int nDevices = getDeviceCount();
if (nDevices == 0)
{
errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
error(RtAudioError::INVALID_USE);
return info;
}
if (device >= nDevices)
{
errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
error(RtAudioError::INVALID_USE);
return info;
}
// If a stream is already open, we cannot probe other devices. Thus, use the saved results.
if (stream_.state != STREAM_CLOSED)
{
if (device >= devices_.size())
{
errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
error(RtAudioError::WARNING);
return info;
}
return devices_[device];
}
char driverName[32];
ASIOError result = drivers.asioGetDriverName((int)device, driverName, 32);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString(result) << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
info.name = driverName;
if (!drivers.loadDriver(driverName))
{
errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
result = ASIOInit(&driverInfo);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString(result) << ") initializing driver (" << driverName << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Determine the device channel information.
long inputChannels, outputChannels;
result = ASIOGetChannels(&inputChannels, &outputChannels);
if (result != ASE_OK)
{
drivers.removeCurrentDriver();
errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString(result) << ") getting channel count (" << driverName << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
info.outputChannels = outputChannels;
info.inputChannels = inputChannels;
if (info.outputChannels > 0 && info.inputChannels > 0)
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// Determine the supported sample rates.
info.sampleRates.clear();
for (unsigned int i = 0; i < MAX_SAMPLE_RATES; i++)
{
result = ASIOCanSampleRate((ASIOSampleRate)SAMPLE_RATES[i]);
if (result == ASE_OK)
{
info.sampleRates.push_back(SAMPLE_RATES[i]);
if (!info.preferredSampleRate || (SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate))
info.preferredSampleRate = SAMPLE_RATES[i];
}
}
// Determine supported data types ... just check first channel and assume rest are the same.
ASIOChannelInfo channelInfo;
channelInfo.channel = 0;
channelInfo.isInput = true;
if (info.inputChannels <= 0) channelInfo.isInput = false;
result = ASIOGetChannelInfo(&channelInfo);
if (result != ASE_OK)
{
drivers.removeCurrentDriver();
errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString(result) << ") getting driver channel info (" << driverName << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
info.nativeFormats = 0;
if (channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB)
info.nativeFormats |= RTAUDIO_SINT16;
else if (channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB)
info.nativeFormats |= RTAUDIO_SINT32;
else if (channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB)
info.nativeFormats |= RTAUDIO_FLOAT32;
else if (channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB)
info.nativeFormats |= RTAUDIO_FLOAT64;
else if (channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB)
info.nativeFormats |= RTAUDIO_SINT24;
if (info.outputChannels > 0)
if (getDefaultOutputDevice() == device) info.isDefaultOutput = true;
if (info.inputChannels > 0)
if (getDefaultInputDevice() == device) info.isDefaultInput = true;
info.probed = true;
drivers.removeCurrentDriver();
return info;
}
static void bufferSwitch(long index, ASIOBool /*processNow*/)
{
RtApiAsio *object = (RtApiAsio *)asioCallbackInfo->object;
object->callbackEvent(index);
}
void RtApiAsio ::saveDeviceInfo(void)
{
devices_.clear();
unsigned int nDevices = getDeviceCount();
devices_.resize(nDevices);
for (unsigned int i = 0; i < nDevices; i++)
devices_[i] = getDeviceInfo(i);
}
bool RtApiAsio ::probeDeviceOpen(unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options)
{ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;
// For ASIO, a duplex stream MUST use the same driver.
if (isDuplexInput && stream_.device[0] != device)
{
errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
return FAILURE;
}
char driverName[32];
ASIOError result = drivers.asioGetDriverName((int)device, driverName, 32);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString(result) << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Only load the driver once for duplex stream.
if (!isDuplexInput)
{
// The getDeviceInfo() function will not work when a stream is open
// because ASIO does not allow multiple devices to run at the same
// time. Thus, we'll probe the system before opening a stream and
// save the results for use by getDeviceInfo().
this->saveDeviceInfo();
if (!drivers.loadDriver(driverName))
{
errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
result = ASIOInit(&driverInfo);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString(result) << ") initializing driver (" << driverName << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// keep them before any "goto error", they are used for error cleanup + goto device boundary checks
bool buffersAllocated = false;
AsioHandle *handle = (AsioHandle *)stream_.apiHandle;
unsigned int nChannels;
// Check the device channel count.
long inputChannels, outputChannels;
result = ASIOGetChannels(&inputChannels, &outputChannels);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString(result) << ") getting channel count (" << driverName << ").";
errorText_ = errorStream_.str();
goto error;
}
if ((mode == OUTPUT && (channels + firstChannel) > (unsigned int)outputChannels) ||
(mode == INPUT && (channels + firstChannel) > (unsigned int)inputChannels))
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
errorText_ = errorStream_.str();
goto error;
}
stream_.nDeviceChannels[mode] = channels;
stream_.nUserChannels[mode] = channels;
stream_.channelOffset[mode] = firstChannel;
// Verify the sample rate is supported.
result = ASIOCanSampleRate((ASIOSampleRate)sampleRate);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
errorText_ = errorStream_.str();
goto error;
}
// Get the current sample rate
ASIOSampleRate currentRate;
result = ASIOGetSampleRate(¤tRate);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
errorText_ = errorStream_.str();
goto error;
}
// Set the sample rate only if necessary
if (currentRate != sampleRate)
{
result = ASIOSetSampleRate((ASIOSampleRate)sampleRate);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
errorText_ = errorStream_.str();
goto error;
}
}
// Determine the driver data type.
ASIOChannelInfo channelInfo;
channelInfo.channel = 0;
if (mode == OUTPUT)
channelInfo.isInput = false;
else
channelInfo.isInput = true;
result = ASIOGetChannelInfo(&channelInfo);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString(result) << ") getting data format.";
errorText_ = errorStream_.str();
goto error;
}
// Assuming WINDOWS host is always little-endian.
stream_.doByteSwap[mode] = false;
stream_.userFormat = format;
stream_.deviceFormat[mode] = 0;
if (channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB)
{
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
if (channelInfo.type == ASIOSTInt16MSB) stream_.doByteSwap[mode] = true;
}
else if (channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB)
{
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
if (channelInfo.type == ASIOSTInt32MSB) stream_.doByteSwap[mode] = true;
}
else if (channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB)
{
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
if (channelInfo.type == ASIOSTFloat32MSB) stream_.doByteSwap[mode] = true;
}
else if (channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB)
{
stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
if (channelInfo.type == ASIOSTFloat64MSB) stream_.doByteSwap[mode] = true;
}
else if (channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB)
{
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
if (channelInfo.type == ASIOSTInt24MSB) stream_.doByteSwap[mode] = true;
}
if (stream_.deviceFormat[mode] == 0)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
goto error;
}
// Set the buffer size. For a duplex stream, this will end up
// setting the buffer size based on the input constraints, which
// should be ok.
long minSize, maxSize, preferSize, granularity;
result = ASIOGetBufferSize(&minSize, &maxSize, &preferSize, &granularity);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString(result) << ") getting buffer size.";
errorText_ = errorStream_.str();
goto error;
}
if (isDuplexInput)
{
// When this is the duplex input (output was opened before), then we have to use the same
// buffersize as the output, because it might use the preferred buffer size, which most
// likely wasn't passed as input to this. The buffer sizes have to be identically anyway,
// So instead of throwing an error, make them equal. The caller uses the reference
// to the "bufferSize" param as usual to set up processing buffers.
*bufferSize = stream_.bufferSize;
}
else
{
if (*bufferSize == 0)
*bufferSize = preferSize;
else if (*bufferSize < (unsigned int)minSize)
*bufferSize = (unsigned int)minSize;
else if (*bufferSize > (unsigned int)maxSize)
*bufferSize = (unsigned int)maxSize;
else if (granularity == -1)
{
// Make sure bufferSize is a power of two.
int log2_of_min_size = 0;
int log2_of_max_size = 0;
for (unsigned int i = 0; i < sizeof(long) * 8; i++)
{
if (minSize & ((long)1 << i)) log2_of_min_size = i;
if (maxSize & ((long)1 << i)) log2_of_max_size = i;
}
long min_delta = std::abs((long)*bufferSize - ((long)1 << log2_of_min_size));
int min_delta_num = log2_of_min_size;
for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++)
{
long current_delta = std::abs((long)*bufferSize - ((long)1 << i));
if (current_delta < min_delta)
{
min_delta = current_delta;
min_delta_num = i;
}
}
*bufferSize = ((unsigned int)1 << min_delta_num);
if (*bufferSize < (unsigned int)minSize)
*bufferSize = (unsigned int)minSize;
else if (*bufferSize > (unsigned int)maxSize)
*bufferSize = (unsigned int)maxSize;
}
else if (granularity != 0)
{
// Set to an even multiple of granularity, rounding up.
*bufferSize = (*bufferSize + granularity - 1) / granularity * granularity;
}
}
/*
// we don't use it anymore, see above!
// Just left it here for the case...
if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {
errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
goto error;
}
*/
stream_.bufferSize = *bufferSize;
stream_.nBuffers = 2;
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
stream_.userInterleaved = false;
else
stream_.userInterleaved = true;
// ASIO always uses non-interleaved buffers.
stream_.deviceInterleaved[mode] = false;
// Allocate, if necessary, our AsioHandle structure for the stream.
if (handle == 0)
{
try
{
handle = new AsioHandle;
}
catch (std::bad_alloc &)
{
errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
goto error;
}
handle->bufferInfos = 0;
// Create a manual-reset event.
handle->condition = CreateEvent(NULL, // no security
TRUE, // manual-reset
FALSE, // non-signaled initially
NULL); // unnamed
stream_.apiHandle = (void *)handle;
}
// Create the ASIO internal buffers. Since RtAudio sets up input
// and output separately, we'll have to dispose of previously
// created output buffers for a duplex stream.
if (mode == INPUT && stream_.mode == OUTPUT)
{
ASIODisposeBuffers();
if (handle->bufferInfos) free(handle->bufferInfos);
}
// Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
unsigned int i;
nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
handle->bufferInfos = (ASIOBufferInfo *)malloc(nChannels * sizeof(ASIOBufferInfo));
if (handle->bufferInfos == NULL)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
errorText_ = errorStream_.str();
goto error;
}
ASIOBufferInfo *infos;
infos = handle->bufferInfos;
for (i = 0; i < stream_.nDeviceChannels[0]; i++, infos++)
{
infos->isInput = ASIOFalse;
infos->channelNum = i + stream_.channelOffset[0];
infos->buffers[0] = infos->buffers[1] = 0;
}
for (i = 0; i < stream_.nDeviceChannels[1]; i++, infos++)
{
infos->isInput = ASIOTrue;
infos->channelNum = i + stream_.channelOffset[1];
infos->buffers[0] = infos->buffers[1] = 0;
}
// prepare for callbacks
stream_.sampleRate = sampleRate;
stream_.device[mode] = device;
stream_.mode = isDuplexInput ? DUPLEX : mode;
// store this class instance before registering callbacks, that are going to use it
asioCallbackInfo = &stream_.callbackInfo;
stream_.callbackInfo.object = (void *)this;
// Set up the ASIO callback structure and create the ASIO data buffers.
asioCallbacks.bufferSwitch = &bufferSwitch;
asioCallbacks.sampleRateDidChange = &sampleRateChanged;
asioCallbacks.asioMessage = &asioMessages;
asioCallbacks.bufferSwitchTimeInfo = NULL;
result = ASIOCreateBuffers(handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks);
if (result != ASE_OK)
{
// Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges
// but only accept the preferred buffer size as parameter for ASIOCreateBuffers. eg. Creatives ASIO driver
// in that case, let's be na´ve and try that instead
*bufferSize = preferSize;
stream_.bufferSize = *bufferSize;
result = ASIOCreateBuffers(handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks);
}
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString(result) << ") creating buffers.";
errorText_ = errorStream_.str();
goto error;
}
buffersAllocated = true;
stream_.state = STREAM_STOPPED;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1)
stream_.doConvertBuffer[mode] = true;
// Allocate necessary internal buffers
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes(stream_.userFormat);
stream_.userBuffer[mode] = (char *)calloc(bufferBytes, 1);
if (stream_.userBuffer[mode] == NULL)
{
errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if (stream_.doConvertBuffer[mode])
{
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes(stream_.deviceFormat[mode]);
if (isDuplexInput && stream_.deviceBuffer)
{
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if (bufferBytes <= bytesOut) makeBuffer = false;
}
if (makeBuffer)
{
bufferBytes *= *bufferSize;
if (stream_.deviceBuffer) free(stream_.deviceBuffer);
stream_.deviceBuffer = (char *)calloc(bufferBytes, 1);
if (stream_.deviceBuffer == NULL)
{
errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
// Determine device latencies
long inputLatency, outputLatency;
result = ASIOGetLatencies(&inputLatency, &outputLatency);
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString(result) << ") getting latency.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING); // warn but don't fail
}
else
{
stream_.latency[0] = outputLatency;
stream_.latency[1] = inputLatency;
}
// Setup the buffer conversion information structure. We don't use
// buffers to do channel offsets, so we override that parameter
// here.
if (stream_.doConvertBuffer[mode]) setConvertInfo(mode, 0);
return SUCCESS;
error:
if (!isDuplexInput)
{
// the cleanup for error in the duplex input, is done by RtApi::openStream
// So we clean up for single channel only
if (buffersAllocated)
ASIODisposeBuffers();
drivers.removeCurrentDriver();
if (handle)
{
CloseHandle(handle->condition);
if (handle->bufferInfos)
free(handle->bufferInfos);
delete handle;
stream_.apiHandle = 0;
}
if (stream_.userBuffer[mode])
{
free(stream_.userBuffer[mode]);
stream_.userBuffer[mode] = 0;
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
}
return FAILURE;
} ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RtApiAsio ::closeStream()
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
error(RtAudioError::WARNING);
return;
}
if (stream_.state == STREAM_RUNNING)
{
stream_.state = STREAM_STOPPED;
ASIOStop();
}
ASIODisposeBuffers();
drivers.removeCurrentDriver();
AsioHandle *handle = (AsioHandle *)stream_.apiHandle;
if (handle)
{
CloseHandle(handle->condition);
if (handle->bufferInfos)
free(handle->bufferInfos);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
}
bool stopThreadCalled = false;
void RtApiAsio ::startStream()
{
verifyStream();
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiAsio::startStream(): the stream is already running!";
error(RtAudioError::WARNING);
return;
}
AsioHandle *handle = (AsioHandle *)stream_.apiHandle;
ASIOError result = ASIOStart();
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString(result) << ") starting device.";
errorText_ = errorStream_.str();
goto unlock;
}
handle->drainCounter = 0;
handle->internalDrain = false;
ResetEvent(handle->condition);
stream_.state = STREAM_RUNNING;
asioXRun = false;
unlock:
stopThreadCalled = false;
if (result == ASE_OK) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiAsio ::stopStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
AsioHandle *handle = (AsioHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (handle->drainCounter == 0)
{
handle->drainCounter = 2;
WaitForSingleObject(handle->condition, INFINITE); // block until signaled
}
}
stream_.state = STREAM_STOPPED;
ASIOError result = ASIOStop();
if (result != ASE_OK)
{
errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString(result) << ") stopping device.";
errorText_ = errorStream_.str();
}
if (result == ASE_OK) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiAsio ::abortStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
// The following lines were commented-out because some behavior was
// noted where the device buffers need to be zeroed to avoid
// continuing sound, even when the device buffers are completely
// disposed. So now, calling abort is the same as calling stop.
// AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
// handle->drainCounter = 2;
stopStream();
}
// This function will be called by a spawned thread when the user
// callback function signals that the stream should be stopped or
// aborted. It is necessary to handle it this way because the
// callbackEvent() function must return before the ASIOStop()
// function will return.
static unsigned __stdcall asioStopStream(void *ptr)
{
CallbackInfo *info = (CallbackInfo *)ptr;
RtApiAsio *object = (RtApiAsio *)info->object;
object->stopStream();
_endthreadex(0);
return 0;
}
bool RtApiAsio ::callbackEvent(long bufferIndex)
{
if (stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING) return SUCCESS;
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
error(RtAudioError::WARNING);
return FAILURE;
}
CallbackInfo *info = (CallbackInfo *)&stream_.callbackInfo;
AsioHandle *handle = (AsioHandle *)stream_.apiHandle;
// Check if we were draining the stream and signal if finished.
if (handle->drainCounter > 3)
{
stream_.state = STREAM_STOPPING;
if (handle->internalDrain == false)
SetEvent(handle->condition);
else
{ // spawn a thread to stop the stream
unsigned threadId;
stream_.callbackInfo.thread = _beginthreadex(NULL, 0, &asioStopStream,
&stream_.callbackInfo, 0, &threadId);
}
return SUCCESS;
}
// Invoke user callback to get fresh output data UNLESS we are
// draining stream.
if (handle->drainCounter == 0)
{
RtAudioCallback callback = (RtAudioCallback)info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if (stream_.mode != INPUT && asioXRun == true)
{
status |= RTAUDIO_OUTPUT_UNDERFLOW;
asioXRun = false;
}
if (stream_.mode != OUTPUT && asioXRun == true)
{
status |= RTAUDIO_INPUT_OVERFLOW;
asioXRun = false;
}
int cbReturnValue = callback(stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData);
if (cbReturnValue == 2)
{
stream_.state = STREAM_STOPPING;
handle->drainCounter = 2;
unsigned threadId;
stream_.callbackInfo.thread = _beginthreadex(NULL, 0, &asioStopStream,
&stream_.callbackInfo, 0, &threadId);
return SUCCESS;
}
else if (cbReturnValue == 1)
{
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
unsigned int nChannels, bufferBytes, i, j;
nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[0]);
if (handle->drainCounter > 1)
{ // write zeros to the output stream
for (i = 0, j = 0; i < nChannels; i++)
{
if (handle->bufferInfos[i].isInput != ASIOTrue)
memset(handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes);
}
}
else if (stream_.doConvertBuffer[0])
{
convertBuffer(stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0]);
if (stream_.doByteSwap[0])
byteSwapBuffer(stream_.deviceBuffer,
stream_.bufferSize * stream_.nDeviceChannels[0],
stream_.deviceFormat[0]);
for (i = 0, j = 0; i < nChannels; i++)
{
if (handle->bufferInfos[i].isInput != ASIOTrue)
memcpy(handle->bufferInfos[i].buffers[bufferIndex],
&stream_.deviceBuffer[j++ * bufferBytes], bufferBytes);
}
}
else
{
if (stream_.doByteSwap[0])
byteSwapBuffer(stream_.userBuffer[0],
stream_.bufferSize * stream_.nUserChannels[0],
stream_.userFormat);
for (i = 0, j = 0; i < nChannels; i++)
{
if (handle->bufferInfos[i].isInput != ASIOTrue)
memcpy(handle->bufferInfos[i].buffers[bufferIndex],
&stream_.userBuffer[0][bufferBytes * j++], bufferBytes);
}
}
}
// Don't bother draining input
if (handle->drainCounter)
{
handle->drainCounter++;
goto unlock;
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
if (stream_.doConvertBuffer[1])
{
// Always interleave ASIO input data.
for (i = 0, j = 0; i < nChannels; i++)
{
if (handle->bufferInfos[i].isInput == ASIOTrue)
memcpy(&stream_.deviceBuffer[j++ * bufferBytes],
handle->bufferInfos[i].buffers[bufferIndex],
bufferBytes);
}
if (stream_.doByteSwap[1])
byteSwapBuffer(stream_.deviceBuffer,
stream_.bufferSize * stream_.nDeviceChannels[1],
stream_.deviceFormat[1]);
convertBuffer(stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1]);
}
else
{
for (i = 0, j = 0; i < nChannels; i++)
{
if (handle->bufferInfos[i].isInput == ASIOTrue)
{
memcpy(&stream_.userBuffer[1][bufferBytes * j++],
handle->bufferInfos[i].buffers[bufferIndex],
bufferBytes);
}
}
if (stream_.doByteSwap[1])
byteSwapBuffer(stream_.userBuffer[1],
stream_.bufferSize * stream_.nUserChannels[1],
stream_.userFormat);
}
}
unlock:
// The following call was suggested by Malte Clasen. While the API
// documentation indicates it should not be required, some device
// drivers apparently do not function correctly without it.
ASIOOutputReady();
RtApi::tickStreamTime();
return SUCCESS;
}
static void sampleRateChanged(ASIOSampleRate sRate)
{
// The ASIO documentation says that this usually only happens during
// external sync. Audio processing is not stopped by the driver,
// actual sample rate might not have even changed, maybe only the
// sample rate status of an AES/EBU or S/PDIF digital input at the
// audio device.
RtApi *object = (RtApi *)asioCallbackInfo->object;
try
{
object->stopStream();
}
catch (RtAudioError &exception)
{
std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n"
<< std::endl;
return;
}
std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n"
<< std::endl;
}
static long asioMessages(long selector, long value, void * /*message*/, double * /*opt*/)
{
long ret = 0;
switch (selector)
{
case kAsioSelectorSupported:
if (value == kAsioResetRequest || value == kAsioEngineVersion || value == kAsioResyncRequest || value == kAsioLatenciesChanged
// The following three were added for ASIO 2.0, you don't
// necessarily have to support them.
|| value == kAsioSupportsTimeInfo || value == kAsioSupportsTimeCode || value == kAsioSupportsInputMonitor)
ret = 1L;
break;
case kAsioResetRequest:
// Defer the task and perform the reset of the driver during the
// next "safe" situation. You cannot reset the driver right now,
// as this code is called from the driver. Reset the driver is
// done by completely destruct is. I.e. ASIOStop(),
// ASIODisposeBuffers(), Destruction Afterwards you initialize the
// driver again.
std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
ret = 1L;
break;
case kAsioResyncRequest:
// This informs the application that the driver encountered some
// non-fatal data loss. It is used for synchronization purposes
// of different media. Added mainly to work around the Win16Mutex
// problems in Windows 95/98 with the Windows Multimedia system,
// which could lose data because the Mutex was held too long by
// another thread. However a driver can issue it in other
// situations, too.
// std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
asioXRun = true;
ret = 1L;
break;
case kAsioLatenciesChanged:
// This will inform the host application that the drivers were
// latencies changed. Beware, it this does not mean that the
// buffer sizes have changed! You might need to update internal
// delay data.
std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
ret = 1L;
break;
case kAsioEngineVersion:
// Return the supported ASIO version of the host application. If
// a host application does not implement this selector, ASIO 1.0
// is assumed by the driver.
ret = 2L;
break;
case kAsioSupportsTimeInfo:
// Informs the driver whether the
// asioCallbacks.bufferSwitchTimeInfo() callback is supported.
// For compatibility with ASIO 1.0 drivers the host application
// should always support the "old" bufferSwitch method, too.
ret = 0;
break;
case kAsioSupportsTimeCode:
// Informs the driver whether application is interested in time
// code info. If an application does not need to know about time
// code, the driver has less work to do.
ret = 0;
break;
}
return ret;
}
static const char *getAsioErrorString(ASIOError result)
{
struct Messages
{
ASIOError value;
const char *message;
};
static const Messages m[] =
{
{ASE_NotPresent, "Hardware input or output is not present or available."},
{ASE_HWMalfunction, "Hardware is malfunctioning."},
{ASE_InvalidParameter, "Invalid input parameter."},
{ASE_InvalidMode, "Invalid mode."},
{ASE_SPNotAdvancing, "Sample position not advancing."},
{ASE_NoClock, "Sample clock or rate cannot be determined or is not present."},
{ASE_NoMemory, "Not enough memory to complete the request."}};
for (unsigned int i = 0; i < sizeof(m) / sizeof(m[0]); ++i)
if (m[i].value == result) return m[i].message;
return "Unknown error.";
}
//******************** End of __WINDOWS_ASIO__ *********************//
#endif
#if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
// Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014
// - Introduces support for the Windows WASAPI API
// - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required
// - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface
// - Includes automatic internal conversion of sample rate and buffer size between hardware and the user
#ifndef INITGUID
#define INITGUID
#endif
#include <audioclient.h>
#include <avrt.h>
#include <mmdeviceapi.h>
#include <functiondiscoverykeys_devpkey.h>
//=============================================================================
#define SAFE_RELEASE(objectPtr) \
if (objectPtr) \
{ \
objectPtr->Release(); \
objectPtr = NULL; \
}
typedef HANDLE(__stdcall *TAvSetMmThreadCharacteristicsPtr)(LPCWSTR TaskName, LPDWORD TaskIndex);
//-----------------------------------------------------------------------------
// WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
// Therefore we must perform all necessary conversions to user buffers in order to satisfy these
// requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
// provide intermediate storage for read / write synchronization.
class WasapiBuffer
{
public:
WasapiBuffer()
: buffer_(NULL),
bufferSize_(0),
inIndex_(0),
outIndex_(0) {}
~WasapiBuffer()
{
free(buffer_);
}
// sets the length of the internal ring buffer
void setBufferSize(unsigned int bufferSize, unsigned int formatBytes)
{
free(buffer_);
buffer_ = (char *)calloc(bufferSize, formatBytes);
bufferSize_ = bufferSize;
inIndex_ = 0;
outIndex_ = 0;
}
// attempt to push a buffer into the ring buffer at the current "in" index
bool pushBuffer(char *buffer, unsigned int bufferSize, RtAudioFormat format)
{
if (!buffer || // incoming buffer is NULL
bufferSize == 0 || // incoming buffer has no data
bufferSize > bufferSize_) // incoming buffer too large
{
return false;
}
unsigned int relOutIndex = outIndex_;
unsigned int inIndexEnd = inIndex_ + bufferSize;
if (relOutIndex < inIndex_ && inIndexEnd >= bufferSize_)
{
relOutIndex += bufferSize_;
}
// "in" index can end on the "out" index but cannot begin at it
if (inIndex_ <= relOutIndex && inIndexEnd > relOutIndex)
{
return false; // not enough space between "in" index and "out" index
}
// copy buffer from external to internal
int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
int fromInSize = bufferSize - fromZeroSize;
switch (format)
{
case RTAUDIO_SINT8:
memcpy(&((char *)buffer_)[inIndex_], buffer, fromInSize * sizeof(char));
memcpy(buffer_, &((char *)buffer)[fromInSize], fromZeroSize * sizeof(char));
break;
case RTAUDIO_SINT16:
memcpy(&((short *)buffer_)[inIndex_], buffer, fromInSize * sizeof(short));
memcpy(buffer_, &((short *)buffer)[fromInSize], fromZeroSize * sizeof(short));
break;
case RTAUDIO_SINT24:
memcpy(&((S24 *)buffer_)[inIndex_], buffer, fromInSize * sizeof(S24));
memcpy(buffer_, &((S24 *)buffer)[fromInSize], fromZeroSize * sizeof(S24));
break;
case RTAUDIO_SINT32:
memcpy(&((int *)buffer_)[inIndex_], buffer, fromInSize * sizeof(int));
memcpy(buffer_, &((int *)buffer)[fromInSize], fromZeroSize * sizeof(int));
break;
case RTAUDIO_FLOAT32:
memcpy(&((float *)buffer_)[inIndex_], buffer, fromInSize * sizeof(float));
memcpy(buffer_, &((float *)buffer)[fromInSize], fromZeroSize * sizeof(float));
break;
case RTAUDIO_FLOAT64:
memcpy(&((double *)buffer_)[inIndex_], buffer, fromInSize * sizeof(double));
memcpy(buffer_, &((double *)buffer)[fromInSize], fromZeroSize * sizeof(double));
break;
}
// update "in" index
inIndex_ += bufferSize;
inIndex_ %= bufferSize_;
return true;
}
// attempt to pull a buffer from the ring buffer from the current "out" index
bool pullBuffer(char *buffer, unsigned int bufferSize, RtAudioFormat format)
{
if (!buffer || // incoming buffer is NULL
bufferSize == 0 || // incoming buffer has no data
bufferSize > bufferSize_) // incoming buffer too large
{
return false;
}
unsigned int relInIndex = inIndex_;
unsigned int outIndexEnd = outIndex_ + bufferSize;
if (relInIndex < outIndex_ && outIndexEnd >= bufferSize_)
{
relInIndex += bufferSize_;
}
// "out" index can begin at and end on the "in" index
if (outIndex_ < relInIndex && outIndexEnd > relInIndex)
{
return false; // not enough space between "out" index and "in" index
}
// copy buffer from internal to external
int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
int fromOutSize = bufferSize - fromZeroSize;
switch (format)
{
case RTAUDIO_SINT8:
memcpy(buffer, &((char *)buffer_)[outIndex_], fromOutSize * sizeof(char));
memcpy(&((char *)buffer)[fromOutSize], buffer_, fromZeroSize * sizeof(char));
break;
case RTAUDIO_SINT16:
memcpy(buffer, &((short *)buffer_)[outIndex_], fromOutSize * sizeof(short));
memcpy(&((short *)buffer)[fromOutSize], buffer_, fromZeroSize * sizeof(short));
break;
case RTAUDIO_SINT24:
memcpy(buffer, &((S24 *)buffer_)[outIndex_], fromOutSize * sizeof(S24));
memcpy(&((S24 *)buffer)[fromOutSize], buffer_, fromZeroSize * sizeof(S24));
break;
case RTAUDIO_SINT32:
memcpy(buffer, &((int *)buffer_)[outIndex_], fromOutSize * sizeof(int));
memcpy(&((int *)buffer)[fromOutSize], buffer_, fromZeroSize * sizeof(int));
break;
case RTAUDIO_FLOAT32:
memcpy(buffer, &((float *)buffer_)[outIndex_], fromOutSize * sizeof(float));
memcpy(&((float *)buffer)[fromOutSize], buffer_, fromZeroSize * sizeof(float));
break;
case RTAUDIO_FLOAT64:
memcpy(buffer, &((double *)buffer_)[outIndex_], fromOutSize * sizeof(double));
memcpy(&((double *)buffer)[fromOutSize], buffer_, fromZeroSize * sizeof(double));
break;
}
// update "out" index
outIndex_ += bufferSize;
outIndex_ %= bufferSize_;
return true;
}
private:
char *buffer_;
unsigned int bufferSize_;
unsigned int inIndex_;
unsigned int outIndex_;
};
//-----------------------------------------------------------------------------
// In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate
// between HW and the user. The convertBufferWasapi function is used to perform this conversion
// between HwIn->UserIn and UserOut->HwOut during the stream callback loop.
// This sample rate converter favors speed over quality, and works best with conversions between
// one rate and its multiple.
void convertBufferWasapi(char *outBuffer,
const char *inBuffer,
const unsigned int &channelCount,
const unsigned int &inSampleRate,
const unsigned int &outSampleRate,
const unsigned int &inSampleCount,
unsigned int &outSampleCount,
const RtAudioFormat &format)
{
// calculate the new outSampleCount and relative sampleStep
float sampleRatio = (float)outSampleRate / inSampleRate;
float sampleStep = 1.0f / sampleRatio;
float inSampleFraction = 0.0f;
outSampleCount = (unsigned int)roundf(inSampleCount * sampleRatio);
// frame-by-frame, copy each relative input sample into it's corresponding output sample
for (unsigned int outSample = 0; outSample < outSampleCount; outSample++)
{
unsigned int inSample = (unsigned int)inSampleFraction;
switch (format)
{
case RTAUDIO_SINT8:
memcpy(&((char *)outBuffer)[outSample * channelCount], &((char *)inBuffer)[inSample * channelCount], channelCount * sizeof(char));
break;
case RTAUDIO_SINT16:
memcpy(&((short *)outBuffer)[outSample * channelCount], &((short *)inBuffer)[inSample * channelCount], channelCount * sizeof(short));
break;
case RTAUDIO_SINT24:
memcpy(&((S24 *)outBuffer)[outSample * channelCount], &((S24 *)inBuffer)[inSample * channelCount], channelCount * sizeof(S24));
break;
case RTAUDIO_SINT32:
memcpy(&((int *)outBuffer)[outSample * channelCount], &((int *)inBuffer)[inSample * channelCount], channelCount * sizeof(int));
break;
case RTAUDIO_FLOAT32:
memcpy(&((float *)outBuffer)[outSample * channelCount], &((float *)inBuffer)[inSample * channelCount], channelCount * sizeof(float));
break;
case RTAUDIO_FLOAT64:
memcpy(&((double *)outBuffer)[outSample * channelCount], &((double *)inBuffer)[inSample * channelCount], channelCount * sizeof(double));
break;
}
// jump to next in sample
inSampleFraction += sampleStep;
}
}
//-----------------------------------------------------------------------------
// A structure to hold various information related to the WASAPI implementation.
struct WasapiHandle
{
IAudioClient *captureAudioClient;
IAudioClient *renderAudioClient;
IAudioCaptureClient *captureClient;
IAudioRenderClient *renderClient;
HANDLE captureEvent;
HANDLE renderEvent;
WasapiHandle()
: captureAudioClient(NULL),
renderAudioClient(NULL),
captureClient(NULL),
renderClient(NULL),
captureEvent(NULL),
renderEvent(NULL) {}
};
//=============================================================================
RtApiWasapi::RtApiWasapi()
: coInitialized_(false), deviceEnumerator_(NULL)
{
// WASAPI can run either apartment or multi-threaded
HRESULT hr = CoInitialize(NULL);
if (!FAILED(hr))
coInitialized_ = true;
// Instantiate device enumerator
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL,
CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
(void **)&deviceEnumerator_);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::RtApiWasapi: Unable to instantiate device enumerator";
error(RtAudioError::DRIVER_ERROR);
}
}
//-----------------------------------------------------------------------------
RtApiWasapi::~RtApiWasapi()
{
if (stream_.state != STREAM_CLOSED)
closeStream();
SAFE_RELEASE(deviceEnumerator_);
// If this object previously called CoInitialize()
if (coInitialized_)
CoUninitialize();
}
//=============================================================================
unsigned int RtApiWasapi::getDeviceCount(void)
{
unsigned int captureDeviceCount = 0;
unsigned int renderDeviceCount = 0;
IMMDeviceCollection *captureDevices = NULL;
IMMDeviceCollection *renderDevices = NULL;
// Count capture devices
errorText_.clear();
HRESULT hr = deviceEnumerator_->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &captureDevices);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
goto Exit;
}
hr = captureDevices->GetCount(&captureDeviceCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
goto Exit;
}
// Count render devices
hr = deviceEnumerator_->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &renderDevices);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
goto Exit;
}
hr = renderDevices->GetCount(&renderDeviceCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
goto Exit;
}
Exit:
// release all references
SAFE_RELEASE(captureDevices);
SAFE_RELEASE(renderDevices);
if (errorText_.empty())
return captureDeviceCount + renderDeviceCount;
error(RtAudioError::DRIVER_ERROR);
return 0;
}
//-----------------------------------------------------------------------------
RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo(unsigned int device)
{
RtAudio::DeviceInfo info;
unsigned int captureDeviceCount = 0;
unsigned int renderDeviceCount = 0;
std::string defaultDeviceName;
bool isCaptureDevice = false;
PROPVARIANT deviceNameProp;
PROPVARIANT defaultDeviceNameProp;
IMMDeviceCollection *captureDevices = NULL;
IMMDeviceCollection *renderDevices = NULL;
IMMDevice *devicePtr = NULL;
IMMDevice *defaultDevicePtr = NULL;
IAudioClient *audioClient = NULL;
IPropertyStore *devicePropStore = NULL;
IPropertyStore *defaultDevicePropStore = NULL;
WAVEFORMATEX *deviceFormat = NULL;
WAVEFORMATEX *closestMatchFormat = NULL;
// probed
info.probed = false;
// Count capture devices
errorText_.clear();
RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
HRESULT hr = deviceEnumerator_->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &captureDevices);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
goto Exit;
}
hr = captureDevices->GetCount(&captureDeviceCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
goto Exit;
}
// Count render devices
hr = deviceEnumerator_->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &renderDevices);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
goto Exit;
}
hr = renderDevices->GetCount(&renderDeviceCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
goto Exit;
}
// validate device index
if (device >= captureDeviceCount + renderDeviceCount)
{
errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
errorType = RtAudioError::INVALID_USE;
goto Exit;
}
// determine whether index falls within capture or render devices
if (device >= renderDeviceCount)
{
hr = captureDevices->Item(device - renderDeviceCount, &devicePtr);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
goto Exit;
}
isCaptureDevice = true;
}
else
{
hr = renderDevices->Item(device, &devicePtr);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
goto Exit;
}
isCaptureDevice = false;
}
// get default device name
if (isCaptureDevice)
{
hr = deviceEnumerator_->GetDefaultAudioEndpoint(eCapture, eConsole, &defaultDevicePtr);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
goto Exit;
}
}
else
{
hr = deviceEnumerator_->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevicePtr);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
goto Exit;
}
}
hr = defaultDevicePtr->OpenPropertyStore(STGM_READ, &defaultDevicePropStore);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
goto Exit;
}
PropVariantInit(&defaultDeviceNameProp);
hr = defaultDevicePropStore->GetValue(PKEY_Device_FriendlyName, &defaultDeviceNameProp);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
goto Exit;
}
defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);
// name
hr = devicePtr->OpenPropertyStore(STGM_READ, &devicePropStore);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
goto Exit;
}
PropVariantInit(&deviceNameProp);
hr = devicePropStore->GetValue(PKEY_Device_FriendlyName, &deviceNameProp);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
goto Exit;
}
info.name = convertCharPointerToStdString(deviceNameProp.pwszVal);
// is default
if (isCaptureDevice)
{
info.isDefaultInput = info.name == defaultDeviceName;
info.isDefaultOutput = false;
}
else
{
info.isDefaultInput = false;
info.isDefaultOutput = info.name == defaultDeviceName;
}
// channel count
hr = devicePtr->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void **)&audioClient);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
goto Exit;
}
hr = audioClient->GetMixFormat(&deviceFormat);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
goto Exit;
}
if (isCaptureDevice)
{
info.inputChannels = deviceFormat->nChannels;
info.outputChannels = 0;
info.duplexChannels = 0;
}
else
{
info.inputChannels = 0;
info.outputChannels = deviceFormat->nChannels;
info.duplexChannels = 0;
}
// sample rates
info.sampleRates.clear();
// allow support for all sample rates as we have a built-in sample rate converter
for (unsigned int i = 0; i < MAX_SAMPLE_RATES; i++)
{
info.sampleRates.push_back(SAMPLE_RATES[i]);
}
info.preferredSampleRate = deviceFormat->nSamplesPerSec;
// native format
info.nativeFormats = 0;
if (deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
(deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
((WAVEFORMATEXTENSIBLE *)deviceFormat)->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
{
if (deviceFormat->wBitsPerSample == 32)
{
info.nativeFormats |= RTAUDIO_FLOAT32;
}
else if (deviceFormat->wBitsPerSample == 64)
{
info.nativeFormats |= RTAUDIO_FLOAT64;
}
}
else if (deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
(deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
((WAVEFORMATEXTENSIBLE *)deviceFormat)->SubFormat == KSDATAFORMAT_SUBTYPE_PCM))
{
if (deviceFormat->wBitsPerSample == 8)
{
info.nativeFormats |= RTAUDIO_SINT8;
}
else if (deviceFormat->wBitsPerSample == 16)
{
info.nativeFormats |= RTAUDIO_SINT16;
}
else if (deviceFormat->wBitsPerSample == 24)
{
info.nativeFormats |= RTAUDIO_SINT24;
}
else if (deviceFormat->wBitsPerSample == 32)
{
info.nativeFormats |= RTAUDIO_SINT32;
}
}
// probed
info.probed = true;
Exit:
// release all references
PropVariantClear(&deviceNameProp);
PropVariantClear(&defaultDeviceNameProp);
SAFE_RELEASE(captureDevices);
SAFE_RELEASE(renderDevices);
SAFE_RELEASE(devicePtr);
SAFE_RELEASE(defaultDevicePtr);
SAFE_RELEASE(audioClient);
SAFE_RELEASE(devicePropStore);
SAFE_RELEASE(defaultDevicePropStore);
CoTaskMemFree(deviceFormat);
CoTaskMemFree(closestMatchFormat);
if (!errorText_.empty())
error(errorType);
return info;
}
//-----------------------------------------------------------------------------
unsigned int RtApiWasapi::getDefaultOutputDevice(void)
{
for (unsigned int i = 0; i < getDeviceCount(); i++)
{
if (getDeviceInfo(i).isDefaultOutput)
{
return i;
}
}
return 0;
}
//-----------------------------------------------------------------------------
unsigned int RtApiWasapi::getDefaultInputDevice(void)
{
for (unsigned int i = 0; i < getDeviceCount(); i++)
{
if (getDeviceInfo(i).isDefaultInput)
{
return i;
}
}
return 0;
}
//-----------------------------------------------------------------------------
void RtApiWasapi::closeStream(void)
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
error(RtAudioError::WARNING);
return;
}
if (stream_.state != STREAM_STOPPED)
stopStream();
// clean up stream memory
SAFE_RELEASE(((WasapiHandle *)stream_.apiHandle)->captureAudioClient)
SAFE_RELEASE(((WasapiHandle *)stream_.apiHandle)->renderAudioClient)
SAFE_RELEASE(((WasapiHandle *)stream_.apiHandle)->captureClient)
SAFE_RELEASE(((WasapiHandle *)stream_.apiHandle)->renderClient)
if (((WasapiHandle *)stream_.apiHandle)->captureEvent)
CloseHandle(((WasapiHandle *)stream_.apiHandle)->captureEvent);
if (((WasapiHandle *)stream_.apiHandle)->renderEvent)
CloseHandle(((WasapiHandle *)stream_.apiHandle)->renderEvent);
delete (WasapiHandle *)stream_.apiHandle;
stream_.apiHandle = NULL;
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
// update stream state
stream_.state = STREAM_CLOSED;
}
//-----------------------------------------------------------------------------
void RtApiWasapi::startStream(void)
{
verifyStream();
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiWasapi::startStream: The stream is already running.";
error(RtAudioError::WARNING);
return;
}
// update stream state
stream_.state = STREAM_RUNNING;
// create WASAPI stream thread
stream_.callbackInfo.thread = (ThreadHandle)CreateThread(NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL);
if (!stream_.callbackInfo.thread)
{
errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
error(RtAudioError::THREAD_ERROR);
}
else
{
SetThreadPriority((void *)stream_.callbackInfo.thread, stream_.callbackInfo.priority);
ResumeThread((void *)stream_.callbackInfo.thread);
}
}
//-----------------------------------------------------------------------------
void RtApiWasapi::stopStream(void)
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
error(RtAudioError::WARNING);
return;
}
// inform stream thread by setting stream state to STREAM_STOPPING
stream_.state = STREAM_STOPPING;
// wait until stream thread is stopped
while (stream_.state != STREAM_STOPPED)
{
Sleep(1);
}
// Wait for the last buffer to play before stopping.
Sleep(1000 * stream_.bufferSize / stream_.sampleRate);
// stop capture client if applicable
if (((WasapiHandle *)stream_.apiHandle)->captureAudioClient)
{
HRESULT hr = ((WasapiHandle *)stream_.apiHandle)->captureAudioClient->Stop();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::stopStream: Unable to stop capture stream.";
error(RtAudioError::DRIVER_ERROR);
return;
}
}
// stop render client if applicable
if (((WasapiHandle *)stream_.apiHandle)->renderAudioClient)
{
HRESULT hr = ((WasapiHandle *)stream_.apiHandle)->renderAudioClient->Stop();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::stopStream: Unable to stop render stream.";
error(RtAudioError::DRIVER_ERROR);
return;
}
}
// close thread handle
if (stream_.callbackInfo.thread && !CloseHandle((void *)stream_.callbackInfo.thread))
{
errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
error(RtAudioError::THREAD_ERROR);
return;
}
stream_.callbackInfo.thread = (ThreadHandle)NULL;
}
//-----------------------------------------------------------------------------
void RtApiWasapi::abortStream(void)
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
error(RtAudioError::WARNING);
return;
}
// inform stream thread by setting stream state to STREAM_STOPPING
stream_.state = STREAM_STOPPING;
// wait until stream thread is stopped
while (stream_.state != STREAM_STOPPED)
{
Sleep(1);
}
// stop capture client if applicable
if (((WasapiHandle *)stream_.apiHandle)->captureAudioClient)
{
HRESULT hr = ((WasapiHandle *)stream_.apiHandle)->captureAudioClient->Stop();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::abortStream: Unable to stop capture stream.";
error(RtAudioError::DRIVER_ERROR);
return;
}
}
// stop render client if applicable
if (((WasapiHandle *)stream_.apiHandle)->renderAudioClient)
{
HRESULT hr = ((WasapiHandle *)stream_.apiHandle)->renderAudioClient->Stop();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::abortStream: Unable to stop render stream.";
error(RtAudioError::DRIVER_ERROR);
return;
}
}
// close thread handle
if (stream_.callbackInfo.thread && !CloseHandle((void *)stream_.callbackInfo.thread))
{
errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
error(RtAudioError::THREAD_ERROR);
return;
}
stream_.callbackInfo.thread = (ThreadHandle)NULL;
}
//-----------------------------------------------------------------------------
bool RtApiWasapi::probeDeviceOpen(unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options)
{
bool methodResult = FAILURE;
unsigned int captureDeviceCount = 0;
unsigned int renderDeviceCount = 0;
IMMDeviceCollection *captureDevices = NULL;
IMMDeviceCollection *renderDevices = NULL;
IMMDevice *devicePtr = NULL;
WAVEFORMATEX *deviceFormat = NULL;
unsigned int bufferBytes;
stream_.state = STREAM_STOPPED;
// create API Handle if not already created
if (!stream_.apiHandle)
stream_.apiHandle = (void *)new WasapiHandle();
// Count capture devices
errorText_.clear();
RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
HRESULT hr = deviceEnumerator_->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &captureDevices);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
goto Exit;
}
hr = captureDevices->GetCount(&captureDeviceCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
goto Exit;
}
// Count render devices
hr = deviceEnumerator_->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &renderDevices);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
goto Exit;
}
hr = renderDevices->GetCount(&renderDeviceCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
goto Exit;
}
// validate device index
if (device >= captureDeviceCount + renderDeviceCount)
{
errorType = RtAudioError::INVALID_USE;
errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
goto Exit;
}
// determine whether index falls within capture or render devices
if (device >= renderDeviceCount)
{
if (mode != INPUT)
{
errorType = RtAudioError::INVALID_USE;
errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
goto Exit;
}
// retrieve captureAudioClient from devicePtr
IAudioClient *&captureAudioClient = ((WasapiHandle *)stream_.apiHandle)->captureAudioClient;
hr = captureDevices->Item(device - renderDeviceCount, &devicePtr);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
goto Exit;
}
hr = devicePtr->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
NULL, (void **)&captureAudioClient);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
goto Exit;
}
hr = captureAudioClient->GetMixFormat(&deviceFormat);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
goto Exit;
}
stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
captureAudioClient->GetStreamLatency((long long *)&stream_.latency[mode]);
}
else
{
if (mode != OUTPUT)
{
errorType = RtAudioError::INVALID_USE;
errorText_ = "RtApiWasapi::probeDeviceOpen: Render device selected as input device.";
goto Exit;
}
// retrieve renderAudioClient from devicePtr
IAudioClient *&renderAudioClient = ((WasapiHandle *)stream_.apiHandle)->renderAudioClient;
hr = renderDevices->Item(device, &devicePtr);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
goto Exit;
}
hr = devicePtr->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
NULL, (void **)&renderAudioClient);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
goto Exit;
}
hr = renderAudioClient->GetMixFormat(&deviceFormat);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
goto Exit;
}
stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
renderAudioClient->GetStreamLatency((long long *)&stream_.latency[mode]);
}
// fill stream data
if ((stream_.mode == OUTPUT && mode == INPUT) ||
(stream_.mode == INPUT && mode == OUTPUT))
{
stream_.mode = DUPLEX;
}
else
{
stream_.mode = mode;
}
stream_.device[mode] = device;
stream_.doByteSwap[mode] = false;
stream_.sampleRate = sampleRate;
stream_.bufferSize = *bufferSize;
stream_.nBuffers = 1;
stream_.nUserChannels[mode] = channels;
stream_.channelOffset[mode] = firstChannel;
stream_.userFormat = format;
stream_.deviceFormat[mode] = getDeviceInfo(device).nativeFormats;
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
stream_.userInterleaved = false;
else
stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if (stream_.userFormat != stream_.deviceFormat[mode] ||
stream_.nUserChannels != stream_.nDeviceChannels)
stream_.doConvertBuffer[mode] = true;
else if (stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1)
stream_.doConvertBuffer[mode] = true;
if (stream_.doConvertBuffer[mode])
setConvertInfo(mode, 0);
// Allocate necessary internal buffers
bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes(stream_.userFormat);
stream_.userBuffer[mode] = (char *)calloc(bufferBytes, 1);
if (!stream_.userBuffer[mode])
{
errorType = RtAudioError::MEMORY_ERROR;
errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
goto Exit;
}
if (options && options->flags & RTAUDIO_SCHEDULE_REALTIME)
stream_.callbackInfo.priority = 15;
else
stream_.callbackInfo.priority = 0;
///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
methodResult = SUCCESS;
Exit:
//clean up
SAFE_RELEASE(captureDevices);
SAFE_RELEASE(renderDevices);
SAFE_RELEASE(devicePtr);
CoTaskMemFree(deviceFormat);
// if method failed, close the stream
if (methodResult == FAILURE)
closeStream();
if (!errorText_.empty())
error(errorType);
return methodResult;
}
//=============================================================================
DWORD WINAPI RtApiWasapi::runWasapiThread(void *wasapiPtr)
{
if (wasapiPtr)
((RtApiWasapi *)wasapiPtr)->wasapiThread();
return 0;
}
DWORD WINAPI RtApiWasapi::stopWasapiThread(void *wasapiPtr)
{
if (wasapiPtr)
((RtApiWasapi *)wasapiPtr)->stopStream();
return 0;
}
DWORD WINAPI RtApiWasapi::abortWasapiThread(void *wasapiPtr)
{
if (wasapiPtr)
((RtApiWasapi *)wasapiPtr)->abortStream();
return 0;
}
//-----------------------------------------------------------------------------
void RtApiWasapi::wasapiThread()
{
// as this is a new thread, we must CoInitialize it
CoInitialize(NULL);
HRESULT hr;
IAudioClient *captureAudioClient = ((WasapiHandle *)stream_.apiHandle)->captureAudioClient;
IAudioClient *renderAudioClient = ((WasapiHandle *)stream_.apiHandle)->renderAudioClient;
IAudioCaptureClient *captureClient = ((WasapiHandle *)stream_.apiHandle)->captureClient;
IAudioRenderClient *renderClient = ((WasapiHandle *)stream_.apiHandle)->renderClient;
HANDLE captureEvent = ((WasapiHandle *)stream_.apiHandle)->captureEvent;
HANDLE renderEvent = ((WasapiHandle *)stream_.apiHandle)->renderEvent;
WAVEFORMATEX *captureFormat = NULL;
WAVEFORMATEX *renderFormat = NULL;
float captureSrRatio = 0.0f;
float renderSrRatio = 0.0f;
WasapiBuffer captureBuffer;
WasapiBuffer renderBuffer;
// declare local stream variables
RtAudioCallback callback = (RtAudioCallback)stream_.callbackInfo.callback;
BYTE *streamBuffer = NULL;
unsigned long captureFlags = 0;
unsigned int bufferFrameCount = 0;
unsigned int numFramesPadding = 0;
unsigned int convBufferSize = 0;
bool callbackPushed = false;
bool callbackPulled = false;
bool callbackStopped = false;
int callbackResult = 0;
// convBuffer is used to store converted buffers between WASAPI and the user
char *convBuffer = NULL;
unsigned int convBuffSize = 0;
unsigned int deviceBuffSize = 0;
errorText_.clear();
RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
// Attempt to assign "Pro Audio" characteristic to thread
HMODULE AvrtDll = LoadLibrary((LPCTSTR) "AVRT.dll");
if (AvrtDll)
{
DWORD taskIndex = 0;
TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = (TAvSetMmThreadCharacteristicsPtr)GetProcAddress(AvrtDll, "AvSetMmThreadCharacteristicsW");
AvSetMmThreadCharacteristicsPtr(L"Pro Audio", &taskIndex);
FreeLibrary(AvrtDll);
}
// start capture stream if applicable
if (captureAudioClient)
{
hr = captureAudioClient->GetMixFormat(&captureFormat);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
goto Exit;
}
captureSrRatio = ((float)captureFormat->nSamplesPerSec / stream_.sampleRate);
// initialize capture stream according to desire buffer size
float desiredBufferSize = stream_.bufferSize * captureSrRatio;
REFERENCE_TIME desiredBufferPeriod = (REFERENCE_TIME)((float)desiredBufferSize * 10000000 / captureFormat->nSamplesPerSec);
if (!captureClient)
{
hr = captureAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
desiredBufferPeriod,
desiredBufferPeriod,
captureFormat,
NULL);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
goto Exit;
}
hr = captureAudioClient->GetService(__uuidof(IAudioCaptureClient),
(void **)&captureClient);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
goto Exit;
}
// configure captureEvent to trigger on every available capture buffer
captureEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!captureEvent)
{
errorType = RtAudioError::SYSTEM_ERROR;
errorText_ = "RtApiWasapi::wasapiThread: Unable to create capture event.";
goto Exit;
}
hr = captureAudioClient->SetEventHandle(captureEvent);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
goto Exit;
}
((WasapiHandle *)stream_.apiHandle)->captureClient = captureClient;
((WasapiHandle *)stream_.apiHandle)->captureEvent = captureEvent;
}
unsigned int inBufferSize = 0;
hr = captureAudioClient->GetBufferSize(&inBufferSize);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
goto Exit;
}
// scale outBufferSize according to stream->user sample rate ratio
unsigned int outBufferSize = (unsigned int)(stream_.bufferSize * captureSrRatio) * stream_.nDeviceChannels[INPUT];
inBufferSize *= stream_.nDeviceChannels[INPUT];
// set captureBuffer size
captureBuffer.setBufferSize(inBufferSize + outBufferSize, formatBytes(stream_.deviceFormat[INPUT]));
// reset the capture stream
hr = captureAudioClient->Reset();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
goto Exit;
}
// start the capture stream
hr = captureAudioClient->Start();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
goto Exit;
}
}
// start render stream if applicable
if (renderAudioClient)
{
hr = renderAudioClient->GetMixFormat(&renderFormat);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
goto Exit;
}
renderSrRatio = ((float)renderFormat->nSamplesPerSec / stream_.sampleRate);
// initialize render stream according to desire buffer size
float desiredBufferSize = stream_.bufferSize * renderSrRatio;
REFERENCE_TIME desiredBufferPeriod = (REFERENCE_TIME)((float)desiredBufferSize * 10000000 / renderFormat->nSamplesPerSec);
if (!renderClient)
{
hr = renderAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
desiredBufferPeriod,
desiredBufferPeriod,
renderFormat,
NULL);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
goto Exit;
}
hr = renderAudioClient->GetService(__uuidof(IAudioRenderClient),
(void **)&renderClient);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
goto Exit;
}
// configure renderEvent to trigger on every available render buffer
renderEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!renderEvent)
{
errorType = RtAudioError::SYSTEM_ERROR;
errorText_ = "RtApiWasapi::wasapiThread: Unable to create render event.";
goto Exit;
}
hr = renderAudioClient->SetEventHandle(renderEvent);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
goto Exit;
}
((WasapiHandle *)stream_.apiHandle)->renderClient = renderClient;
((WasapiHandle *)stream_.apiHandle)->renderEvent = renderEvent;
}
unsigned int outBufferSize = 0;
hr = renderAudioClient->GetBufferSize(&outBufferSize);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
goto Exit;
}
// scale inBufferSize according to user->stream sample rate ratio
unsigned int inBufferSize = (unsigned int)(stream_.bufferSize * renderSrRatio) * stream_.nDeviceChannels[OUTPUT];
outBufferSize *= stream_.nDeviceChannels[OUTPUT];
// set renderBuffer size
renderBuffer.setBufferSize(inBufferSize + outBufferSize, formatBytes(stream_.deviceFormat[OUTPUT]));
// reset the render stream
hr = renderAudioClient->Reset();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
goto Exit;
}
// start the render stream
hr = renderAudioClient->Start();
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to start render stream.";
goto Exit;
}
}
if (stream_.mode == INPUT)
{
convBuffSize = (size_t)(stream_.bufferSize * captureSrRatio) * stream_.nDeviceChannels[INPUT] * formatBytes(stream_.deviceFormat[INPUT]);
deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes(stream_.deviceFormat[INPUT]);
}
else if (stream_.mode == OUTPUT)
{
convBuffSize = (size_t)(stream_.bufferSize * renderSrRatio) * stream_.nDeviceChannels[OUTPUT] * formatBytes(stream_.deviceFormat[OUTPUT]);
deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes(stream_.deviceFormat[OUTPUT]);
}
else if (stream_.mode == DUPLEX)
{
convBuffSize = std::max((size_t)(stream_.bufferSize * captureSrRatio) * stream_.nDeviceChannels[INPUT] * formatBytes(stream_.deviceFormat[INPUT]),
(size_t)(stream_.bufferSize * renderSrRatio) * stream_.nDeviceChannels[OUTPUT] * formatBytes(stream_.deviceFormat[OUTPUT]));
deviceBuffSize = std::max(stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes(stream_.deviceFormat[INPUT]),
stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes(stream_.deviceFormat[OUTPUT]));
}
convBuffer = (char *)malloc(convBuffSize);
stream_.deviceBuffer = (char *)malloc(deviceBuffSize);
if (!convBuffer || !stream_.deviceBuffer)
{
errorType = RtAudioError::MEMORY_ERROR;
errorText_ = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
goto Exit;
}
// stream process loop
while (stream_.state != STREAM_STOPPING)
{
if (!callbackPulled)
{
// Callback Input
// ==============
// 1. Pull callback buffer from inputBuffer
// 2. If 1. was successful: Convert callback buffer to user sample rate and channel count
// Convert callback buffer to user format
if (captureAudioClient)
{
// Pull callback buffer from inputBuffer
callbackPulled = captureBuffer.pullBuffer(convBuffer,
(unsigned int)(stream_.bufferSize * captureSrRatio) * stream_.nDeviceChannels[INPUT],
stream_.deviceFormat[INPUT]);
if (callbackPulled)
{
// Convert callback buffer to user sample rate
convertBufferWasapi(stream_.deviceBuffer,
convBuffer,
stream_.nDeviceChannels[INPUT],
captureFormat->nSamplesPerSec,
stream_.sampleRate,
(unsigned int)(stream_.bufferSize * captureSrRatio),
convBufferSize,
stream_.deviceFormat[INPUT]);
if (stream_.doConvertBuffer[INPUT])
{
// Convert callback buffer to user format
convertBuffer(stream_.userBuffer[INPUT],
stream_.deviceBuffer,
stream_.convertInfo[INPUT]);
}
else
{
// no further conversion, simple copy deviceBuffer to userBuffer
memcpy(stream_.userBuffer[INPUT],
stream_.deviceBuffer,
stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes(stream_.userFormat));
}
}
}
else
{
// if there is no capture stream, set callbackPulled flag
callbackPulled = true;
}
// Execute Callback
// ================
// 1. Execute user callback method
// 2. Handle return value from callback
// if callback has not requested the stream to stop
if (callbackPulled && !callbackStopped)
{
// Execute user callback method
callbackResult = callback(stream_.userBuffer[OUTPUT],
stream_.userBuffer[INPUT],
stream_.bufferSize,
getStreamTime(),
captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
stream_.callbackInfo.userData);
// Handle return value from callback
if (callbackResult == 1)
{
// instantiate a thread to stop this thread
HANDLE threadHandle = CreateThread(NULL, 0, stopWasapiThread, this, 0, NULL);
if (!threadHandle)
{
errorType = RtAudioError::THREAD_ERROR;
errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
goto Exit;
}
else if (!CloseHandle(threadHandle))
{
errorType = RtAudioError::THREAD_ERROR;
errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
goto Exit;
}
callbackStopped = true;
}
else if (callbackResult == 2)
{
// instantiate a thread to stop this thread
HANDLE threadHandle = CreateThread(NULL, 0, abortWasapiThread, this, 0, NULL);
if (!threadHandle)
{
errorType = RtAudioError::THREAD_ERROR;
errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
goto Exit;
}
else if (!CloseHandle(threadHandle))
{
errorType = RtAudioError::THREAD_ERROR;
errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
goto Exit;
}
callbackStopped = true;
}
}
}
// Callback Output
// ===============
// 1. Convert callback buffer to stream format
// 2. Convert callback buffer to stream sample rate and channel count
// 3. Push callback buffer into outputBuffer
if (renderAudioClient && callbackPulled)
{
if (stream_.doConvertBuffer[OUTPUT])
{
// Convert callback buffer to stream format
convertBuffer(stream_.deviceBuffer,
stream_.userBuffer[OUTPUT],
stream_.convertInfo[OUTPUT]);
}
// Convert callback buffer to stream sample rate
convertBufferWasapi(convBuffer,
stream_.deviceBuffer,
stream_.nDeviceChannels[OUTPUT],
stream_.sampleRate,
renderFormat->nSamplesPerSec,
stream_.bufferSize,
convBufferSize,
stream_.deviceFormat[OUTPUT]);
// Push callback buffer into outputBuffer
callbackPushed = renderBuffer.pushBuffer(convBuffer,
convBufferSize * stream_.nDeviceChannels[OUTPUT],
stream_.deviceFormat[OUTPUT]);
}
else
{
// if there is no render stream, set callbackPushed flag
callbackPushed = true;
}
// Stream Capture
// ==============
// 1. Get capture buffer from stream
// 2. Push capture buffer into inputBuffer
// 3. If 2. was successful: Release capture buffer
if (captureAudioClient)
{
// if the callback input buffer was not pulled from captureBuffer, wait for next capture event
if (!callbackPulled)
{
WaitForSingleObject(captureEvent, INFINITE);
}
// Get capture buffer from stream
hr = captureClient->GetBuffer(&streamBuffer,
&bufferFrameCount,
&captureFlags, NULL, NULL);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
goto Exit;
}
if (bufferFrameCount != 0)
{
// Push capture buffer into inputBuffer
if (captureBuffer.pushBuffer((char *)streamBuffer,
bufferFrameCount * stream_.nDeviceChannels[INPUT],
stream_.deviceFormat[INPUT]))
{
// Release capture buffer
hr = captureClient->ReleaseBuffer(bufferFrameCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
goto Exit;
}
}
else
{
// Inform WASAPI that capture was unsuccessful
hr = captureClient->ReleaseBuffer(0);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
goto Exit;
}
}
}
else
{
// Inform WASAPI that capture was unsuccessful
hr = captureClient->ReleaseBuffer(0);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
goto Exit;
}
}
}
// Stream Render
// =============
// 1. Get render buffer from stream
// 2. Pull next buffer from outputBuffer
// 3. If 2. was successful: Fill render buffer with next buffer
// Release render buffer
if (renderAudioClient)
{
// if the callback output buffer was not pushed to renderBuffer, wait for next render event
if (callbackPulled && !callbackPushed)
{
WaitForSingleObject(renderEvent, INFINITE);
}
// Get render buffer from stream
hr = renderAudioClient->GetBufferSize(&bufferFrameCount);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
goto Exit;
}
hr = renderAudioClient->GetCurrentPadding(&numFramesPadding);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
goto Exit;
}
bufferFrameCount -= numFramesPadding;
if (bufferFrameCount != 0)
{
hr = renderClient->GetBuffer(bufferFrameCount, &streamBuffer);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
goto Exit;
}
// Pull next buffer from outputBuffer
// Fill render buffer with next buffer
if (renderBuffer.pullBuffer((char *)streamBuffer,
bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
stream_.deviceFormat[OUTPUT]))
{
// Release render buffer
hr = renderClient->ReleaseBuffer(bufferFrameCount, 0);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
goto Exit;
}
}
else
{
// Inform WASAPI that render was unsuccessful
hr = renderClient->ReleaseBuffer(0, 0);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
goto Exit;
}
}
}
else
{
// Inform WASAPI that render was unsuccessful
hr = renderClient->ReleaseBuffer(0, 0);
if (FAILED(hr))
{
errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
goto Exit;
}
}
}
// if the callback buffer was pushed renderBuffer reset callbackPulled flag
if (callbackPushed)
{
callbackPulled = false;
// tick stream time
RtApi::tickStreamTime();
}
}
Exit:
// clean up
CoTaskMemFree(captureFormat);
CoTaskMemFree(renderFormat);
free(convBuffer);
CoUninitialize();
// update stream state
stream_.state = STREAM_STOPPED;
if (errorText_.empty())
return;
else
error(errorType);
}
//******************** End of __WINDOWS_WASAPI__ *********************//
#endif
#if defined(__WINDOWS_DS__) // Windows DirectSound API
// Modified by Robin Davies, October 2005
// - Improvements to DirectX pointer chasing.
// - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
// - Auto-call CoInitialize for DSOUND and ASIO platforms.
// Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
// Changed device query structure for RtAudio 4.0.7, January 2010
#include <dsound.h>
#include <assert.h>
#include <algorithm>
#if defined(__MINGW32__)
// missing from latest mingw winapi
#define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
#define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
#define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
#define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
#endif
#define MINIMUM_DEVICE_BUFFER_SIZE 32768
#ifdef _MSC_VER // if Microsoft Visual C++
#pragma comment(lib, "winmm.lib") // then, auto-link winmm.lib. Otherwise, it has to be added manually.
#endif
static inline DWORD dsPointerBetween(DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize)
{
if (pointer > bufferSize) pointer -= bufferSize;
if (laterPointer < earlierPointer) laterPointer += bufferSize;
if (pointer < earlierPointer) pointer += bufferSize;
return pointer >= earlierPointer && pointer < laterPointer;
}
// A structure to hold various information related to the DirectSound
// API implementation.
struct DsHandle
{
unsigned int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
void *id[2];
void *buffer[2];
bool xrun[2];
UINT bufferPointer[2];
DWORD dsBufferSize[2];
DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
HANDLE condition;
DsHandle()
: drainCounter(0), internalDrain(false)
{
id[0] = 0;
id[1] = 0;
buffer[0] = 0;
buffer[1] = 0;
xrun[0] = false;
xrun[1] = false;
bufferPointer[0] = 0;
bufferPointer[1] = 0;
}
};
// Declarations for utility functions, callbacks, and structures
// specific to the DirectSound implementation.
static BOOL CALLBACK deviceQueryCallback(LPGUID lpguid,
LPCTSTR description,
LPCTSTR module,
LPVOID lpContext);
static const char *getErrorString(int code);
static unsigned __stdcall callbackHandler(void *ptr);
struct DsDevice
{
LPGUID id[2];
bool validId[2];
bool found;
std::string name;
DsDevice()
: found(false)
{
validId[0] = false;
validId[1] = false;
}
};
struct DsProbeData
{
bool isInput;
std::vector<struct DsDevice> *dsDevices;
};
RtApiDs ::RtApiDs()
{
// Dsound will run both-threaded. If CoInitialize fails, then just
// accept whatever the mainline chose for a threading model.
coInitialized_ = false;
HRESULT hr = CoInitialize(NULL);
if (!FAILED(hr)) coInitialized_ = true;
}
RtApiDs ::~RtApiDs()
{
if (coInitialized_) CoUninitialize(); // balanced call.
if (stream_.state != STREAM_CLOSED) closeStream();
}
// The DirectSound default output is always the first device.
unsigned int RtApiDs ::getDefaultOutputDevice(void)
{
return 0;
}
// The DirectSound default input is always the first input device,
// which is the first capture device enumerated.
unsigned int RtApiDs ::getDefaultInputDevice(void)
{
return 0;
}
unsigned int RtApiDs ::getDeviceCount(void)
{
// Set query flag for previously found devices to false, so that we
// can check for any devices that have disappeared.
for (unsigned int i = 0; i < dsDevices.size(); i++)
dsDevices[i].found = false;
// Query DirectSound devices.
struct DsProbeData probeInfo;
probeInfo.isInput = false;
probeInfo.dsDevices = &dsDevices;
HRESULT result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceQueryCallback, &probeInfo);
if (FAILED(result))
{
errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString(result) << ") enumerating output devices!";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
}
// Query DirectSoundCapture devices.
probeInfo.isInput = true;
result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceQueryCallback, &probeInfo);
if (FAILED(result))
{
errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString(result) << ") enumerating input devices!";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
}
// Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).
for (unsigned int i = 0; i < dsDevices.size();)
{
if (dsDevices[i].found == false)
dsDevices.erase(dsDevices.begin() + i);
else
i++;
}
return static_cast<unsigned int>(dsDevices.size());
}
RtAudio::DeviceInfo RtApiDs ::getDeviceInfo(unsigned int device)
{
RtAudio::DeviceInfo info;
info.probed = false;
if (dsDevices.size() == 0)
{
// Force a query of all devices
getDeviceCount();
if (dsDevices.size() == 0)
{
errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
error(RtAudioError::INVALID_USE);
return info;
}
}
if (device >= dsDevices.size())
{
errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
error(RtAudioError::INVALID_USE);
return info;
}
HRESULT result;
if (dsDevices[device].validId[0] == false) goto probeInput;
LPDIRECTSOUND output;
DSCAPS outCaps;
result = DirectSoundCreate(dsDevices[device].id[0], &output, NULL);
if (FAILED(result))
{
errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString(result) << ") opening output device (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
goto probeInput;
}
outCaps.dwSize = sizeof(outCaps);
result = output->GetCaps(&outCaps);
if (FAILED(result))
{
output->Release();
errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString(result) << ") getting capabilities!";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
goto probeInput;
}
// Get output channel information.
info.outputChannels = (outCaps.dwFlags & DSCAPS_PRIMARYSTEREO) ? 2 : 1;
// Get sample rate information.
info.sampleRates.clear();
for (unsigned int k = 0; k < MAX_SAMPLE_RATES; k++)
{
if (SAMPLE_RATES[k] >= (unsigned int)outCaps.dwMinSecondarySampleRate &&
SAMPLE_RATES[k] <= (unsigned int)outCaps.dwMaxSecondarySampleRate)
{
info.sampleRates.push_back(SAMPLE_RATES[k]);
if (!info.preferredSampleRate || (SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate))
info.preferredSampleRate = SAMPLE_RATES[k];
}
}
// Get format information.
if (outCaps.dwFlags & DSCAPS_PRIMARY16BIT) info.nativeFormats |= RTAUDIO_SINT16;
if (outCaps.dwFlags & DSCAPS_PRIMARY8BIT) info.nativeFormats |= RTAUDIO_SINT8;
output->Release();
if (getDefaultOutputDevice() == device)
info.isDefaultOutput = true;
if (dsDevices[device].validId[1] == false)
{
info.name = dsDevices[device].name;
info.probed = true;
return info;
}
probeInput:
LPDIRECTSOUNDCAPTURE input;
result = DirectSoundCaptureCreate(dsDevices[device].id[1], &input, NULL);
if (FAILED(result))
{
errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString(result) << ") opening input device (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
DSCCAPS inCaps;
inCaps.dwSize = sizeof(inCaps);
result = input->GetCaps(&inCaps);
if (FAILED(result))
{
input->Release();
errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString(result) << ") getting object capabilities (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Get input channel information.
info.inputChannels = inCaps.dwChannels;
// Get sample rate and format information.
std::vector<unsigned int> rates;
if (inCaps.dwChannels >= 2)
{
if (inCaps.dwFormats & WAVE_FORMAT_1S16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_2S16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_4S16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_96S16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_1S08) info.nativeFormats |= RTAUDIO_SINT8;
if (inCaps.dwFormats & WAVE_FORMAT_2S08) info.nativeFormats |= RTAUDIO_SINT8;
if (inCaps.dwFormats & WAVE_FORMAT_4S08) info.nativeFormats |= RTAUDIO_SINT8;
if (inCaps.dwFormats & WAVE_FORMAT_96S08) info.nativeFormats |= RTAUDIO_SINT8;
if (info.nativeFormats & RTAUDIO_SINT16)
{
if (inCaps.dwFormats & WAVE_FORMAT_1S16) rates.push_back(11025);
if (inCaps.dwFormats & WAVE_FORMAT_2S16) rates.push_back(22050);
if (inCaps.dwFormats & WAVE_FORMAT_4S16) rates.push_back(44100);
if (inCaps.dwFormats & WAVE_FORMAT_96S16) rates.push_back(96000);
}
else if (info.nativeFormats & RTAUDIO_SINT8)
{
if (inCaps.dwFormats & WAVE_FORMAT_1S08) rates.push_back(11025);
if (inCaps.dwFormats & WAVE_FORMAT_2S08) rates.push_back(22050);
if (inCaps.dwFormats & WAVE_FORMAT_4S08) rates.push_back(44100);
if (inCaps.dwFormats & WAVE_FORMAT_96S08) rates.push_back(96000);
}
}
else if (inCaps.dwChannels == 1)
{
if (inCaps.dwFormats & WAVE_FORMAT_1M16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_2M16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_4M16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_96M16) info.nativeFormats |= RTAUDIO_SINT16;
if (inCaps.dwFormats & WAVE_FORMAT_1M08) info.nativeFormats |= RTAUDIO_SINT8;
if (inCaps.dwFormats & WAVE_FORMAT_2M08) info.nativeFormats |= RTAUDIO_SINT8;
if (inCaps.dwFormats & WAVE_FORMAT_4M08) info.nativeFormats |= RTAUDIO_SINT8;
if (inCaps.dwFormats & WAVE_FORMAT_96M08) info.nativeFormats |= RTAUDIO_SINT8;
if (info.nativeFormats & RTAUDIO_SINT16)
{
if (inCaps.dwFormats & WAVE_FORMAT_1M16) rates.push_back(11025);
if (inCaps.dwFormats & WAVE_FORMAT_2M16) rates.push_back(22050);
if (inCaps.dwFormats & WAVE_FORMAT_4M16) rates.push_back(44100);
if (inCaps.dwFormats & WAVE_FORMAT_96M16) rates.push_back(96000);
}
else if (info.nativeFormats & RTAUDIO_SINT8)
{
if (inCaps.dwFormats & WAVE_FORMAT_1M08) rates.push_back(11025);
if (inCaps.dwFormats & WAVE_FORMAT_2M08) rates.push_back(22050);
if (inCaps.dwFormats & WAVE_FORMAT_4M08) rates.push_back(44100);
if (inCaps.dwFormats & WAVE_FORMAT_96M08) rates.push_back(96000);
}
}
else
info.inputChannels = 0; // technically, this would be an error
input->Release();
if (info.inputChannels == 0) return info;
// Copy the supported rates to the info structure but avoid duplication.
bool found;
for (unsigned int i = 0; i < rates.size(); i++)
{
found = false;
for (unsigned int j = 0; j < info.sampleRates.size(); j++)
{
if (rates[i] == info.sampleRates[j])
{
found = true;
break;
}
}
if (found == false) info.sampleRates.push_back(rates[i]);
}
std::sort(info.sampleRates.begin(), info.sampleRates.end());
// If device opens for both playback and capture, we determine the channels.
if (info.outputChannels > 0 && info.inputChannels > 0)
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
if (device == 0) info.isDefaultInput = true;
// Copy name and return.
info.name = dsDevices[device].name;
info.probed = true;
return info;
}
bool RtApiDs ::probeDeviceOpen(unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options)
{
if (channels + firstChannel > 2)
{
errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
return FAILURE;
}
size_t nDevices = dsDevices.size();
if (nDevices == 0)
{
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
return FAILURE;
}
if (device >= nDevices)
{
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
if (mode == OUTPUT)
{
if (dsDevices[device].validId[0] == false)
{
errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
else
{ // mode == INPUT
if (dsDevices[device].validId[1] == false)
{
errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// According to a note in PortAudio, using GetDesktopWindow()
// instead of GetForegroundWindow() is supposed to avoid problems
// that occur when the application's window is not the foreground
// window. Also, if the application window closes before the
// DirectSound buffer, DirectSound can crash. In the past, I had
// problems when using GetDesktopWindow() but it seems fine now
// (January 2010). I'll leave it commented here.
// HWND hWnd = GetForegroundWindow();
HWND hWnd = GetDesktopWindow();
// Check the numberOfBuffers parameter and limit the lowest value to
// two. This is a judgement call and a value of two is probably too
// low for capture, but it should work for playback.
int nBuffers = 0;
if (options) nBuffers = options->numberOfBuffers;
if (options && options->flags & RTAUDIO_MINIMIZE_LATENCY) nBuffers = 2;
if (nBuffers < 2) nBuffers = 3;
// Check the lower range of the user-specified buffer size and set
// (arbitrarily) to a lower bound of 32.
if (*bufferSize < 32) *bufferSize = 32;
// Create the wave format structure. The data format setting will
// be determined later.
WAVEFORMATEX waveFormat;
ZeroMemory(&waveFormat, sizeof(WAVEFORMATEX));
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nChannels = channels + firstChannel;
waveFormat.nSamplesPerSec = (unsigned long)sampleRate;
// Determine the device buffer size. By default, we'll use the value
// defined above (32K), but we will grow it to make allowances for
// very large software buffer sizes.
DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
DWORD dsPointerLeadTime = 0;
void *ohandle = 0, *bhandle = 0;
HRESULT result;
if (mode == OUTPUT)
{
LPDIRECTSOUND output;
result = DirectSoundCreate(dsDevices[device].id[0], &output, NULL);
if (FAILED(result))
{
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") opening output device (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
DSCAPS outCaps;
outCaps.dwSize = sizeof(outCaps);
result = output->GetCaps(&outCaps);
if (FAILED(result))
{
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") getting capabilities (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check channel information.
if (channels + firstChannel == 2 && !(outCaps.dwFlags & DSCAPS_PRIMARYSTEREO))
{
errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[device].name << ") does not support stereo playback.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check format information. Use 16-bit format unless not
// supported or user requests 8-bit.
if (outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
!(format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT))
{
waveFormat.wBitsPerSample = 16;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
else
{
waveFormat.wBitsPerSample = 8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
stream_.userFormat = format;
// Update wave format structure and buffer information.
waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
// If the user wants an even bigger buffer, increase the device buffer size accordingly.
while (dsPointerLeadTime * 2U > dsBufferSize)
dsBufferSize *= 2;
// Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
// result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
// Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
result = output->SetCooperativeLevel(hWnd, DSSCL_PRIORITY);
if (FAILED(result))
{
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") setting cooperative level (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Even though we will write to the secondary buffer, we need to
// access the primary buffer to set the correct output format
// (since the default is 8-bit, 22 kHz!). Setup the DS primary
// buffer description.
DSBUFFERDESC bufferDescription;
ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC));
bufferDescription.dwSize = sizeof(DSBUFFERDESC);
bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
// Obtain the primary buffer
LPDIRECTSOUNDBUFFER buffer;
result = output->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
if (FAILED(result))
{
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") accessing primary buffer (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the primary DS buffer sound format.
result = buffer->SetFormat(&waveFormat);
if (FAILED(result))
{
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") setting primary buffer format (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Setup the secondary DS buffer description.
ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC));
bufferDescription.dwSize = sizeof(DSBUFFERDESC);
bufferDescription.dwFlags = (DSBCAPS_STICKYFOCUS |
DSBCAPS_GLOBALFOCUS |
DSBCAPS_GETCURRENTPOSITION2 |
DSBCAPS_LOCHARDWARE); // Force hardware mixing
bufferDescription.dwBufferBytes = dsBufferSize;
bufferDescription.lpwfxFormat = &waveFormat;
// Try to create the secondary DS buffer. If that doesn't work,
// try to use software mixing. Otherwise, there's a problem.
result = output->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
if (FAILED(result))
{
bufferDescription.dwFlags = (DSBCAPS_STICKYFOCUS |
DSBCAPS_GLOBALFOCUS |
DSBCAPS_GETCURRENTPOSITION2 |
DSBCAPS_LOCSOFTWARE); // Force software mixing
result = output->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
if (FAILED(result))
{
output->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") creating secondary buffer (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Get the buffer size ... might be different from what we specified.
DSBCAPS dsbcaps;
dsbcaps.dwSize = sizeof(DSBCAPS);
result = buffer->GetCaps(&dsbcaps);
if (FAILED(result))
{
output->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") getting buffer settings (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
dsBufferSize = dsbcaps.dwBufferBytes;
// Lock the DS buffer
LPVOID audioPtr;
DWORD dataLen;
result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0);
if (FAILED(result))
{
output->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") locking buffer (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Zero the DS buffer
ZeroMemory(audioPtr, dataLen);
// Unlock the DS buffer
result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
if (FAILED(result))
{
output->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") unlocking buffer (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
ohandle = (void *)output;
bhandle = (void *)buffer;
}
if (mode == INPUT)
{
LPDIRECTSOUNDCAPTURE input;
result = DirectSoundCaptureCreate(dsDevices[device].id[1], &input, NULL);
if (FAILED(result))
{
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") opening input device (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
DSCCAPS inCaps;
inCaps.dwSize = sizeof(inCaps);
result = input->GetCaps(&inCaps);
if (FAILED(result))
{
input->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") getting input capabilities (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check channel information.
if (inCaps.dwChannels < channels + firstChannel)
{
errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
return FAILURE;
}
// Check format information. Use 16-bit format unless user
// requests 8-bit.
DWORD deviceFormats;
if (channels + firstChannel == 2)
{
deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
if (format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats)
{
waveFormat.wBitsPerSample = 8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
else
{ // assume 16-bit is supported
waveFormat.wBitsPerSample = 16;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
}
else
{ // channel == 1
deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
if (format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats)
{
waveFormat.wBitsPerSample = 8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
else
{ // assume 16-bit is supported
waveFormat.wBitsPerSample = 16;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
}
stream_.userFormat = format;
// Update wave format structure and buffer information.
waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
// If the user wants an even bigger buffer, increase the device buffer size accordingly.
while (dsPointerLeadTime * 2U > dsBufferSize)
dsBufferSize *= 2;
// Setup the secondary DS buffer description.
DSCBUFFERDESC bufferDescription;
ZeroMemory(&bufferDescription, sizeof(DSCBUFFERDESC));
bufferDescription.dwSize = sizeof(DSCBUFFERDESC);
bufferDescription.dwFlags = 0;
bufferDescription.dwReserved = 0;
bufferDescription.dwBufferBytes = dsBufferSize;
bufferDescription.lpwfxFormat = &waveFormat;
// Create the capture buffer.
LPDIRECTSOUNDCAPTUREBUFFER buffer;
result = input->CreateCaptureBuffer(&bufferDescription, &buffer, NULL);
if (FAILED(result))
{
input->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") creating input buffer (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Get the buffer size ... might be different from what we specified.
DSCBCAPS dscbcaps;
dscbcaps.dwSize = sizeof(DSCBCAPS);
result = buffer->GetCaps(&dscbcaps);
if (FAILED(result))
{
input->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") getting buffer settings (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
dsBufferSize = dscbcaps.dwBufferBytes;
// NOTE: We could have a problem here if this is a duplex stream
// and the play and capture hardware buffer sizes are different
// (I'm actually not sure if that is a problem or not).
// Currently, we are not verifying that.
// Lock the capture buffer
LPVOID audioPtr;
DWORD dataLen;
result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0);
if (FAILED(result))
{
input->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") locking input buffer (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
// Zero the buffer
ZeroMemory(audioPtr, dataLen);
// Unlock the buffer
result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
if (FAILED(result))
{
input->Release();
buffer->Release();
errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString(result) << ") unlocking input buffer (" << dsDevices[device].name << ")!";
errorText_ = errorStream_.str();
return FAILURE;
}
ohandle = (void *)input;
bhandle = (void *)buffer;
}
// Set various stream parameters
DsHandle *handle = 0;
stream_.nDeviceChannels[mode] = channels + firstChannel;
stream_.nUserChannels[mode] = channels;
stream_.bufferSize = *bufferSize;
stream_.channelOffset[mode] = firstChannel;
stream_.deviceInterleaved[mode] = true;
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
stream_.userInterleaved = false;
else
stream_.userInterleaved = true;
// Set flag for buffer conversion
stream_.doConvertBuffer[mode] = false;
if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1)
stream_.doConvertBuffer[mode] = true;
// Allocate necessary internal buffers
long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes(stream_.userFormat);
stream_.userBuffer[mode] = (char *)calloc(bufferBytes, 1);
if (stream_.userBuffer[mode] == NULL)
{
errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if (stream_.doConvertBuffer[mode])
{
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes(stream_.deviceFormat[mode]);
if (mode == INPUT)
{
if (stream_.mode == OUTPUT && stream_.deviceBuffer)
{
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if (bufferBytes <= (long)bytesOut) makeBuffer = false;
}
}
if (makeBuffer)
{
bufferBytes *= *bufferSize;
if (stream_.deviceBuffer) free(stream_.deviceBuffer);
stream_.deviceBuffer = (char *)calloc(bufferBytes, 1);
if (stream_.deviceBuffer == NULL)
{
errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
// Allocate our DsHandle structures for the stream.
if (stream_.apiHandle == 0)
{
try
{
handle = new DsHandle;
}
catch (std::bad_alloc &)
{
errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
goto error;
}
// Create a manual-reset event.
handle->condition = CreateEvent(NULL, // no security
TRUE, // manual-reset
FALSE, // non-signaled initially
NULL); // unnamed
stream_.apiHandle = (void *)handle;
}
else
handle = (DsHandle *)stream_.apiHandle;
handle->id[mode] = ohandle;
handle->buffer[mode] = bhandle;
handle->dsBufferSize[mode] = dsBufferSize;
handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
stream_.device[mode] = device;
stream_.state = STREAM_STOPPED;
if (stream_.mode == OUTPUT && mode == INPUT)
// We had already set up an output stream.
stream_.mode = DUPLEX;
else
stream_.mode = mode;
stream_.nBuffers = nBuffers;
stream_.sampleRate = sampleRate;
// Setup the buffer conversion information structure.
if (stream_.doConvertBuffer[mode]) setConvertInfo(mode, firstChannel);
// Setup the callback thread.
if (stream_.callbackInfo.isRunning == false)
{
unsigned threadId;
stream_.callbackInfo.isRunning = true;
stream_.callbackInfo.object = (void *)this;
stream_.callbackInfo.thread = _beginthreadex(NULL, 0, &callbackHandler,
&stream_.callbackInfo, 0, &threadId);
if (stream_.callbackInfo.thread == 0)
{
errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
goto error;
}
// Boost DS thread priority
SetThreadPriority((HANDLE)stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST);
}
return SUCCESS;
error:
if (handle)
{
if (handle->buffer[0])
{ // the object pointer can be NULL and valid
LPDIRECTSOUND object = (LPDIRECTSOUND)handle->id[0];
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER)handle->buffer[0];
if (buffer) buffer->Release();
object->Release();
}
if (handle->buffer[1])
{
LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE)handle->id[1];
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER)handle->buffer[1];
if (buffer) buffer->Release();
object->Release();
}
CloseHandle(handle->condition);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.state = STREAM_CLOSED;
return FAILURE;
}
void RtApiDs ::closeStream()
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiDs::closeStream(): no open stream to close!";
error(RtAudioError::WARNING);
return;
}
// Stop the callback thread.
stream_.callbackInfo.isRunning = false;
WaitForSingleObject((HANDLE)stream_.callbackInfo.thread, INFINITE);
CloseHandle((HANDLE)stream_.callbackInfo.thread);
DsHandle *handle = (DsHandle *)stream_.apiHandle;
if (handle)
{
if (handle->buffer[0])
{ // the object pointer can be NULL and valid
LPDIRECTSOUND object = (LPDIRECTSOUND)handle->id[0];
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER)handle->buffer[0];
if (buffer)
{
buffer->Stop();
buffer->Release();
}
object->Release();
}
if (handle->buffer[1])
{
LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE)handle->id[1];
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER)handle->buffer[1];
if (buffer)
{
buffer->Stop();
buffer->Release();
}
object->Release();
}
CloseHandle(handle->condition);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
}
void RtApiDs ::startStream()
{
verifyStream();
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiDs::startStream(): the stream is already running!";
error(RtAudioError::WARNING);
return;
}
DsHandle *handle = (DsHandle *)stream_.apiHandle;
// Increase scheduler frequency on lesser windows (a side-effect of
// increasing timer accuracy). On greater windows (Win2K or later),
// this is already in effect.
timeBeginPeriod(1);
buffersRolling = false;
duplexPrerollBytes = 0;
if (stream_.mode == DUPLEX)
{
// 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
duplexPrerollBytes = (int)(0.5 * stream_.sampleRate * formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1]);
}
HRESULT result = 0;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER)handle->buffer[0];
result = buffer->Play(0, 0, DSBPLAY_LOOPING);
if (FAILED(result))
{
errorStream_ << "RtApiDs::startStream: error (" << getErrorString(result) << ") starting output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER)handle->buffer[1];
result = buffer->Start(DSCBSTART_LOOPING);
if (FAILED(result))
{
errorStream_ << "RtApiDs::startStream: error (" << getErrorString(result) << ") starting input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
}
handle->drainCounter = 0;
handle->internalDrain = false;
ResetEvent(handle->condition);
stream_.state = STREAM_RUNNING;
unlock:
if (FAILED(result)) error(RtAudioError::SYSTEM_ERROR);
}
void RtApiDs ::stopStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
HRESULT result = 0;
LPVOID audioPtr;
DWORD dataLen;
DsHandle *handle = (DsHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (handle->drainCounter == 0)
{
handle->drainCounter = 2;
WaitForSingleObject(handle->condition, INFINITE); // block until signaled
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK(&stream_.mutex);
// Stop the buffer and clear memory
LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER)handle->buffer[0];
result = buffer->Stop();
if (FAILED(result))
{
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString(result) << ") stopping output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Lock the buffer and clear it so that if we start to play again,
// we won't have old data playing.
result = buffer->Lock(0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0);
if (FAILED(result))
{
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString(result) << ") locking output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Zero the DS buffer
ZeroMemory(audioPtr, dataLen);
// Unlock the DS buffer
result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
if (FAILED(result))
{
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString(result) << ") unlocking output buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// If we start playing again, we must begin at beginning of buffer.
handle->bufferPointer[0] = 0;
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER)handle->buffer[1];
audioPtr = NULL;
dataLen = 0;
stream_.state = STREAM_STOPPED;
if (stream_.mode != DUPLEX)
MUTEX_LOCK(&stream_.mutex);
result = buffer->Stop();
if (FAILED(result))
{
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString(result) << ") stopping input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Lock the buffer and clear it so that if we start to play again,
// we won't have old data playing.
result = buffer->Lock(0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0);
if (FAILED(result))
{
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString(result) << ") locking input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// Zero the DS buffer
ZeroMemory(audioPtr, dataLen);
// Unlock the DS buffer
result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
if (FAILED(result))
{
errorStream_ << "RtApiDs::stopStream: error (" << getErrorString(result) << ") unlocking input buffer!";
errorText_ = errorStream_.str();
goto unlock;
}
// If we start recording again, we must begin at beginning of buffer.
handle->bufferPointer[1] = 0;
}
unlock:
timeEndPeriod(1); // revert to normal scheduler frequency on lesser windows.
MUTEX_UNLOCK(&stream_.mutex);
if (FAILED(result)) error(RtAudioError::SYSTEM_ERROR);
}
void RtApiDs ::abortStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
DsHandle *handle = (DsHandle *)stream_.apiHandle;
handle->drainCounter = 2;
stopStream();
}
void RtApiDs ::callbackEvent()
{
if (stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING)
{
Sleep(50); // sleep 50 milliseconds
return;
}
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
error(RtAudioError::WARNING);
return;
}
CallbackInfo *info = (CallbackInfo *)&stream_.callbackInfo;
DsHandle *handle = (DsHandle *)stream_.apiHandle;
// Check if we were draining the stream and signal is finished.
if (handle->drainCounter > stream_.nBuffers + 2)
{
stream_.state = STREAM_STOPPING;
if (handle->internalDrain == false)
SetEvent(handle->condition);
else
stopStream();
return;
}
// Invoke user callback to get fresh output data UNLESS we are
// draining stream.
if (handle->drainCounter == 0)
{
RtAudioCallback callback = (RtAudioCallback)info->callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if (stream_.mode != INPUT && handle->xrun[0] == true)
{
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if (stream_.mode != OUTPUT && handle->xrun[1] == true)
{
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
int cbReturnValue = callback(stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, info->userData);
if (cbReturnValue == 2)
{
stream_.state = STREAM_STOPPING;
handle->drainCounter = 2;
abortStream();
return;
}
else if (cbReturnValue == 1)
{
handle->drainCounter = 1;
handle->internalDrain = true;
}
}
HRESULT result;
DWORD currentWritePointer, safeWritePointer;
DWORD currentReadPointer, safeReadPointer;
UINT nextWritePointer;
LPVOID buffer1 = NULL;
LPVOID buffer2 = NULL;
DWORD bufferSize1 = 0;
DWORD bufferSize2 = 0;
char *buffer;
long bufferBytes;
MUTEX_LOCK(&stream_.mutex);
if (stream_.state == STREAM_STOPPED)
{
MUTEX_UNLOCK(&stream_.mutex);
return;
}
if (buffersRolling == false)
{
if (stream_.mode == DUPLEX)
{
//assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
// It takes a while for the devices to get rolling. As a result,
// there's no guarantee that the capture and write device pointers
// will move in lockstep. Wait here for both devices to start
// rolling, and then set our buffer pointers accordingly.
// e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
// bytes later than the write buffer.
// Stub: a serious risk of having a pre-emptive scheduling round
// take place between the two GetCurrentPosition calls... but I'm
// really not sure how to solve the problem. Temporarily boost to
// Realtime priority, maybe; but I'm not sure what priority the
// DirectSound service threads run at. We *should* be roughly
// within a ms or so of correct.
LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER)handle->buffer[0];
LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER)handle->buffer[1];
DWORD startSafeWritePointer, startSafeReadPointer;
result = dsWriteBuffer->GetCurrentPosition(NULL, &startSafeWritePointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
result = dsCaptureBuffer->GetCurrentPosition(NULL, &startSafeReadPointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
while (true)
{
result = dsWriteBuffer->GetCurrentPosition(NULL, &safeWritePointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
result = dsCaptureBuffer->GetCurrentPosition(NULL, &safeReadPointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
if (safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer) break;
Sleep(1);
}
//assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
if (handle->bufferPointer[0] >= handle->dsBufferSize[0]) handle->bufferPointer[0] -= handle->dsBufferSize[0];
handle->bufferPointer[1] = safeReadPointer;
}
else if (stream_.mode == OUTPUT)
{
// Set the proper nextWritePosition after initial startup.
LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER)handle->buffer[0];
result = dsWriteBuffer->GetCurrentPosition(¤tWritePointer, &safeWritePointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
if (handle->bufferPointer[0] >= handle->dsBufferSize[0]) handle->bufferPointer[0] -= handle->dsBufferSize[0];
}
buffersRolling = true;
}
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER)handle->buffer[0];
if (handle->drainCounter > 1)
{ // write zeros to the output stream
bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
bufferBytes *= formatBytes(stream_.userFormat);
memset(stream_.userBuffer[0], 0, bufferBytes);
}
// Setup parameters and do buffer conversion if necessary.
if (stream_.doConvertBuffer[0])
{
buffer = stream_.deviceBuffer;
convertBuffer(buffer, stream_.userBuffer[0], stream_.convertInfo[0]);
bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
bufferBytes *= formatBytes(stream_.deviceFormat[0]);
}
else
{
buffer = stream_.userBuffer[0];
bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
bufferBytes *= formatBytes(stream_.userFormat);
}
// No byte swapping necessary in DirectSound implementation.
// Ahhh ... windoze. 16-bit data is signed but 8-bit data is
// unsigned. So, we need to convert our signed 8-bit data here to
// unsigned.
if (stream_.deviceFormat[0] == RTAUDIO_SINT8)
for (int i = 0; i < bufferBytes; i++) buffer[i] = (unsigned char)(buffer[i] + 128);
DWORD dsBufferSize = handle->dsBufferSize[0];
nextWritePointer = handle->bufferPointer[0];
DWORD endWrite, leadPointer;
while (true)
{
// Find out where the read and "safe write" pointers are.
result = dsBuffer->GetCurrentPosition(¤tWritePointer, &safeWritePointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current write position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
// We will copy our output buffer into the region between
// safeWritePointer and leadPointer. If leadPointer is not
// beyond the next endWrite position, wait until it is.
leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
//std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
if (leadPointer > dsBufferSize) leadPointer -= dsBufferSize;
if (leadPointer < nextWritePointer) leadPointer += dsBufferSize; // unwrap offset
endWrite = nextWritePointer + bufferBytes;
// Check whether the entire write region is behind the play pointer.
if (leadPointer >= endWrite) break;
// If we are here, then we must wait until the leadPointer advances
// beyond the end of our next write region. We use the
// Sleep() function to suspend operation until that happens.
double millis = (endWrite - leadPointer) * 1000.0;
millis /= (formatBytes(stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
if (millis < 1.0) millis = 1.0;
Sleep((DWORD)millis);
}
if (dsPointerBetween(nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize) || dsPointerBetween(endWrite, safeWritePointer, currentWritePointer, dsBufferSize))
{
// We've strayed into the forbidden zone ... resync the read pointer.
handle->xrun[0] = true;
nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
if (nextWritePointer >= dsBufferSize) nextWritePointer -= dsBufferSize;
handle->bufferPointer[0] = nextWritePointer;
endWrite = nextWritePointer + bufferBytes;
}
// Lock free space in the buffer
result = dsBuffer->Lock(nextWritePointer, bufferBytes, &buffer1,
&bufferSize1, &buffer2, &bufferSize2, 0);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") locking buffer during playback!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
// Copy our buffer into the DS buffer
CopyMemory(buffer1, buffer, bufferSize1);
if (buffer2 != NULL) CopyMemory(buffer2, buffer + bufferSize1, bufferSize2);
// Update our buffer offset and unlock sound buffer
dsBuffer->Unlock(buffer1, bufferSize1, buffer2, bufferSize2);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") unlocking buffer during playback!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
nextWritePointer = (nextWritePointer + bufferSize1 + bufferSize2) % dsBufferSize;
handle->bufferPointer[0] = nextWritePointer;
}
// Don't bother draining input
if (handle->drainCounter)
{
handle->drainCounter++;
goto unlock;
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
// Setup parameters.
if (stream_.doConvertBuffer[1])
{
buffer = stream_.deviceBuffer;
bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
bufferBytes *= formatBytes(stream_.deviceFormat[1]);
}
else
{
buffer = stream_.userBuffer[1];
bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
bufferBytes *= formatBytes(stream_.userFormat);
}
LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER)handle->buffer[1];
long nextReadPointer = handle->bufferPointer[1];
DWORD dsBufferSize = handle->dsBufferSize[1];
// Find out where the write and "safe read" pointers are.
result = dsBuffer->GetCurrentPosition(¤tReadPointer, &safeReadPointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
if (safeReadPointer < (DWORD)nextReadPointer) safeReadPointer += dsBufferSize; // unwrap offset
DWORD endRead = nextReadPointer + bufferBytes;
// Handling depends on whether we are INPUT or DUPLEX.
// If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
// then a wait here will drag the write pointers into the forbidden zone.
//
// In DUPLEX mode, rather than wait, we will back off the read pointer until
// it's in a safe position. This causes dropouts, but it seems to be the only
// practical way to sync up the read and write pointers reliably, given the
// the very complex relationship between phase and increment of the read and write
// pointers.
//
// In order to minimize audible dropouts in DUPLEX mode, we will
// provide a pre-roll period of 0.5 seconds in which we return
// zeros from the read buffer while the pointers sync up.
if (stream_.mode == DUPLEX)
{
if (safeReadPointer < endRead)
{
if (duplexPrerollBytes <= 0)
{
// Pre-roll time over. Be more agressive.
int adjustment = endRead - safeReadPointer;
handle->xrun[1] = true;
// Two cases:
// - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
// and perform fine adjustments later.
// - small adjustments: back off by twice as much.
if (adjustment >= 2 * bufferBytes)
nextReadPointer = safeReadPointer - 2 * bufferBytes;
else
nextReadPointer = safeReadPointer - bufferBytes - adjustment;
if (nextReadPointer < 0) nextReadPointer += dsBufferSize;
}
else
{
// In pre=roll time. Just do it.
nextReadPointer = safeReadPointer - bufferBytes;
while (nextReadPointer < 0) nextReadPointer += dsBufferSize;
}
endRead = nextReadPointer + bufferBytes;
}
}
else
{ // mode == INPUT
while (safeReadPointer < endRead && stream_.callbackInfo.isRunning)
{
// See comments for playback.
double millis = (endRead - safeReadPointer) * 1000.0;
millis /= (formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
if (millis < 1.0) millis = 1.0;
Sleep((DWORD)millis);
// Wake up and find out where we are now.
result = dsBuffer->GetCurrentPosition(¤tReadPointer, &safeReadPointer);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") getting current read position!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
if (safeReadPointer < (DWORD)nextReadPointer) safeReadPointer += dsBufferSize; // unwrap offset
}
}
// Lock free space in the buffer
result = dsBuffer->Lock(nextReadPointer, bufferBytes, &buffer1,
&bufferSize1, &buffer2, &bufferSize2, 0);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") locking capture buffer!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
if (duplexPrerollBytes <= 0)
{
// Copy our buffer into the DS buffer
CopyMemory(buffer, buffer1, bufferSize1);
if (buffer2 != NULL) CopyMemory(buffer + bufferSize1, buffer2, bufferSize2);
}
else
{
memset(buffer, 0, bufferSize1);
if (buffer2 != NULL) memset(buffer + bufferSize1, 0, bufferSize2);
duplexPrerollBytes -= bufferSize1 + bufferSize2;
}
// Update our buffer offset and unlock sound buffer
nextReadPointer = (nextReadPointer + bufferSize1 + bufferSize2) % dsBufferSize;
dsBuffer->Unlock(buffer1, bufferSize1, buffer2, bufferSize2);
if (FAILED(result))
{
errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString(result) << ") unlocking capture buffer!";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
handle->bufferPointer[1] = nextReadPointer;
// No byte swapping necessary in DirectSound implementation.
// If necessary, convert 8-bit data from unsigned to signed.
if (stream_.deviceFormat[1] == RTAUDIO_SINT8)
for (int j = 0; j < bufferBytes; j++) buffer[j] = (signed char)(buffer[j] - 128);
// Do buffer conversion if necessary.
if (stream_.doConvertBuffer[1])
convertBuffer(stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1]);
}
unlock:
MUTEX_UNLOCK(&stream_.mutex);
RtApi::tickStreamTime();
}
// Definitions for utility functions and callbacks
// specific to the DirectSound implementation.
static unsigned __stdcall callbackHandler(void *ptr)
{
CallbackInfo *info = (CallbackInfo *)ptr;
RtApiDs *object = (RtApiDs *)info->object;
bool *isRunning = &info->isRunning;
while (*isRunning == true)
{
object->callbackEvent();
}
_endthreadex(0);
return 0;
}
static BOOL CALLBACK deviceQueryCallback(LPGUID lpguid,
LPCTSTR description,
LPCTSTR /*module*/,
LPVOID lpContext)
{
struct DsProbeData &probeInfo = *(struct DsProbeData *)lpContext;
std::vector<struct DsDevice> &dsDevices = *probeInfo.dsDevices;
HRESULT hr;
bool validDevice = false;
if (probeInfo.isInput == true)
{
DSCCAPS caps;
LPDIRECTSOUNDCAPTURE object;
hr = DirectSoundCaptureCreate(lpguid, &object, NULL);
if (hr != DS_OK) return TRUE;
caps.dwSize = sizeof(caps);
hr = object->GetCaps(&caps);
if (hr == DS_OK)
{
if (caps.dwChannels > 0 && caps.dwFormats > 0)
validDevice = true;
}
object->Release();
}
else
{
DSCAPS caps;
LPDIRECTSOUND object;
hr = DirectSoundCreate(lpguid, &object, NULL);
if (hr != DS_OK) return TRUE;
caps.dwSize = sizeof(caps);
hr = object->GetCaps(&caps);
if (hr == DS_OK)
{
if (caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO)
validDevice = true;
}
object->Release();
}
// If good device, then save its name and guid.
std::string name = convertCharPointerToStdString(description);
//if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
if (lpguid == NULL)
name = "Default Device";
if (validDevice)
{
for (unsigned int i = 0; i < dsDevices.size(); i++)
{
if (dsDevices[i].name == name)
{
dsDevices[i].found = true;
if (probeInfo.isInput)
{
dsDevices[i].id[1] = lpguid;
dsDevices[i].validId[1] = true;
}
else
{
dsDevices[i].id[0] = lpguid;
dsDevices[i].validId[0] = true;
}
return TRUE;
}
}
DsDevice device;
device.name = name;
device.found = true;
if (probeInfo.isInput)
{
device.id[1] = lpguid;
device.validId[1] = true;
}
else
{
device.id[0] = lpguid;
device.validId[0] = true;
}
dsDevices.push_back(device);
}
return TRUE;
}
static const char *getErrorString(int code)
{
switch (code)
{
case DSERR_ALLOCATED:
return "Already allocated";
case DSERR_CONTROLUNAVAIL:
return "Control unavailable";
case DSERR_INVALIDPARAM:
return "Invalid parameter";
case DSERR_INVALIDCALL:
return "Invalid call";
case DSERR_GENERIC:
return "Generic error";
case DSERR_PRIOLEVELNEEDED:
return "Priority level needed";
case DSERR_OUTOFMEMORY:
return "Out of memory";
case DSERR_BADFORMAT:
return "The sample rate or the channel format is not supported";
case DSERR_UNSUPPORTED:
return "Not supported";
case DSERR_NODRIVER:
return "No driver";
case DSERR_ALREADYINITIALIZED:
return "Already initialized";
case DSERR_NOAGGREGATION:
return "No aggregation";
case DSERR_BUFFERLOST:
return "Buffer lost";
case DSERR_OTHERAPPHASPRIO:
return "Another application already has priority";
case DSERR_UNINITIALIZED:
return "Uninitialized";
default:
return "DirectSound unknown error";
}
}
//******************** End of __WINDOWS_DS__ *********************//
#endif
#if defined(__LINUX_ALSA__)
#include <alsa/asoundlib.h>
#include <unistd.h>
// A structure to hold various information related to the ALSA API
// implementation.
struct AlsaHandle
{
snd_pcm_t *handles[2];
bool synchronized;
bool xrun[2];
pthread_cond_t runnable_cv;
bool runnable;
AlsaHandle()
: synchronized(false), runnable(false)
{
xrun[0] = false;
xrun[1] = false;
}
};
static void *alsaCallbackHandler(void *ptr);
RtApiAlsa ::RtApiAlsa()
{
// Nothing to do here.
}
RtApiAlsa ::~RtApiAlsa()
{
if (stream_.state != STREAM_CLOSED) closeStream();
}
unsigned int RtApiAlsa ::getDeviceCount(void)
{
unsigned nDevices = 0;
int result, subdevice, card;
char name[64];
snd_ctl_t *handle;
// Count cards and devices
card = -1;
snd_card_next(&card);
while (card >= 0)
{
sprintf(name, "hw:%d", card);
result = snd_ctl_open(&handle, name, 0);
if (result < 0)
{
errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
goto nextcard;
}
subdevice = -1;
while (1)
{
result = snd_ctl_pcm_next_device(handle, &subdevice);
if (result < 0)
{
errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
break;
}
if (subdevice < 0)
break;
nDevices++;
}
nextcard:
snd_ctl_close(handle);
snd_card_next(&card);
}
result = snd_ctl_open(&handle, "default", 0);
if (result == 0)
{
nDevices++;
snd_ctl_close(handle);
}
return nDevices;
}
RtAudio::DeviceInfo RtApiAlsa ::getDeviceInfo(unsigned int device)
{
RtAudio::DeviceInfo info;
info.probed = false;
unsigned nDevices = 0;
int result, subdevice, card;
char name[64];
snd_ctl_t *chandle;
// Count cards and devices
card = -1;
subdevice = -1;
snd_card_next(&card);
while (card >= 0)
{
sprintf(name, "hw:%d", card);
result = snd_ctl_open(&chandle, name, SND_CTL_NONBLOCK);
if (result < 0)
{
errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
goto nextcard;
}
subdevice = -1;
while (1)
{
result = snd_ctl_pcm_next_device(chandle, &subdevice);
if (result < 0)
{
errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
break;
}
if (subdevice < 0) break;
if (nDevices == device)
{
sprintf(name, "hw:%d,%d", card, subdevice);
goto foundDevice;
}
nDevices++;
}
nextcard:
snd_ctl_close(chandle);
snd_card_next(&card);
}
result = snd_ctl_open(&chandle, "default", SND_CTL_NONBLOCK);
if (result == 0)
{
if (nDevices == device)
{
strcpy(name, "default");
goto foundDevice;
}
nDevices++;
}
if (nDevices == 0)
{
errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
error(RtAudioError::INVALID_USE);
return info;
}
if (device >= nDevices)
{
errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
error(RtAudioError::INVALID_USE);
return info;
}
foundDevice:
// If a stream is already open, we cannot probe the stream devices.
// Thus, use the saved results.
if (stream_.state != STREAM_CLOSED &&
(stream_.device[0] == device || stream_.device[1] == device))
{
snd_ctl_close(chandle);
if (device >= devices_.size())
{
errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
error(RtAudioError::WARNING);
return info;
}
return devices_[device];
}
int openMode = SND_PCM_ASYNC;
snd_pcm_stream_t stream;
snd_pcm_info_t *pcminfo;
snd_pcm_info_alloca(&pcminfo);
snd_pcm_t *phandle;
snd_pcm_hw_params_t *params;
snd_pcm_hw_params_alloca(¶ms);
// First try for playback unless default device (which has subdev -1)
stream = SND_PCM_STREAM_PLAYBACK;
snd_pcm_info_set_stream(pcminfo, stream);
if (subdevice != -1)
{
snd_pcm_info_set_device(pcminfo, subdevice);
snd_pcm_info_set_subdevice(pcminfo, 0);
result = snd_ctl_pcm_info(chandle, pcminfo);
if (result < 0)
{
// Device probably doesn't support playback.
goto captureProbe;
}
}
result = snd_pcm_open(&phandle, name, stream, openMode | SND_PCM_NONBLOCK);
if (result < 0)
{
errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
goto captureProbe;
}
// The device is open ... fill the parameter structure.
result = snd_pcm_hw_params_any(phandle, params);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
goto captureProbe;
}
// Get output channel information.
unsigned int value;
result = snd_pcm_hw_params_get_channels_max(params, &value);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
goto captureProbe;
}
info.outputChannels = value;
snd_pcm_close(phandle);
captureProbe:
stream = SND_PCM_STREAM_CAPTURE;
snd_pcm_info_set_stream(pcminfo, stream);
// Now try for capture unless default device (with subdev = -1)
if (subdevice != -1)
{
result = snd_ctl_pcm_info(chandle, pcminfo);
snd_ctl_close(chandle);
if (result < 0)
{
// Device probably doesn't support capture.
if (info.outputChannels == 0) return info;
goto probeParameters;
}
}
else
snd_ctl_close(chandle);
result = snd_pcm_open(&phandle, name, stream, openMode | SND_PCM_NONBLOCK);
if (result < 0)
{
errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
if (info.outputChannels == 0) return info;
goto probeParameters;
}
// The device is open ... fill the parameter structure.
result = snd_pcm_hw_params_any(phandle, params);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
if (info.outputChannels == 0) return info;
goto probeParameters;
}
result = snd_pcm_hw_params_get_channels_max(params, &value);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
if (info.outputChannels == 0) return info;
goto probeParameters;
}
info.inputChannels = value;
snd_pcm_close(phandle);
// If device opens for both playback and capture, we determine the channels.
if (info.outputChannels > 0 && info.inputChannels > 0)
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// ALSA doesn't provide default devices so we'll use the first available one.
if (device == 0 && info.outputChannels > 0)
info.isDefaultOutput = true;
if (device == 0 && info.inputChannels > 0)
info.isDefaultInput = true;
probeParameters:
// At this point, we just need to figure out the supported data
// formats and sample rates. We'll proceed by opening the device in
// the direction with the maximum number of channels, or playback if
// they are equal. This might limit our sample rate options, but so
// be it.
if (info.outputChannels >= info.inputChannels)
stream = SND_PCM_STREAM_PLAYBACK;
else
stream = SND_PCM_STREAM_CAPTURE;
snd_pcm_info_set_stream(pcminfo, stream);
result = snd_pcm_open(&phandle, name, stream, openMode | SND_PCM_NONBLOCK);
if (result < 0)
{
errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// The device is open ... fill the parameter structure.
result = snd_pcm_hw_params_any(phandle, params);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Test our discrete set of sample rate values.
info.sampleRates.clear();
for (unsigned int i = 0; i < MAX_SAMPLE_RATES; i++)
{
if (snd_pcm_hw_params_test_rate(phandle, params, SAMPLE_RATES[i], 0) == 0)
{
info.sampleRates.push_back(SAMPLE_RATES[i]);
if (!info.preferredSampleRate || (SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate))
info.preferredSampleRate = SAMPLE_RATES[i];
}
}
if (info.sampleRates.size() == 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Probe the supported data formats ... we don't care about endian-ness just yet
snd_pcm_format_t format;
info.nativeFormats = 0;
format = SND_PCM_FORMAT_S8;
if (snd_pcm_hw_params_test_format(phandle, params, format) == 0)
info.nativeFormats |= RTAUDIO_SINT8;
format = SND_PCM_FORMAT_S16;
if (snd_pcm_hw_params_test_format(phandle, params, format) == 0)
info.nativeFormats |= RTAUDIO_SINT16;
format = SND_PCM_FORMAT_S24;
if (snd_pcm_hw_params_test_format(phandle, params, format) == 0)
info.nativeFormats |= RTAUDIO_SINT24;
format = SND_PCM_FORMAT_S32;
if (snd_pcm_hw_params_test_format(phandle, params, format) == 0)
info.nativeFormats |= RTAUDIO_SINT32;
format = SND_PCM_FORMAT_FLOAT;
if (snd_pcm_hw_params_test_format(phandle, params, format) == 0)
info.nativeFormats |= RTAUDIO_FLOAT32;
format = SND_PCM_FORMAT_FLOAT64;
if (snd_pcm_hw_params_test_format(phandle, params, format) == 0)
info.nativeFormats |= RTAUDIO_FLOAT64;
// Check that we have at least one supported format
if (info.nativeFormats == 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Get the device name
char *cardname;
result = snd_card_get_name(card, &cardname);
if (result >= 0)
{
sprintf(name, "hw:%s,%d", cardname, subdevice);
free(cardname);
}
info.name = name;
// That's all ... close the device and return
snd_pcm_close(phandle);
info.probed = true;
return info;
}
void RtApiAlsa ::saveDeviceInfo(void)
{
devices_.clear();
unsigned int nDevices = getDeviceCount();
devices_.resize(nDevices);
for (unsigned int i = 0; i < nDevices; i++)
devices_[i] = getDeviceInfo(i);
}
bool RtApiAlsa ::probeDeviceOpen(unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options)
{
#if defined(__RTAUDIO_DEBUG__)
snd_output_t *out;
snd_output_stdio_attach(&out, stderr, 0);
#endif
// I'm not using the "plug" interface ... too much inconsistent behavior.
unsigned nDevices = 0;
int result, subdevice, card;
char name[64];
snd_ctl_t *chandle;
if (options && options->flags & RTAUDIO_ALSA_USE_DEFAULT)
snprintf(name, sizeof(name), "%s", "default");
else
{
// Count cards and devices
card = -1;
snd_card_next(&card);
while (card >= 0)
{
sprintf(name, "hw:%d", card);
result = snd_ctl_open(&chandle, name, SND_CTL_NONBLOCK);
if (result < 0)
{
errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
subdevice = -1;
while (1)
{
result = snd_ctl_pcm_next_device(chandle, &subdevice);
if (result < 0) break;
if (subdevice < 0) break;
if (nDevices == device)
{
sprintf(name, "hw:%d,%d", card, subdevice);
snd_ctl_close(chandle);
goto foundDevice;
}
nDevices++;
}
snd_ctl_close(chandle);
snd_card_next(&card);
}
result = snd_ctl_open(&chandle, "default", SND_CTL_NONBLOCK);
if (result == 0)
{
if (nDevices == device)
{
strcpy(name, "default");
goto foundDevice;
}
nDevices++;
}
if (nDevices == 0)
{
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
return FAILURE;
}
if (device >= nDevices)
{
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
}
foundDevice:
// The getDeviceInfo() function will not work for a device that is
// already open. Thus, we'll probe the system before opening a
// stream and save the results for use by getDeviceInfo().
if (mode == OUTPUT || (mode == INPUT && stream_.mode != OUTPUT)) // only do once
this->saveDeviceInfo();
snd_pcm_stream_t stream;
if (mode == OUTPUT)
stream = SND_PCM_STREAM_PLAYBACK;
else
stream = SND_PCM_STREAM_CAPTURE;
snd_pcm_t *phandle;
int openMode = SND_PCM_ASYNC;
result = snd_pcm_open(&phandle, name, stream, openMode);
if (result < 0)
{
if (mode == OUTPUT)
errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
else
errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Fill the parameter structure.
snd_pcm_hw_params_t *hw_params;
snd_pcm_hw_params_alloca(&hw_params);
result = snd_pcm_hw_params_any(phandle, hw_params);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
#if defined(__RTAUDIO_DEBUG__)
fprintf(stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n");
snd_pcm_hw_params_dump(hw_params, out);
#endif
// Set access ... check user preference.
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
{
stream_.userInterleaved = false;
result = snd_pcm_hw_params_set_access(phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED);
if (result < 0)
{
result = snd_pcm_hw_params_set_access(phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
stream_.deviceInterleaved[mode] = true;
}
else
stream_.deviceInterleaved[mode] = false;
}
else
{
stream_.userInterleaved = true;
result = snd_pcm_hw_params_set_access(phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
if (result < 0)
{
result = snd_pcm_hw_params_set_access(phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED);
stream_.deviceInterleaved[mode] = false;
}
else
stream_.deviceInterleaved[mode] = true;
}
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine how to set the device format.
stream_.userFormat = format;
snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
if (format == RTAUDIO_SINT8)
deviceFormat = SND_PCM_FORMAT_S8;
else if (format == RTAUDIO_SINT16)
deviceFormat = SND_PCM_FORMAT_S16;
else if (format == RTAUDIO_SINT24)
deviceFormat = SND_PCM_FORMAT_S24;
else if (format == RTAUDIO_SINT32)
deviceFormat = SND_PCM_FORMAT_S32;
else if (format == RTAUDIO_FLOAT32)
deviceFormat = SND_PCM_FORMAT_FLOAT;
else if (format == RTAUDIO_FLOAT64)
deviceFormat = SND_PCM_FORMAT_FLOAT64;
if (snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0)
{
stream_.deviceFormat[mode] = format;
goto setFormat;
}
// The user requested format is not natively supported by the device.
deviceFormat = SND_PCM_FORMAT_FLOAT64;
if (snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0)
{
stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_FLOAT;
if (snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0)
{
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S32;
if (snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0)
{
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S24;
if (snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0)
{
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S16;
if (snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0)
{
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
goto setFormat;
}
deviceFormat = SND_PCM_FORMAT_S8;
if (snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0)
{
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
goto setFormat;
}
// If we get here, no supported format was found.
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
errorText_ = errorStream_.str();
return FAILURE;
setFormat:
result = snd_pcm_hw_params_set_format(phandle, hw_params, deviceFormat);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine whether byte-swaping is necessary.
stream_.doByteSwap[mode] = false;
if (deviceFormat != SND_PCM_FORMAT_S8)
{
result = snd_pcm_format_cpu_endian(deviceFormat);
if (result == 0)
stream_.doByteSwap[mode] = true;
else if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
}
// Set the sample rate.
result = snd_pcm_hw_params_set_rate_near(phandle, hw_params, (unsigned int *)&sampleRate, 0);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine the number of channels for this device. We support a possible
// minimum device channel number > than the value requested by the user.
stream_.nUserChannels[mode] = channels;
unsigned int value;
result = snd_pcm_hw_params_get_channels_max(hw_params, &value);
unsigned int deviceChannels = value;
if (result < 0 || deviceChannels < channels + firstChannel)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
result = snd_pcm_hw_params_get_channels_min(hw_params, &value);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
deviceChannels = value;
if (deviceChannels < channels + firstChannel) deviceChannels = channels + firstChannel;
stream_.nDeviceChannels[mode] = deviceChannels;
// Set the device channels.
result = snd_pcm_hw_params_set_channels(phandle, hw_params, deviceChannels);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the buffer (or period) size.
int dir = 0;
snd_pcm_uframes_t periodSize = *bufferSize;
result = snd_pcm_hw_params_set_period_size_near(phandle, hw_params, &periodSize, &dir);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
*bufferSize = periodSize;
// Set the buffer number, which in ALSA is referred to as the "period".
unsigned int periods = 0;
if (options && options->flags & RTAUDIO_MINIMIZE_LATENCY) periods = 2;
if (options && options->numberOfBuffers > 0) periods = options->numberOfBuffers;
if (periods < 2) periods = 4; // a fairly safe default value
result = snd_pcm_hw_params_set_periods_near(phandle, hw_params, &periods, &dir);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
// If attempting to setup a duplex stream, the bufferSize parameter
// MUST be the same in both directions!
if (stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.bufferSize = *bufferSize;
// Install the hardware configuration
result = snd_pcm_hw_params(phandle, hw_params);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
#if defined(__RTAUDIO_DEBUG__)
fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
snd_pcm_hw_params_dump(hw_params, out);
#endif
// Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
snd_pcm_sw_params_t *sw_params = NULL;
snd_pcm_sw_params_alloca(&sw_params);
snd_pcm_sw_params_current(phandle, sw_params);
snd_pcm_sw_params_set_start_threshold(phandle, sw_params, *bufferSize);
snd_pcm_sw_params_set_stop_threshold(phandle, sw_params, ULONG_MAX);
snd_pcm_sw_params_set_silence_threshold(phandle, sw_params, 0);
// The following two settings were suggested by Theo Veenker
//snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
//snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
// here are two options for a fix
//snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
snd_pcm_uframes_t val;
snd_pcm_sw_params_get_boundary(sw_params, &val);
snd_pcm_sw_params_set_silence_size(phandle, sw_params, val);
result = snd_pcm_sw_params(phandle, sw_params);
if (result < 0)
{
snd_pcm_close(phandle);
errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
return FAILURE;
}
#if defined(__RTAUDIO_DEBUG__)
fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
snd_pcm_sw_params_dump(sw_params, out);
#endif
// Set flags for buffer conversion
stream_.doConvertBuffer[mode] = false;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1)
stream_.doConvertBuffer[mode] = true;
// Allocate the ApiHandle if necessary and then save.
AlsaHandle *apiInfo = 0;
if (stream_.apiHandle == 0)
{
try
{
apiInfo = (AlsaHandle *)new AlsaHandle;
}
catch (std::bad_alloc &)
{
errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
goto error;
}
if (pthread_cond_init(&apiInfo->runnable_cv, NULL))
{
errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *)apiInfo;
apiInfo->handles[0] = 0;
apiInfo->handles[1] = 0;
}
else
{
apiInfo = (AlsaHandle *)stream_.apiHandle;
}
apiInfo->handles[mode] = phandle;
phandle = 0;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes(stream_.userFormat);
stream_.userBuffer[mode] = (char *)calloc(bufferBytes, 1);
if (stream_.userBuffer[mode] == NULL)
{
errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if (stream_.doConvertBuffer[mode])
{
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes(stream_.deviceFormat[mode]);
if (mode == INPUT)
{
if (stream_.mode == OUTPUT && stream_.deviceBuffer)
{
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if (bufferBytes <= bytesOut) makeBuffer = false;
}
}
if (makeBuffer)
{
bufferBytes *= *bufferSize;
if (stream_.deviceBuffer) free(stream_.deviceBuffer);
stream_.deviceBuffer = (char *)calloc(bufferBytes, 1);
if (stream_.deviceBuffer == NULL)
{
errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.sampleRate = sampleRate;
stream_.nBuffers = periods;
stream_.device[mode] = device;
stream_.state = STREAM_STOPPED;
// Setup the buffer conversion information structure.
if (stream_.doConvertBuffer[mode]) setConvertInfo(mode, firstChannel);
// Setup thread if necessary.
if (stream_.mode == OUTPUT && mode == INPUT)
{
// We had already set up an output stream.
stream_.mode = DUPLEX;
// Link the streams if possible.
apiInfo->synchronized = false;
if (snd_pcm_link(apiInfo->handles[0], apiInfo->handles[1]) == 0)
apiInfo->synchronized = true;
else
{
errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
error(RtAudioError::WARNING);
}
}
else
{
stream_.mode = mode;
// Setup callback thread.
stream_.callbackInfo.object = (void *)this;
// Set the thread attributes for joinable and realtime scheduling
// priority (optional). The higher priority will only take affect
// if the program is run as root or suid. Note, under Linux
// processes with CAP_SYS_NICE privilege, a user can change
// scheduling policy and priority (thus need not be root). See
// POSIX "capabilities".
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
if (options && options->flags & RTAUDIO_SCHEDULE_REALTIME)
{
// We previously attempted to increase the audio callback priority
// to SCHED_RR here via the attributes. However, while no errors
// were reported in doing so, it did not work. So, now this is
// done in the alsaCallbackHandler function.
stream_.callbackInfo.doRealtime = true;
int priority = options->priority;
int min = sched_get_priority_min(SCHED_RR);
int max = sched_get_priority_max(SCHED_RR);
if (priority < min)
priority = min;
else if (priority > max)
priority = max;
stream_.callbackInfo.priority = priority;
}
#endif
stream_.callbackInfo.isRunning = true;
result = pthread_create(&stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo);
pthread_attr_destroy(&attr);
if (result)
{
stream_.callbackInfo.isRunning = false;
errorText_ = "RtApiAlsa::error creating callback thread!";
goto error;
}
}
return SUCCESS;
error:
if (apiInfo)
{
pthread_cond_destroy(&apiInfo->runnable_cv);
if (apiInfo->handles[0]) snd_pcm_close(apiInfo->handles[0]);
if (apiInfo->handles[1]) snd_pcm_close(apiInfo->handles[1]);
delete apiInfo;
stream_.apiHandle = 0;
}
if (phandle) snd_pcm_close(phandle);
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.state = STREAM_CLOSED;
return FAILURE;
}
void RtApiAlsa ::closeStream()
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
error(RtAudioError::WARNING);
return;
}
AlsaHandle *apiInfo = (AlsaHandle *)stream_.apiHandle;
stream_.callbackInfo.isRunning = false;
MUTEX_LOCK(&stream_.mutex);
if (stream_.state == STREAM_STOPPED)
{
apiInfo->runnable = true;
pthread_cond_signal(&apiInfo->runnable_cv);
}
MUTEX_UNLOCK(&stream_.mutex);
pthread_join(stream_.callbackInfo.thread, NULL);
if (stream_.state == STREAM_RUNNING)
{
stream_.state = STREAM_STOPPED;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
snd_pcm_drop(apiInfo->handles[0]);
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
snd_pcm_drop(apiInfo->handles[1]);
}
if (apiInfo)
{
pthread_cond_destroy(&apiInfo->runnable_cv);
if (apiInfo->handles[0]) snd_pcm_close(apiInfo->handles[0]);
if (apiInfo->handles[1]) snd_pcm_close(apiInfo->handles[1]);
delete apiInfo;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
}
void RtApiAlsa ::startStream()
{
// This method calls snd_pcm_prepare if the device isn't already in that state.
verifyStream();
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
error(RtAudioError::WARNING);
return;
}
MUTEX_LOCK(&stream_.mutex);
int result = 0;
snd_pcm_state_t state;
AlsaHandle *apiInfo = (AlsaHandle *)stream_.apiHandle;
snd_pcm_t **handle = (snd_pcm_t **)apiInfo->handles;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
state = snd_pcm_state(handle[0]);
if (state != SND_PCM_STATE_PREPARED)
{
result = snd_pcm_prepare(handle[0]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
}
if ((stream_.mode == INPUT || stream_.mode == DUPLEX) && !apiInfo->synchronized)
{
result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open
state = snd_pcm_state(handle[1]);
if (state != SND_PCM_STATE_PREPARED)
{
result = snd_pcm_prepare(handle[1]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
}
stream_.state = STREAM_RUNNING;
unlock:
apiInfo->runnable = true;
pthread_cond_signal(&apiInfo->runnable_cv);
MUTEX_UNLOCK(&stream_.mutex);
if (result >= 0) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiAlsa ::stopStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK(&stream_.mutex);
int result = 0;
AlsaHandle *apiInfo = (AlsaHandle *)stream_.apiHandle;
snd_pcm_t **handle = (snd_pcm_t **)apiInfo->handles;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (apiInfo->synchronized)
result = snd_pcm_drop(handle[0]);
else
result = snd_pcm_drain(handle[0]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
if ((stream_.mode == INPUT || stream_.mode == DUPLEX) && !apiInfo->synchronized)
{
result = snd_pcm_drop(handle[1]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
apiInfo->runnable = false; // fixes high CPU usage when stopped
MUTEX_UNLOCK(&stream_.mutex);
if (result >= 0) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiAlsa ::abortStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK(&stream_.mutex);
int result = 0;
AlsaHandle *apiInfo = (AlsaHandle *)stream_.apiHandle;
snd_pcm_t **handle = (snd_pcm_t **)apiInfo->handles;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
result = snd_pcm_drop(handle[0]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
if ((stream_.mode == INPUT || stream_.mode == DUPLEX) && !apiInfo->synchronized)
{
result = snd_pcm_drop(handle[1]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
apiInfo->runnable = false; // fixes high CPU usage when stopped
MUTEX_UNLOCK(&stream_.mutex);
if (result >= 0) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiAlsa ::callbackEvent()
{
AlsaHandle *apiInfo = (AlsaHandle *)stream_.apiHandle;
if (stream_.state == STREAM_STOPPED)
{
MUTEX_LOCK(&stream_.mutex);
while (!apiInfo->runnable)
pthread_cond_wait(&apiInfo->runnable_cv, &stream_.mutex);
if (stream_.state != STREAM_RUNNING)
{
MUTEX_UNLOCK(&stream_.mutex);
return;
}
MUTEX_UNLOCK(&stream_.mutex);
}
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
error(RtAudioError::WARNING);
return;
}
int doStopStream = 0;
RtAudioCallback callback = (RtAudioCallback)stream_.callbackInfo.callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if (stream_.mode != INPUT && apiInfo->xrun[0] == true)
{
status |= RTAUDIO_OUTPUT_UNDERFLOW;
apiInfo->xrun[0] = false;
}
if (stream_.mode != OUTPUT && apiInfo->xrun[1] == true)
{
status |= RTAUDIO_INPUT_OVERFLOW;
apiInfo->xrun[1] = false;
}
doStopStream = callback(stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData);
if (doStopStream == 2)
{
abortStream();
return;
}
MUTEX_LOCK(&stream_.mutex);
// The state might change while waiting on a mutex.
if (stream_.state == STREAM_STOPPED) goto unlock;
int result;
char *buffer;
int channels;
snd_pcm_t **handle;
snd_pcm_sframes_t frames;
RtAudioFormat format;
handle = (snd_pcm_t **)apiInfo->handles;
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
// Setup parameters.
if (stream_.doConvertBuffer[1])
{
buffer = stream_.deviceBuffer;
channels = stream_.nDeviceChannels[1];
format = stream_.deviceFormat[1];
}
else
{
buffer = stream_.userBuffer[1];
channels = stream_.nUserChannels[1];
format = stream_.userFormat;
}
// Read samples from device in interleaved/non-interleaved format.
if (stream_.deviceInterleaved[1])
result = snd_pcm_readi(handle[1], buffer, stream_.bufferSize);
else
{
void *bufs[channels];
size_t offset = stream_.bufferSize * formatBytes(format);
for (int i = 0; i < channels; i++)
bufs[i] = (void *)(buffer + (i * offset));
result = snd_pcm_readn(handle[1], bufs, stream_.bufferSize);
}
if (result < (int)stream_.bufferSize)
{
// Either an error or overrun occured.
if (result == -EPIPE)
{
snd_pcm_state_t state = snd_pcm_state(handle[1]);
if (state == SND_PCM_STATE_XRUN)
{
apiInfo->xrun[1] = true;
result = snd_pcm_prepare(handle[1]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
}
}
else
{
errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name(state) << ", " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
}
}
else
{
errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
}
error(RtAudioError::WARNING);
goto tryOutput;
}
// Do byte swapping if necessary.
if (stream_.doByteSwap[1])
byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
// Do buffer conversion if necessary.
if (stream_.doConvertBuffer[1])
convertBuffer(stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1]);
// Check stream latency
result = snd_pcm_delay(handle[1], &frames);
if (result == 0 && frames > 0) stream_.latency[1] = frames;
}
tryOutput:
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
// Setup parameters and do buffer conversion if necessary.
if (stream_.doConvertBuffer[0])
{
buffer = stream_.deviceBuffer;
convertBuffer(buffer, stream_.userBuffer[0], stream_.convertInfo[0]);
channels = stream_.nDeviceChannels[0];
format = stream_.deviceFormat[0];
}
else
{
buffer = stream_.userBuffer[0];
channels = stream_.nUserChannels[0];
format = stream_.userFormat;
}
// Do byte swapping if necessary.
if (stream_.doByteSwap[0])
byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
// Write samples to device in interleaved/non-interleaved format.
if (stream_.deviceInterleaved[0])
result = snd_pcm_writei(handle[0], buffer, stream_.bufferSize);
else
{
void *bufs[channels];
size_t offset = stream_.bufferSize * formatBytes(format);
for (int i = 0; i < channels; i++)
bufs[i] = (void *)(buffer + (i * offset));
result = snd_pcm_writen(handle[0], bufs, stream_.bufferSize);
}
if (result < (int)stream_.bufferSize)
{
// Either an error or underrun occured.
if (result == -EPIPE)
{
snd_pcm_state_t state = snd_pcm_state(handle[0]);
if (state == SND_PCM_STATE_XRUN)
{
apiInfo->xrun[0] = true;
result = snd_pcm_prepare(handle[0]);
if (result < 0)
{
errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
}
else
errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun.";
}
else
{
errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name(state) << ", " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
}
}
else
{
errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror(result) << ".";
errorText_ = errorStream_.str();
}
error(RtAudioError::WARNING);
goto unlock;
}
// Check stream latency
result = snd_pcm_delay(handle[0], &frames);
if (result == 0 && frames > 0) stream_.latency[0] = frames;
}
unlock:
MUTEX_UNLOCK(&stream_.mutex);
RtApi::tickStreamTime();
if (doStopStream == 1) this->stopStream();
}
static void *alsaCallbackHandler(void *ptr)
{
CallbackInfo *info = (CallbackInfo *)ptr;
RtApiAlsa *object = (RtApiAlsa *)info->object;
bool *isRunning = &info->isRunning;
#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
if (info->doRealtime)
{
pthread_t tID = pthread_self(); // ID of this thread
sched_param prio = {info->priority}; // scheduling priority of thread
pthread_setschedparam(tID, SCHED_RR, &prio);
}
#endif
while (*isRunning == true)
{
pthread_testcancel();
object->callbackEvent();
}
pthread_exit(NULL);
}
//******************** End of __LINUX_ALSA__ *********************//
#endif
#if defined(__LINUX_PULSE__)
// Code written by Peter Meerwald, pmeerw@pmeerw.net
// and Tristan Matthews.
#include <pulse/error.h>
#include <pulse/simple.h>
#include <cstdio>
static const unsigned int SUPPORTED_SAMPLERATES[] = {8000, 16000, 22050, 32000,
44100, 48000, 96000, 0};
struct rtaudio_pa_format_mapping_t
{
RtAudioFormat rtaudio_format;
pa_sample_format_t pa_format;
};
static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {
{RTAUDIO_SINT16, PA_SAMPLE_S16LE},
{RTAUDIO_SINT32, PA_SAMPLE_S32LE},
{RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},
{0, PA_SAMPLE_INVALID}};
struct PulseAudioHandle
{
pa_simple *s_play;
pa_simple *s_rec;
pthread_t thread;
pthread_cond_t runnable_cv;
bool runnable;
PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) {}
};
RtApiPulse::~RtApiPulse()
{
if (stream_.state != STREAM_CLOSED)
closeStream();
}
unsigned int RtApiPulse::getDeviceCount(void)
{
return 1;
}
RtAudio::DeviceInfo RtApiPulse::getDeviceInfo(unsigned int /*device*/)
{
RtAudio::DeviceInfo info;
info.probed = true;
info.name = "PulseAudio";
info.outputChannels = 2;
info.inputChannels = 2;
info.duplexChannels = 2;
info.isDefaultOutput = true;
info.isDefaultInput = true;
for (const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr)
info.sampleRates.push_back(*sr);
info.preferredSampleRate = 48000;
info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;
return info;
}
static void *pulseaudio_callback(void *user)
{
CallbackInfo *cbi = static_cast<CallbackInfo *>(user);
RtApiPulse *context = static_cast<RtApiPulse *>(cbi->object);
volatile bool *isRunning = &cbi->isRunning;
while (*isRunning)
{
pthread_testcancel();
context->callbackEvent();
}
pthread_exit(NULL);
}
void RtApiPulse::closeStream(void)
{
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>(stream_.apiHandle);
stream_.callbackInfo.isRunning = false;
if (pah)
{
MUTEX_LOCK(&stream_.mutex);
if (stream_.state == STREAM_STOPPED)
{
pah->runnable = true;
pthread_cond_signal(&pah->runnable_cv);
}
MUTEX_UNLOCK(&stream_.mutex);
pthread_join(pah->thread, 0);
if (pah->s_play)
{
pa_simple_flush(pah->s_play, NULL);
pa_simple_free(pah->s_play);
}
if (pah->s_rec)
pa_simple_free(pah->s_rec);
pthread_cond_destroy(&pah->runnable_cv);
delete pah;
stream_.apiHandle = 0;
}
if (stream_.userBuffer[0])
{
free(stream_.userBuffer[0]);
stream_.userBuffer[0] = 0;
}
if (stream_.userBuffer[1])
{
free(stream_.userBuffer[1]);
stream_.userBuffer[1] = 0;
}
stream_.state = STREAM_CLOSED;
stream_.mode = UNINITIALIZED;
}
void RtApiPulse::callbackEvent(void)
{
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>(stream_.apiHandle);
if (stream_.state == STREAM_STOPPED)
{
MUTEX_LOCK(&stream_.mutex);
while (!pah->runnable)
pthread_cond_wait(&pah->runnable_cv, &stream_.mutex);
if (stream_.state != STREAM_RUNNING)
{
MUTEX_UNLOCK(&stream_.mutex);
return;
}
MUTEX_UNLOCK(&stream_.mutex);
}
if (stream_.state == STREAM_CLOSED)
{
errorText_ =
"RtApiPulse::callbackEvent(): the stream is closed ... "
"this shouldn't happen!";
error(RtAudioError::WARNING);
return;
}
RtAudioCallback callback = (RtAudioCallback)stream_.callbackInfo.callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
int doStopStream = callback(stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],
stream_.bufferSize, streamTime, status,
stream_.callbackInfo.userData);
if (doStopStream == 2)
{
abortStream();
return;
}
MUTEX_LOCK(&stream_.mutex);
void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];
void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];
if (stream_.state != STREAM_RUNNING)
goto unlock;
int pa_error;
size_t bytes;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
if (stream_.doConvertBuffer[OUTPUT])
{
convertBuffer(stream_.deviceBuffer,
stream_.userBuffer[OUTPUT],
stream_.convertInfo[OUTPUT]);
bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *
formatBytes(stream_.deviceFormat[OUTPUT]);
}
else
bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *
formatBytes(stream_.userFormat);
if (pa_simple_write(pah->s_play, pulse_out, bytes, &pa_error) < 0)
{
errorStream_ << "RtApiPulse::callbackEvent: audio write error, " << pa_strerror(pa_error) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
}
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
if (stream_.doConvertBuffer[INPUT])
bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *
formatBytes(stream_.deviceFormat[INPUT]);
else
bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *
formatBytes(stream_.userFormat);
if (pa_simple_read(pah->s_rec, pulse_in, bytes, &pa_error) < 0)
{
errorStream_ << "RtApiPulse::callbackEvent: audio read error, " << pa_strerror(pa_error) << ".";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
}
if (stream_.doConvertBuffer[INPUT])
{
convertBuffer(stream_.userBuffer[INPUT],
stream_.deviceBuffer,
stream_.convertInfo[INPUT]);
}
}
unlock:
MUTEX_UNLOCK(&stream_.mutex);
RtApi::tickStreamTime();
if (doStopStream == 1)
stopStream();
}
void RtApiPulse::startStream(void)
{
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>(stream_.apiHandle);
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiPulse::startStream(): the stream is not open!";
error(RtAudioError::INVALID_USE);
return;
}
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiPulse::startStream(): the stream is already running!";
error(RtAudioError::WARNING);
return;
}
MUTEX_LOCK(&stream_.mutex);
stream_.state = STREAM_RUNNING;
pah->runnable = true;
pthread_cond_signal(&pah->runnable_cv);
MUTEX_UNLOCK(&stream_.mutex);
}
void RtApiPulse::stopStream(void)
{
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>(stream_.apiHandle);
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiPulse::stopStream(): the stream is not open!";
error(RtAudioError::INVALID_USE);
return;
}
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK(&stream_.mutex);
if (pah && pah->s_play)
{
int pa_error;
if (pa_simple_drain(pah->s_play, &pa_error) < 0)
{
errorStream_ << "RtApiPulse::stopStream: error draining output device, " << pa_strerror(pa_error) << ".";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
}
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK(&stream_.mutex);
}
void RtApiPulse::abortStream(void)
{
PulseAudioHandle *pah = static_cast<PulseAudioHandle *>(stream_.apiHandle);
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiPulse::abortStream(): the stream is not open!";
error(RtAudioError::INVALID_USE);
return;
}
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
stream_.state = STREAM_STOPPED;
MUTEX_LOCK(&stream_.mutex);
if (pah && pah->s_play)
{
int pa_error;
if (pa_simple_flush(pah->s_play, &pa_error) < 0)
{
errorStream_ << "RtApiPulse::abortStream: error flushing output device, " << pa_strerror(pa_error) << ".";
errorText_ = errorStream_.str();
MUTEX_UNLOCK(&stream_.mutex);
error(RtAudioError::SYSTEM_ERROR);
return;
}
}
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK(&stream_.mutex);
}
bool RtApiPulse::probeDeviceOpen(unsigned int device, StreamMode mode,
unsigned int channels, unsigned int firstChannel,
unsigned int sampleRate, RtAudioFormat format,
unsigned int *bufferSize, RtAudio::StreamOptions *options)
{
PulseAudioHandle *pah = 0;
unsigned long bufferBytes = 0;
pa_sample_spec ss;
if (device != 0) return false;
if (mode != INPUT && mode != OUTPUT) return false;
if (channels != 1 && channels != 2)
{
errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";
return false;
}
ss.channels = channels;
if (firstChannel != 0) return false;
bool sr_found = false;
for (const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr)
{
if (sampleRate == *sr)
{
sr_found = true;
stream_.sampleRate = sampleRate;
ss.rate = sampleRate;
break;
}
}
if (!sr_found)
{
errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";
return false;
}
bool sf_found = 0;
for (const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;
sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf)
{
if (format == sf->rtaudio_format)
{
sf_found = true;
stream_.userFormat = sf->rtaudio_format;
stream_.deviceFormat[mode] = stream_.userFormat;
ss.format = sf->pa_format;
break;
}
}
if (!sf_found)
{ // Use internal data format conversion.
stream_.userFormat = format;
stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
ss.format = PA_SAMPLE_FLOAT32LE;
}
// Set other stream parameters.
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
stream_.userInterleaved = false;
else
stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
stream_.nBuffers = 1;
stream_.doByteSwap[mode] = false;
stream_.nUserChannels[mode] = channels;
stream_.nDeviceChannels[mode] = channels + firstChannel;
stream_.channelOffset[mode] = 0;
std::string streamName = "RtAudio";
// Set flags for buffer conversion.
stream_.doConvertBuffer[mode] = false;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode])
stream_.doConvertBuffer[mode] = true;
// Allocate necessary internal buffers.
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes(stream_.userFormat);
stream_.userBuffer[mode] = (char *)calloc(bufferBytes, 1);
if (stream_.userBuffer[mode] == NULL)
{
errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
stream_.bufferSize = *bufferSize;
if (stream_.doConvertBuffer[mode])
{
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes(stream_.deviceFormat[mode]);
if (mode == INPUT)
{
if (stream_.mode == OUTPUT && stream_.deviceBuffer)
{
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if (bufferBytes <= bytesOut) makeBuffer = false;
}
}
if (makeBuffer)
{
bufferBytes *= *bufferSize;
if (stream_.deviceBuffer) free(stream_.deviceBuffer);
stream_.deviceBuffer = (char *)calloc(bufferBytes, 1);
if (stream_.deviceBuffer == NULL)
{
errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.device[mode] = device;
// Setup the buffer conversion information structure.
if (stream_.doConvertBuffer[mode]) setConvertInfo(mode, firstChannel);
if (!stream_.apiHandle)
{
PulseAudioHandle *pah = new PulseAudioHandle;
if (!pah)
{
errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";
goto error;
}
stream_.apiHandle = pah;
if (pthread_cond_init(&pah->runnable_cv, NULL) != 0)
{
errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";
goto error;
}
}
pah = static_cast<PulseAudioHandle *>(stream_.apiHandle);
int error;
if (options && !options->streamName.empty()) streamName = options->streamName;
switch (mode)
{
case INPUT:
pa_buffer_attr buffer_attr;
buffer_attr.fragsize = bufferBytes;
buffer_attr.maxlength = -1;
pah->s_rec = pa_simple_new(NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error);
if (!pah->s_rec)
{
errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";
goto error;
}
break;
case OUTPUT:
pah->s_play = pa_simple_new(NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error);
if (!pah->s_play)
{
errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";
goto error;
}
break;
default:
goto error;
}
if (stream_.mode == UNINITIALIZED)
stream_.mode = mode;
else if (stream_.mode == mode)
goto error;
else
stream_.mode = DUPLEX;
if (!stream_.callbackInfo.isRunning)
{
stream_.callbackInfo.object = this;
stream_.callbackInfo.isRunning = true;
if (pthread_create(&pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo) != 0)
{
errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";
goto error;
}
}
stream_.state = STREAM_STOPPED;
return true;
error:
if (pah && stream_.callbackInfo.isRunning)
{
pthread_cond_destroy(&pah->runnable_cv);
delete pah;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
return FAILURE;
}
//******************** End of __LINUX_PULSE__ *********************//
#endif
#if defined(__LINUX_OSS__)
#include <unistd.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#include <errno.h>
#include <math.h>
static void *ossCallbackHandler(void *ptr);
// A structure to hold various information related to the OSS API
// implementation.
struct OssHandle
{
int id[2]; // device ids
bool xrun[2];
bool triggered;
pthread_cond_t runnable;
OssHandle()
: triggered(false)
{
id[0] = 0;
id[1] = 0;
xrun[0] = false;
xrun[1] = false;
}
};
RtApiOss ::RtApiOss()
{
// Nothing to do here.
}
RtApiOss ::~RtApiOss()
{
if (stream_.state != STREAM_CLOSED) closeStream();
}
unsigned int RtApiOss ::getDeviceCount(void)
{
int mixerfd = open("/dev/mixer", O_RDWR, 0);
if (mixerfd == -1)
{
errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
error(RtAudioError::WARNING);
return 0;
}
oss_sysinfo sysinfo;
if (ioctl(mixerfd, SNDCTL_SYSINFO, &sysinfo) == -1)
{
close(mixerfd);
errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
error(RtAudioError::WARNING);
return 0;
}
close(mixerfd);
return sysinfo.numaudios;
}
RtAudio::DeviceInfo RtApiOss ::getDeviceInfo(unsigned int device)
{
RtAudio::DeviceInfo info;
info.probed = false;
int mixerfd = open("/dev/mixer", O_RDWR, 0);
if (mixerfd == -1)
{
errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
error(RtAudioError::WARNING);
return info;
}
oss_sysinfo sysinfo;
int result = ioctl(mixerfd, SNDCTL_SYSINFO, &sysinfo);
if (result == -1)
{
close(mixerfd);
errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
error(RtAudioError::WARNING);
return info;
}
unsigned nDevices = sysinfo.numaudios;
if (nDevices == 0)
{
close(mixerfd);
errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
error(RtAudioError::INVALID_USE);
return info;
}
if (device >= nDevices)
{
close(mixerfd);
errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
error(RtAudioError::INVALID_USE);
return info;
}
oss_audioinfo ainfo;
ainfo.dev = device;
result = ioctl(mixerfd, SNDCTL_AUDIOINFO, &ainfo);
close(mixerfd);
if (result == -1)
{
errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Probe channels
if (ainfo.caps & PCM_CAP_OUTPUT) info.outputChannels = ainfo.max_channels;
if (ainfo.caps & PCM_CAP_INPUT) info.inputChannels = ainfo.max_channels;
if (ainfo.caps & PCM_CAP_DUPLEX)
{
if (info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX)
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
}
// Probe data formats ... do for input
unsigned long mask = ainfo.iformats;
if (mask & AFMT_S16_LE || mask & AFMT_S16_BE)
info.nativeFormats |= RTAUDIO_SINT16;
if (mask & AFMT_S8)
info.nativeFormats |= RTAUDIO_SINT8;
if (mask & AFMT_S32_LE || mask & AFMT_S32_BE)
info.nativeFormats |= RTAUDIO_SINT32;
if (mask & AFMT_FLOAT)
info.nativeFormats |= RTAUDIO_FLOAT32;
if (mask & AFMT_S24_LE || mask & AFMT_S24_BE)
info.nativeFormats |= RTAUDIO_SINT24;
// Check that we have at least one supported format
if (info.nativeFormats == 0)
{
errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
return info;
}
// Probe the supported sample rates.
info.sampleRates.clear();
if (ainfo.nrates)
{
for (unsigned int i = 0; i < ainfo.nrates; i++)
{
for (unsigned int k = 0; k < MAX_SAMPLE_RATES; k++)
{
if (ainfo.rates[i] == SAMPLE_RATES[k])
{
info.sampleRates.push_back(SAMPLE_RATES[k]);
if (!info.preferredSampleRate || (SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate))
info.preferredSampleRate = SAMPLE_RATES[k];
break;
}
}
}
}
else
{
// Check min and max rate values;
for (unsigned int k = 0; k < MAX_SAMPLE_RATES; k++)
{
if (ainfo.min_rate <= (int)SAMPLE_RATES[k] && ainfo.max_rate >= (int)SAMPLE_RATES[k])
{
info.sampleRates.push_back(SAMPLE_RATES[k]);
if (!info.preferredSampleRate || (SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate))
info.preferredSampleRate = SAMPLE_RATES[k];
}
}
}
if (info.sampleRates.size() == 0)
{
errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
error(RtAudioError::WARNING);
}
else
{
info.probed = true;
info.name = ainfo.name;
}
return info;
}
bool RtApiOss ::probeDeviceOpen(unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options)
{
int mixerfd = open("/dev/mixer", O_RDWR, 0);
if (mixerfd == -1)
{
errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
return FAILURE;
}
oss_sysinfo sysinfo;
int result = ioctl(mixerfd, SNDCTL_SYSINFO, &sysinfo);
if (result == -1)
{
close(mixerfd);
errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
return FAILURE;
}
unsigned nDevices = sysinfo.numaudios;
if (nDevices == 0)
{
// This should not happen because a check is made before this function is called.
close(mixerfd);
errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
return FAILURE;
}
if (device >= nDevices)
{
// This should not happen because a check is made before this function is called.
close(mixerfd);
errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
oss_audioinfo ainfo;
ainfo.dev = device;
result = ioctl(mixerfd, SNDCTL_AUDIOINFO, &ainfo);
close(mixerfd);
if (result == -1)
{
errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check if device supports input or output
if ((mode == OUTPUT && !(ainfo.caps & PCM_CAP_OUTPUT)) ||
(mode == INPUT && !(ainfo.caps & PCM_CAP_INPUT)))
{
if (mode == OUTPUT)
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
else
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
errorText_ = errorStream_.str();
return FAILURE;
}
int flags = 0;
OssHandle *handle = (OssHandle *)stream_.apiHandle;
if (mode == OUTPUT)
flags |= O_WRONLY;
else
{ // mode == INPUT
if (stream_.mode == OUTPUT && stream_.device[0] == device)
{
// We just set the same device for playback ... close and reopen for duplex (OSS only).
close(handle->id[0]);
handle->id[0] = 0;
if (!(ainfo.caps & PCM_CAP_DUPLEX))
{
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Check that the number previously set channels is the same.
if (stream_.nUserChannels[0] != channels)
{
errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
flags |= O_RDWR;
}
else
flags |= O_RDONLY;
}
// Set exclusive access if specified.
if (options && options->flags & RTAUDIO_HOG_DEVICE) flags |= O_EXCL;
// Try to open the device.
int fd;
fd = open(ainfo.devnode, flags, 0);
if (fd == -1)
{
if (errno == EBUSY)
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
else
errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// For duplex operation, specifically set this mode (this doesn't seem to work).
/*
if ( flags | O_RDWR ) {
result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
if ( result == -1) {
errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
}
*/
// Check the device channel support.
stream_.nUserChannels[mode] = channels;
if (ainfo.max_channels < (int)(channels + firstChannel))
{
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the number of channels.
int deviceChannels = channels + firstChannel;
result = ioctl(fd, SNDCTL_DSP_CHANNELS, &deviceChannels);
if (result == -1 || deviceChannels < (int)(channels + firstChannel))
{
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.nDeviceChannels[mode] = deviceChannels;
// Get the data format mask
int mask;
result = ioctl(fd, SNDCTL_DSP_GETFMTS, &mask);
if (result == -1)
{
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Determine how to set the device format.
stream_.userFormat = format;
int deviceFormat = -1;
stream_.doByteSwap[mode] = false;
if (format == RTAUDIO_SINT8)
{
if (mask & AFMT_S8)
{
deviceFormat = AFMT_S8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
}
else if (format == RTAUDIO_SINT16)
{
if (mask & AFMT_S16_NE)
{
deviceFormat = AFMT_S16_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
else if (mask & AFMT_S16_OE)
{
deviceFormat = AFMT_S16_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
stream_.doByteSwap[mode] = true;
}
}
else if (format == RTAUDIO_SINT24)
{
if (mask & AFMT_S24_NE)
{
deviceFormat = AFMT_S24_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
}
else if (mask & AFMT_S24_OE)
{
deviceFormat = AFMT_S24_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
stream_.doByteSwap[mode] = true;
}
}
else if (format == RTAUDIO_SINT32)
{
if (mask & AFMT_S32_NE)
{
deviceFormat = AFMT_S32_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
}
else if (mask & AFMT_S32_OE)
{
deviceFormat = AFMT_S32_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
stream_.doByteSwap[mode] = true;
}
}
if (deviceFormat == -1)
{
// The user requested format is not natively supported by the device.
if (mask & AFMT_S16_NE)
{
deviceFormat = AFMT_S16_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
}
else if (mask & AFMT_S32_NE)
{
deviceFormat = AFMT_S32_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
}
else if (mask & AFMT_S24_NE)
{
deviceFormat = AFMT_S24_NE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
}
else if (mask & AFMT_S16_OE)
{
deviceFormat = AFMT_S16_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT16;
stream_.doByteSwap[mode] = true;
}
else if (mask & AFMT_S32_OE)
{
deviceFormat = AFMT_S32_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT32;
stream_.doByteSwap[mode] = true;
}
else if (mask & AFMT_S24_OE)
{
deviceFormat = AFMT_S24_OE;
stream_.deviceFormat[mode] = RTAUDIO_SINT24;
stream_.doByteSwap[mode] = true;
}
else if (mask & AFMT_S8)
{
deviceFormat = AFMT_S8;
stream_.deviceFormat[mode] = RTAUDIO_SINT8;
}
}
if (stream_.deviceFormat[mode] == 0)
{
// This really shouldn't happen ...
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
errorText_ = errorStream_.str();
return FAILURE;
}
// Set the data format.
int temp = deviceFormat;
result = ioctl(fd, SNDCTL_DSP_SETFMT, &deviceFormat);
if (result == -1 || deviceFormat != temp)
{
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Attempt to set the buffer size. According to OSS, the minimum
// number of buffers is two. The supposed minimum buffer size is 16
// bytes, so that will be our lower bound. The argument to this
// call is in the form 0xMMMMSSSS (hex), where the buffer size (in
// bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
// We'll check the actual value used near the end of the setup
// procedure.
int ossBufferBytes = *bufferSize * formatBytes(stream_.deviceFormat[mode]) * deviceChannels;
if (ossBufferBytes < 16) ossBufferBytes = 16;
int buffers = 0;
if (options) buffers = options->numberOfBuffers;
if (options && options->flags & RTAUDIO_MINIMIZE_LATENCY) buffers = 2;
if (buffers < 2) buffers = 3;
temp = ((int)buffers << 16) + (int)(log10((double)ossBufferBytes) / log10(2.0));
result = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &temp);
if (result == -1)
{
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.nBuffers = buffers;
// Save buffer size (in sample frames).
*bufferSize = ossBufferBytes / (formatBytes(stream_.deviceFormat[mode]) * deviceChannels);
stream_.bufferSize = *bufferSize;
// Set the sample rate.
int srate = sampleRate;
result = ioctl(fd, SNDCTL_DSP_SPEED, &srate);
if (result == -1)
{
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Verify the sample rate setup worked.
if (abs(srate - sampleRate) > 100)
{
close(fd);
errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
stream_.sampleRate = sampleRate;
if (mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device)
{
// We're doing duplex setup here.
stream_.deviceFormat[0] = stream_.deviceFormat[1];
stream_.nDeviceChannels[0] = deviceChannels;
}
// Set interleaving parameters.
stream_.userInterleaved = true;
stream_.deviceInterleaved[mode] = true;
if (options && options->flags & RTAUDIO_NONINTERLEAVED)
stream_.userInterleaved = false;
// Set flags for buffer conversion
stream_.doConvertBuffer[mode] = false;
if (stream_.userFormat != stream_.deviceFormat[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode])
stream_.doConvertBuffer[mode] = true;
if (stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
stream_.nUserChannels[mode] > 1)
stream_.doConvertBuffer[mode] = true;
// Allocate the stream handles if necessary and then save.
if (stream_.apiHandle == 0)
{
try
{
handle = new OssHandle;
}
catch (std::bad_alloc &)
{
errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
goto error;
}
if (pthread_cond_init(&handle->runnable, NULL))
{
errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
goto error;
}
stream_.apiHandle = (void *)handle;
}
else
{
handle = (OssHandle *)stream_.apiHandle;
}
handle->id[mode] = fd;
// Allocate necessary internal buffers.
unsigned long bufferBytes;
bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes(stream_.userFormat);
stream_.userBuffer[mode] = (char *)calloc(bufferBytes, 1);
if (stream_.userBuffer[mode] == NULL)
{
errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
goto error;
}
if (stream_.doConvertBuffer[mode])
{
bool makeBuffer = true;
bufferBytes = stream_.nDeviceChannels[mode] * formatBytes(stream_.deviceFormat[mode]);
if (mode == INPUT)
{
if (stream_.mode == OUTPUT && stream_.deviceBuffer)
{
unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
if (bufferBytes <= bytesOut) makeBuffer = false;
}
}
if (makeBuffer)
{
bufferBytes *= *bufferSize;
if (stream_.deviceBuffer) free(stream_.deviceBuffer);
stream_.deviceBuffer = (char *)calloc(bufferBytes, 1);
if (stream_.deviceBuffer == NULL)
{
errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
goto error;
}
}
}
stream_.device[mode] = device;
stream_.state = STREAM_STOPPED;
// Setup the buffer conversion information structure.
if (stream_.doConvertBuffer[mode]) setConvertInfo(mode, firstChannel);
// Setup thread if necessary.
if (stream_.mode == OUTPUT && mode == INPUT)
{
// We had already set up an output stream.
stream_.mode = DUPLEX;
if (stream_.device[0] == device) handle->id[0] = fd;
}
else
{
stream_.mode = mode;
// Setup callback thread.
stream_.callbackInfo.object = (void *)this;
// Set the thread attributes for joinable and realtime scheduling
// priority. The higher priority will only take affect if the
// program is run as root or suid.
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
if (options && options->flags & RTAUDIO_SCHEDULE_REALTIME)
{
struct sched_param param;
int priority = options->priority;
int min = sched_get_priority_min(SCHED_RR);
int max = sched_get_priority_max(SCHED_RR);
if (priority < min)
priority = min;
else if (priority > max)
priority = max;
param.sched_priority = priority;
pthread_attr_setschedparam(&attr, ¶m);
pthread_attr_setschedpolicy(&attr, SCHED_RR);
}
else
pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
#else
pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
#endif
stream_.callbackInfo.isRunning = true;
result = pthread_create(&stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo);
pthread_attr_destroy(&attr);
if (result)
{
stream_.callbackInfo.isRunning = false;
errorText_ = "RtApiOss::error creating callback thread!";
goto error;
}
}
return SUCCESS;
error:
if (handle)
{
pthread_cond_destroy(&handle->runnable);
if (handle->id[0]) close(handle->id[0]);
if (handle->id[1]) close(handle->id[1]);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
return FAILURE;
}
void RtApiOss ::closeStream()
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiOss::closeStream(): no open stream to close!";
error(RtAudioError::WARNING);
return;
}
OssHandle *handle = (OssHandle *)stream_.apiHandle;
stream_.callbackInfo.isRunning = false;
MUTEX_LOCK(&stream_.mutex);
if (stream_.state == STREAM_STOPPED)
pthread_cond_signal(&handle->runnable);
MUTEX_UNLOCK(&stream_.mutex);
pthread_join(stream_.callbackInfo.thread, NULL);
if (stream_.state == STREAM_RUNNING)
{
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
ioctl(handle->id[0], SNDCTL_DSP_HALT, 0);
else
ioctl(handle->id[1], SNDCTL_DSP_HALT, 0);
stream_.state = STREAM_STOPPED;
}
if (handle)
{
pthread_cond_destroy(&handle->runnable);
if (handle->id[0]) close(handle->id[0]);
if (handle->id[1]) close(handle->id[1]);
delete handle;
stream_.apiHandle = 0;
}
for (int i = 0; i < 2; i++)
{
if (stream_.userBuffer[i])
{
free(stream_.userBuffer[i]);
stream_.userBuffer[i] = 0;
}
}
if (stream_.deviceBuffer)
{
free(stream_.deviceBuffer);
stream_.deviceBuffer = 0;
}
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
}
void RtApiOss ::startStream()
{
verifyStream();
if (stream_.state == STREAM_RUNNING)
{
errorText_ = "RtApiOss::startStream(): the stream is already running!";
error(RtAudioError::WARNING);
return;
}
MUTEX_LOCK(&stream_.mutex);
stream_.state = STREAM_RUNNING;
// No need to do anything else here ... OSS automatically starts
// when fed samples.
MUTEX_UNLOCK(&stream_.mutex);
OssHandle *handle = (OssHandle *)stream_.apiHandle;
pthread_cond_signal(&handle->runnable);
}
void RtApiOss ::stopStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
MUTEX_LOCK(&stream_.mutex);
// The state might change while waiting on a mutex.
if (stream_.state == STREAM_STOPPED)
{
MUTEX_UNLOCK(&stream_.mutex);
return;
}
int result = 0;
OssHandle *handle = (OssHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
// Flush the output with zeros a few times.
char *buffer;
int samples;
RtAudioFormat format;
if (stream_.doConvertBuffer[0])
{
buffer = stream_.deviceBuffer;
samples = stream_.bufferSize * stream_.nDeviceChannels[0];
format = stream_.deviceFormat[0];
}
else
{
buffer = stream_.userBuffer[0];
samples = stream_.bufferSize * stream_.nUserChannels[0];
format = stream_.userFormat;
}
memset(buffer, 0, samples * formatBytes(format));
for (unsigned int i = 0; i < stream_.nBuffers + 1; i++)
{
result = write(handle->id[0], buffer, samples * formatBytes(format));
if (result == -1)
{
errorText_ = "RtApiOss::stopStream: audio write error.";
error(RtAudioError::WARNING);
}
}
result = ioctl(handle->id[0], SNDCTL_DSP_HALT, 0);
if (result == -1)
{
errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
handle->triggered = false;
}
if (stream_.mode == INPUT || (stream_.mode == DUPLEX && handle->id[0] != handle->id[1]))
{
result = ioctl(handle->id[1], SNDCTL_DSP_HALT, 0);
if (result == -1)
{
errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK(&stream_.mutex);
if (result != -1) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiOss ::abortStream()
{
verifyStream();
if (stream_.state == STREAM_STOPPED)
{
errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
error(RtAudioError::WARNING);
return;
}
MUTEX_LOCK(&stream_.mutex);
// The state might change while waiting on a mutex.
if (stream_.state == STREAM_STOPPED)
{
MUTEX_UNLOCK(&stream_.mutex);
return;
}
int result = 0;
OssHandle *handle = (OssHandle *)stream_.apiHandle;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
result = ioctl(handle->id[0], SNDCTL_DSP_HALT, 0);
if (result == -1)
{
errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
handle->triggered = false;
}
if (stream_.mode == INPUT || (stream_.mode == DUPLEX && handle->id[0] != handle->id[1]))
{
result = ioctl(handle->id[1], SNDCTL_DSP_HALT, 0);
if (result == -1)
{
errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
errorText_ = errorStream_.str();
goto unlock;
}
}
unlock:
stream_.state = STREAM_STOPPED;
MUTEX_UNLOCK(&stream_.mutex);
if (result != -1) return;
error(RtAudioError::SYSTEM_ERROR);
}
void RtApiOss ::callbackEvent()
{
OssHandle *handle = (OssHandle *)stream_.apiHandle;
if (stream_.state == STREAM_STOPPED)
{
MUTEX_LOCK(&stream_.mutex);
pthread_cond_wait(&handle->runnable, &stream_.mutex);
if (stream_.state != STREAM_RUNNING)
{
MUTEX_UNLOCK(&stream_.mutex);
return;
}
MUTEX_UNLOCK(&stream_.mutex);
}
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
error(RtAudioError::WARNING);
return;
}
// Invoke user callback to get fresh output data.
int doStopStream = 0;
RtAudioCallback callback = (RtAudioCallback)stream_.callbackInfo.callback;
double streamTime = getStreamTime();
RtAudioStreamStatus status = 0;
if (stream_.mode != INPUT && handle->xrun[0] == true)
{
status |= RTAUDIO_OUTPUT_UNDERFLOW;
handle->xrun[0] = false;
}
if (stream_.mode != OUTPUT && handle->xrun[1] == true)
{
status |= RTAUDIO_INPUT_OVERFLOW;
handle->xrun[1] = false;
}
doStopStream = callback(stream_.userBuffer[0], stream_.userBuffer[1],
stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData);
if (doStopStream == 2)
{
this->abortStream();
return;
}
MUTEX_LOCK(&stream_.mutex);
// The state might change while waiting on a mutex.
if (stream_.state == STREAM_STOPPED) goto unlock;
int result;
char *buffer;
int samples;
RtAudioFormat format;
if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
{
// Setup parameters and do buffer conversion if necessary.
if (stream_.doConvertBuffer[0])
{
buffer = stream_.deviceBuffer;
convertBuffer(buffer, stream_.userBuffer[0], stream_.convertInfo[0]);
samples = stream_.bufferSize * stream_.nDeviceChannels[0];
format = stream_.deviceFormat[0];
}
else
{
buffer = stream_.userBuffer[0];
samples = stream_.bufferSize * stream_.nUserChannels[0];
format = stream_.userFormat;
}
// Do byte swapping if necessary.
if (stream_.doByteSwap[0])
byteSwapBuffer(buffer, samples, format);
if (stream_.mode == DUPLEX && handle->triggered == false)
{
int trig = 0;
ioctl(handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig);
result = write(handle->id[0], buffer, samples * formatBytes(format));
trig = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
ioctl(handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig);
handle->triggered = true;
}
else
// Write samples to device.
result = write(handle->id[0], buffer, samples * formatBytes(format));
if (result == -1)
{
// We'll assume this is an underrun, though there isn't a
// specific means for determining that.
handle->xrun[0] = true;
errorText_ = "RtApiOss::callbackEvent: audio write error.";
error(RtAudioError::WARNING);
// Continue on to input section.
}
}
if (stream_.mode == INPUT || stream_.mode == DUPLEX)
{
// Setup parameters.
if (stream_.doConvertBuffer[1])
{
buffer = stream_.deviceBuffer;
samples = stream_.bufferSize * stream_.nDeviceChannels[1];
format = stream_.deviceFormat[1];
}
else
{
buffer = stream_.userBuffer[1];
samples = stream_.bufferSize * stream_.nUserChannels[1];
format = stream_.userFormat;
}
// Read samples from device.
result = read(handle->id[1], buffer, samples * formatBytes(format));
if (result == -1)
{
// We'll assume this is an overrun, though there isn't a
// specific means for determining that.
handle->xrun[1] = true;
errorText_ = "RtApiOss::callbackEvent: audio read error.";
error(RtAudioError::WARNING);
goto unlock;
}
// Do byte swapping if necessary.
if (stream_.doByteSwap[1])
byteSwapBuffer(buffer, samples, format);
// Do buffer conversion if necessary.
if (stream_.doConvertBuffer[1])
convertBuffer(stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1]);
}
unlock:
MUTEX_UNLOCK(&stream_.mutex);
RtApi::tickStreamTime();
if (doStopStream == 1) this->stopStream();
}
static void *ossCallbackHandler(void *ptr)
{
CallbackInfo *info = (CallbackInfo *)ptr;
RtApiOss *object = (RtApiOss *)info->object;
bool *isRunning = &info->isRunning;
while (*isRunning == true)
{
pthread_testcancel();
object->callbackEvent();
}
pthread_exit(NULL);
}
//******************** End of __LINUX_OSS__ *********************//
#endif
// *************************************************** //
//
// Protected common (OS-independent) RtAudio methods.
//
// *************************************************** //
// This method can be modified to control the behavior of error
// message printing.
void RtApi ::error(RtAudioError::Type type)
{
errorStream_.str(""); // clear the ostringstream
RtAudioErrorCallback errorCallback = (RtAudioErrorCallback)stream_.callbackInfo.errorCallback;
if (errorCallback)
{
// abortStream() can generate new error messages. Ignore them. Just keep original one.
if (firstErrorOccurred_)
return;
firstErrorOccurred_ = true;
const std::string errorMessage = errorText_;
if (type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED)
{
stream_.callbackInfo.isRunning = false; // exit from the thread
abortStream();
}
errorCallback(type, errorMessage);
firstErrorOccurred_ = false;
return;
}
if (type == RtAudioError::WARNING && showWarnings_ == true)
std::cerr << '\n'
<< errorText_ << "\n\n";
else if (type != RtAudioError::WARNING)
throw(RtAudioError(errorText_, type));
}
void RtApi ::verifyStream()
{
if (stream_.state == STREAM_CLOSED)
{
errorText_ = "RtApi:: a stream is not open!";
error(RtAudioError::INVALID_USE);
}
}
void RtApi ::clearStreamInfo()
{
stream_.mode = UNINITIALIZED;
stream_.state = STREAM_CLOSED;
stream_.sampleRate = 0;
stream_.bufferSize = 0;
stream_.nBuffers = 0;
stream_.userFormat = 0;
stream_.userInterleaved = true;
stream_.streamTime = 0.0;
stream_.apiHandle = 0;
stream_.deviceBuffer = 0;
stream_.callbackInfo.callback = 0;
stream_.callbackInfo.userData = 0;
stream_.callbackInfo.isRunning = false;
stream_.callbackInfo.errorCallback = 0;
for (int i = 0; i < 2; i++)
{
stream_.device[i] = 11111;
stream_.doConvertBuffer[i] = false;
stream_.deviceInterleaved[i] = true;
stream_.doByteSwap[i] = false;
stream_.nUserChannels[i] = 0;
stream_.nDeviceChannels[i] = 0;
stream_.channelOffset[i] = 0;
stream_.deviceFormat[i] = 0;
stream_.latency[i] = 0;
stream_.userBuffer[i] = 0;
stream_.convertInfo[i].channels = 0;
stream_.convertInfo[i].inJump = 0;
stream_.convertInfo[i].outJump = 0;
stream_.convertInfo[i].inFormat = 0;
stream_.convertInfo[i].outFormat = 0;
stream_.convertInfo[i].inOffset.clear();
stream_.convertInfo[i].outOffset.clear();
}
}
unsigned int RtApi ::formatBytes(RtAudioFormat format)
{
if (format == RTAUDIO_SINT16)
return 2;
else if (format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32)
return 4;
else if (format == RTAUDIO_FLOAT64)
return 8;
else if (format == RTAUDIO_SINT24)
return 3;
else if (format == RTAUDIO_SINT8)
return 1;
errorText_ = "RtApi::formatBytes: undefined format.";
error(RtAudioError::WARNING);
return 0;
}
void RtApi ::setConvertInfo(StreamMode mode, unsigned int firstChannel)
{
if (mode == INPUT)
{ // convert device to user buffer
stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
stream_.convertInfo[mode].outFormat = stream_.userFormat;
}
else
{ // convert user to device buffer
stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
stream_.convertInfo[mode].inFormat = stream_.userFormat;
stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
}
if (stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump)
stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
else
stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
// Set up the interleave/deinterleave offsets.
if (stream_.deviceInterleaved[mode] != stream_.userInterleaved)
{
if ((mode == OUTPUT && stream_.deviceInterleaved[mode]) ||
(mode == INPUT && stream_.userInterleaved))
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
{
stream_.convertInfo[mode].inOffset.push_back(k * stream_.bufferSize);
stream_.convertInfo[mode].outOffset.push_back(k);
stream_.convertInfo[mode].inJump = 1;
}
}
else
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
{
stream_.convertInfo[mode].inOffset.push_back(k);
stream_.convertInfo[mode].outOffset.push_back(k * stream_.bufferSize);
stream_.convertInfo[mode].outJump = 1;
}
}
}
else
{ // no (de)interleaving
if (stream_.userInterleaved)
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
{
stream_.convertInfo[mode].inOffset.push_back(k);
stream_.convertInfo[mode].outOffset.push_back(k);
}
}
else
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
{
stream_.convertInfo[mode].inOffset.push_back(k * stream_.bufferSize);
stream_.convertInfo[mode].outOffset.push_back(k * stream_.bufferSize);
stream_.convertInfo[mode].inJump = 1;
stream_.convertInfo[mode].outJump = 1;
}
}
}
// Add channel offset.
if (firstChannel > 0)
{
if (stream_.deviceInterleaved[mode])
{
if (mode == OUTPUT)
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
stream_.convertInfo[mode].outOffset[k] += firstChannel;
}
else
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
stream_.convertInfo[mode].inOffset[k] += firstChannel;
}
}
else
{
if (mode == OUTPUT)
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
stream_.convertInfo[mode].outOffset[k] += (firstChannel * stream_.bufferSize);
}
else
{
for (int k = 0; k < stream_.convertInfo[mode].channels; k++)
stream_.convertInfo[mode].inOffset[k] += (firstChannel * stream_.bufferSize);
}
}
}
}
void RtApi ::convertBuffer(char *outBuffer, char *inBuffer, ConvertInfo &info)
{
// This function does format conversion, input/output channel compensation, and
// data interleaving/deinterleaving. 24-bit integers are assumed to occupy
// the lower three bytes of a 32-bit integer.
// Clear our device buffer when in/out duplex device channels are different
if (outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
(stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1]))
memset(outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes(info.outFormat));
int j;
if (info.outFormat == RTAUDIO_FLOAT64)
{
Float64 scale;
Float64 *out = (Float64 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8)
{
signed char *in = (signed char *)inBuffer;
scale = 1.0 / 127.5;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float64)in[info.inOffset[j]];
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16)
{
Int16 *in = (Int16 *)inBuffer;
scale = 1.0 / 32767.5;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float64)in[info.inOffset[j]];
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24)
{
Int24 *in = (Int24 *)inBuffer;
scale = 1.0 / 8388607.5;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float64)(in[info.inOffset[j]].asInt());
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32)
{
Int32 *in = (Int32 *)inBuffer;
scale = 1.0 / 2147483647.5;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float64)in[info.inOffset[j]];
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32)
{
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float64)in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64)
{
// Channel compensation and/or (de)interleaving only.
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_FLOAT32)
{
Float32 scale;
Float32 *out = (Float32 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8)
{
signed char *in = (signed char *)inBuffer;
scale = (Float32)(1.0 / 127.5);
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float32)in[info.inOffset[j]];
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16)
{
Int16 *in = (Int16 *)inBuffer;
scale = (Float32)(1.0 / 32767.5);
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float32)in[info.inOffset[j]];
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24)
{
Int24 *in = (Int24 *)inBuffer;
scale = (Float32)(1.0 / 8388607.5);
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float32)(in[info.inOffset[j]].asInt());
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32)
{
Int32 *in = (Int32 *)inBuffer;
scale = (Float32)(1.0 / 2147483647.5);
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float32)in[info.inOffset[j]];
out[info.outOffset[j]] += 0.5;
out[info.outOffset[j]] *= scale;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32)
{
// Channel compensation and/or (de)interleaving only.
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64)
{
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Float32)in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT32)
{
Int32 *out = (Int32 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8)
{
signed char *in = (signed char *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)in[info.inOffset[j]];
out[info.outOffset[j]] <<= 24;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16)
{
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)in[info.inOffset[j]];
out[info.outOffset[j]] <<= 16;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24)
{
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)in[info.inOffset[j]].asInt();
out[info.outOffset[j]] <<= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32)
{
// Channel compensation and/or (de)interleaving only.
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32)
{
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)(in[info.inOffset[j]] * 2147483647.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64)
{
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)(in[info.inOffset[j]] * 2147483647.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT24)
{
Int24 *out = (Int24 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8)
{
signed char *in = (signed char *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)(in[info.inOffset[j]] << 16);
//out[info.outOffset[j]] <<= 16;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16)
{
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)(in[info.inOffset[j]] << 8);
//out[info.outOffset[j]] <<= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24)
{
// Channel compensation and/or (de)interleaving only.
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32)
{
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)(in[info.inOffset[j]] >> 8);
//out[info.outOffset[j]] >>= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32)
{
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)(in[info.inOffset[j]] * 8388607.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64)
{
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int32)(in[info.inOffset[j]] * 8388607.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT16)
{
Int16 *out = (Int16 *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8)
{
signed char *in = (signed char *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int16)in[info.inOffset[j]];
out[info.outOffset[j]] <<= 8;
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT16)
{
// Channel compensation and/or (de)interleaving only.
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24)
{
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int16)(in[info.inOffset[j]].asInt() >> 8);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32)
{
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int16)((in[info.inOffset[j]] >> 16) & 0x0000ffff);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32)
{
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int16)(in[info.inOffset[j]] * 32767.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64)
{
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (Int16)(in[info.inOffset[j]] * 32767.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
}
else if (info.outFormat == RTAUDIO_SINT8)
{
signed char *out = (signed char *)outBuffer;
if (info.inFormat == RTAUDIO_SINT8)
{
// Channel compensation and/or (de)interleaving only.
signed char *in = (signed char *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = in[info.inOffset[j]];
}
in += info.inJump;
out += info.outJump;
}
}
if (info.inFormat == RTAUDIO_SINT16)
{
Int16 *in = (Int16 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (signed char)((in[info.inOffset[j]] >> 8) & 0x00ff);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT24)
{
Int24 *in = (Int24 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (signed char)(in[info.inOffset[j]].asInt() >> 16);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_SINT32)
{
Int32 *in = (Int32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (signed char)((in[info.inOffset[j]] >> 24) & 0x000000ff);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT32)
{
Float32 *in = (Float32 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (signed char)(in[info.inOffset[j]] * 127.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
else if (info.inFormat == RTAUDIO_FLOAT64)
{
Float64 *in = (Float64 *)inBuffer;
for (unsigned int i = 0; i < stream_.bufferSize; i++)
{
for (j = 0; j < info.channels; j++)
{
out[info.outOffset[j]] = (signed char)(in[info.inOffset[j]] * 127.5 - 0.5);
}
in += info.inJump;
out += info.outJump;
}
}
}
}
//static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
//static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
//static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
void RtApi ::byteSwapBuffer(char *buffer, unsigned int samples, RtAudioFormat format)
{
char val;
char *ptr;
ptr = buffer;
if (format == RTAUDIO_SINT16)
{
for (unsigned int i = 0; i < samples; i++)
{
// Swap 1st and 2nd bytes.
val = *(ptr);
*(ptr) = *(ptr + 1);
*(ptr + 1) = val;
// Increment 2 bytes.
ptr += 2;
}
}
else if (format == RTAUDIO_SINT32 ||
format == RTAUDIO_FLOAT32)
{
for (unsigned int i = 0; i < samples; i++)
{
// Swap 1st and 4th bytes.
val = *(ptr);
*(ptr) = *(ptr + 3);
*(ptr + 3) = val;
// Swap 2nd and 3rd bytes.
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr + 1);
*(ptr + 1) = val;
// Increment 3 more bytes.
ptr += 3;
}
}
else if (format == RTAUDIO_SINT24)
{
for (unsigned int i = 0; i < samples; i++)
{
// Swap 1st and 3rd bytes.
val = *(ptr);
*(ptr) = *(ptr + 2);
*(ptr + 2) = val;
// Increment 2 more bytes.
ptr += 2;
}
}
else if (format == RTAUDIO_FLOAT64)
{
for (unsigned int i = 0; i < samples; i++)
{
// Swap 1st and 8th bytes
val = *(ptr);
*(ptr) = *(ptr + 7);
*(ptr + 7) = val;
// Swap 2nd and 7th bytes
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr + 5);
*(ptr + 5) = val;
// Swap 3rd and 6th bytes
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr + 3);
*(ptr + 3) = val;
// Swap 4th and 5th bytes
ptr += 1;
val = *(ptr);
*(ptr) = *(ptr + 1);
*(ptr + 1) = val;
// Increment 5 more bytes.
ptr += 5;
}
}
}
// Indentation settings for Vim and Emacs
//
// Local Variables:
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:
//
// vim: et sts=2 sw=2
|
9dc8224570da243e8663b6ef7bc0d7e5b404e1e4 | 3ea89940622fdedd3122a94d9c0b0b39cdb1eba5 | /UVa/532 Dungeon Master.cpp | 8fb582f13c787817cc16fe05ff959edcbffa6444 | [] | no_license | Mr-Bangladesh/Problem-Solving | aba2ea1306551528bcc4963bbdb6b3a843a4fa1d | 2d8aebe50fc8df467bbc9dc8b09bc171de551414 | refs/heads/master | 2023-08-02T08:20:37.830119 | 2021-09-05T11:50:36 | 2021-09-05T11:50:36 | 401,593,516 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,900 | cpp | 532 Dungeon Master.cpp | ///***Bismillahir Rahmanir Rahim***
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 100000000000000000
#define pb push_back
#define mp make_pair
///cin.ignore();
void FastIO()
{
ios_base:: sync_with_stdio(false);
cin.tie(0);
cout.precision(20);
}
ll max(ll a,ll b)
{
if(a>b) return a;
else return b;
}
ll min(ll a,ll b)
{
if(a<b) return a;
else return b;
}
ll pow(ll B,ll P)
{
ll S=1;
for(ll i=1; i<=P; i++) S=S*B;
return S;
}
///***Faizul***CSE**4th batch**BU
int fx[]= {1,-1,0,0,0,0};
int fy[]= {0,0,1,-1,0,0};
int fz[]= {0,0,0,0,1,-1};
struct nodes
{
int a;
int b;
int c;
nodes(int x,int y,int z)
{
a=x;
b=y;
c=z;
}
};
int dist[35][35][35];
int graph[35][35][35];
void BFS(int s1,int s2,int s3,int L,int R,int C)
{
int visited[35][35][35];
memset(visited,0,sizeof(visited));
queue<nodes> Q;
Q.push(nodes(s1,s2,s3));
while(!Q.empty())
{
nodes u=Q.front();
Q.pop();
int u1=u.a;
int u2=u.b;
int u3=u.c;
for(int j=0; j<6; j++)
{
int v1=u1+fz[j];
int v2=u2+fx[j];
int v3=u3+fy[j];
if(visited[v1][v2][v3]==0 && v1>=0 && v2>=0 && v3>=0 && v1<L && v2<R && v3<C && graph[v1][v2][v3]!=2)
{
visited[v1][v2][v3]=1;
//cout<<"visited "<<v1<<v2<<v3<<endl;
Q.push(nodes(v1,v2,v3));
dist[v1][v2][v3]=dist[u1][u2][u3]+1;
}
}
}
}
int main()
{
FastIO();
//freopen("1.txt","r",stdin);
int L,R,C;
while(cin>>L>>R>>C)
{
if(L==0 && R==0 && C==0) break;
memset(dist,0,sizeof(dist));
memset(graph,0,sizeof(graph));
string S[35][35];
int s1,s2,s3,d1,d2,d3;
for(int i=0; i<L; i++)
{
for(int j=0; j<R; j++)
{
cin>>S[i][j];
for(int k=0; k<C; k++)
{
if(S[i][j][k]=='.') graph[i][j][k]=1;
else if(S[i][j][k]=='#') graph[i][j][k]=2;
else if(S[i][j][k]=='S')
{
s1=i;
s2=j;
s3=k;
}
else if(S[i][j][k]=='E')
{
d1=i;
d2=j;
d3=k;
}
}
}
}
BFS(s1,s2,s3,L,R,C);
int ans=dist[d1][d2][d3];
if(ans>0) printf("Escaped in %d minute(s).\n",ans);
else printf("Trapped!\n");
}
return 0;
}
|
e9f9ddc6d31a764dbac740ed39c01d70811a627c | 2a0698d5691ebc6387111298dce33bea95fa1656 | /bitwise/variation_of_odd_count.cpp | 9726048d825326334a9c348f7d570313938ea8a5 | [] | no_license | nish-works/DSA-Probs-Sols | 5d6b1635a12507077d52e1fbcac18222335cad55 | 4c6ab204f3ab6bd1ba63bbb44dc0b524236b26e9 | refs/heads/main | 2023-01-02T15:28:17.641811 | 2020-10-22T11:18:06 | 2020-10-22T11:18:06 | 305,269,387 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | variation_of_odd_count.cpp | // Find the missing number from 1 to n+1 in the given array
#include <bits/stdc++.h>
using namespace std;
// Efficient solution
// TC: O(n+1)
int solve(vector<int> &arr, int n)
{
int res1 = 0;
for (int i = 1; i <= n + 1; i++)
res1 = res1 ^ i;
int res2 = 0;
for (int i = 0; i < n; i++)
res2 = res2 ^ arr[i];
return res1 ^ res2;
}
int main()
{
ios_base::sync_with_stdio(0); // fast IO
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
int res = solve(arr, n);
cout << res;
return 0;
}
|
0240e4583727efec58dc5fc27f709151f402da69 | fb3c1e036f18193d6ffe59f443dad8323cb6e371 | /src/flash/AVMSWF/api/flash/display/AS3StageDisplayState.cpp | 1b9602c8df27d68a08753a539098f14929d6d27b | [] | no_license | playbar/nstest | a61aed443af816fdc6e7beab65e935824dcd07b2 | d56141912bc2b0e22d1652aa7aff182e05142005 | refs/heads/master | 2021-06-03T21:56:17.779018 | 2016-08-01T03:17:39 | 2016-08-01T03:17:39 | 64,627,195 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 938 | cpp | AS3StageDisplayState.cpp | #include "StdAfxflash.h"
#include "avmplus.h"
using namespace avmplus;
#include "AS3StageDisplayState.h"
namespace avmshell{
StageDisplayStateClass::StageDisplayStateClass(VTable* cvtable):ClassClosure(cvtable)
{
createVanillaPrototype();
//prototype = new (core()->GetGC(), cvtable->getExtraSize())StageDisplayStateObject(cvtable, toplevel()->objectClass->prototype, 0);
//Add your construct code here...
};
ScriptObject* StageDisplayStateClass::createInstance(VTable *ivtable, ScriptObject* prototype)
{
return new (core()->GetGC(), ivtable->getExtraSize()) StageDisplayStateObject(ivtable, prototype, 0);
//AS3 'new' opt...Add your init code here...
}
StageDisplayStateObject::StageDisplayStateObject(VTable *vtable, ScriptObject* proto, int capacity): ScriptObject(vtable, proto, 0)
{
//Add your construct code here...
}
//////////////////////////////////////////////////////////
//Native Method start...
} |
f757bebf7da1c3224a496fe04a03fd9f5d8d2a04 | 405ffdf7437ed9ee514e544f8b50c7bd8ba06b89 | /Analysis.h | 7aa2c88e8820eaf32b621f878a5aa3e6a3d1563d | [] | no_license | Liliana2410/no_cuts | 1174f603657b580196d061c91c90ee67d1350b72 | 5bb96ae11b1b3005ffc42828a76a05ced5c058ca | refs/heads/main | 2023-06-11T20:25:31.670660 | 2021-07-06T16:18:38 | 2021-07-06T16:18:38 | 383,529,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,550 | h | Analysis.h | #ifndef analysis_Analysis_h
#define analysis_Analysis_h
#include "SampleAnalyzer/Process/Analyzer/AnalyzerBase.h"
#include <TH1F.h>
#include <TFile.h>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <string>
#include <math.h>
namespace MA5
{
class Analysis : public AnalyzerBase
{
INIT_ANALYSIS(Analysis,"Analysis")
//**************************************************************************************************************************************************************************************************
//**************************************************************************************************************************************************************************************************
//PLOTS OF THE FIRST PAIR OF DIJET AND B_DIJET******************************************************************************************************************************************************
//general plots
TH1F* plot_FoundPair;
TH1F* plot_N_Merged1;
//general plots dijet1
TH1F* plot_PT_dijet1;
TH1F* plot_ETA_dijet1;
TH1F* plot_M_dijet1;
TH1F* plot_PHI_dijet1;
TH1F* plot_DR_dijet1;
//general plots b_dijet1
TH1F* plot_PT_b_dijet1;
TH1F* plot_ETA_b_dijet1;
TH1F* plot_M_b_dijet1;
TH1F* plot_PHI_b_dijet1;
TH1F* plot_DR_b_dijet1;
//DIJET1 ********************************************************************************************************************************************************************************************
//plots of the dijet1 pairs that are not merged.
TH1F* plot_PT_dijet1_not;
TH1F* plot_ETA_dijet1_not;
TH1F* plot_M_dijet1_not;
TH1F* plot_PHI_dijet1_not;
TH1F* plot_DR_dijet1_not;
//plots of the dijet1 pairs that are partially merged.
TH1F* plot_PT_dijet1_partially;
TH1F* plot_ETA_dijet1_partially;
TH1F* plot_M_dijet1_partially;
TH1F* plot_PHI_dijet1_partially;
TH1F* plot_DR_dijet1_partially;
//plots of the dijet1 pairs that are fully merged.
TH1F* plot_PT_dijet1_fully;
TH1F* plot_ETA_dijet1_fully;
TH1F* plot_M_dijet1_fully;
TH1F* plot_PHI_dijet1_fully;
TH1F* plot_DR_dijet1_fully;
//B_DIJET1 ******************************************************************************************************************************************************************************************
//plots of the b_dijet1 pairs that are partially merged.
TH1F* plot_PT_b_dijet1_partially;
TH1F* plot_ETA_b_dijet1_partially;
TH1F* plot_M_b_dijet1_partially;
TH1F* plot_PHI_b_dijet1_partially;
TH1F* plot_DR_b_dijet1_partially;
//plots of the b_dijet1 pairs that are fully merged.
TH1F* plot_PT_b_dijet1_fully;
TH1F* plot_ETA_b_dijet1_fully;
TH1F* plot_M_b_dijet1_fully;
TH1F* plot_PHI_b_dijet1_fully;
TH1F* plot_DR_b_dijet1_fully;
//PLOTS OF THE THE TWO B****************************************************************************************************************************************************************************
//plots of b1.
TH1F* plot_PT_b1;
TH1F* plot_ETA_b1;
TH1F* plot_PHI_b1;
//plots of b2.
TH1F* plot_PT_b2;
TH1F* plot_ETA_b2;
TH1F* plot_PHI_b2;
//PLOTS OF THE SECOND PAIR OF DIJET AND B_DIJET *****************************************************************************************************************************************************
//ONLY USED IN THE FULLY HADRONIC CHANNEL ***********************************************************************************************************************************************************
//general plots
TH1F* plot_N_Merged2;
TH1F* plot_Smallest_DR_dijet;
TH1F* plot_Smallest_DR_b_dijet;
TH1F* plot_Pairs;
TH1F* plot_Pairs_b;
TH1F* plot_Mother_Particles_dijets;
//general plots dijet2
TH1F* plot_PT_dijet2;
TH1F* plot_ETA_dijet2;
TH1F* plot_M_dijet2;
TH1F* plot_PHI_dijet2;
TH1F* plot_DR_dijet2;
//dETA, dPHI, dDR plots for the first dijet.
TH1F* plot_dETA_dijet1;
TH1F* plot_dPHI_dijet1;
TH1F* plot_dDR_dijet1;
//dETA, dPHI, dDR plots for the second dijet.
TH1F* plot_dETA_dijet2;
TH1F* plot_dPHI_dijet2;
TH1F* plot_dDR_dijet2;
//dETA, dPHI, dDR plots for the first pair not used: (1,2).
TH1F* plot_dETA_pair12;
TH1F* plot_dPHI_pair12;
TH1F* plot_dDR_pair12;
//dETA, dPHI, dDR plots for the second pair not used: (1,3).
TH1F* plot_dETA_pair13;
TH1F* plot_dPHI_pair13;
TH1F* plot_dDR_pair13;
//dETA, dPHI, dDR plots for the third pair not used: (1,4).
TH1F* plot_dETA_pair14;
TH1F* plot_dPHI_pair14;
TH1F* plot_dDR_pair14;
//dETA, dPHI, dDR plots for the fourth pair not used: (2,3).
TH1F* plot_dETA_pair23;
TH1F* plot_dPHI_pair23;
TH1F* plot_dDR_pair23;
//dETA, dPHI, dDR plots for the fifth pair not used: (2,4).
TH1F* plot_dETA_pair24;
TH1F* plot_dPHI_pair24;
TH1F* plot_dDR_pair24;
//dETA, dPHI, dDR plots for the sixth pair not used: (3,4).
TH1F* plot_dETA_pair34;
TH1F* plot_dPHI_pair34;
TH1F* plot_dDR_pair34;
//general plots b_dijet2
TH1F* plot_PT_b_dijet2;
TH1F* plot_ETA_b_dijet2;
TH1F* plot_M_b_dijet2;
TH1F* plot_PHI_b_dijet2;
TH1F* plot_DR_b_dijet2;
//DIJET2 ********************************************************************************************************************************************************************************************
//plots of the dijet2 pairs that are not merged.
TH1F* plot_PT_dijet2_not;
TH1F* plot_ETA_dijet2_not;
TH1F* plot_M_dijet2_not;
TH1F* plot_PHI_dijet2_not;
TH1F* plot_DR_dijet2_not;
//plots of the dijet2 pairs that are partially merged.
TH1F* plot_PT_dijet2_partially;
TH1F* plot_ETA_dijet2_partially;
TH1F* plot_M_dijet2_partially;
TH1F* plot_PHI_dijet2_partially;
TH1F* plot_DR_dijet2_partially;
//plots of the dijet2 pairs that are fully merged.
TH1F* plot_PT_dijet2_fully;
TH1F* plot_ETA_dijet2_fully;
TH1F* plot_M_dijet2_fully;
TH1F* plot_PHI_dijet2_fully;
TH1F* plot_DR_dijet2_fully;
//B_DIJET2 ******************************************************************************************************************************************************************************************
//plots of the b_dijet2 pairs that are partially merged.
TH1F* plot_PT_b_dijet2_partially;
TH1F* plot_ETA_b_dijet2_partially;
TH1F* plot_M_b_dijet2_partially;
TH1F* plot_PHI_b_dijet2_partially;
TH1F* plot_DR_b_dijet2_partially;
//plots of the b_dijet2 pairs that are fully merged.
TH1F* plot_PT_b_dijet2_fully;
TH1F* plot_ETA_b_dijet2_fully;
TH1F* plot_M_b_dijet2_fully;
TH1F* plot_PHI_b_dijet2_fully;
TH1F* plot_DR_b_dijet2_fully;
//SEMI-LEPTONIC EXCLUSIVE PLOTS**********************************************************************************************************************************************************************
//***************************************************************************************************************************************************************************************************
//***************************************************************************************************************************************************************************************************
//PLOTS FOR THE CASE IN WHICH W -> e nu_e.
//general plots.
TH1F* plot_Efficiencies_e;
TH1F* plot_StMet_e;
TH1F* plot_PT_Scalar_leptons_e;
TH1F* plot_PT_Vector_leptons_e;
TH1F* plot_M_leptons_e;
TH1F* plot_DR_leptons_e;
//plots of the two leptons coming from the Z'.
TH1F* plot_dETA_leptons_e;
TH1F* plot_ETA_lepton1_e;
TH1F* plot_ETA_lepton2_e;
TH1F* plot_dPHI_leptons_e;
TH1F* plot_PHI_lepton1_e;
TH1F* plot_PHI_lepton2_e;
TH1F* plot_dPT_Scalar_leptons_e;
TH1F* plot_dPT_Vector_leptons_e;
//PLOTS FOR THE CASE IN WHICH W -> mu nu_mu.
//general plots.
TH1F* plot_Efficiencies_mu;
TH1F* plot_StMet_mu;
TH1F* plot_PT_Scalar_leptons_mu;
TH1F* plot_PT_Vector_leptons_mu;
TH1F* plot_M_leptons_mu;
TH1F* plot_DR_leptons_mu;
//plots of the two leptons coming from the Z'.
TH1F* plot_dETA_leptons_mu;
TH1F* plot_ETA_lepton1_mu;
TH1F* plot_ETA_lepton2_mu;
TH1F* plot_dPHI_leptons_mu;
TH1F* plot_PHI_lepton1_mu;
TH1F* plot_PHI_lepton2_mu;
TH1F* plot_dPT_Scalar_leptons_mu;
TH1F* plot_dPT_Vector_leptons_mu;
/*
TH1F* plot_deltaR_b1b2;
TH1F* plot_PT_leptons;
TH1F* plot_ETA_leptons;
TH1F* plot_PT_b1;
TH1F* plot_MET;
TH1F* plot_sdETA_b1b2;
TH1F* plot_PT_b_not_used;
TH1F* plot_ETA_b_not_used;
TH1F* plot_sdPHI_lMET;
*/
public:
virtual bool Initialize(const MA5::Configuration& cfg, const std::map<std::string,std::string>& parameters);
virtual void Finalize(const SampleFormat& summary, const std::vector<SampleFormat>& files);
virtual bool Execute(SampleFormat& sample, const EventFormat& event);
private:
//Arrays of all final state particles.
std::vector<const MCParticleFormat*> FinalStateLeptons;
std::vector<const MCParticleFormat*> FinalStateNeutrinos;
std::vector<const MCParticleFormat*> FinalStateJs;
std::vector<const MCParticleFormat*> FinalStateBs;
//Indexes of the different final state jets: 4 for the fully-hadronic channel and 2 for the semi-leptonic channel. Pairs are always indentified as (j1,j2) and (j3,j4) in fully-hadronic.
MAuint32 index_j1;
MAuint32 index_j2;
MAuint32 index_j3;
MAuint32 index_j4;
//Indexes of the different final state b-quarks: Always 2 for both channels. Pairs are always indentified as (j1,j2,b1) and (j3,j4,b2) for the fully-hadronic.
//In the semi-leptonic, index_b2 makes reference to the b-quark not used (the one coming from the leptonic decaying top).
MAuint32 index_b1;
MAuint32 index_b2;
//Indexes of the final state leptons (muons or tauons) coming from the Z', only this two exist in fully-hadronic.
//Another one might exists in the semi-leptonic from the W decay.
MAuint32 index_lepton1;
MAuint32 index_lepton2;
//Index of the remaining lepton that is not the two leptons coming from the Z'. Might be an electron or a muon. Only in the semi-leptonic channel.
//The particle exist if after the analysis index_remaining > 0, else it was not found (fully-hadronic channel).
MAuint32 index_remaining = -10;
//Four-momentum of the reconstructed W (dijet) and top-quark (b_dijet). The second pair is only used in the fully-hadronic.
MALorentzVector dijet1;
MALorentzVector b_dijet1;
MALorentzVector dijet2;
MALorentzVector b_dijet2;
//Vectors that state wether the dijets and b_dijets were producted not, partially or fully merged. Both (only first) components used in fully-hadronic (semi-leptonic) channel.
std::vector<bool> notMerged;
std::vector<bool> partiallyMerged;
std::vector<bool> fullyMerged;
//Vector that states in the first (second) component if the dijets (b_dijets) are the possible pairs that minimize the dR between its constituents. Only used in fully-hadronic.
std::vector<bool> smallestdr;
//Vector that states wether the event has passed the different selection criteria applied to it or not. First component simple counts the number of events (a no-cut).
std::vector<bool> cuts;
//Indicates if the particle given is a final state lepton.
bool IsFinalState_lepton(const MCParticleFormat* particle){
bool final_state = false;
if ((particle != 0) && (PHYSICS->Id->IsFinalState(particle))){
if ((particle->pdgid()==15) || (particle->pdgid()==13) || (particle->pdgid()==11) || (particle->pdgid()==-15) || (particle->pdgid()==-13) || (particle->pdgid()==-11)){
final_state = true;
}
}
return final_state;
}
//Indicates if the particle given is a final state neutrino.
bool IsFinalState_neutrino(const MCParticleFormat* particle){
bool final_state = false;
if ((particle != 0) && (PHYSICS->Id->IsFinalState(particle))){
if ((particle->pdgid()==16) || (particle->pdgid()==14) || (particle->pdgid()==12) || (particle->pdgid()==-16) || (particle->pdgid()==-14) || (particle->pdgid()==-12)){
final_state = true;
}
}
return final_state;
}
//Indicates if the particle given is a final state b-quark.
bool IsFinalState_b(const MCParticleFormat* particle){
bool final_state = false;
if ((particle != 0) && (PHYSICS->Id->IsFinalState(particle))){
if ((particle->pdgid()==5) || (particle->pdgid()==-5)){
final_state = true;
}
}
return final_state;
}
//Indicates if the particle given is a final state jet.
bool IsFinalState_j(const MCParticleFormat* particle){
bool final_state = false;
if ((particle != 0) && (PHYSICS->Id->IsFinalState(particle))){
if ((particle->pdgid()==1) || (particle->pdgid()==2) || (particle->pdgid()==3) || (particle->pdgid()==4) || (particle->pdgid()==-1) || (particle->pdgid()==-2) || (particle->pdgid()==-3) || (particle->pdgid()==-4)){
final_state = true;
}
}
return final_state;
}
//Fills the vectors of final state particles classified by wether they are leptons, neutrinos, js or bs.
void ClassifyParticles(const MCParticleFormat* particle, std::vector<const MCParticleFormat*> &FinalStateLeptons, std::vector<const MCParticleFormat*> &FinalStateNeutrinos, std::vector<const MCParticleFormat*> &FinalStateJs, std::vector<const MCParticleFormat*> &FinalStateBs){
if (IsFinalState_lepton(particle) == true){
FinalStateLeptons.push_back(particle);
}
else if (IsFinalState_neutrino(particle) == true){
FinalStateNeutrinos.push_back(particle);
}
else if (IsFinalState_b(particle) == true){
FinalStateBs.push_back(particle);
}
else if (IsFinalState_j(particle) == true){
FinalStateJs.push_back(particle);
}
}
//Organizes components of the final state vectors in terms of their PT (greatest to smallest).
void OrganizeByPT(std::vector<const MCParticleFormat*> &initialVector){
std::vector<const MCParticleFormat*> newVector;
for (MAuint32 i = 0; i < initialVector.size(); i++){
std::vector<const MCParticleFormat*> temporalVector = SORTER->rankFilter(initialVector,i+1,PTordering);
newVector.push_back(temporalVector[0]);
temporalVector.clear();
}
initialVector.clear();
initialVector = newVector;
}
//Returns the charge of the particle required in units of e (electron charge).
Double_t Charge(const MCParticleFormat* particle){
Double_t charge = -50.0;
if (particle != 0){
//If the particle is a down quark.
if ((particle->pdgid()==1) || (particle->pdgid()==3) || (particle->pdgid()==5)){
charge = -1.0/3.0;
}
//If the particle is a down anti-quark.
else if ((particle->pdgid()==-1) || (particle->pdgid()==-3) || (particle->pdgid()==-5)){
charge = 1.0/3.0;
}
//If the particle is an up quark.
else if ((particle->pdgid()==2) || (particle->pdgid()==4) || (particle->pdgid()==6)){
charge = 2.0/3.0;
}
//If the particle is an up anti-quark.
else if ((particle->pdgid()==-2) || (particle->pdgid()==-4) || (particle->pdgid()==-6)){
charge = -2.0/3.0;
}
//If the particle is an electron.
else if ((particle->pdgid()==11) || (particle->pdgid()==13) || (particle->pdgid()==15)){
charge = -1.0;
}
//If the particle is an anti-electron.
else if ((particle->pdgid()==-11) || (particle->pdgid()==-13) || (particle->pdgid()==-15)){
charge = 1.0;
}
//If the particle is a neutrino or anti-neutrino.
else if ((particle->pdgid()==12) || (particle->pdgid()==14) || (particle->pdgid()==16) || (particle->pdgid()==-12) || (particle->pdgid()==-14) || (particle->pdgid()==-16)){
charge = 0.0;
}
}
return charge;
}
//FULLY-HADRONIC FUNCTIONS*********************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************************************
//Returns the indexes not use for dijet reconstruction. The first pair of dijet comes from the pair with index (0, index).
boost::tuple<int, int> RemainingIndexes(int index){
if (index == 1){
return boost::make_tuple(2,3);
}
else if (index == 2){
return boost::make_tuple(1,3);
}
else{
return boost::make_tuple(1,2);
}
}
//Define selection criteria for selection of dijet and b_dijet pairs for W and t reconstruction. The pairs of jets and bs must be PT ordered. Index2 and index5 are the PT index
//of the jet that acompanies the greatest PT jet in the first dijet pair, and the PT index of the b that acompanies this first dijet pair respectively.
boost::tuple<int, int> ReconstructedEventFullyHadronic(std::vector<const MCParticleFormat*> jets, std::vector<const MCParticleFormat*> b){
MAuint32 index2 = 0;
Double_t best_Err = 999999.9;
//Masses value for the W and t, taken from the PDG.
Double_t Mt = 172.76;
Double_t MW = 80.379;
//Defines the first layer criteria for the W reconstruction: dR_dijet{1,2} < dR_cutOff.
Double_t dR_cutOff = 10000000.0;
for (MAuint32 i = 1; i < jets.size(); i++){
MAuint32 indextemp1;
MAuint32 indextemp2;
MALorentzVector jtemp1 = jets[0]->momentum();
MALorentzVector jtemp2 = jets[i]->momentum();
boost::tie(indextemp1, indextemp2) = RemainingIndexes(i);
MALorentzVector jtemp3 = jets[indextemp1]->momentum();
MALorentzVector jtemp4 = jets[indextemp2]->momentum();
Double_t dR1 = jtemp1.DeltaR(jtemp2);
Double_t dR2 = jtemp3.DeltaR(jtemp4);
//First selection criteria.
if ((dR1 < dR_cutOff) && (dR2 < dR_cutOff)){
Double_t Err1 = (abs((jtemp1 + jtemp2).M() - MW))*100/MW;
Double_t Err2 = (abs((jtemp3 + jtemp4).M() - MW))*100/MW;
//Second selection criteria.
if (Err1 + Err2 < best_Err){
//Checks if the first dijet is not merged.
if (dR1 > 0.8){
//Third selection criteria for the dijet1.
if ((Charge(jets[0]) + Charge(jets[i]) == 1.0) || (Charge(jets[0]) + Charge(jets[i]) == -1.0)){
best_Err = Err1 + Err2;
index2 = i;
}
}
//Checks if the second dijet is not merged.
else if (dR2 > 0.8){
//Third selection criteria for the dijet2.
if ((Charge(jets[indextemp1]) + Charge(jets[indextemp2]) == 1.0) || (Charge(jets[indextemp1]) + Charge(jets[indextemp2]) == -1.0)){
best_Err = Err1 + Err2;
index2 = i;
}
}
else{
best_Err = Err1 + Err2;
index2 = i;
}
}
}
}
MAuint32 index5 = 0;
Double_t best_Err_b = 999999.9;
MALorentzVector dijet1 = jets[0]->momentum() + jets[index2]->momentum();
MAuint32 index3;
MAuint32 index4;
boost::tie(index3, index4) = RemainingIndexes(index2);
MALorentzVector dijet2 = jets[index3]->momentum() + jets[index4]->momentum();
for (MAuint32 j = 0; j < b.size(); j++){
MALorentzVector b_dijet1 = b[j]->momentum() + dijet1;
MALorentzVector b_dijet2 = b[1-j]->momentum() + dijet2;
Double_t Err3 = (abs(b_dijet1.M() - Mt))*100/Mt;
Double_t Err4 = (abs(b_dijet2.M() - Mt))*100/Mt;
if (Err3 + Err4 < best_Err_b){
best_Err_b = Err3 + Err4;
index5 = j;
}
}
return boost::make_tuple(index2,index5);
}
//Checks if the dijets (0, index) and the remaining others, are the ones with the smallest sum of dR. Same for the b_dijet (0, index, b_index) and the rest.
std::vector<bool> SmallestDR(std::vector<const MCParticleFormat*> jets, std::vector<const MCParticleFormat*> b, int index, int b_index){
std::vector<bool> smallest;
smallest.push_back(true);
smallest.push_back(true);
MALorentzVector jet1 = jets[0]->momentum();
MALorentzVector jet2 = jets[index]->momentum();
MAuint32 index3;
MAuint32 index4;
boost::tie(index3, index4) = RemainingIndexes(index);
MALorentzVector jet3 = jets[index3]->momentum();
MALorentzVector jet4 = jets[index4]->momentum();
Double_t best_dR = jet1.DeltaR(jet2) + jet3.DeltaR(jet4);
for (MAuint32 i = 1; i < jets.size(); i++){
if (smallest[0] != false){
MAuint32 indextemp1;
MAuint32 indextemp2;
MALorentzVector jtemp1 = jets[0]->momentum();
MALorentzVector jtemp2 = jets[i]->momentum();
boost::tie(indextemp1, indextemp2) = RemainingIndexes(i);
MALorentzVector jtemp3 = jets[indextemp1]->momentum();
MALorentzVector jtemp4 = jets[indextemp2]->momentum();
Double_t dR = jtemp1.DeltaR(jtemp2) + jtemp3.DeltaR(jtemp4);
if (jets[i] != jets[index]){
if (dR < best_dR){
smallest[0] = false;
}
}
}
}
MALorentzVector dijet1 = (jet1 + jet2);
MALorentzVector b1 = b[b_index]->momentum();
MALorentzVector dijet2 = (jet3 + jet4);
MALorentzVector b2 = b[1 - b_index]->momentum();
Double_t b_dR = b1.DeltaR(dijet1) + b2.DeltaR(dijet2);
Double_t temp_b_dR = b1.DeltaR(dijet2) + b2.DeltaR(dijet1);
if (temp_b_dR < b_dR){
smallest[1] = false;
}
return smallest;
}
//Defines the two dijets and b_dijets coming from the fully hadronic channel using the criteria defined in ReconstructedEventFullyHadronic, checking if they are not, partially or fullymerged.
//The two components of the bool vectors notMerged, partiallyMerged, fullyMerged and smallestdr are used (each component for each pair), b_used is not used (all bs are used).
//Remember jets has 4 jets in this channel.
void MergedFullyHadronic(std::vector<const MCParticleFormat*> jets, std::vector<const MCParticleFormat*> b, MA5::MALorentzVector &dijet1, MA5::MALorentzVector &dijet2, MA5::MALorentzVector &b_dijet1, MA5::MALorentzVector &b_dijet2){
index_lepton1 = 0;
index_lepton2 = 1;
index_j1 = 0;
boost::tie(index_j2, index_b1) = ReconstructedEventFullyHadronic(jets, b);
std::vector<int> indexesj;
indexesj.push_back(index_j1);
indexesj.push_back(index_j2);
boost::tie(index_j3, index_j4) = RemainingIndexes(index_j2);
indexesj.push_back(index_j3);
indexesj.push_back(index_j4);
std::vector<int> indexesb;
indexesb.push_back(index_b1);
index_b2 = 1 - index_b1;
indexesb.push_back(index_b2);
smallestdr = SmallestDR(jets, b, index_j2, index_b1);
dijet1 = MALorentzVector();
b_dijet1 = MALorentzVector();
dijet2 = MALorentzVector();
b_dijet2 = MALorentzVector();
for (MAuint32 i = 0; i < 2; i++){
MALorentzVector jet1 = jets[indexesj[2*i]]->momentum();
MALorentzVector jet2 = jets[indexesj[(2*i) + 1]]->momentum();
MALorentzVector dijet = jet1 + jet2;
Double_t dR_dijet = jet1.DeltaR(jet2);
MALorentzVector p_b = b[indexesb[i]]->momentum();
MALorentzVector b_dijet = p_b + dijet;
if (i == 0){
dijet1 = dijet;
b_dijet1 = b_dijet;
}
else{
dijet2 = dijet;
b_dijet2 = b_dijet;
}
if (dR_dijet > 0.8){
notMerged.push_back(true);
partiallyMerged.push_back(false);
fullyMerged.push_back(false);
}
else{
notMerged.push_back(false);
Double_t dR_bdijet = p_b.DeltaR(dijet);
if (dR_bdijet > 1.0){
fullyMerged.push_back(false);
partiallyMerged.push_back(true);
}
else{
fullyMerged.push_back(true);
partiallyMerged.push_back(false);
}
}
}
}
//SEMI-LEPTONIC FUNCTIONS**********************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************************************
//Defines the dijet and b_dijet coming from the semi leptonic channel searching for the smallest dr between the dijet and bs (2), checking if they are not, partially or fully merged.
//Only the first component of the bool vectors notMerged, partiallyMerged and fullyMerged are used, smallestdr is not used (as there is only one possible pair).
//Rememeber jets now only has 2 jets. Also applies the different selection criteria to distinguish the signal over the backgrounds.
void MergedSemiLeptonic(std::vector<const MCParticleFormat*> jets, std::vector<const MCParticleFormat*> leptons, std::vector<const MCParticleFormat*> neutrinos, std::vector<const MCParticleFormat*> bs, MA5::MALorentzVector &dijet1, MA5::MALorentzVector &b_dijet1, const EventFormat& event, std::string channel){
//This pdgid = 0 has no physical value: just to avoid warnings from initialization of variables. PDGid of the leptons coming from the Z' decay.
int leptonpdgid = 0;
if (channel == "muon"){
leptonpdgid = 13;
}
else if (channel == "tauon"){
leptonpdgid = 15;
}
else{
std::cout << "Variable [channel] was not correctly defined in .cpp: please only use values of [muon] or [tauon] and try again." << std::endl;
}
MAuint32 contador = 0;
//Checks if there are at least two muons (tauons, depending on the channel studied) in the final states: the ones poduced by the Z'.
//If the signal is correctly generated there should exist this two leptons. Only searches for them if the variable channel was correctly defined in the cpp as muon or tauon.
//Then leptonpdgid and leptonPTcut are correctly initialized (they are different from 0: this was just to avoid warnings from initialization of variables).
if ((channel == "muon") || (channel == "tauon")){
for (MAuint32 i = 0; i < leptons.size(); i++){
if((leptons[i]->pdgid()==leptonpdgid) || (leptons[i]->pdgid()==-leptonpdgid)){
contador = contador + 1;
}
}
}
//Checks the two leptons from the Z' were found. Also checks that leptonpdgid was correctly initialized (cannot be 0).
if ((contador >= 2) && (leptonpdgid != 0)){
//Searches for the pair of muons (tauons) with the biggest sum of |p|, as there might be a third one. The pair always exists (coming from the Z').
Double_t biggest_PT_mag = 0.0;
for (MAuint32 i = 0; i < leptons.size() - 1; i++){
for (MAuint32 j = i + 1; j < leptons.size(); j++){
if (((leptons[i]->pdgid()==leptonpdgid) || (leptons[i]->pdgid()==-leptonpdgid)) && ((leptons[j]->pdgid()==leptonpdgid) || (leptons[j]->pdgid()==-leptonpdgid))){
MALorentzVector leptontemp1 = leptons[i]->momentum();
MALorentzVector leptontemp2 = leptons[j]->momentum();
MAVector3 p1 = leptontemp1.Vect();
MAVector3 p2 = leptontemp2.Vect();
if (p1.Mag() + p2.Mag() > biggest_PT_mag){
biggest_PT_mag = p1.Mag() + p2.Mag();
index_lepton1 = i;
index_lepton2 = j;
}
}
}
}
//Index of the remaining final state lepton that is not the two muons (tauons) coming from the Z'. Might be an electron or a muon.
if ((index_lepton1 == 0) && (index_lepton2 == 1)){
index_remaining = 2;
}
else if ((index_lepton1 == 0) && (index_lepton2 == 2)){
index_remaining = 1;
}
else if ((index_lepton1 == 1) && (index_lepton2 == 2)){
index_remaining = 0;
}
MALorentzVector lepton1 = leptons[index_lepton1]->momentum();
MALorentzVector lepton2 = leptons[index_lepton2]->momentum();
//Remaining lepton, the one that does not come from the Z' but rather from the W leptonic decay.
MALorentzVector lepton = leptons[index_remaining]->momentum();
index_j1 = 0;
index_j2 = 1;
MALorentzVector jet1 = jets[index_j1]->momentum();
MALorentzVector jet2 = jets[index_j2]->momentum();
dijet1 = MALorentzVector();
b_dijet1 = MALorentzVector();
dijet1 = jet1 + jet2;
Double_t dR_dijet = jet1.DeltaR(jet2);
Double_t best_dR = 999999.9;
for (MAuint32 i = 0; i < bs.size(); i++){
const MALorentzVector p_b = bs[i]->momentum();
Double_t dR = p_b.DeltaR(dijet1);
if (dR < best_dR){
best_dR = dR;
index_b1 = i;
}
}
MALorentzVector b1 = bs[index_b1]->momentum();
index_b2 = 1 - index_b1;
MALorentzVector b2 = bs[index_b2]->momentum();
MALorentzVector n1 = neutrinos[0]->momentum();
b_dijet1 = b1 + dijet1;
//Counter of the number of events (a no_cut).
cuts.push_back(true);
//Checks if the jets are produced not merged, and applies all the selection criteria to the event.
if (dR_dijet > 0.8){
notMerged.push_back(true);
partiallyMerged.push_back(false);
fullyMerged.push_back(false);
}
else{
notMerged.push_back(false);
if (best_dR > 1.0){
fullyMerged.push_back(false);
partiallyMerged.push_back(true);
}
else{
fullyMerged.push_back(true);
partiallyMerged.push_back(false);
}
}
}
else{
std::cout << "Two final state leptons of the required channel were not found. Should exist: the signal might not be correctly generated." << std::endl;
}
}
};
}
#endif
|
be08ffb6ebbcd243b9c7a41d5c6de6da964ef3f6 | 8fae890d43e686f7de7123d9290651a562cb926d | /src/gateway/gateway/gateway_biz.cpp | 2f8ca4a45b480d14224becd12996cfd5c3a180b7 | [] | no_license | github188/sms_gateway | 9f4d2d9563e4b272d98a2e063e0d58e9003d4235 | 0a6fdc87329a480d1329d7a44e61c039523a01dd | refs/heads/master | 2022-01-07T19:15:00.508350 | 2019-01-30T09:06:00 | 2019-01-30T09:06:00 | 392,702,012 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 30,634 | cpp | gateway_biz.cpp | #include "gateway_db.h"
#include "gateway_biz.h"
#include "gateway_util.h"
#include <json/json.h>
int handle_channel_packet( connection_t** pcon )
{
if ( *pcon == NULL )
{
LOG_ERROR("parameters are illegal.\n");
return -1;
}
if(unlikely(g_biz == NULL))
{
LOG_ERROR("biz dll pointer is null!\n");
return -1;
}
buffer_t *rcvbuf = (*pcon)->rcvbuf;
const char *readptr = rcvbuf->get_read_ptr(rcvbuf);
int datalen = rcvbuf->get_data_size(rcvbuf);
if (datalen <= 0)
{
*pcon = NULL;
return 0;
}
//从缓冲区复制数据出来
char* inbuf = (char *)malloc( g_conf.package_buff_size );
if( inbuf == NULL )
{
LOG_ERROR("failed to allocate memory for inbuf.\n");
return -1;
}
memcpy(inbuf, readptr, datalen);
inbuf[datalen] = '\0';
//调用业务库判断是否为完整报文
int ret = g_biz->is_packet_complete(inbuf, datalen);
if( ret <= 0 )
{
*pcon = NULL;
if( inbuf != NULL )
{
free(inbuf);
inbuf = NULL;
}
if(ret == 0) // 不完整报文
{
return ret;
}
else // 无效报文
{
LOG_ERROR("is_packet_complete fatal error.\n");
return -2;
}
}
datalen = ret;
rcvbuf->set_read_size(rcvbuf, datalen);
//完整报文
//输出缓冲区
char* outbuf = (char *)malloc( g_conf.package_buff_size );
if( outbuf == NULL )
{
LOG_ERROR("failed to allocate memory for outbuf.\n");
return -1;
}
int outlen = 0;
//调用业务库处理
ret = g_biz->channel_req(inbuf, datalen,outbuf, outlen);
if (unlikely(ret < 0))
{
LOG_ERROR("channel_req failed!\n");
if( inbuf != NULL )
{
free(inbuf);
inbuf = NULL;
}
if( outbuf != NULL )
{
free(inbuf);
outbuf = NULL;
}
return -1;
}
if ( ret > 0 || outlen <= 0 )
{
if( inbuf != NULL )
{
free(inbuf);
inbuf = NULL;
}
if( outbuf != NULL )
{
free(inbuf);
outbuf = NULL;
}
return 1;
}
//写数据进发送缓冲区
buffer_t * pbuffer = (*pcon)->sndbuf;
int freesize = pbuffer->get_free_size(pbuffer);
char* writeptr = pbuffer->get_write_ptr(pbuffer);
if (outlen <= freesize)
{
memcpy(writeptr, outbuf, outlen);
pbuffer->set_write_size(pbuffer, outlen);
}
if( inbuf != NULL )
{
free(inbuf);
inbuf = NULL;
}
if( outbuf != NULL )
{
free(inbuf);
outbuf = NULL;
}
return ret;
}
int handle_gateway_packet( connection_t** pcon )
{
if ( *pcon == NULL )
{
LOG_ERROR("parameters are illegal.\n");
return -1;
}
buffer_t *rcvbuf = (*pcon)->rcvbuf;
const char *readptr = rcvbuf->get_read_ptr(rcvbuf);
int datalen = rcvbuf->get_data_size(rcvbuf);
if (datalen <= 0)
{
*pcon = NULL;
return 0;
}
int ret = is_packet_complete(readptr, datalen);
if( ret <= 0 )
{
*pcon = NULL;
if(ret == 0) // 不完整报文
{
return ret;
}
else // 无效报文
{
LOG_ERROR("is_packet_complete fatal error.\n");
return -2;
}
}
//解析报文头
message_head_t hdr;
if (parse_header(readptr, datalen, &hdr) != 0)
{
LOG_ERROR("parse_header failed.\n");
return -1;
}
//从缓冲区复制数据出来
char* inbuf = (char *)malloc( g_conf.package_buff_size );
if( inbuf == NULL )
{
LOG_ERROR("failed to allocate memory for inbuf.\n");
return -1;
}
memcpy(inbuf, readptr, hdr.length);
rcvbuf->set_read_size(rcvbuf, hdr.length);
switch(hdr.command)
{
case CMD_HEARTBEAT_RSP://处理心跳应答
{
ret = handle_heartbeat_rsp(&hdr,
inbuf + PROTOCOL_HEADER_LENGTH,
hdr.length - PROTOCOL_HEADER_LENGTH);
}
break;
case CMD_SVR_REG_RSP://处理注册应答
{
ret = handle_svr_reg_rsp(&hdr,
inbuf + PROTOCOL_HEADER_LENGTH,
hdr.length - PROTOCOL_HEADER_LENGTH,
*pcon);
}
break;
case CMD_CHANNEL_MGR_REQ: // 通道参数变更请求
{
ret = handle_channel_mgr_req(&hdr,
inbuf + PROTOCOL_HEADER_LENGTH,
hdr.length - PROTOCOL_HEADER_LENGTH,
*pcon);
}
break;
case CMD_GATEWAY_MSG_SEND_REQ: //信息发送请求
{
ret = handle_gateway_msg_send_req(&hdr,
inbuf + PROTOCOL_HEADER_LENGTH,
hdr.length - PROTOCOL_HEADER_LENGTH,
*pcon);
}
break;
default:
{
LOG_ERROR("unknown command : 0x%x\n", hdr.command);
ret = -1;
break;
}
}
if( inbuf != NULL )
{
free(inbuf);
inbuf = NULL;
}
return ret;
}
// 处理心跳应答包
int handle_heartbeat_rsp(message_head_t* hdr, const char* data, int len)
{
HeartBeatRsp rsp;
if (parse_msg(data, len, &rsp) != 0)
{
LOG_ERROR("parse_msg HeartBeatRsp failed.\n");
return -1;
}
dump(hdr, &rsp);
return 1;
}
//处理注册应答包
int handle_svr_reg_rsp(message_head_t* hdr, const char* data, int len, connection_t *pcon)
{
SvrRegRsp rsp;
if (parse_msg(data, len, &rsp) != 0)
{
LOG_ERROR("parse_msg SvrRegRsp failed.\n");
return -1;
}
dump(hdr, &rsp);
LOG_INFO("svr reg rsp! [%s][%d]\n",rsp.sid().c_str(),rsp.retcode());
vector<server_info_t>::iterator it = g_conf.server_info.begin();
for(;it!=g_conf.server_info.end();it++)
{
if(it->fd == pcon->fd)
{
if(rsp.retcode() == 0)
{
it->is_reg = true;
}
else
{
it->is_reg = false;
}
}
}
return 1;
}
// 通道参数变更请求
int handle_channel_mgr_req(message_head_t* hdr, const char* data, int len, connection_t *pcon)
{
ChannelMgrReq req;
if (parse_msg(data, len, &req) != 0)
{
LOG_ERROR("parse_msg ChannelMgrReq failed.\n");
return -1;
}
dump(hdr, &req);
LOG_INFO("channel mgr req! [%s][%s][%d]\n",
req.sid().c_str(),
req.channelid().c_str(),
req.mgrtype());
int ret = 0;
//收到退出报文,退出程序
if( req.mgrtype() == 2 )
{
g_exit = 1;
}
else
{
//更新通道参数报文
if( strcasecmp(g_conf.channel_id,req.channelid().c_str()) == 0 )
{
//加载通道参数
ret = load_channel_info(req.channelid().c_str());
if( ret == 0 )
{
LOG_INFO("reload channel successful.channelid[%s]\n",req.channelid().c_str());
//调用业务库重读参数
g_biz->reload_channel( &g_channel_conf );
//处理子进程退出
handle_child_exit();
//重启所有发送子进程
ret = fork_proc();
if( ret != 0 )
{
LOG_ERROR("fail to fork_proc!\n");
}
//数据设置成可发送
g_ready_to_send = 1;
}
else
{
LOG_ERROR("reload channel failed.\n");
}
}
}
ChannelMgrRsp rsp;
rsp.set_sid(req.sid());
rsp.set_retcode(ret);
if (make_rsp(hdr, &rsp, pcon) < 0)
{
LOG_ERROR("make_rsp failed.\n");
return -1;
}
return 0;
}
//信息发送请求
int handle_gateway_msg_send_req(message_head_t* hdr, const char* data, int len, connection_t *pcon)
{
GateWayMsgSendReq req;
if (parse_msg(data,len,&req) != 0)
{
LOG_ERROR("parse_msg failed.\n");
return -1;
}
dump(hdr,&req);
LOG_INFO("gateway msg send req! [%s][%s]\n",
req.sid().c_str(),
req.channelid().c_str());
//将消息写入消息队列
int ret = msg_send(hdr,&req);
if( ret != 0 )
{
LOG_ERROR("msg_send failed.\n");
}
GateWayMsgSendRsp rsp;
rsp.set_sid(req.sid());
rsp.set_retcode(ret);
if (make_rsp(hdr, &rsp, pcon) < 0)
{
LOG_ERROR("make_rsp failed.\n");
return -1;
}
return 0;
}
int msg_to_json( GateWayMsgSendReq *req,string &msg_json )
{
if( req == NULL ) return -1;
//组装成json
Json::FastWriter jsonWriter;
Json::Value jsonRoot, jsonArgument;
jsonRoot["src_phone"] = Json::Value(req->srcphone());
jsonRoot["message_content"] = Json::Value(req->messagecontent());
jsonRoot["channel_type"] = Json::Value(req->channeltype());
jsonRoot["channel_id"] = Json::Value(req->channelid());
jsonRoot["channel_groupid"] = Json::Value(req->channelgroupid());
jsonRoot["service_id"] = Json::Value(req->serviceid());
// 拼装sms_argument
jsonArgument["datetime"] = Json::Value(req->datetime());
jsonArgument["submit_id"] = Json::Value(req->submitid());
jsonArgument["batchno"] = Json::Value(req->batchno());
jsonArgument["operator_id"] = Json::Value(req->operatorid());
jsonArgument["client_id"] = Json::Value(req->customerid());
jsonArgument["account_id"] = Json::Value(req->accountid());
jsonArgument["company_id"] = Json::Value(req->companyid());
jsonArgument["submit_way"] = Json::Value(req->submitway());
bool isotosend;
if( req->isotosend() == 1 )
{
isotosend = true;
}
else
{
isotosend = false;
}
jsonArgument["oto_send"] = Json::Value(isotosend);
if( req->issmsresend() == 1 )
{
isotosend = true;
}
else
{
isotosend = false;
}
jsonArgument["sms_resend"] = Json::Value(isotosend);
jsonArgument["return_type"] = Json::Value(req->returntype());
jsonArgument["smsdata"] = Json::Value(req->smsdata());
jsonRoot["sms_argument"] = jsonArgument;
// 拼装phone_list
for ( int index = 0; index < req->phonelist_size(); index++ )
{
const GateWayMsgSendReq::PhoneListGroup& phonelist = req->phonelist(index);
Json::Value jsonPhone;
jsonPhone["send_id"] = Json::Value(phonelist.sendid());
if( phonelist.isneedsend() == 1 )
{
isotosend = true;
}
else
{
isotosend = false;
}
jsonPhone["need_send"] = Json::Value(isotosend);
jsonPhone["virtual_status"] = Json::Value(phonelist.virtualstatus());
jsonPhone["convert_status"] = Json::Value(phonelist.convertstatus());
jsonPhone["mobile_phone"] = Json::Value(phonelist.mobilephone());
jsonPhone["sms_content"] = Json::Value(phonelist.smscontent());
jsonPhone["mobile_city"] = Json::Value(phonelist.mobilecity());
jsonRoot["phone_list"].append(jsonPhone);
}
msg_json = jsonWriter.write(jsonRoot);
return 0;
}
int get_phone_packet(map<string,sms_attribute_t> *plist,GateWayMsgSendReq *req,int num)
{
if( plist == NULL || req == NULL ) return -1;
//情况之前号码列表
req->clear_phonelist();
map<string, sms_attribute_t>::iterator itPhone = plist->begin();
for( int i = 0; i < num; i++ )
{
if( itPhone != plist->end() )
{
GateWayMsgSendReq::PhoneListGroup* phonelist = req->add_phonelist();
phonelist->set_sendid(itPhone->first);
phonelist->set_isneedsend(itPhone->second.bNeedSend);
phonelist->set_virtualstatus(itPhone->second.sVirtualStatus);
phonelist->set_convertstatus(itPhone->second.sConvertStatus);
phonelist->set_mobilephone(itPhone->second.sMobilePhone);
phonelist->set_smscontent(itPhone->second.sSmsContent);
phonelist->set_mobilecity(itPhone->second.sMobileCity);
plist->erase(itPhone++);
}
}
return 0;
}
int msg_send(message_head_t* hdr,GateWayMsgSendReq *req)
{
if( hdr == NULL || req == NULL ) return -1;
GateWayMsgSendReq send_req;
send_req.set_sid(req->sid());
send_req.set_srcphone(req->srcphone());
send_req.set_messagecontent(req->messagecontent());
send_req.set_channeltype(req->channeltype());
send_req.set_channelid(req->channelid());
send_req.set_channelgroupid(req->channelgroupid());
send_req.set_serviceid(req->serviceid());
send_req.set_datetime(req->datetime());
send_req.set_submitid(req->submitid());
send_req.set_batchno(req->batchno());
send_req.set_operatorid(req->operatorid());
send_req.set_customerid(req->customerid());
send_req.set_accountid(req->accountid());
send_req.set_companyid(req->companyid());
send_req.set_submitway(req->submitway());
send_req.set_isotosend(req->isotosend());
send_req.set_issmsresend(req->issmsresend());
send_req.set_returntype(req->returntype());
send_req.set_smsdata(req->smsdata());
map<string,sms_attribute_t> phonelist;
for ( int index = 0; index < req->phonelist_size(); index++ )
{
const GateWayMsgSendReq::PhoneListGroup& phone_group = req->phonelist(index);
sms_attribute_t phone;
string sSendId = phone_group.sendid();
phone.bNeedSend = phone_group.isneedsend();
phone.sVirtualStatus = phone_group.virtualstatus();
phone.sConvertStatus = phone_group.convertstatus();
phone.sMobilePhone = phone_group.mobilephone();
phone.sSmsContent = phone_group.smscontent();
phone.sMobileCity = phone_group.mobilecity();
phonelist[sSendId] = phone;
}
while( phonelist.size() > 0 )
{
g_msgform->mtype = 1L;
if( g_channel_conf.uMassSupport == 0 )
{
//单发通道只发一个号码
get_phone_packet(&phonelist,&send_req,1);
}
else
{
//群发通道取最大值
uint32_t uMassNum = (g_channel_conf.uMassNum > 0 ) ? g_channel_conf.uMassNum : 30;
get_phone_packet(&phonelist,&send_req,uMassNum);
}
send_req.SerializeToArray(g_msgform->mtext, sizeof(g_msgform->mtext));
g_msgform->data_len = send_req.ByteSize();
int mq_len = g_msgform->data_len + sizeof(long);
//写入mq
if( g_mq.write(g_msgform, mq_len, IPC_NOWAIT) < 0 )
{
LOG_WARN("write mq failed.len:%d,err:%s\n", mq_len, strerror(errno));
string msg_json;
msg_to_json(&send_req,msg_json);
//mq满了,重写回redis
int ret = save_channel_msg( g_conf.channel_id, msg_json );
if( ret != 0 )
{
LOG_ERROR("save_channel_msg failed.\n");
break;
}
}
}
return 0;
}
int load_channel_info(const char* channel_id)
{
string info;
int ret = query_channel_info(channel_id,info);
if( ret != 0 )
{
LOG_ERROR("query_channel_info fail.\n");
return -1;
}
Json::Reader jsonReader;
Json::Value jsonValue;
if (!jsonReader.parse(info, jsonValue))
{
LOG_ERROR("Parse json is failure.The json:%s.", info.c_str());
return -1;
}
uint32_t http_type = 0;
uint32_t uProtoType = jsonValue["sc_proto_type"].asUInt();
if ( uProtoType == 3 )
{
string sInterfaceId = jsonValue["sc_it_id"].asString();
ret = query_httpchannel_info(sInterfaceId.c_str(),http_type);
if( ret != 0 )
{
LOG_ERROR("query_httpchannel_info fail.\n");
return -1;
}
}
g_channel_conf.sChannelId = jsonValue["sc_id"].asString();
g_channel_conf.sChannelName = jsonValue["sc_channel_name"].asString();
g_channel_conf.uProtoType = uProtoType;
g_channel_conf.uMassSupport = jsonValue["sc_mass_support"].asUInt();
g_channel_conf.uMassNum = jsonValue["sc_mass_num"].asUInt();
g_channel_conf.lHeartbeatInterval = jsonValue["sc_heartbeat_interval"].asUInt();
g_channel_conf.uSendSpeed = jsonValue["sc_send_speed"].asUInt();
g_channel_conf.uLinkCount = jsonValue["sc_link_count"].asUInt();
g_channel_conf.sIpAddress = jsonValue["sc_server_addr"].asString();
g_channel_conf.lPort = jsonValue["sc_server_port"].asUInt();
g_channel_conf.uListenPort = jsonValue["sc_listen_port"].asUInt();
g_channel_conf.uSignType = jsonValue["sc_sign_type"].asUInt();
g_channel_conf.uTimeout = jsonValue["sc_send_timeout"].asUInt();
g_channel_conf.sAccessCode = jsonValue["sc_access_code"].asString();
g_channel_conf.sUserName = jsonValue["sc_login_name"].asString();
g_channel_conf.sPassword = jsonValue["sc_login_passwd"].asString();
g_channel_conf.sSpId = jsonValue["sc_sp_code"].asString();
g_channel_conf.sServiceId = jsonValue["sc_service_id"].asString();
g_channel_conf.sFeeType = jsonValue["sc_fee_type"].asString();
g_channel_conf.sFeeCode = jsonValue["sc_fee_code"].asString();
g_channel_conf.sVersion = 0x0;
g_channel_conf.uSpnodeCode = atoi(jsonValue["sc_spnode_code"].asString().c_str());
g_channel_conf.uHttpType = http_type;
g_channel_conf.sHttpUrl = jsonValue["sc_http_url"].asString();
g_channel_conf.uCustomParam1 = jsonValue["sc_custom_param1"].asUInt();
g_channel_conf.uCustomParam2 = jsonValue["sc_custom_param2"].asUInt();
g_channel_conf.uCustomParam3 = jsonValue["sc_custom_param3"].asUInt();
g_channel_conf.uCustomParam4 = jsonValue["sc_custom_param4"].asUInt();
g_channel_conf.uCustomParam5 = jsonValue["sc_custom_param5"].asUInt();
if (g_channel_conf.lHeartbeatInterval == 0)
g_channel_conf.lHeartbeatInterval = 30000; // 默认为30s
if (g_channel_conf.uTimeout == 0)
g_channel_conf.uTimeout = 5000; // 默认为5s
return 0;
}
int json_to_msg(string msg_json,GateWayMsgSendReq *req,map<string,sms_attribute_t> &phonelist)
{
if( msg_json.empty() || req == NULL ) return -1;
// 解析json
try
{
Json::Reader jsonReader;
Json::Value jsonRoot, jsonValue;
if (!jsonReader.parse(msg_json, jsonRoot))
{
LOG_ERROR("Parse the json is failure.\n");
return -1;
}
// 消息包组装
// 接入号
jsonValue = jsonRoot["src_phone"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("src_phone property is not exist\n");
return -1;
}
req->set_srcphone(jsonValue.asString());
// 通用内容
jsonValue = jsonRoot["message_content"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("message_content property is not exist\n");
return -1;
}
req->set_messagecontent(jsonValue.asString());
// 通道类型
jsonValue = jsonRoot["channel_type"];
if (jsonValue.isNull() || !jsonValue.isInt())
{
LOG_ERROR("channel_type property is not exist.\n");
return -1;
}
req->set_channeltype(jsonValue.asInt());
// 通道ID
jsonValue = jsonRoot["channel_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("channel_id property is not exist.\n");
return -1;
}
req->set_channelid(jsonValue.asString());
// 通道组ID
jsonValue = jsonRoot["channel_groupid"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("channel_groupid property is not exist.\n");
return -1;
}
req->set_channelgroupid(jsonValue.asString());
// 业务代码
jsonValue = jsonRoot["service_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("service_id property is not exist.\n");
return -1;
}
req->set_serviceid(jsonValue.asString());
// sms_argument
Json::Value jsonArgument = jsonRoot["sms_argument"];
if (jsonArgument.isNull())
{
LOG_ERROR("sms_argument property is not exist.\n");
return -1;
}
// 日期
jsonValue = jsonArgument["datetime"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("sms_argument.datetime property is not exist.\n");
return -1;
}
req->set_datetime(jsonValue.asString());
// 子批次号
jsonValue = jsonArgument["submit_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("sms_argument.submit_id property is not exist.\n");
return -1;
}
req->set_submitid(jsonValue.asString());
// 批次号
jsonValue = jsonArgument["batchno"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("sms_argument.batchno property is not exist.\n");
return -1;
}
req->set_batchno(jsonValue.asString());
// 操作员ID
jsonValue = jsonArgument["operator_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("sms_argument.operator_id property is not exist.\n");
return -1;
}
req->set_operatorid(jsonValue.asString());
// 客户ID
jsonValue = jsonArgument["client_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("sms_argument.client_id property is not exist.\n");
return -1;
}
req->set_customerid(jsonValue.asString());
// 账号ID
jsonValue = jsonArgument["account_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("sms_argument.account_id property is not exist.\n");
return -1;
}
req->set_accountid(jsonValue.asString());
// 公司ID
jsonValue = jsonArgument["company_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
LOG_ERROR("sms_argument.company_id property is not exist.\n");
return -1;
}
req->set_companyid(jsonValue.asString());
// 提交方式
jsonValue = jsonArgument["submit_way"];
if (jsonValue.isNull() || !jsonValue.isInt())
{
LOG_ERROR("sms_argument.submit_way property is not exist.\n");
return -1;
}
req->set_submitway(jsonValue.asInt());
// 是否一对一短信
jsonValue = jsonArgument["oto_send"];
if (jsonValue.isNull() || !jsonValue.isBool())
{
LOG_ERROR("sms_argument.oto_send property is not exist.\n");
return -1;
}
bool oto_send = jsonValue.asBool();
if( oto_send )
{
req->set_isotosend(1);
}
else
{
req->set_isotosend(0);
}
// 是否重发短信
jsonValue = jsonArgument["sms_resend"];
if (jsonValue.isNull() || !jsonValue.isBool())
{
LOG_ERROR( "sms_argument.sms_resend property is not exist.\n");
return -1;
}
bool sms_resend = jsonValue.asBool();
if( sms_resend )
{
req->set_issmsresend(1);
}
else
{
req->set_issmsresend(0);
}
// 返量类型
jsonValue = jsonArgument["return_type"];
if (jsonValue.isNull() || !jsonValue.isInt())
{
LOG_ERROR( "sms_argument.return_type property is not exist.\n");
return -1;
}
req->set_returntype(jsonValue.asInt());
// SMS数据
jsonValue = jsonArgument["smsdata"];
if (jsonValue.isNull() || !jsonValue.isString())
{
req->set_smsdata("");
}
else
{
req->set_smsdata(jsonValue.asString());
}
// phone_list
Json::Value jsonPhoneList = jsonRoot["phone_list"];
if (jsonPhoneList.isNull() || !jsonPhoneList.isArray())
{
LOG_ERROR( "phone_list property is not exist.\n");
return -1;
}
for (unsigned int index = 0; index < jsonPhoneList.size(); index++)
{
Json::Value jsonSms = jsonPhoneList[index];
// 发送ID
jsonValue = jsonSms["send_id"];
if (jsonValue.isNull() || !jsonValue.isString())
{
continue;
}
// 是否实发
jsonValue = jsonSms["need_send"];
if (jsonValue.isNull() || !jsonValue.isBool())
{
continue;
}
// 虚拟状态
jsonValue = jsonSms["virtual_status"];
if (jsonValue.isNull() || !jsonValue.isString())
{
continue;
}
// 转换状态
jsonValue = jsonSms["convert_status"];
if (jsonValue.isNull() || !jsonValue.isString())
{
continue;
}
// 手机号码
jsonValue = jsonSms["mobile_phone"];
if (jsonValue.isNull() || !jsonValue.isString())
{
continue;
}
// 一对一短信内容
jsonValue = jsonSms["sms_content"];
if (jsonValue.isNull() || !jsonValue.isString())
{
continue;
}
// 手机号码所属城市
jsonValue = jsonSms["mobile_city"];
if (jsonValue.isNull() || !jsonValue.isString())
{
continue;
}
// PhoneList组装结构
sms_attribute_t smsAttribute;
std::string sSendId = jsonSms["send_id"].asString();
smsAttribute.bNeedSend = jsonSms["need_send"].asBool();
smsAttribute.sVirtualStatus = jsonSms["virtual_status"].asString();
smsAttribute.sConvertStatus = jsonSms["convert_status"].asString();
smsAttribute.sMobilePhone = jsonSms["mobile_phone"].asString();
smsAttribute.sSmsContent = jsonSms["sms_content"].asString();
smsAttribute.sMobileCity = jsonSms["mobile_city"].asString();
phonelist[sSendId] = smsAttribute;
}
}
catch (Json::LogicError &ex)
{
LOG_ERROR( "Parse the json is failure.The json:%s.\n", msg_json.c_str());
return -1;
}
return 0;
}
int fork_proc()
{
//是否启用多连接
if( g_conf.is_need_multi_conn == 0 )
{
//不启用,连接数为1个
g_channel_conf.uLinkCount = 1;
}
for(uint32_t i = 0; i < g_channel_conf.uLinkCount; i++)
{
pid_t pid = 0;
if((pid = fork()) > 0)// parent
{
LOG_INFO("fork send. child id=%d\n",pid);
g_send_pid.push_back(pid);
}
else if(pid == 0)// child
{
//关闭日志
log_only_close(g_log);
//执行通道进程
int ret = execl(g_conf.exe_name,g_conf.exe_name,
"-t",g_conf.channel_type,
"-i",g_conf.channel_id,
"-c",g_conf.conf_file,
(char*)NULL);
if(ret == -1)
{
perror("execl");
exit(0);
}
}
else
{
LOG_ERROR("execl send failed.\n");
return -1;
}
}
return 0;
}
//程序异常退出告警信息
int send_exit_alarm_msg(int pid)
{
string sTemplateParam,sTime;
char error_msg[128] = {0};
snprintf(error_msg,sizeof(error_msg),"网关发送子程序[%d]退出",pid);
sTime = MakeDateTime();
sTemplateParam = "{\"pid\":\"";
sTemplateParam += to_string(pid);
sTemplateParam += "\",\"time\":\"";
sTemplateParam += sTime;
sTemplateParam += "\",\"channel\":\"";
sTemplateParam += g_channel_conf.sChannelName;
sTemplateParam += "\"}";
Json::FastWriter jsonWriter;
Json::Value jsonValue;
jsonValue["modle_name"] = Json::Value("gateway_send");
jsonValue["level"] = Json::Value(5);
jsonValue["error_msg"] = Json::Value(error_msg);
jsonValue["sms_template_id"] = Json::Value(g_conf.template_id);
jsonValue["sms_template_param"] = Json::Value(sTemplateParam);
jsonValue["send_time"] = Json::Value(sTime);
string json_msg = jsonWriter.write(jsonValue);
save_alarm_msg(json_msg);
return 0;
}
int handle_mq_msg()
{
msgform_t mq_msg;
while( true )
{
//从消息队列里读取数据出来
int ret = g_mq.read(&mq_msg, sizeof(msgform_t), 1, IPC_NOWAIT);
if( ret <= 0 )
{
//mq里没数据,退出循环
break;
}
//解包
GateWayMsgSendReq req;
if (parse_msg(mq_msg.mtext,mq_msg.data_len,&req) != 0)
{
LOG_ERROR("parse_msg GateWayMsgSendReq failed.\n");
break;
}
//组成json
string one_msg;
msg_to_json(&req,one_msg);
//重写回redis
ret = save_channel_msg( g_conf.channel_id, one_msg );
if( ret != 0 )
{
LOG_ERROR("save_channel_msg failed.\n");
break;
}
}
return 0;
}
int handle_child_exit()
{
//将mq数据回填redis
handle_mq_msg();
//杀死所有发送子进程
vector<pid_t>::iterator it = g_send_pid.begin();
for(;it!=g_send_pid.end();)
{
//杀死子进程
kill(*it, SIGTERM);
//等待子进程退出,防止僵尸进程
waitpid(*it, NULL, 0);
it=g_send_pid.erase(it); //从列表删除
}
return 0;
} |
8d107c2c8d551a323772398ad48692d71cceae87 | 7178af3583618f23334585154fb82b6cd9847707 | /src/core/lindenb/io/lexer.h | f1dd811c6324bb7c39c71727aed501b73582a59f | [
"MIT"
] | permissive | lindenb/cclindenb | 5434c6aa760ced424bba4aa690861630f5c12f5e | d76c96ff0cbaec308a95f8be3752e588e0c58f9e | refs/heads/master | 2022-10-16T18:14:51.927699 | 2022-10-02T11:04:27 | 2022-10-02T11:04:27 | 716,170 | 18 | 15 | NOASSERTION | 2022-10-02T12:06:09 | 2010-06-11T18:41:53 | C++ | UTF-8 | C++ | false | false | 2,557 | h | lexer.h | #ifndef _LINDENB_IO_LEXER_H
#define _LINDENB_IO_LEXER_H
#include <string>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <cstring>
namespace lindenb { namespace io {
/**
Motivation:
a simple queue-based Lexer
Usage:
*/
class Lexer
{
private:
std::istream& in;
std::vector<char> buffer;
public:
typedef std::vector<char>::size_type size_type;
Lexer(std::istream& in):in(in)
{
}
int mustWhitespaces()
{
int c=0;
while(!isEof() &&
std::isspace(get()))
{
c++;
consumme(1);
}
if(c==0)
{
throw std::runtime_error("Error expected whitespace before "/* +toString() */);
}
return c;
}
/** skip all withspaces, returns the next get() character */
int skipWhitespaces()
{
int c;
while((c=get())!=EOF &&
std::isspace(c))
{
consumme(1);
}
return get();
}
/** return the next char without removing it from the stack */
int get()
{
return get(0);
}
/** return the index-th char without removing it from the stack */
int get(int index)
{
while(buffer.size()<=(size_type)index)
{
int c= in.get();
if(c==EOF) return EOF;
buffer.push_back((char)c);
}
return buffer[index];
}
/** pop and returns the next element in the stack */
int pop()
{
if(!buffer.empty())
{
char c= buffer.at(0);
buffer.erase(buffer.begin());
return c;
}
return in.get();
}
bool inAvail(const char* s)
{
return inAvail(0,s);
}
bool inAvail(int index,const char* s)
{
std::size_t len=std::strlen(s);
for(std::size_t i=0;i< (std::size_t)len;++i)
{
if(get(index+i)!=s[i]) return false;
}
return true;
}
int consumme(const int index,const int n)
{
int n_read=0;
while( (int) buffer.size()< index )
{
int c= in.get();
if(c==EOF) return 0;
buffer.push_back((char)c);
}
while( n_read<n && (int)buffer.size()>index )
{
n_read++;
buffer.erase(buffer.begin()+index);
}
while(n_read<n)
{
if(in.get()==-1) break;
n_read++;
}
return n_read;
}
int consumme( int n)
{
return consumme(0,n);
}
bool isEof()
{
return get()==EOF;
}
std::string toString(int i)
{
std::string str;
for(int j=0;j< i;++j)
{
int c=get(j);
if(c==EOF) { str.append("<<EOF>>"); break; }
str+=(char)c;
}
return str;
}
std::string toString()
{
return toString(20);
}
};
}}//namespaces
#endif |
cecf15aab1c9f22d6346378522aaeb957d0b47cb | 65a003b040520730f0db71d0df1d0d52a30c2c50 | /control/corba/cli/filterwheelcommand.h | 9565f9daf2da633a778c2bdc6824f700f71e9330 | [] | no_license | AndreasFMueller/AstroPhotography | dd4db3b90bd14eaf0f8cc225d19da1477a21418d | 23174595f1d0cb64bfcba46db75ade9925d245a4 | refs/heads/master | 2023-01-12T12:53:51.582049 | 2023-01-02T20:43:42 | 2023-01-02T20:43:42 | 7,716,135 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,151 | h | filterwheelcommand.h | /*
* filterwheelcommand.h -- commands for the filterwheel
*
* (c) 2013 Prof Dr Andreas Mueller, Hochschule Rapperswil
*/
#ifndef _filterwheelcommand_h
#define _filterwheelcommand_h
#include <clicommand.h>
#include <Filterwheels.h>
namespace astro {
namespace cli {
class filterwheelcommand : public clicommand {
void release(const std::string& filterwheelid,
const std::vector<std::string>& arguments);
void info(FilterwheelWrapper& filterwheel,
const std::vector<std::string>& arguments);
void assign(const std::string& filterwheelid,
const std::vector<std::string>& arguments);
void position(FilterwheelWrapper& filterwheel,
const std::vector<std::string>& arguments);
void wait(FilterwheelWrapper& filterwheel,
const std::vector<std::string>& arguments);
public:
filterwheelcommand(commandfactory& factory)
: clicommand(factory, std::string("filterwheel")) { }
virtual void operator()(const std::string& commandname,
const std::vector<std::string>& arguments);
virtual std::string help() const;
virtual std::string summary() const;
};
} // namespace astro
} // namespace cli
#endif /* _filterwheelcommand_h */
|
d2becc3d2180978a429578797222bc1ece79879e | 42422db8020c49dcd821a842ccba9dc295ebc912 | /queueinglib/WRClassifier.cc | 3f5f1ebb34f8822db7bbccd7f4968ca6896b7432 | [] | no_license | bradomyn/queue | 018adb69c7f74d94ee62dc034f89240adf1b2d42 | 59b616e73d3491fa0801b9e56b49fbda86e1f5d6 | refs/heads/master | 2020-04-05T23:04:16.549252 | 2012-03-08T08:30:41 | 2012-03-08T08:30:41 | 3,599,058 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,292 | cc | WRClassifier.cc | //
// This file is part of an OMNeT++/OMNEST simulation example.
//
// Copyright (C) 2006-2008 OpenSim Ltd.
//
// This file is distributed WITHOUT ANY WARRANTY. See the file
// `license' for details on this and other legal matters.
//
// SMa, 11.01.2012
#include "WRClassifier.h"
#include "Job.h"
namespace queueing {
Define_Module(WRClassifier);
void WRClassifier::initialize()
{
dispatchField = par("dispatchField");
}
void WRClassifier::handleMessage(cMessage *msg)
{
Job *job = check_and_cast<Job *>(msg);
int priority = job->getPriority();
int outGateIndex = -1;
if (strcmp(dispatchField, "type") == 0)
outGateIndex = job->getKind();
else if (strcmp(dispatchField, "priority") == 0) {
outGateIndex = job->getPriority();
std::cout << "priority " << job->getPriority() << std::endl;
}
else
error("invalid dispatchField parameter, must be \"type\" or \"priority\"");
// TODO we could look for the value in the dynamically added parameters too
//send(job, "out", outGateIndex);
//std::cout << "sent to outGateIndex: " << outGateIndex << std::endl;
std::string queue;
//sprintf(queue, "wrQueue%d", priority);
queue = "wrQueue";
char buffer[3];
sprintf(buffer,"%d\0",priority);
std::cout << "buf " << buffer << std::endl;
queue += buffer;
std::cout << "Classifier in: send package with priority " << priority << " to " << queue << std::endl;
cModule *targetModule = getParentModule()->getSubmodule(queue.c_str());
sendDirect(msg, targetModule, "sendDirect");
// SMa, 13.01.2012
//if( priority<7 ) {
/* if (outGateIndex < 0 || outGateIndex >= gateSize("out")) {
//send(job, "rest");
//error("outGateIndex < 0 || outGateIndex >= gateSize(out): %d (%d)", outGateIndex, gateSize("out"));
std::cout << "outGateIndex: " << outGateIndex << std::endl;
//send(job, "out", 0); // danger of overriding something?
cModule *targetModule = getParentModule()->getSubmodule("switch");
sendDirect(msg, targetModule, "sendDirect");
} */
/*} else {
// packets with highest priority send immediately
cModule *targetModule = getParentModule()->getSubmodule("switch");
sendDirect(msg, targetModule, "sendDirect");
}*/
/*
if (outGateIndex < 0 || outGateIndex >= gateSize("out")) {
//send(job, "rest");
//error("outGateIndex < 0 || outGateIndex >= gateSize(out): %d (%d)", outGateIndex, gateSize("out"));
std::cout << "outGateIndex: " << outGateIndex << std::endl;
//send(job, "out", 0); // danger of overriding something?
cModule *targetModule = getParentModule()->getSubmodule("wrQueue");
sendDirect(msg, targetModule, "sendDirect");
}
else if (outGateIndex>=7) {
// packets with highest priority send immediately
//send(job, "out", 0); // danger of overriding something?
cModule *targetModule = getParentModule()->getSubmodule("switch");
sendDirect(msg, targetModule, "sendDirect");
}
else {
// insert into queue that should be emptied if there is no high priority packet
// TODO
//send(job, "out", outGateIndex);
cModule *targetModule = getParentModule()->getSubmodule("wrQueue");
sendDirect(msg, targetModule, "sendDirect");
}*/
}
}; //namespace
|
89b4864d5d9f677771e9ab0424baeb93cc399979 | d4e8ac87bd41f311d196c62b5b8725ec5189ab1b | /reactive_framework7/reactive_context7.h | 56ed159f3326bac3d4bc3c51fd8f81d8e72ce3d1 | [] | no_license | HyenaSoftware/Libraries | 00b91dc1624741e74b9cb67f42a1a73ae9de6871 | 3fa431c5d60050fc2a1b6d5d2a2f9dbeef4aba6b | refs/heads/master | 2020-04-06T07:11:43.913451 | 2016-09-04T12:09:00 | 2016-09-04T12:09:00 | 63,279,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224 | h | reactive_context7.h | #pragma once
namespace reactive_framework7
{
namespace detail
{
class inode;
struct ireactive_context
{
virtual void on_value_holder_changed(inode&) = 0;
virtual void release_rv(const inode&) = 0;
};
}
}
|
754a1b9f5d00412b78ef11ab5eda1ee3f08dc953 | f8aa6e689d132d660e71335552b37cc1a5cb0786 | /TrainData/常用模板/结构/堆(binary).cpp | 67c2cb157926120850b710f6ac046770c56a731e | [] | no_license | VarickQ/ACM | 91171f381fa57b6644f10b1a4a5a9aeaeeff12b2 | 5d4f2c14272b28c7ff2cb7ebcd4e91400345a096 | refs/heads/master | 2021-01-10T14:34:07.812097 | 2017-05-14T09:58:54 | 2017-05-14T09:58:54 | 8,500,751 | 4 | 1 | null | null | null | null | GB18030 | C++ | false | false | 519 | cpp | 堆(binary).cpp | //二分堆
//可插入,获取并删除最小(最大)元素,复杂度均O(logn)
//可更改元素类型,修改比较符号或换成比较函数
#define MAXN 10000
#define _cp(a,b) ((a)<(b))
typedef int elem_t;
struct heap{
elem_t h[MAXN];
int n,p,c;
void init(){n=0;}
void ins(elem_t e){
for (p=++n;p>1&&_cp(e,h[p>>1]);h[p]=h[p>>1],p>>=1);
h[p]=e;
}
int del(elem_t& e){
if (!n) return 0;
for (e=h[p=1],c=2;c<n&&_cp(h[c+=(c<n-1&&_cp(h[c+1],h[c]))],h[n]);h[p]=h[c],p=c,c<<=1);
h[p]=h[n--];return 1;
}
}; |
69ed36d2574876692b7a572e3ccbbfc7ba2ea104 | 0467ca865829efeb3c64fd319e554d85eda101c3 | /Final Project/src/grid.h | f96880519ec9e95163419b3d804a52c1d150b448 | [] | no_license | ChenWendi2001/Principles-and-Practice-of-Problem-Solving | 9d144c529b2a7e11fd976e33ddf81b0b23edda70 | 96c4fe877d946f737c880de955c1bedcef53961d | refs/heads/master | 2023-02-05T20:07:33.962996 | 2020-12-29T01:59:36 | 2020-12-29T01:59:36 | 298,751,908 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 265 | h | grid.h | #ifndef GRID_H
#define GRID_H
#include <QVector>
#include <QString>
#include <QStringList>
class Grid
{
private:
int grid_id;
QVector<double> lat;
QVector<double> lng;
public:
Grid();
Grid(QString str);
};
#endif // GRID_H
|
624817521660c90357f562bafd62aafef82fa173 | 317748633a5a1f0755a544e68120ec9d7322f09b | /OJ/2018寒假训练/永远不会被删的文件/总/寒假/2.1/7-18.cpp | 276a6c113fa7a6d37a7d4a44ba44c5f6b32df0d4 | [] | no_license | ordinarv/ACM | b08ab46ef46b34248a2cb596d52dba63b8475c67 | 9027d0f580aa02f3ca18f2fb3b65e98743bafd69 | refs/heads/master | 2020-03-28T05:14:31.524194 | 2019-08-26T09:34:04 | 2019-08-26T09:34:04 | 147,764,655 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | cpp | 7-18.cpp | #include<stdio.h>
#include<queue>
using namespace std;
int main()
{
int a[1010],n;
queue<int> qa,qb;
scanf("%d",&n);
while(!qa.empty())
qa.pop();
while(!qb.empty())
qb.pop();
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
if(a[i]%2!=0)
qa.push(a[i]);
else
qb.push(a[i]);
}
int flag=1;
while(qa.size()>=2)
{
if(flag)
{
printf("%d",qa.front());
qa.pop();
flag=0;
}
else
{
printf(" %d",qa.front());
qa.pop();
}
printf(" %d",qa.front());
qa.pop();
if(!qb.empty())
{
printf(" %d",qb.front());
qb.pop();
}
}
while(!qa.empty())
{
printf(" %d",qa.front());
qa.pop();
}
while(!qb.empty())
{
printf(" %d",qb.front());
qb.pop();
}
printf("\n");
return 0;
}
|
8b0f15c4208972c83e71aa73e6a8f13a905dfae9 | dc92fbe3854bc79e60382ba090912bca63c0337b | /number-complement/number-complement.cpp | c8a007856ffb9d051cb4449a4455c8faae6b6cf1 | [] | no_license | Nikhilsharmaiiita/LeetcodeCracker | c613783348a46fec4850e88473d2fccd433a872a | 1b4b4454888746a1dd71a8ab48e866a12989c105 | refs/heads/main | 2023-08-13T15:31:33.765099 | 2021-10-11T13:54:44 | 2021-10-11T13:54:44 | 380,446,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | number-complement.cpp | class Solution {
public:
int findComplement(int num) {
int j=0;
for(int i=0;i<32;i++)
{
int mask=1<<i;
if(mask&num)j=i;
}
int ans=0;
cout<<j;
for(int i=0;i<=j;i++)
{
int mask=1<<i;
if((mask&num)==0)
ans+=(pow(2,i));
}
return ans;
}
}; |
be9034418760116720a1c2afe51ab2b53229059e | 0ad1e75df68fb14976c79c8921249dcd6e74f967 | /ETF - Euler Totient Function spoj.cpp | 4b91684ad538b6033eab873daa33f013983b9ab7 | [] | no_license | variablemayank/competetive-programming-codes | 9010d215832f4937735d6b35b1df35df0f8a59e6 | 71bbc70049089fcc24444471dd4504b1d29c371f | refs/heads/master | 2021-09-06T04:17:29.052221 | 2018-02-02T08:57:56 | 2018-02-02T08:57:56 | 119,955,414 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 330 | cpp | ETF - Euler Totient Function spoj.cpp | #include<bits/stdc++.h>
using namespace std;
int seive(int n)
{
int result =n;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
result -= result/i;
while(n%i==0) n /= i;
}
if(n>1) result -= result/n;
return result;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
cout<<seive(n)<<endl;
}
}
|
34947f96aa4279ca901933f6484d64a56f018bc1 | 05d0cdf14776f0ba714996d86ef92e4fef50516a | /libs/directag/pwiz-src/pwiz/data/msdata/RAMPAdapter.cpp | 9b89806f3dc9da69e823edea3ca02eb945c3f9d7 | [
"MIT",
"Apache-2.0"
] | permissive | buotex/BICEPS | 5a10396374da2e70e262c9304cf9710a147da484 | 10ed3938af8b05e372758ebe01dcb012a671a16a | refs/heads/master | 2020-05-30T20:20:55.378536 | 2014-01-06T21:31:56 | 2014-01-06T21:31:56 | 1,382,740 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 7,984 | cpp | RAMPAdapter.cpp | //
// RAMPAdapter.cpp
//
//
// Original author: Darren Kessner <Darren.Kessner@cshs.org>
//
// Copyright 2008 Spielberg Family Center for Applied Proteomics
// Cedars-Sinai Medical Center, Los Angeles, California 90048
//
// 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.
//
#define PWIZ_SOURCE
#include "RAMPAdapter.hpp"
#include "MSDataFile.hpp"
#include "LegacyAdapter.hpp"
#include "CVTranslator.hpp"
#include "boost/lexical_cast.hpp"
#include "boost/static_assert.hpp"
#include <stdexcept>
#include <iostream>
#include <algorithm>
namespace pwiz {
namespace msdata {
using namespace std;
using boost::lexical_cast;
using boost::bad_lexical_cast;
class RAMPAdapter::Impl
{
public:
Impl(const string& filename)
: msd_(filename)
{
if (!msd_.run.spectrumListPtr.get())
throw runtime_error("[RAMPAdapter] Null spectrumListPtr.");
}
size_t scanCount() const
{
return msd_.run.spectrumListPtr->size();
}
size_t index(int scanNumber) const
{
return msd_.run.spectrumListPtr->findNative(lexical_cast<string>(scanNumber));
}
void getScanHeader(size_t index, ScanHeaderStruct& result) const;
void getScanPeaks(size_t index, std::vector<double>& result) const;
void getRunHeader(RunHeaderStruct& result) const;
void getInstrument(InstrumentStruct& result) const;
private:
MSDataFile msd_;
CVTranslator cvTranslator_;
};
namespace {
double retentionTime(const Scan& scan)
{
CVParam param = scan.cvParam(MS_scan_time);
if (param.units == MS_second)
return param.valueAs<double>();
else if (param.units == MS_minute)
return param.valueAs<double>() * 60;
return 0;
}
int scanNumber(const string& nativeID)
{
try
{
return lexical_cast<int>(nativeID);
}
catch (bad_lexical_cast&)
{
return 0;
}
}
} // namespace
void RAMPAdapter::Impl::getScanHeader(size_t index, ScanHeaderStruct& result) const
{
const SpectrumList& spectrumList = *msd_.run.spectrumListPtr;
SpectrumPtr spectrum = spectrumList.spectrum(index);
const SpectrumDescription& sd = spectrum->spectrumDescription;
result.seqNum = static_cast<int>(index + 1);
result.acquisitionNum = scanNumber(spectrum->nativeID);
result.msLevel = spectrum->cvParam(MS_ms_level).valueAs<int>();
result.peaksCount = static_cast<int>(spectrum->defaultArrayLength);
result.totIonCurrent = sd.cvParam(MS_total_ion_current).valueAs<double>();
result.retentionTime = sd.scan.cvParam(MS_scan_time).timeInSeconds();
result.basePeakMZ = sd.cvParam(MS_base_peak_m_z).valueAs<double>();
result.basePeakIntensity = sd.cvParam(MS_base_peak_intensity).valueAs<double>();
result.collisionEnergy = 0;
result.ionisationEnergy = sd.cvParam(MS_ionization_energy).valueAs<double>();
result.lowMZ = sd.cvParam(MS_lowest_m_z_value).valueAs<double>();
result.highMZ = sd.cvParam(MS_highest_m_z_value).valueAs<double>();
result.precursorScanNum = 0;
result.precursorMZ = 0;
result.precursorCharge = 0;
result.precursorIntensity = 0;
if (!sd.precursors.empty())
{
const Precursor& precursor = sd.precursors[0];
result.collisionEnergy = precursor.activation.cvParam(MS_collision_energy).valueAs<double>();
size_t precursorIndex = msd_.run.spectrumListPtr->find(precursor.spectrumID);
if (precursorIndex < spectrumList.size())
result.precursorScanNum = scanNumber(spectrumList.spectrum(precursorIndex)->nativeID);
if (!precursor.selectedIons.empty())
{
result.precursorMZ = precursor.selectedIons[0].cvParam(MS_m_z).valueAs<double>();
result.precursorCharge = precursor.selectedIons[0].cvParam(MS_charge_state).valueAs<int>();
result.precursorIntensity = precursor.selectedIons[0].cvParam(MS_intensity).valueAs<double>();
}
}
BOOST_STATIC_ASSERT(SCANTYPE_LENGTH > 4);
memset(result.scanType, 0, SCANTYPE_LENGTH);
CVParam paramScanType = sd.scan.cvParamChild(MS_scanning_method);
if (paramScanType.cvid == MS_full_scan) strcpy(result.scanType, "Full");
if (paramScanType.cvid == MS_zoom_scan) strcpy(result.scanType, "Zoom");
result.mergedScan = 0; // TODO
result.mergedResultScanNum = 0; // TODO
result.mergedResultStartScanNum = 0; // TODO
result.mergedResultEndScanNum = 0; // TODO
result.filePosition = spectrum->sourceFilePosition;
}
void RAMPAdapter::Impl::getScanPeaks(size_t index, std::vector<double>& result) const
{
SpectrumPtr spectrum = msd_.run.spectrumListPtr->spectrum(index, true);
result.clear();
result.resize(spectrum->defaultArrayLength * 2);
if (spectrum->defaultArrayLength == 0) return;
spectrum->getMZIntensityPairs(reinterpret_cast<MZIntensityPair*>(&result[0]),
spectrum->defaultArrayLength);
}
void RAMPAdapter::Impl::getRunHeader(RunHeaderStruct& result) const
{
const SpectrumList& spectrumList = *msd_.run.spectrumListPtr;
result.scanCount = static_cast<int>(spectrumList.size());
result.lowMZ = 0; // TODO
result.highMZ = 0; // TODO
result.startMZ = 0; // TODO
result.endMZ = 0; // TODO
SpectrumPtr spectrum = spectrumList.spectrum(0, false);
result.dStartTime = retentionTime(spectrum->spectrumDescription.scan);
spectrum = spectrumList.spectrum(1, false);
result.dEndTime = retentionTime(spectrum->spectrumDescription.scan);
}
namespace {
inline void copyInstrumentString(char* to, const string& from)
{
strncpy(to, from.substr(0,INSTRUMENT_LENGTH-1).c_str(), INSTRUMENT_LENGTH);
}
} // namespace
void RAMPAdapter::Impl::getInstrument(InstrumentStruct& result) const
{
const InstrumentConfiguration& instrumentConfiguration =
(!msd_.instrumentConfigurationPtrs.empty() && msd_.instrumentConfigurationPtrs[0].get()) ?
*msd_.instrumentConfigurationPtrs[0] :
InstrumentConfiguration(); // temporary bound to const reference
// this const_cast is ok since we're only calling const functions,
// but we wish C++ had "const constructors"
const LegacyAdapter_Instrument adapter(const_cast<InstrumentConfiguration&>(instrumentConfiguration), cvTranslator_);
copyInstrumentString(result.manufacturer, adapter.manufacturer());
copyInstrumentString(result.model, adapter.model());
copyInstrumentString(result.ionisation, adapter.ionisation());
copyInstrumentString(result.analyzer, adapter.analyzer());
copyInstrumentString(result.detector, adapter.detector());
}
//
// RAMPAdapter
//
PWIZ_API_DECL RAMPAdapter::RAMPAdapter(const std::string& filename) : impl_(new Impl(filename)) {}
PWIZ_API_DECL size_t RAMPAdapter::scanCount() const {return impl_->scanCount();}
PWIZ_API_DECL size_t RAMPAdapter::index(int scanNumber) const {return impl_->index(scanNumber);}
PWIZ_API_DECL void RAMPAdapter::getScanHeader(size_t index, ScanHeaderStruct& result) const {impl_->getScanHeader(index, result);}
PWIZ_API_DECL void RAMPAdapter::getScanPeaks(size_t index, std::vector<double>& result) const {impl_->getScanPeaks(index, result);}
PWIZ_API_DECL void RAMPAdapter::getRunHeader(RunHeaderStruct& result) const {impl_->getRunHeader(result);}
PWIZ_API_DECL void RAMPAdapter::getInstrument(InstrumentStruct& result) const {impl_->getInstrument(result);}
} // namespace msdata
} // namespace pwiz
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.