id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
750,311
|
atomco64.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomco64.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomco64.h"
AtomCO64::AtomCO64(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
}
AtomCO64::~AtomCO64() {
}
vector<uint64_t> AtomCO64::GetEntries() {
return _entries;
}
bool AtomCO64::ReadData() {
uint32_t count;
if (!ReadUInt32(count)) {
FATAL("Unable to read count");
return false;
}
for (uint32_t i = 0; i < count; i++) {
uint64_t offset;
if (!ReadUInt64(offset)) {
FATAL("Unable to read offset");
return false;
}
ADD_VECTOR_END(_entries, offset);
}
return true;
}
#endif /* HAS_MEDIA_MP4 */
| 1,429
|
C++
|
.cpp
| 45
| 29.577778
| 88
| 0.727074
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,312
|
atomtfhd.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomtfhd.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomtfhd.h"
AtomTFHD::AtomTFHD(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
_trackID = 0;
_baseDataOffset = 0;
_sampleDescriptionIndex = 0;
_defaultSampleDuration = 0;
_defaultSampleSize = 0;
_defaultSampleFlags = 0;
}
AtomTFHD::~AtomTFHD() {
}
uint32_t AtomTFHD::GetTrackId() {
return _trackID;
}
int64_t AtomTFHD::GetBaseDataOffset() {
return _baseDataOffset;
}
bool AtomTFHD::HasBaseDataOffset() {
return (_flags[2]&0x01) != 0;
}
bool AtomTFHD::HasSampleDescriptionIndex() {
return (_flags[2]&0x02) != 0;
}
bool AtomTFHD::HasDefaultSampleDuration() {
return (_flags[2]&0x08) != 0;
}
bool AtomTFHD::HasDefaultSampleSize() {
return (_flags[2]&0x10) != 0;
}
bool AtomTFHD::HasDefaultSampleFlags() {
return (_flags[2]&0x20) != 0;
}
bool AtomTFHD::DurationIsEmpty() {
return (_flags[0]&0x01) != 0;
}
bool AtomTFHD::ReadData() {
//FINEST("TFHD");
if (!ReadInt32(_trackID)) {
FATAL("Unable to read track ID");
return false;
}
//FINEST("_trackID: %"PRIi32, _trackID);
if (HasBaseDataOffset()) {
if (!ReadInt64(_baseDataOffset)) {
FATAL("Unable to read base data offset");
return false;
}
//FINEST("_baseDataOffset: %"PRIi64, _baseDataOffset);
}
if (HasSampleDescriptionIndex()) {
if (!ReadInt32(_sampleDescriptionIndex)) {
FATAL("Unable to read sample description index");
return false;
}
//FINEST("_sampleDescriptionIndex: %"PRIi32, _sampleDescriptionIndex);
}
if (HasDefaultSampleDuration()) {
if (!ReadInt32(_defaultSampleDuration)) {
FATAL("Unable to read default sample duration");
return false;
}
//FINEST("_defaultSampleDuration: %"PRIi32, _defaultSampleDuration);
}
if (HasDefaultSampleSize()) {
if (!ReadInt32(_defaultSampleSize)) {
FATAL("Unable to read default sample size");
return false;
}
//FINEST("_defaultSampleSize: %"PRIi32, _defaultSampleSize);
}
if (HasDefaultSampleFlags()) {
if (!ReadInt32(_defaultSampleFlags)) {
FATAL("Unable to read default sample flags");
return false;
}
//FINEST("_defaultSampleFlags: %"PRIi32, _defaultSampleFlags);
}
return true;
}
#endif /* HAS_MEDIA_MP4 */
| 3,014
|
C++
|
.cpp
| 100
| 27.85
| 88
| 0.724673
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,313
|
atomstss.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomstss.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomstss.h"
AtomSTSS::AtomSTSS(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
}
AtomSTSS::~AtomSTSS() {
}
vector<uint32_t> AtomSTSS::GetEntries() {
return _entries;
}
bool AtomSTSS::ReadData() {
uint32_t count;
if (!ReadUInt32(count)) {
FATAL("Unable to read count");
return false;
}
for (uint32_t i = 0; i < count; i++) {
uint32_t sampleNumber;
if (!ReadUInt32(sampleNumber)) {
FATAL("Unable to read sample number");
return false;
}
ADD_VECTOR_END(_entries, sampleNumber);
}
return true;
}
#endif /* HAS_MEDIA_MP4 */
| 1,453
|
C++
|
.cpp
| 45
| 30.133333
| 88
| 0.731237
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,314
|
atomdref.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomdref.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomdref.h"
#include "mediaformats/readers/mp4/mp4document.h"
AtomDREF::AtomDREF(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedBoxAtom(pDocument, type, size, start) {
}
AtomDREF::~AtomDREF() {
}
bool AtomDREF::ReadData() {
uint32_t count;
if (!ReadUInt32(count)) {
FATAL("Unable to read count");
return false;
}
return true;
}
bool AtomDREF::AtomCreated(BaseAtom *pAtom) {
switch (pAtom->GetTypeNumeric()) {
case A_URL:
ADD_VECTOR_END(_urls, (AtomURL *) pAtom);
return true;
default:
{
FATAL("Invalid atom type: %s", STR(pAtom->GetTypeString()));
return false;
}
}
}
#endif /* HAS_MEDIA_MP4 */
| 1,495
|
C++
|
.cpp
| 47
| 29.659574
| 88
| 0.73301
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,315
|
atomtkhd.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomtkhd.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomtkhd.h"
AtomTKHD::AtomTKHD(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
_creationTime = 0;
_modificationTime = 0;
_trackId = 0;
memset(_reserved1, 0, 4);
_duration = 0;
memset(_reserved2, 0, 8);
_layer = 0;
_alternateGroup = 0;
_volume = 0;
memset(_reserved3, 0, 2);
memset(_matrixStructure, 0, 36);
_trackWidth = 0;
_trackHeight = 0;
}
AtomTKHD::~AtomTKHD() {
}
uint32_t AtomTKHD::GetTrackId() {
return _trackId;
}
uint32_t AtomTKHD::GetWidth() {
return _trackWidth >> 16;
}
uint32_t AtomTKHD::GetHeight() {
return _trackHeight >> 16;
}
bool AtomTKHD::ReadData() {
if (_version == 1) {
if (!ReadUInt64(_creationTime)) {
FATAL("Unable to read creation time");
return false;
}
if (!ReadUInt64(_modificationTime)) {
FATAL("Unable to read modification time");
return false;
}
} else {
uint32_t temp = 0;
if (!ReadUInt32(temp)) {
FATAL("Unable to read creation time");
return false;
}
_creationTime = temp;
if (!ReadUInt32(temp)) {
FATAL("Unable to read modification time");
return false;
}
_modificationTime = temp;
}
if (!ReadUInt32(_trackId)) {
FATAL("Unable to read track id");
return false;
}
if (!ReadArray(_reserved1, 4)) {
FATAL("Unable to read reserved 1");
return false;
}
if (_version == 1) {
if (!ReadUInt64(_duration)) {
FATAL("Unable to read duration");
return false;
}
} else {
uint32_t temp = 0;
if (!ReadUInt32(temp)) {
FATAL("Unable to read duration");
return false;
}
_duration = temp;
}
if (!ReadArray(_reserved2, 8)) {
FATAL("Unable to read reserved 2");
return false;
}
if (!ReadUInt16(_layer)) {
FATAL("Unable to read layer");
return false;
}
if (!ReadUInt16(_alternateGroup)) {
FATAL("Unable to read alternate group");
return false;
}
if (!ReadUInt16(_volume)) {
FATAL("Unable to read volume");
return false;
}
if (!ReadArray(_reserved3, 2)) {
FATAL("Unable to read reserved 3");
return false;
}
if (!ReadArray(_matrixStructure, 36)) {
FATAL("Unable to read matrix structure");
return false;
}
if (!ReadUInt32(_trackWidth)) {
FATAL("Unable to read track width");
return false;
}
if (!ReadUInt32(_trackHeight)) {
FATAL("Unable to read track height");
return false;
}
return true;
}
#endif /* HAS_MEDIA_MP4 */
| 3,210
|
C++
|
.cpp
| 126
| 22.944444
| 88
| 0.695851
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,316
|
atomavc1.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomavc1.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomavc1.h"
#include "mediaformats/readers/mp4/mp4document.h"
#include "mediaformats/readers/mp4/atomavcc.h"
AtomAVC1::AtomAVC1(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: BoxAtom(pDocument, type, size, start) {
_pAVCC = NULL;
}
AtomAVC1::~AtomAVC1() {
}
bool AtomAVC1::Read() {
//aligned(8) abstract class SampleEntry (unsigned int(32) format) extends Box(format){
// const unsigned int(8)[6] reserved = 0;
// unsigned int(16) data_reference_index;
//}
//class VisualSampleEntry(codingname) extends SampleEntry (codingname){
// unsigned int(16) pre_defined = 0;
// const unsigned int(16) reserved = 0;
// unsigned int(32)[3] pre_defined = 0;
// unsigned int(16) width;
// unsigned int(16) height;
// template unsigned int(32) horizresolution = 0x00480000; // 72 dpi template
// unsigned int(32) vertresolution = 0x00480000; // 72 dpi
// const unsigned int(32) reserved = 0;
// template unsigned int(16) frame_count = 1;
// string[32] compressorname;
// template unsigned int(16) depth = 0x0018;
// int(16) pre_defined = -1;
//}
if (!SkipBytes(78)) {
FATAL("Unable to skip 78 bytes");
return false;
}
return BoxAtom::Read();
}
bool AtomAVC1::AtomCreated(BaseAtom *pAtom) {
switch (pAtom->GetTypeNumeric()) {
//TODO: What is the deal with all this order stuff!?
case A_AVCC:
_pAVCC = (AtomAVCC *) pAtom;
return true;
default:
{
FATAL("Invalid atom type: %s", STR(pAtom->GetTypeString()));
return false;
}
}
}
#endif /* HAS_MEDIA_MP4 */
| 2,354
|
C++
|
.cpp
| 67
| 33
| 88
| 0.720053
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,317
|
atomilst.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomilst.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomilst.h"
#include "mediaformats/readers/mp4/mp4document.h"
#include "mediaformats/readers/mp4/atommetafield.h"
AtomILST::AtomILST(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: BoxAtom(pDocument, type, size, start) {
_metadata.IsArray(false);
}
AtomILST::~AtomILST() {
}
Variant &AtomILST::GetMetadata() {
return _metadata;
}
bool AtomILST::AtomCreated(BaseAtom *pAtom) {
if ((pAtom->GetTypeNumeric() >> 24) == 0xa9) {
AtomMetaField *pField = (AtomMetaField *) pAtom;
_metadata[pField->GetName()] = pField->GetValue();
return true;
}
switch (pAtom->GetTypeNumeric()) {
case A_AART:
case A_COVR:
case A_CPIL:
case A_DESC:
case A_DISK:
case A_GNRE:
case A_PGAP:
case A_TMPO:
case A_TRKN:
case A_TVEN:
case A_TVES:
case A_TVSH:
case A_TVSN:
case A_SONM:
case A_SOAL:
case A_SOAR:
case A_SOAA:
case A_SOCO:
case A_SOSN:
{
AtomMetaField *pField = (AtomMetaField *) pAtom;
_metadata[pField->GetName()] = pField->GetValue();
return true;
}
default:
{
FATAL("Invalid atom type: %s", STR(pAtom->GetTypeString()));
return false;
}
}
}
#endif /* HAS_MEDIA_MP4 */
| 1,990
|
C++
|
.cpp
| 70
| 26.028571
| 88
| 0.718391
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,318
|
atomstsz.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomstsz.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomstsz.h"
AtomSTSZ::AtomSTSZ(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
}
AtomSTSZ::~AtomSTSZ() {
}
vector<uint64_t> AtomSTSZ::GetEntries() {
return _entries;
}
bool AtomSTSZ::ReadData() {
if (!ReadUInt32(_sampleSize)) {
FATAL("Unable to read sample size");
return false;
}
if (!ReadUInt32(_sampleCount)) {
FATAL("Unable to read sample count");
return false;
}
if (_sampleSize != 0) {
for (uint32_t i = 0; i < _sampleCount; i++) {
ADD_VECTOR_END(_entries, _sampleSize);
}
return true;
} else {
for (uint32_t i = 0; i < _sampleCount; i++) {
uint32_t size;
if (!ReadUInt32(size)) {
FATAL("Unable to read size");
return false;
}
ADD_VECTOR_END(_entries, size);
}
return true;
}
}
#endif /* HAS_MEDIA_MP4 */
| 1,671
|
C++
|
.cpp
| 55
| 27.963636
| 88
| 0.708152
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,319
|
boxatom.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/boxatom.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/boxatom.h"
#include "mediaformats/readers/mp4/mp4document.h"
BoxAtom::BoxAtom(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: BaseAtom(pDocument, type, size, start) {
}
BoxAtom::~BoxAtom() {
}
bool BoxAtom::Read() {
while (CurrentPosition() != _start + _size) {
BaseAtom *pAtom = GetDoc()->ReadAtom(this);
if (pAtom == NULL) {
FATAL("Unable to read atom. Parent atom is %s",
STR(GetTypeString()));
return false;
}
if (!pAtom->IsIgnored()) {
if (!AtomCreated(pAtom)) {
FATAL("Unable to signal AtomCreated for atom %s (%"PRIx64")",
STR(GetTypeString()), _start);
return false;
}
}
ADD_VECTOR_END(_subAtoms, pAtom);
}
return true;
}
string BoxAtom::Hierarchy(uint32_t indent) {
string result = string(indent * 4, ' ') + GetTypeString() + "\n";
if (_subAtoms.size() == 0) {
result += string((indent + 1) * 4, ' ') + "[empty]";
return result;
}
for (uint32_t i = 0; i < _subAtoms.size(); i++) {
result += _subAtoms[i]->Hierarchy(indent + 1);
if (i != _subAtoms.size() - 1)
result += "\n";
}
return result;
}
BaseAtom * BoxAtom::GetPath(uint8_t depth, ...) {
vector<uint32_t> path;
va_list arguments;
va_start(arguments, depth);
for (uint8_t i = 0; i < depth; i++) {
uint32_t pathElement = va_arg(arguments, uint32_t);
ADD_VECTOR_END(path, pathElement);
}
va_end(arguments);
if (path.size() == 0)
return NULL;
return GetPath(path);
}
BaseAtom * BoxAtom::GetPath(vector<uint32_t> path) {
if (path.size() == 0)
return NULL;
uint32_t search = path[0];
path.erase(path.begin());
for (uint32_t i = 0; i < _subAtoms.size(); i++) {
if (_subAtoms[i]->GetTypeNumeric() == search) {
if (path.size() == 0)
return _subAtoms[i];
return _subAtoms[i]->GetPath(path);
}
}
return NULL;
}
#endif /* HAS_MEDIA_MP4 */
| 2,657
|
C++
|
.cpp
| 86
| 28.395349
| 86
| 0.676827
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,320
|
atomurl.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomurl.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomurl.h"
AtomURL::AtomURL(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
}
AtomURL::~AtomURL() {
}
bool AtomURL::ReadData() {
if (!ReadString(_location, _size - 12)) {
FATAL("Unable to read location");
return false;
}
return true;
}
#endif /* HAS_MEDIA_MP4 */
| 1,176
|
C++
|
.cpp
| 33
| 33.69697
| 86
| 0.738786
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,321
|
atomtrun.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomtrun.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomtrun.h"
AtomTRUN::AtomTRUN(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
}
AtomTRUN::~AtomTRUN() {
for (uint32_t i = 0; i < _samples.size(); i++) {
delete _samples[i];
}
_samples.clear();
}
bool AtomTRUN::HasDataOffset() {
return (_flags[2]&0x01) != 0;
}
bool AtomTRUN::HasFirstSampleFlags() {
return (_flags[2]&0x04) != 0;
}
bool AtomTRUN::HasSampleDuration() {
return (_flags[1]&0x01) != 0;
}
bool AtomTRUN::HasSampleSize() {
return (_flags[1]&0x02) != 0;
}
bool AtomTRUN::HasSampleFlags() {
return (_flags[1]&0x04) != 0;
}
bool AtomTRUN::HasSampleCompositionTimeOffsets() {
return (_flags[1]&0x08) != 0;
}
uint32_t AtomTRUN::GetDataOffset() {
return _dataOffset;
}
vector<TRUNSample *> &AtomTRUN::GetSamples() {
return _samples;
}
bool AtomTRUN::ReadData() {
//FINEST("TRUN");
if (!ReadUInt32(_sampleCount)) {
FATAL("Unable to read sample count");
return false;
}
//FINEST("_sampleCount: %"PRIu32, _sampleCount);
if (HasDataOffset()) {
if (!ReadInt32(_dataOffset)) {
FATAL("Unable to read data offset");
return false;
}
//FINEST("_dataOffset: %"PRIi32, _dataOffset);
}
if (HasFirstSampleFlags()) {
if (!ReadUInt32(_firstSampleFlags)) {
FATAL("Unable to read first sample flags");
return false;
}
//FINEST("_firstSampleFlags: %"PRIu32, _firstSampleFlags);
}
for (uint32_t i = 0; i < _sampleCount; i++) {
TRUNSample *pSample = new TRUNSample();
if (HasSampleDuration()) {
if (!ReadUInt32(pSample->duration)) {
FATAL("Unable to read sample duration");
return false;
}
//FINEST("duration: %"PRIu32, pSample->duration);
}
if (HasSampleSize()) {
if (!ReadUInt32(pSample->size)) {
FATAL("Unable to read sample size");
return false;
}
//FINEST("size: %"PRIu32, pSample->size);
}
if (HasSampleFlags()) {
if (!ReadUInt32(pSample->flags)) {
FATAL("Unable to read sample flags");
return false;
}
//FINEST("flags: %"PRIu32, pSample->flags);
}
if (HasSampleCompositionTimeOffsets()) {
if (!ReadUInt32(pSample->compositionTimeOffset)) {
FATAL("Unable to read sample composition time offset");
return false;
}
//FINEST("compositionTimeOffset: %"PRIu32, pSample->compositionTimeOffset);
}
ADD_VECTOR_END(_samples, pSample);
}
return true;
}
#endif /* HAS_MEDIA_MP4 */
| 3,219
|
C++
|
.cpp
| 109
| 26.908257
| 88
| 0.697449
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,322
|
atommdia.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atommdia.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atommdia.h"
#include "mediaformats/readers/mp4/mp4document.h"
AtomMDIA::AtomMDIA(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: BoxAtom(pDocument, type, size, start) {
_pMDHD = NULL;
_pHDLR = NULL;
_pMINF = NULL;
_pDINF = NULL;
_pSTBL = NULL;
}
AtomMDIA::~AtomMDIA() {
}
bool AtomMDIA::AtomCreated(BaseAtom *pAtom) {
switch (pAtom->GetTypeNumeric()) {
case A_MDHD:
_pMDHD = (AtomMDHD *) pAtom;
return true;
case A_HDLR:
_pHDLR = (AtomHDLR *) pAtom;
return true;
case A_MINF:
_pMINF = (AtomMINF *) pAtom;
return true;
case A_DINF:
_pDINF = (AtomDINF *) pAtom;
return true;
case A_STBL:
_pSTBL = (AtomSTBL *) pAtom;
return true;
default:
{
FATAL("Invalid atom type: %s", STR(pAtom->GetTypeString()));
return false;
}
}
}
#endif /* HAS_MEDIA_MP4 */
| 1,666
|
C++
|
.cpp
| 56
| 27.267857
| 88
| 0.710723
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,323
|
atomavcc.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/mp4/atomavcc.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomavcc.h"
AtomAVCC::AtomAVCC(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: BaseAtom(pDocument, type, size, start) {
_configurationVersion = 0;
_profile = 0;
_profileCompatibility = 0;
_level = 0;
_naluLengthSize = 0;
}
AtomAVCC::~AtomAVCC() {
FOR_VECTOR_ITERATOR(AVCCParameter, _seqParameters, i) {
if (VECTOR_VAL(i).pData != NULL)
delete[] VECTOR_VAL(i).pData;
}
FOR_VECTOR_ITERATOR(AVCCParameter, _picParameters, i) {
if (VECTOR_VAL(i).pData != NULL)
delete[] VECTOR_VAL(i).pData;
}
}
uint64_t AtomAVCC::GetExtraDataStart() {
return _start + 8;
}
uint64_t AtomAVCC::GetExtraDataLength() {
return _size - 8;
}
bool AtomAVCC::Read() {
uint8_t _seqCount;
uint8_t _picCount;
if (!ReadUInt8(_configurationVersion)) {
FATAL("Unable to read _configurationVersion");
return false;
}
if (!ReadUInt8(_profile)) {
FATAL("Unable to read _profile");
return false;
}
if (!ReadUInt8(_profileCompatibility)) {
FATAL("Unable to read _profileCompatibility");
return false;
}
if (!ReadUInt8(_level)) {
FATAL("Unable to read _level");
return false;
}
if (!ReadUInt8(_naluLengthSize)) {
FATAL("Unable to read _naluLengthSize");
return false;
}
_naluLengthSize = 1 + (_naluLengthSize & 0x03);
if (!ReadUInt8(_seqCount)) {
FATAL("Unable to read _seqCount");
return false;
}
_seqCount = _seqCount & 0x1f;
for (uint8_t i = 0; i < _seqCount; i++) {
AVCCParameter parameter = {0};
if (!ReadUInt16(parameter.size)) {
FATAL("Unable to read parameter.size");
return false;
}
if (parameter.size > 0) {
parameter.pData = new uint8_t[parameter.size];
if (!ReadArray(parameter.pData, parameter.size)) {
FATAL("Unable to read parameter.pData");
return false;
}
}
ADD_VECTOR_END(_seqParameters, parameter);
}
if (!ReadUInt8(_picCount)) {
FATAL("Unable to read _picCount");
return false;
}
for (uint8_t i = 0; i < _picCount; i++) {
AVCCParameter parameter = {0, 0};
if (!ReadUInt16(parameter.size)) {
FATAL("Unable to read parameter.size");
return false;
}
if (parameter.size > 0) {
parameter.pData = new uint8_t[parameter.size];
if (!ReadArray(parameter.pData, parameter.size)) {
FATAL("Unable to read parameter.pData");
return false;
}
}
ADD_VECTOR_END(_picParameters, parameter);
}
return true;
}
string AtomAVCC::Hierarchy(uint32_t indent) {
return string(4 * indent, ' ') + GetTypeString();
}
#endif /* HAS_MEDIA_MP4 */
| 3,319
|
C++
|
.cpp
| 113
| 26.699115
| 88
| 0.706419
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,324
|
tsframereader.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/ts/tsframereader.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_TS
#include "mediaformats/readers/ts/tsframereader.h"
#include "mediaformats/readers/ts/avcontext.h"
#include "mediaformats/readers/ts/tsframereaderinterface.h"
TSFrameReader::TSFrameReader(TSFrameReaderInterface *pInterface)
: TSParser(this) {
_pFile = NULL;
_freeFile = false;
_chunkSizeDetectionCount = 0;
_chunkSize = 0;
_chunkSizeErrors = false;
_frameAvailable = false;
_eof = true;
_pInterface = pInterface;
if (_pInterface == NULL) {
ASSERT("TSFrame reader can't have NULL interface");
}
}
TSFrameReader::~TSFrameReader() {
FreeFile();
}
bool TSFrameReader::SetFile(string filePath) {
FreeFile();
_freeFile = true;
_pFile = GetFile(filePath, 4 * 1024 * 1024);
if (_pFile == NULL) {
FATAL("Unable to open file %s", STR(filePath));
return false;
}
if (!DetermineChunkSize()) {
FATAL("Unable to determine chunk size");
FreeFile();
return false;
}
SetChunkSize(_chunkSize);
if (!_pFile->SeekTo(_chunkSizeDetectionCount)) {
FATAL("Unable to seek to the beginning of file");
FreeFile();
return false;
}
_eof = _pFile->IsEOF();
_defaultBlockSize = ((1024 * 1024 * 2) / _chunkSize) * _chunkSize;
return true;
}
bool TSFrameReader::IsEOF() {
return _eof;
}
bool TSFrameReader::Seek(uint64_t offset) {
if (_pFile == NULL)
return false;
return _pFile->SeekTo(offset);
}
bool TSFrameReader::ReadFrame() {
_frameAvailable = false;
if (GETAVAILABLEBYTESCOUNT(_chunkBuffer) < _chunkSize) {
uint64_t available = _pFile->Size() - _pFile->Cursor();
available = available < _defaultBlockSize ? available : _defaultBlockSize;
available /= _chunkSize;
available *= _chunkSize;
if (available < _chunkSize) {
_eof = true;
return true;
}
_chunkBuffer.MoveData();
if (!_chunkBuffer.ReadFromFs(*_pFile, (uint32_t) available)) {
FATAL("Unable to read %"PRIu8" bytes from file", _chunkSize);
return false;
}
}
while ((!_chunkSizeErrors)
&& (!_frameAvailable)
&& (GETAVAILABLEBYTESCOUNT(_chunkBuffer) >= _chunkSize)) {
if (!ProcessBuffer(_chunkBuffer, true)) {
FATAL("Unable to process block of data");
return false;
}
}
return !_chunkSizeErrors;
}
BaseInStream *TSFrameReader::GetInStream() {
if (_pInterface != NULL)
return _pInterface->GetInStream();
return NULL;
}
void TSFrameReader::SignalResetChunkSize() {
_chunkSizeErrors = true;
}
void TSFrameReader::SignalPAT(TSPacketPAT *pPAT) {
//NYI;
}
void TSFrameReader::SignalPMT(TSPacketPMT *pPMT) {
//NYI;
}
void TSFrameReader::SignalPMTComplete() {
//NYI;
}
bool TSFrameReader::SignalStreamsPIDSChanged(map<uint16_t, TSStreamInfo> &streams) {
return true;
}
bool TSFrameReader::SignalStreamPIDDetected(TSStreamInfo &streamInfo,
BaseAVContext *pContext, PIDType type, bool &ignore) {
pContext->_pStreamCapabilities = &_streamCapabilities;
ignore = false;
return true;
}
void TSFrameReader::SignalUnknownPIDDetected(TSStreamInfo &streamInfo) {
NYI;
}
bool TSFrameReader::FeedData(BaseAVContext *pContext, uint8_t *pData,
uint32_t dataLength, double pts, double dts, bool isAudio) {
if (!_pInterface->SignalFrame(pData, dataLength, pts, dts, isAudio)) {
FATAL("Unable to feed frame");
return false;
}
_frameAvailable = true;
return true;
}
void TSFrameReader::FreeFile() {
if ((_freeFile)&&(_pFile != NULL)) {
ReleaseFile(_pFile);
}
_pFile = NULL;
}
bool TSFrameReader::DetermineChunkSize() {
while (true) {
if (_chunkSizeDetectionCount >= TS_CHUNK_208) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
//FINEST("Check for %"PRIu8" at %"PRIu8, (uint8_t) TS_CHUNK_188, _chunkSizeDetectionCount);
if (!TestChunkSize(TS_CHUNK_188)) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
if (_chunkSize != 0)
return true;
//FINEST("Check for %"PRIu8" at %"PRIu8, (uint8_t) TS_CHUNK_204, _chunkSizeDetectionCount);
if (!TestChunkSize(TS_CHUNK_204)) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
if (_chunkSize != 0)
return true;
//FINEST("Check for %"PRIu8" at %"PRIu8, (uint8_t) TS_CHUNK_208, _chunkSizeDetectionCount);
if (!TestChunkSize(TS_CHUNK_208)) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
if (_chunkSize != 0)
return true;
_chunkSizeDetectionCount++;
}
}
bool TSFrameReader::TestChunkSize(uint8_t chunkSize) {
_chunkSize = 0;
uint8_t byte;
if ((int64_t)(_pFile->Size() - _pFile->Cursor()) <(2 * chunkSize + 1))
return true;
if (!GetByteAt(_chunkSizeDetectionCount, byte)) {
FATAL("Unable to read byte at offset %"PRIu32, _chunkSizeDetectionCount);
return false;
}
if (byte != 0x47)
return true;
if (!GetByteAt(_chunkSizeDetectionCount + chunkSize, byte)) {
FATAL("Unable to read byte at offset %"PRIu32, _chunkSizeDetectionCount + chunkSize);
return false;
}
if (byte != 0x47)
return true;
if (!GetByteAt(_chunkSizeDetectionCount + 2 * chunkSize, byte)) {
FATAL("Unable to read byte at offset %"PRIu32, _chunkSizeDetectionCount + 2 * chunkSize);
return false;
}
if (byte != 0x47)
return true;
_chunkSize = chunkSize;
return true;
}
bool TSFrameReader::GetByteAt(uint64_t offset, uint8_t &byte) {
uint64_t backup = _pFile->Cursor();
if (!_pFile->SeekTo(offset)) {
FATAL("Unable to seek to offset %"PRIu64, offset);
return false;
}
if (!_pFile->ReadUI8(&byte)) {
FATAL("Unable to read byte at offset %"PRIu64, offset);
return false;
}
if (!_pFile->SeekTo(backup)) {
FATAL("Unable to seek to offset %"PRIu64, backup);
return false;
}
return true;
}
#endif /* HAS_MEDIA_TS */
| 6,401
|
C++
|
.cpp
| 214
| 27.495327
| 93
| 0.718653
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,325
|
avcontext.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/ts/avcontext.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_TS
#include "mediaformats/readers/ts/avcontext.h"
#include "mediaformats/readers/ts/tsparsereventsink.h"
#include "streaming/streamcapabilities.h"
#include "streaming/codectypes.h"
#include "streaming/nalutypes.h"
#include "streaming/baseinstream.h"
BaseAVContext::BaseAVContext() {
InternalReset();
};
BaseAVContext::~BaseAVContext() {
InternalReset();
}
void BaseAVContext::Reset() {
InternalReset();
}
void BaseAVContext::DropPacket() {
_bucket.IgnoreAll();
_droppedPacketsCount++;
}
BaseInStream *BaseAVContext::GetInStream() {
if (_pEventsSink == NULL)
return NULL;
return _pEventsSink->GetInStream();
}
bool BaseAVContext::FeedData(uint8_t *pData, uint32_t dataLength, double pts,
double dts, bool isAudio) {
if (_pEventsSink != NULL)
return _pEventsSink->FeedData(this, pData, dataLength, pts, dts, isAudio);
return true;
}
void BaseAVContext::InternalReset() {
memset(&_pts, 0, sizeof (_pts));
memset(&_dts, 0, sizeof (_dts));
_sequenceNumber = -1;
_droppedPacketsCount = 0;
_droppedBytesCount = 0;
_packetsCount = 0;
_bytesCount = 0;
_bucket.IgnoreAll();
_pStreamCapabilities = NULL;
}
H264AVContext::H264AVContext()
: BaseAVContext() {
InternalReset();
}
H264AVContext::~H264AVContext() {
InternalReset();
}
void H264AVContext::Reset() {
BaseAVContext::Reset();
InternalReset();
}
bool H264AVContext::HandleData() {
if (_pts.time < 0 || GETAVAILABLEBYTESCOUNT(_bucket) == 0) {
_droppedPacketsCount++;
_droppedBytesCount += GETAVAILABLEBYTESCOUNT(_bucket);
_bucket.IgnoreAll();
return true;
}
_packetsCount++;
_bytesCount += GETAVAILABLEBYTESCOUNT(_bucket);
uint32_t cursor = 0;
uint32_t length = GETAVAILABLEBYTESCOUNT(_bucket);
uint8_t *pBuffer = GETIBPOINTER(_bucket);
uint8_t *pNalStart = NULL;
uint8_t *pNalEnd = NULL;
uint32_t testValue;
uint8_t markerSize = 0;
bool found = false;
while (cursor + 4 < length) {
testValue = ENTOHLP(pBuffer + cursor);
if (testValue == 1) {
markerSize = 4;
pNalEnd = pBuffer + cursor;
found = true;
} else if ((testValue >> 8) == 1) {
markerSize = 3;
pNalEnd = pBuffer + cursor;
found = true;
}
if (!found) {
cursor++;
continue;
} else {
cursor += markerSize;
}
found = false;
if (pNalStart != NULL) {
if (!ProcessNal(pNalStart, (int32_t) (pNalEnd - pNalStart), _pts.time, _dts.time)) {
FATAL("Unable to process NAL");
return false;
}
}
pNalStart = pNalEnd + markerSize;
}
if (pNalStart != NULL) {
int32_t lastLength = (int32_t) (length - (pNalStart - pBuffer));
if (!ProcessNal(pNalStart, lastLength, _pts.time, _dts.time)) {
FATAL("Unable to process NAL");
return false;
}
}
_bucket.IgnoreAll();
return true;
}
void H264AVContext::EmptyBackBuffers() {
FOR_VECTOR(_backBuffers, i) {
ADD_VECTOR_END(_backBuffersCache, _backBuffers[i]);
}
_backBuffers.clear();
}
void H264AVContext::DiscardBackBuffers() {
_backBuffersPts = -1;
_backBuffersDts = -1;
FOR_VECTOR(_backBuffers, i) {
delete _backBuffers[i];
}
_backBuffers.clear();
FOR_VECTOR(_backBuffersCache, i) {
delete _backBuffersCache[i];
}
_backBuffersCache.clear();
}
void H264AVContext::InsertBackBuffer(uint8_t *pBuffer, int32_t length) {
IOBuffer *pTemp = NULL;
if (_backBuffersCache.size() > 0) {
pTemp = _backBuffersCache[0];
_backBuffersCache.erase(_backBuffersCache.begin());
} else {
pTemp = new IOBuffer();
}
pTemp->IgnoreAll();
pTemp->ReadFromBuffer(pBuffer, length);
ADD_VECTOR_END(_backBuffers, pTemp);
}
bool H264AVContext::ProcessNal(uint8_t *pBuffer, int32_t length, double pts, double dts) {
if ((pBuffer == NULL) || (length <= 0))
return true;
if (_pStreamCapabilities != NULL) {
InitializeCapabilities(pBuffer, length);
if (_pStreamCapabilities->GetVideoCodecType() != CODEC_VIDEO_H264) {
if (_backBuffersPts != pts) {
EmptyBackBuffers();
_backBuffersPts = pts;
_backBuffersDts = dts;
}
InsertBackBuffer(pBuffer, length);
return true;
} else {
if (_backBuffersPts >= 0) {
FOR_VECTOR(_backBuffers, i) {
if (!FeedData(
GETIBPOINTER(*_backBuffers[i]),
GETAVAILABLEBYTESCOUNT(*_backBuffers[i]),
_backBuffersPts,
_backBuffersDts,
false)) {
DiscardBackBuffers();
return false;
}
}
DiscardBackBuffers();
}
}
}
return FeedData(pBuffer, length, pts, dts, false);
}
void H264AVContext::InitializeCapabilities(uint8_t *pData, uint32_t length) {
switch (NALU_TYPE(pData[0])) {
case NALU_TYPE_SPS:
{
_SPS.IgnoreAll();
_SPS.ReadFromBuffer(pData, length);
break;
}
case NALU_TYPE_PPS:
{
if (GETAVAILABLEBYTESCOUNT(_SPS) == 0)
break;
_PPS.IgnoreAll();
_PPS.ReadFromBuffer(pData, length);
BaseInStream *pInStream = NULL;
if (_pEventsSink != NULL)
pInStream = _pEventsSink->GetInStream();
if (_pStreamCapabilities->AddTrackVideoH264(
GETIBPOINTER(_SPS),
GETAVAILABLEBYTESCOUNT(_SPS),
GETIBPOINTER(_PPS),
GETAVAILABLEBYTESCOUNT(_PPS),
90000,
pInStream) == NULL) {
_pStreamCapabilities->ClearVideo();
WARN("Unable to initialize h264 codec");
break;
}
break;
}
default:
{
break;
}
}
}
void H264AVContext::InternalReset() {
_SPS.IgnoreAll();
_PPS.IgnoreAll();
DiscardBackBuffers();
}
AACAVContext::AACAVContext()
: BaseAVContext() {
InternalReset();
}
AACAVContext::~AACAVContext() {
InternalReset();
}
void AACAVContext::Reset() {
BaseAVContext::Reset();
InternalReset();
}
#define TS_MAX_ADTS_DETECTION_COUNT 1024
bool AACAVContext::HandleData() {
if (_pts.time < 0) {
_bucket.IgnoreAll();
return true;
}
_bytesCount += GETAVAILABLEBYTESCOUNT(_bucket);
_packetsCount++;
//2. Get the buffer details: length and pointer
uint32_t bufferLength = GETAVAILABLEBYTESCOUNT(_bucket);
uint8_t *pBuffer = GETIBPOINTER(_bucket);
if (!_initialMarkerFound) {
for (;;) {
bufferLength = GETAVAILABLEBYTESCOUNT(_bucket);
pBuffer = GETIBPOINTER(_bucket);
//3. Do we have at least 6 bytes to read the length?
if (bufferLength < 6) {
break;
}
if ((ENTOHSP(pBuffer)&0xfff0) != 0xfff0) {
_bucket.Ignore(1);
_droppedBytesCount++;
_markerRetryCount++;
//FINEST("_markerRetryCount: %"PRIu32, _markerRetryCount);
if (_markerRetryCount >= TS_MAX_ADTS_DETECTION_COUNT) {
BaseInStream *pInStream = GetInStream();
FATAL("Unable to reliably detect AAC ADTS headers after %"PRIu32" bytes scanned for ADTS marker. Stream %s corrupted",
TS_MAX_ADTS_DETECTION_COUNT,
pInStream != NULL ? STR(*pInStream) : "");
return false;
}
continue;
}
//the payload here respects this format:
//6.2 Audio Data Transport Stream, ADTS
//iso13818-7 page 26/206
if (_pStreamCapabilities != NULL) {
if (_pStreamCapabilities->GetAudioCodecType() != CODEC_AUDIO_AAC) {
InitializeCapabilities(GETIBPOINTER(_bucket), GETAVAILABLEBYTESCOUNT(_bucket));
if (_pStreamCapabilities->GetAudioCodecType() != CODEC_AUDIO_AAC) {
_pStreamCapabilities->ClearAudio();
_bucket.Ignore(1);
_droppedBytesCount++;
_markerRetryCount++;
continue;
}
}
}
_initialMarkerFound = true;
break;
}
}
uint32_t _audioPacketsCount = 0;
for (;;) {
bufferLength = GETAVAILABLEBYTESCOUNT(_bucket);
pBuffer = GETIBPOINTER(_bucket);
//3. Do we have at least 6 bytes to read the length?
if (bufferLength < 6) {
break;
}
if ((ENTOHSP(pBuffer)&0xfff0) != 0xfff0) {
_bucket.Ignore(1);
_droppedBytesCount++;
continue;
}
//4. Read the frame length and see if we have enough data.
//NOTE: frameLength INCLUDES the headers, that is why we test it directly
//on bufferLength
uint32_t frameLength = ((((pBuffer[3]&0x03) << 8) | pBuffer[4]) << 3) | (pBuffer[5] >> 5);
if (frameLength < 8) {
//WARN("Bogus frameLength %u. Skip one byte", frameLength);
//FINEST("_audioBuffer:\n%s", STR(_bucket));
_bucket.Ignore(1);
continue;
}
if (bufferLength < frameLength) {
break;
}
double ts = _pts.time + (((double) _audioPacketsCount * 1024.00) / _samplingRate)*1000.0;
_audioPacketsCount++;
if (_lastSentTimestamp >= ts) {
ts = _lastSentTimestamp;
}
_lastSentTimestamp = ts;
//5. Feed
if (!FeedData(pBuffer, frameLength, ts, ts, true)) {
FATAL("Unable to feed audio data");
return false;
}
//6. Ignore frameLength bytes
_bucket.Ignore(frameLength);
}
return true;
}
void AACAVContext::InitializeCapabilities(uint8_t *pData, uint32_t length) {
if (_pStreamCapabilities->GetAudioCodecType() == CODEC_AUDIO_UNKNOWN) {
_samplingRate = 1;
BitArray codecSetup;
//profile_index from MPEG-TS different from profile_index from RTMP
//so we need a map
uint8_t profile = pData[2] >> 6;
codecSetup.PutBits<uint8_t > (profile + 1, 5);
//frequence mapping is the same
//iso13818-7.pdf page 46/206
uint8_t sampling_frequency_index = (pData[2] >> 2)&0x0f;
codecSetup.PutBits<uint8_t > (sampling_frequency_index, 4);
uint8_t channelsCount = ((pData[2]&0x01) << 2) | (pData[3] >> 6);
codecSetup.PutBits<uint8_t > (channelsCount, 4);
BaseInStream *pInStream = NULL;
if (_pEventsSink != NULL)
pInStream = _pEventsSink->GetInStream();
AudioCodecInfoAAC *pCodecInfo = _pStreamCapabilities->AddTrackAudioAAC(GETIBPOINTER(codecSetup),
(uint8_t) GETAVAILABLEBYTESCOUNT(codecSetup), true, pInStream);
if (pCodecInfo == NULL)
return;
_samplingRate = pCodecInfo->_samplingRate;
}
}
void AACAVContext::InternalReset() {
_lastSentTimestamp = 0;
_samplingRate = 1;
_initialMarkerFound = false;
_markerRetryCount = 0;
}
#endif /* HAS_MEDIA_TS */
| 10,439
|
C++
|
.cpp
| 363
| 25.647383
| 123
| 0.700948
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,326
|
tsparser.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/ts/tsparser.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_TS
#include "mediaformats/readers/ts/tsparser.h"
#include "mediaformats/readers/ts/tspacketheader.h"
#include "mediaformats/readers/ts/tsboundscheck.h"
#include "mediaformats/readers/ts/avcontext.h"
#include "mediaformats/readers/ts/tspacketpat.h"
#include "mediaformats/readers/ts/tspacketpmt.h"
#include "mediaformats/readers/ts/tsparsereventsink.h"
#include "streaming/baseinstream.h"
TSParser::TSParser(TSParserEventsSink *pEventSink) {
_pEventSink = pEventSink;
_chunkSize = 188;
//2. Setup the PAT pid
PIDDescriptor *pPAT = new PIDDescriptor;
pPAT->type = PID_TYPE_PAT;
pPAT->pid = 0;
pPAT->crc = 0;
pPAT->pAVContext = NULL;
_pidMapping[0] = pPAT;
//3. Setup CAT table
PIDDescriptor *pCAT = new PIDDescriptor;
pCAT->type = PID_TYPE_CAT;
pCAT->pid = 1;
pCAT->crc = 0;
pCAT->pAVContext = NULL;
_pidMapping[1] = pCAT;
//4. Setup TSDT table
PIDDescriptor *pTSDT = new PIDDescriptor;
pTSDT->type = PID_TYPE_TSDT;
pTSDT->pid = 2;
pTSDT->crc = 0;
pTSDT->pAVContext = NULL;
_pidMapping[2] = pTSDT;
//5. Setup reserved tables
for (uint16_t i = 3; i < 16; i++) {
PIDDescriptor *pReserved = new PIDDescriptor;
pReserved->type = PID_TYPE_RESERVED;
pReserved->pid = i;
pReserved->crc = 0;
pReserved->pAVContext = NULL;
_pidMapping[i] = pReserved;
}
//6. Setup the NULL pid
PIDDescriptor *pNULL = new PIDDescriptor;
pNULL->type = PID_TYPE_NULL;
pNULL->pid = 0x1fff;
pNULL->crc = 0;
pNULL->pAVContext = NULL;
_pidMapping[0x1fff] = pNULL;
_totalParsedBytes = 0;
}
TSParser::~TSParser() {
//1. Cleanup the pid mappings
FOR_MAP(_pidMapping, uint16_t, PIDDescriptor *, i) {
FreePidDescriptor(MAP_VAL(i));
}
_pidMapping.clear();
}
void TSParser::SetChunkSize(uint32_t chunkSize) {
_chunkSize = chunkSize;
}
bool TSParser::ProcessPacket(uint32_t packetHeader, IOBuffer &buffer,
uint32_t maxCursor) {
//1. Get the PID descriptor or create it if absent
PIDDescriptor *pPIDDescriptor = NULL;
if (MAP_HAS1(_pidMapping, TS_TRANSPORT_PACKET_PID(packetHeader))) {
pPIDDescriptor = _pidMapping[TS_TRANSPORT_PACKET_PID(packetHeader)];
} else {
pPIDDescriptor = new PIDDescriptor;
pPIDDescriptor->type = PID_TYPE_UNKNOWN;
pPIDDescriptor->pAVContext = NULL;
pPIDDescriptor->pid = TS_TRANSPORT_PACKET_PID(packetHeader);
_pidMapping[pPIDDescriptor->pid] = pPIDDescriptor;
}
//2. Skip the transport packet structure
uint8_t *pBuffer = GETIBPOINTER(buffer);
uint32_t cursor = 4;
if (TS_TRANSPORT_PACKET_HAS_ADAPTATION_FIELD(packetHeader)) {
TS_CHECK_BOUNDS(1);
TS_CHECK_BOUNDS(pBuffer[cursor]);
cursor += pBuffer[cursor] + 1;
}
if (!TS_TRANSPORT_PACKET_HAS_PAYLOAD(packetHeader)) {
return true;
}
switch (pPIDDescriptor->type) {
case PID_TYPE_PAT:
{
return ProcessPidTypePAT(packetHeader, *pPIDDescriptor, pBuffer, cursor, maxCursor);
}
case PID_TYPE_NIT:
case PID_TYPE_CAT:
case PID_TYPE_TSDT:
{
// FINEST("%s", STR(IOBuffer::DumpBuffer(pBuffer + cursor,
// _chunkSize - cursor)));
return true;
}
case PID_TYPE_PMT:
{
return ProcessPidTypePMT(packetHeader, *pPIDDescriptor, pBuffer,
cursor, maxCursor);
}
case PID_TYPE_AUDIOSTREAM:
case PID_TYPE_VIDEOSTREAM:
{
return ProcessPidTypeAV(pPIDDescriptor,
pBuffer + cursor, _chunkSize - cursor,
TS_TRANSPORT_PACKET_IS_PAYLOAD_START(packetHeader),
(int8_t) packetHeader & 0x0f);
}
// case PID_TYPE_AUDIOSTREAM:
// {
// if (_pEventSink != NULL)
// return _pEventSink->ProcessData(pPIDDescriptor,
// pBuffer + cursor, _chunkSize - cursor,
// TS_TRANSPORT_PACKET_IS_PAYLOAD_START(packetHeader), true,
// (int8_t) packetHeader & 0x0f);
// return true;
// }
// case PID_TYPE_VIDEOSTREAM:
// {
// if (_pEventSink != NULL)
// return _pEventSink->ProcessData(pPIDDescriptor,
// pBuffer + cursor, _chunkSize - cursor,
// TS_TRANSPORT_PACKET_IS_PAYLOAD_START(packetHeader), false,
// (int8_t) packetHeader & 0x0f);
// return true;
// }
case PID_TYPE_RESERVED:
{
WARN("This PID %hu should not be used because is reserved according to iso13818-1.pdf", pPIDDescriptor->pid);
return true;
}
case PID_TYPE_UNKNOWN:
{
if (!MAP_HAS1(_unknownPids, pPIDDescriptor->pid)) {
//WARN("PID %"PRIu16" not known yet", pPIDDescriptor->pid);
_unknownPids[pPIDDescriptor->pid] = pPIDDescriptor->pid;
}
return true;
}
case PID_TYPE_NULL:
{
//Ignoring NULL pids
return true;
}
default:
{
WARN("PID type not implemented: %d. Pid number: %"PRIu16,
pPIDDescriptor->type, pPIDDescriptor->pid);
return false;
}
}
}
bool TSParser::ProcessBuffer(IOBuffer &buffer, bool chunkByChunk) {
while (GETAVAILABLEBYTESCOUNT(buffer) >= _chunkSize) {
if (GETIBPOINTER(buffer)[0] != 0x47) {
WARN("Bogus chunk detected");
if (_pEventSink != NULL) {
_pEventSink->SignalResetChunkSize();
}
return true;
}
uint32_t packetHeader = ENTOHLP(GETIBPOINTER(buffer));
if (!ProcessPacket(packetHeader, buffer, _chunkSize)) {
FATAL("Unable to process packet");
return false;
}
_totalParsedBytes += _chunkSize;
if (!buffer.Ignore(_chunkSize)) {
FATAL("Unable to ignore %u bytes", _chunkSize);
return false;
}
if (chunkByChunk)
break;
}
if (!chunkByChunk)
buffer.MoveData();
return true;
}
uint64_t TSParser::GetTotalParsedBytes() {
return _totalParsedBytes;
}
void TSParser::FreePidDescriptor(PIDDescriptor *pPIDDescriptor) {
if (pPIDDescriptor != NULL) {
if (pPIDDescriptor->pAVContext != NULL)
delete pPIDDescriptor->pAVContext;
delete pPIDDescriptor;
}
}
bool TSParser::ProcessPidTypePAT(uint32_t packetHeader,
PIDDescriptor &pidDescriptor, uint8_t *pBuffer, uint32_t &cursor,
uint32_t maxCursor) {
//1. Advance the pointer field
if (TS_TRANSPORT_PACKET_IS_PAYLOAD_START(packetHeader)) {
TS_CHECK_BOUNDS(1);
TS_CHECK_BOUNDS(pBuffer[cursor]);
cursor += pBuffer[cursor] + 1;
}
//1. Get the crc from the packet and compare it with the last crc.
//if it is the same, ignore this packet
uint32_t crc = TSPacketPAT::PeekCRC(pBuffer, cursor, maxCursor);
if (crc == 0) {
FATAL("Unable to read crc");
return false;
}
if (pidDescriptor.crc == crc) {
if (_pEventSink != NULL) {
_pEventSink->SignalPAT(NULL);
}
return true;
}
//2. read the packet
TSPacketPAT packetPAT;
if (!packetPAT.Read(pBuffer, cursor, maxCursor)) {
FATAL("Unable to read PAT");
return false;
}
//3. Store the crc
pidDescriptor.crc = packetPAT.GetCRC();
//4. Store the pid types found in PAT
FOR_MAP(packetPAT.GetPMTs(), uint16_t, uint16_t, i) {
PIDDescriptor *pDescr = new PIDDescriptor;
pDescr->pid = MAP_VAL(i);
pDescr->type = PID_TYPE_PMT;
pDescr->crc = 0;
pDescr->pAVContext = NULL;
_pidMapping[pDescr->pid] = pDescr;
}
FOR_MAP(packetPAT.GetNITs(), uint16_t, uint16_t, i) {
PIDDescriptor *pDescr = new PIDDescriptor;
pDescr->pid = MAP_VAL(i);
pDescr->type = PID_TYPE_NIT;
pDescr->pAVContext = NULL;
_pidMapping[pDescr->pid] = pDescr;
}
if (_pEventSink != NULL) {
_pEventSink->SignalPAT(&packetPAT);
}
//5. Done
return true;
}
bool TSParser::ProcessPidTypePMT(uint32_t packetHeader,
PIDDescriptor &pidDescriptor, uint8_t *pBuffer, uint32_t &cursor,
uint32_t maxCursor) {
//1. Advance the pointer field
if (TS_TRANSPORT_PACKET_IS_PAYLOAD_START(packetHeader)) {
TS_CHECK_BOUNDS(1);
TS_CHECK_BOUNDS(pBuffer[cursor]);
cursor += pBuffer[cursor] + 1;
}
//1. Get the crc from the packet and compare it with the last crc.
//if it is the same, ignore this packet. Also test if we have a protocol handler
uint32_t crc = TSPacketPMT::PeekCRC(pBuffer, cursor, maxCursor);
if (crc == 0) {
FATAL("Unable to read crc");
return false;
}
if (pidDescriptor.crc == crc) {
if (_pEventSink != NULL) {
_pEventSink->SignalPMT(NULL);
}
return true;
}
//2. read the packet
TSPacketPMT packetPMT;
if (!packetPMT.Read(pBuffer, cursor, maxCursor)) {
FATAL("Unable to read PAT");
return false;
}
if (_pEventSink != NULL) {
_pEventSink->SignalPMT(&packetPMT);
}
//3. Store the CRC
pidDescriptor.crc = packetPMT.GetCRC();
//4. Gather the info about the streams present inside the program
//videoPid will contain the selected video stream
//audioPid will contain the selected audio stream
//unknownPids will contain the rest of the streams that will be ignored
map<uint16_t, uint16_t> unknownPids;
vector<PIDDescriptor *> pidDescriptors;
PIDDescriptor *pPIDDescriptor = NULL;
map<uint16_t, TSStreamInfo> streamsInfo = packetPMT.GetStreamsInfo();
if (_pEventSink != NULL) {
if (!_pEventSink->SignalStreamsPIDSChanged(streamsInfo)) {
FATAL("SignalStreamsPIDSChanged failed");
return false;
}
}
bool ignore = true;
PIDType pidType = PID_TYPE_NULL;
BaseAVContext *pAVContext = NULL;
FOR_MAP(streamsInfo, uint16_t, TSStreamInfo, i) {
ignore = true;
pidType = PID_TYPE_NULL;
pAVContext = NULL;
switch (MAP_VAL(i).streamType) {
case TS_STREAMTYPE_VIDEO_H264:
{
pidType = PID_TYPE_VIDEOSTREAM;
pAVContext = new H264AVContext();
if (_pEventSink != NULL) {
if (!_pEventSink->SignalStreamPIDDetected(MAP_VAL(i),
pAVContext, pidType, ignore)) {
FATAL("SignalStreamsPIDSChanged failed");
return false;
}
}
break;
}
case TS_STREAMTYPE_AUDIO_AAC:
{
pidType = PID_TYPE_AUDIOSTREAM;
pAVContext = new AACAVContext();
if (_pEventSink != NULL) {
if (!_pEventSink->SignalStreamPIDDetected(MAP_VAL(i),
pAVContext, pidType, ignore)) {
FATAL("SignalStreamsPIDSChanged failed");
return false;
}
}
break;
}
default:
{
if (_pEventSink != NULL)
_pEventSink->SignalUnknownPIDDetected(MAP_VAL(i));
break;
}
}
if (ignore) {
pidType = PID_TYPE_NULL;
if (pAVContext != NULL) {
delete pAVContext;
pAVContext = NULL;
}
}
pPIDDescriptor = new PIDDescriptor();
pPIDDescriptor->pid = MAP_KEY(i);
pPIDDescriptor->type = pidType;
pPIDDescriptor->pAVContext = pAVContext;
if (pPIDDescriptor->pAVContext != NULL)
pPIDDescriptor->pAVContext->_pEventsSink = _pEventSink;
ADD_VECTOR_END(pidDescriptors, pPIDDescriptor);
}
//7. Mount the newly created pids
FOR_VECTOR(pidDescriptors, i) {
if (MAP_HAS1(_pidMapping, pidDescriptors[i]->pid)) {
FreePidDescriptor(_pidMapping[pidDescriptors[i]->pid]);
}
_pidMapping[pidDescriptors[i]->pid] = pidDescriptors[i];
}
if (_pEventSink != NULL) {
_pEventSink->SignalPMTComplete();
}
return true;
}
bool TSParser::ProcessPidTypeAV(PIDDescriptor *pPIDDescriptor, uint8_t *pData,
uint32_t length, bool packetStart, int8_t sequenceNumber) {
if (pPIDDescriptor->pAVContext == NULL) {
FATAL("No AVContext cerated");
return false;
}
if (pPIDDescriptor->pAVContext->_sequenceNumber == -1) {
pPIDDescriptor->pAVContext->_sequenceNumber = sequenceNumber;
} else {
if (((pPIDDescriptor->pAVContext->_sequenceNumber + 1)&0x0f) != sequenceNumber) {
pPIDDescriptor->pAVContext->_sequenceNumber = sequenceNumber;
pPIDDescriptor->pAVContext->DropPacket();
return true;
} else {
pPIDDescriptor->pAVContext->_sequenceNumber = sequenceNumber;
}
}
if (packetStart) {
if (!pPIDDescriptor->pAVContext->HandleData()) {
FATAL("Unable to handle AV data");
return false;
}
if (length >= 8) {
if (((pData[3]&0xE0) != 0xE0)&&((pData[3]&0xC0) != 0xC0)) {
BaseInStream *pTemp = pPIDDescriptor->pAVContext->GetInStream();
WARN("PID %"PRIu16" from %s is not h264/aac. The type is 0x%02"PRIx8,
pPIDDescriptor->pid,
pTemp != NULL ? STR(*pTemp) : "",
pData[3]);
pPIDDescriptor->type = PID_TYPE_NULL;
return true;
}
uint32_t pesHeaderLength = pData[8];
if (pesHeaderLength + 9 > length) {
WARN("Not enough data");
pPIDDescriptor->pAVContext->DropPacket();
return true;
}
//compute the time:
//http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
uint8_t *pPTS = NULL;
uint8_t *pDTS = NULL;
uint8_t ptsdstflags = pData[7] >> 6;
if (ptsdstflags == 2) {
pPTS = pData + 9;
} else if (ptsdstflags == 3) {
pPTS = pData + 9;
pDTS = pData + 14;
}
if (pPTS != NULL) {
uint64_t value = (pPTS[0]&0x0f) >> 1;
value = (value << 8) | pPTS[1];
value = (value << 7) | (pPTS[2] >> 1);
value = (value << 8) | pPTS[3];
value = (value << 7) | (pPTS[4] >> 1);
if (((pPIDDescriptor->pAVContext->_pts.lastRaw >> 32) == 1) && ((value >> 32) == 0)) {
pPIDDescriptor->pAVContext->_pts.rollOverCount++;
}
pPIDDescriptor->pAVContext->_pts.lastRaw = value;
value += (pPIDDescriptor->pAVContext->_pts.rollOverCount * 0x1ffffffffLL);
pPIDDescriptor->pAVContext->_pts.time = (double) value / 90.00;
} else {
WARN("No PTS!");
pPIDDescriptor->pAVContext->DropPacket();
return true;
}
double tempDtsTime = 0;
if (pDTS != NULL) {
uint64_t value = (pDTS[0]&0x0f) >> 1;
value = (value << 8) | pDTS[1];
value = (value << 7) | (pDTS[2] >> 1);
value = (value << 8) | pDTS[3];
value = (value << 7) | (pDTS[4] >> 1);
if (((pPIDDescriptor->pAVContext->_dts.lastRaw >> 32) == 1) && ((value >> 32) == 0)) {
pPIDDescriptor->pAVContext->_dts.rollOverCount++;
}
pPIDDescriptor->pAVContext->_dts.lastRaw = value;
value += (pPIDDescriptor->pAVContext->_dts.rollOverCount * 0x1ffffffffLL);
tempDtsTime = (double) value / 90.00;
} else {
tempDtsTime = pPIDDescriptor->pAVContext->_pts.time;
}
if (pPIDDescriptor->pAVContext->_dts.time > tempDtsTime) {
WARN("Back timestamp: %.2f -> %.2f on pid %"PRIu16,
pPIDDescriptor->pAVContext->_dts.time, tempDtsTime, pPIDDescriptor->pid);
pPIDDescriptor->pAVContext->DropPacket();
return true;
}
pPIDDescriptor->pAVContext->_dts.time = tempDtsTime;
pData += 9 + pesHeaderLength;
length -= (9 + pesHeaderLength);
} else {
WARN("Not enoght data");
pPIDDescriptor->pAVContext->DropPacket();
return true;
}
}
pPIDDescriptor->pAVContext->_bucket.ReadFromBuffer(pData, length);
return true;
}
#endif /* HAS_MEDIA_TS */
| 14,946
|
C++
|
.cpp
| 477
| 28.054507
| 112
| 0.694342
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,327
|
tspacketpat.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/ts/tspacketpat.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_TS
#include "mediaformats/readers/ts/tspacketpat.h"
#include "mediaformats/readers/ts/tsboundscheck.h"
TSPacketPAT::TSPacketPAT() {
//fields
_tableId = 0;
_sectionSyntaxIndicator = false;
_reserved1 = false;
_reserved2 = 0;
_sectionLength = 0;
_transportStreamId = 0;
_reserved3 = 0;
_versionNumber = 0;
_currentNextIndicator = false;
_sectionNumber = 0;
_lastSectionNumber = 0;
_crc = 0;
//internal variables
_patStart = 0;
_patLength = 0;
_entriesCount = 0;
}
TSPacketPAT::~TSPacketPAT() {
}
TSPacketPAT::operator string() {
string result = "";
result += format("tableId: %hhu\n", _tableId);
result += format("sectionSyntaxIndicator: %hhu\n", _sectionSyntaxIndicator);
result += format("reserved1: %hhu\n", _reserved1);
result += format("reserved2: %hhu\n", _reserved2);
result += format("sectionLength: %hu\n", _sectionLength);
result += format("transportStreamId: %hu\n", _transportStreamId);
result += format("reserved3: %hhu\n", _reserved3);
result += format("versionNumber: %hhu\n", _versionNumber);
result += format("currentNextIndicator: %hhu\n", _currentNextIndicator);
result += format("sectionNumber: %hhu\n", _sectionNumber);
result += format("lastSectionNumber: %hhu\n", _lastSectionNumber);
result += format("crc: %x\n", _crc);
result += format("entriesCount: %u\n", _entriesCount);
result += format("NIT count: %"PRIz"u\n", _networkPids.size());
if (_networkPids.size() > 0) {
FOR_MAP(_networkPids, uint16_t, uint16_t, i) {
result += format("\tNIT %hu: %hu\n", MAP_KEY(i), MAP_VAL(i));
}
}
result += format("PMT count: %"PRIz"u\n", _programPids.size());
if (_programPids.size() > 0) {
FOR_MAP(_programPids, uint16_t, uint16_t, i) {
result += format("\tPMT %hu: %hu\n", MAP_KEY(i), MAP_VAL(i));
}
}
return result;
}
bool TSPacketPAT::Read(uint8_t *pBuffer, uint32_t &cursor, uint32_t maxCursor) {
//1. Read table id
TS_CHECK_BOUNDS(1);
_tableId = pBuffer[cursor++];
if (_tableId != 0) {
FATAL("Invalid table id");
return false;
}
//2. read section length and syntax indicator
TS_CHECK_BOUNDS(2);
_sectionSyntaxIndicator = (pBuffer[cursor]&0x80) != 0;
_reserved1 = (pBuffer[cursor]&0x40) != 0;
_reserved2 = (pBuffer[cursor] >> 4)&0x03;
_sectionLength = ENTOHSP((pBuffer + cursor))&0x0fff;
cursor += 2;
//4. Compute entries count
_entriesCount = (_sectionLength - 9) / 4;
//5. Read transport stream id
TS_CHECK_BOUNDS(2);
_transportStreamId = ENTOHSP((pBuffer + cursor));
cursor += 2;
//6. read current next indicator and version
TS_CHECK_BOUNDS(1);
_reserved3 = pBuffer[cursor] >> 6;
_versionNumber = (pBuffer[cursor] >> 1)&0x1f;
_currentNextIndicator = (pBuffer[cursor]&0x01) != 0;
cursor++;
//7. read section number
TS_CHECK_BOUNDS(1);
_sectionNumber = pBuffer[cursor++];
//8. read last section number
TS_CHECK_BOUNDS(1);
_lastSectionNumber = pBuffer[cursor++];
//9. read the table
for (uint32_t i = 0; i < _entriesCount; i++) {
//9.1. read the program number
TS_CHECK_BOUNDS(2);
uint16_t programNumber = ENTOHSP((pBuffer + cursor)); //----MARKED-SHORT----
cursor += 2;
//9.2. read the network or program map pid
TS_CHECK_BOUNDS(2);
uint16_t temp = ENTOHSP((pBuffer + cursor)); //----MARKED-SHORT----
cursor += 2;
temp &= 0x1fff;
if (programNumber == 0)
_networkPids[programNumber] = temp;
else
_programPids[programNumber] = temp;
}
//10. read the CRC
TS_CHECK_BOUNDS(4);
_crc = ENTOHLP((pBuffer + cursor));
cursor += 4;
//12. done
return true;
}
map<uint16_t, uint16_t> &TSPacketPAT::GetPMTs() {
return _programPids;
}
map<uint16_t, uint16_t> &TSPacketPAT::GetNITs() {
return _networkPids;
}
uint32_t TSPacketPAT::GetCRC() {
return _crc;
}
uint32_t TSPacketPAT::PeekCRC(uint8_t *pBuffer, uint32_t cursor, uint32_t maxCursor) {
//1. ignore table id
TS_CHECK_BOUNDS(1);
cursor++;
//3. read section length
TS_CHECK_BOUNDS(2);
uint16_t length = ENTOHSP((pBuffer + cursor)); //----MARKED-SHORT----
length &= 0x0fff;
cursor += 2;
//4. Move to the crc position
TS_CHECK_BOUNDS(length - 4);
cursor += (length - 4);
//5. return the crc
TS_CHECK_BOUNDS(4);
return ENTOHLP((pBuffer + cursor)); //----MARKED-LONG---
}
#endif /* HAS_MEDIA_TS */
| 5,158
|
C++
|
.cpp
| 153
| 31.48366
| 86
| 0.673703
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,328
|
tspacketpmt.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/ts/tspacketpmt.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_TS
#include "mediaformats/readers/ts/tspacketpmt.h"
#include "mediaformats/readers/ts/tsboundscheck.h"
TSPacketPMT::TSPacketPMT() {
}
TSPacketPMT::~TSPacketPMT() {
}
TSPacketPMT::operator string() {
string result = "";
result += format("tableId: %"PRIu8"\n", _tableId);
result += format("sectionSyntaxIndicator: %"PRIu8"\n", (uint8_t) _sectionSyntaxIndicator);
result += format("reserved1: %"PRIu8"\n", (uint8_t) _reserved1);
result += format("reserved2: %"PRIu8"\n", _reserved2);
result += format("sectionLength: %"PRIu16"\n", _sectionLength);
result += format("programNumber: %"PRIu16"\n", _programNumber);
result += format("reserved3: %"PRIu8"\n", _reserved3);
result += format("versionNumber: %"PRIu8"\n", _versionNumber);
result += format("currentNextIndicator: %"PRIu8"\n", (uint8_t) _currentNextIndicator);
result += format("sectionNumber: %"PRIu8"\n", _sectionNumber);
result += format("lastSectionNumber: %"PRIu8"\n", _lastSectionNumber);
result += format("reserved4: %"PRIu8"\n", _reserved4);
result += format("pcrPid: %"PRIu16"\n", _pcrPid);
result += format("reserved5: %"PRIu8"\n", _reserved5);
result += format("programInfoLength: %"PRIu16"\n", _programInfoLength);
result += format("crc: 0x%08"PRIx32"\n", _crc);
result += format("descriptors count: %"PRIz"u\n", _programInfoDescriptors.size());
for (uint32_t i = 0; i < _programInfoDescriptors.size(); i++) {
result += format("\t%s", STR(_programInfoDescriptors[i]));
if (i != _programInfoDescriptors.size() - 1)
result += "\n";
}
result += format("streams count: %"PRIz"u\n", _streams.size());
FOR_MAP(_streams, uint16_t, TSStreamInfo, i) {
result += format("\t%"PRIu16": %s\n", MAP_KEY(i), STR(MAP_VAL(i).toString(1)));
}
return result;
}
uint16_t TSPacketPMT::GetProgramNumber() {
return _programNumber;
}
uint32_t TSPacketPMT::GetCRC() {
return _crc;
}
map<uint16_t, TSStreamInfo> & TSPacketPMT::GetStreamsInfo() {
return _streams;
}
bool TSPacketPMT::Read(uint8_t *pBuffer, uint32_t &cursor, uint32_t maxCursor) {
//1. Read table id
TS_CHECK_BOUNDS(1);
_tableId = pBuffer[cursor++];
if (_tableId != 2) {
FATAL("Invalid table id");
return false;
}
//2. read section length and syntax indicator
TS_CHECK_BOUNDS(2);
_sectionSyntaxIndicator = (pBuffer[cursor]&0x80) != 0;
_reserved1 = (pBuffer[cursor]&0x40) != 0;
_reserved2 = (pBuffer[cursor] >> 4)&0x03;
_sectionLength = ENTOHSP((pBuffer + cursor))&0x0fff;
cursor += 2;
//5. Read transport stream id
TS_CHECK_BOUNDS(2);
_programNumber = ENTOHSP((pBuffer + cursor));
cursor += 2;
//6. read current next indicator and version
TS_CHECK_BOUNDS(1);
_reserved3 = pBuffer[cursor] >> 6;
_versionNumber = (pBuffer[cursor] >> 1)&0x1f;
_currentNextIndicator = (pBuffer[cursor]&0x01) != 0;
cursor++;
//7. read section number
TS_CHECK_BOUNDS(1);
_sectionNumber = pBuffer[cursor++];
//8. read last section number
TS_CHECK_BOUNDS(1);
_lastSectionNumber = pBuffer[cursor++];
//9. read PCR PID
TS_CHECK_BOUNDS(2);
_pcrPid = ENTOHSP((pBuffer + cursor))&0x1fff; //----MARKED-SHORT----
cursor += 2;
//10. read the program info length
TS_CHECK_BOUNDS(2);
_programInfoLength = ENTOHSP((pBuffer + cursor))&0x0fff; //----MARKED-SHORT----
cursor += 2;
//11. Read the descriptors
//TODO read the elementary stream info
//Table 2-39 : Program and program element descriptors (page 63)
uint32_t limit = cursor + _programInfoLength;
while (cursor != limit) {
StreamDescriptor descriptor;
if (!ReadStreamDescriptor(descriptor, pBuffer, cursor, maxCursor)) {
FATAL("Unable to read descriptor");
return false;
}
TS_CHECK_BOUNDS(0);
ADD_VECTOR_END(_programInfoDescriptors, descriptor);
}
//13. Compute the streams info boundries
uint16_t streamsInfoLength = (uint8_t) (_sectionLength - 9 - _programInfoLength - 4);
uint16_t streamsInfoCursor = 0;
//14. Read the streams info
while (streamsInfoCursor < streamsInfoLength) {
TSStreamInfo streamInfo;
//14.1. read the stream type
TS_CHECK_BOUNDS(1);
streamInfo.streamType = pBuffer[cursor++];
streamsInfoCursor++;
//14.2. read the elementary pid
TS_CHECK_BOUNDS(2);
streamInfo.elementaryPID = ENTOHSP((pBuffer + cursor)); //----MARKED-SHORT----
streamInfo.elementaryPID &= 0x1fff;
cursor += 2;
streamsInfoCursor += 2;
//14.3. Read the elementary stream info length
TS_CHECK_BOUNDS(2);
streamInfo.esInfoLength = ENTOHSP((pBuffer + cursor)); //----MARKED-SHORT----
streamInfo.esInfoLength &= 0x0fff;
cursor += 2;
streamsInfoCursor += 2;
//14.4. read the elementary stream descriptor
limit = cursor + streamInfo.esInfoLength;
while (cursor != limit) {
StreamDescriptor descriptor;
if (!ReadStreamDescriptor(descriptor, pBuffer, cursor, maxCursor)) {
FATAL("Unable to read descriptor");
return false;
}
TS_CHECK_BOUNDS(0);
ADD_VECTOR_END(streamInfo.esDescriptors, descriptor);
}
streamsInfoCursor += streamInfo.esInfoLength;
//14.5. store the stream info
_streams[streamInfo.elementaryPID] = streamInfo;
}
//15. Read the crc
TS_CHECK_BOUNDS(4);
_crc = ENTOHLP((pBuffer + cursor)); //----MARKED-LONG---
cursor += 4;
//16. Done
return true;
}
uint32_t TSPacketPMT::PeekCRC(uint8_t *pBuffer, uint32_t cursor, uint32_t maxCursor) {
//2. ignore table id
TS_CHECK_BOUNDS(1);
cursor++;
//3. read section length
TS_CHECK_BOUNDS(2);
uint16_t length = ENTOHSP((pBuffer + cursor))&0x0fff; //----MARKED-SHORT----
cursor += 2;
//4. Move to the crc position
TS_CHECK_BOUNDS(length - 4);
cursor += (length - 4);
//5. return the crc
TS_CHECK_BOUNDS(4);
return ENTOHLP((pBuffer + cursor)); //----MARKED-LONG---
}
uint32_t TSPacketPMT::GetBandwidth() {
for (uint32_t i = 0; i < _programInfoDescriptors.size(); i++) {
if (_programInfoDescriptors[i].type == 14) {
return _programInfoDescriptors[i].payload.maximum_bitrate_descriptor.maximum_bitrate;
}
}
uint32_t result = 0;
FOR_MAP(_streams, uint16_t, TSStreamInfo, i) {
TSStreamInfo &si = MAP_VAL(i);
for (uint32_t j = 0; j < si.esDescriptors.size(); j++) {
if (si.esDescriptors[j].type == 14) {
result += si.esDescriptors[j].payload.maximum_bitrate_descriptor.maximum_bitrate;
break;
}
}
}
return result;
}
#endif /* HAS_MEDIA_TS */
| 7,226
|
C++
|
.cpp
| 194
| 34.798969
| 91
| 0.68792
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,329
|
streamdescriptors.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/ts/streamdescriptors.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_TS
#include "mediaformats/readers/ts/streamdescriptors.h"
#include "mediaformats/readers/ts/tsboundscheck.h"
bool ReadStreamDescriptor(StreamDescriptor &descriptor,
uint8_t *pBuffer, uint32_t &cursor, uint32_t maxCursor) {
TS_CHECK_BOUNDS(2);
descriptor.type = pBuffer[cursor++];
descriptor.length = pBuffer[cursor++];
TS_CHECK_BOUNDS(descriptor.length);
//iso13818-1.pdf Table 2-39, page 81/174
switch (descriptor.type) {
case 14://Maximum_bitrate_descriptor
{
TS_CHECK_BOUNDS(3);
descriptor.payload.maximum_bitrate_descriptor.maximum_bitrate =
(((pBuffer[cursor] << 16) | (pBuffer[cursor + 1] << 8) | (pBuffer[cursor + 2]))&0x3fffff) * 50 * 8;
break;
}
default:
break;
}
cursor += descriptor.length;
return true;
}
#endif /* HAS_MEDIA_TS */
| 1,574
|
C++
|
.cpp
| 43
| 34.255814
| 104
| 0.736566
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,330
|
tsdocument.cpp
|
shiretu_crtmpserver/sources/thelib/src/mediaformats/readers/ts/tsdocument.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_TS
#include "mediaformats/readers/ts/tsdocument.h"
#include "mediaformats/readers/ts/tsparser.h"
#include "mediaformats/readers/ts/avcontext.h"
TSDocument::TSDocument(Metadata &metadata)
: BaseMediaDocument(metadata) {
_chunkSizeDetectionCount = 0;
_chunkSize = 0;
_pParser = new TSParser(this);
_chunkSizeErrors = false;
_lastOffset = 0;
}
TSDocument::~TSDocument() {
if (_pParser != NULL) {
delete _pParser;
_pParser = NULL;
}
}
BaseInStream *TSDocument::GetInStream() {
return NULL;
}
void TSDocument::SignalResetChunkSize() {
_chunkSizeErrors = true;
}
void TSDocument::SignalPAT(TSPacketPAT *pPAT) {
}
void TSDocument::SignalPMT(TSPacketPMT *pPMT) {
}
void TSDocument::SignalPMTComplete() {
}
bool TSDocument::SignalStreamsPIDSChanged(map<uint16_t, TSStreamInfo> &streams) {
return true;
}
bool TSDocument::SignalStreamPIDDetected(TSStreamInfo &streamInfo,
BaseAVContext *pContext, PIDType type, bool &ignore) {
if (pContext == NULL) {
ignore = true;
return true;
}
pContext->_pStreamCapabilities = &_streamCapabilities;
ignore = false;
return true;
}
void TSDocument::SignalUnknownPIDDetected(TSStreamInfo &streamInfo) {
}
bool TSDocument::FeedData(BaseAVContext *pContext, uint8_t *pData,
uint32_t dataLength, double pts, double dts, bool isAudio) {
AddFrame(pContext->_pts.time, pContext->_dts.time,
isAudio ? MEDIAFRAME_TYPE_AUDIO : MEDIAFRAME_TYPE_VIDEO);
if (isAudio) {
_audioSamplesCount++;
} else {
_videoSamplesCount++;
}
return true;
}
bool TSDocument::ParseDocument() {
if (!DetermineChunkSize()) {
FATAL("Unable to determine chunk size");
return false;
}
if (!_mediaFile.SeekTo(_chunkSizeDetectionCount)) {
FATAL("Unable to seek at %"PRIu32, _chunkSizeDetectionCount);
return false;
}
_pParser->SetChunkSize(_chunkSize);
IOBuffer buffer;
uint32_t defaultBlockSize = ((1024 * 1024 * 4) / _chunkSize) * _chunkSize;
while (!_chunkSizeErrors) {
uint32_t available = (uint32_t) (_mediaFile.Size() - _mediaFile.Cursor());
if (available < _chunkSize) {
break;
}
if (GETAVAILABLEBYTESCOUNT(buffer) != 0) {
WARN("Leftovers detected");
break;
}
uint32_t blockSize = defaultBlockSize < available ? defaultBlockSize : available;
buffer.MoveData();
if (!buffer.ReadFromFs(_mediaFile, blockSize)) {
WARN("Unable to read %"PRIu32" bytes from file", blockSize);
break;
}
if (!_pParser->ProcessBuffer(buffer, false)) {
WARN("Unable to process block of data");
break;
}
}
return true;
}
bool TSDocument::BuildFrames() {
return true;
}
Variant TSDocument::GetPublicMeta() {
Variant result;
if (_streamCapabilities.GetVideoCodec<VideoCodecInfo>() != NULL) {
result["width"] = _streamCapabilities.GetVideoCodec<VideoCodecInfo>()->_width;
result["height"] = _streamCapabilities.GetVideoCodec<VideoCodecInfo>()->_height;
}
return result;
}
void TSDocument::AddFrame(double pts, double dts, uint8_t frameType) {
uint64_t currentOffset = _pParser->GetTotalParsedBytes();
bool insert = false;
if (_lastOffset == 0) {
_lastOffset = currentOffset;
insert = true;
} else if ((currentOffset - _lastOffset) < 7 * 188) {
insert = false;
} else {
insert = true;
}
if (!insert)
return;
MediaFrame frame;
frame.cts = dts - pts;
frame.dts = dts;
frame.isBinaryHeader = false;
frame.isKeyFrame = true;
frame.length = 0;
frame.pts = pts;
frame.start = currentOffset + _chunkSizeDetectionCount;
frame.type = frameType;
ADD_VECTOR_END(_frames, frame);
_lastOffset = currentOffset;
}
bool TSDocument::DetermineChunkSize() {
while (true) {
if (_chunkSizeDetectionCount >= TS_CHUNK_208) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
//FINEST("Check for %"PRIu8" at %"PRIu8, (uint8_t) TS_CHUNK_188, _chunkSizeDetectionCount);
if (!TestChunkSize(TS_CHUNK_188)) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
if (_chunkSize != 0)
return true;
//FINEST("Check for %"PRIu8" at %"PRIu8, (uint8_t) TS_CHUNK_204, _chunkSizeDetectionCount);
if (!TestChunkSize(TS_CHUNK_204)) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
if (_chunkSize != 0)
return true;
//FINEST("Check for %"PRIu8" at %"PRIu8, (uint8_t) TS_CHUNK_208, _chunkSizeDetectionCount);
if (!TestChunkSize(TS_CHUNK_208)) {
FATAL("I give up. I'm unable to detect the ts chunk size");
return false;
}
if (_chunkSize != 0)
return true;
_chunkSizeDetectionCount++;
}
}
bool TSDocument::GetByteAt(uint64_t offset, uint8_t &byte) {
uint64_t backup = _mediaFile.Cursor();
if (!_mediaFile.SeekTo(offset)) {
FATAL("Unable to seek to offset %"PRIu64, offset);
return false;
}
if (!_mediaFile.ReadUI8(&byte)) {
FATAL("Unable to read byte at offset %"PRIu64, offset);
return false;
}
if (!_mediaFile.SeekTo(backup)) {
FATAL("Unable to seek to offset %"PRIu64, backup);
return false;
}
return true;
}
bool TSDocument::TestChunkSize(uint8_t chunkSize) {
_chunkSize = 0;
uint8_t byte;
if ((int64_t) (_mediaFile.Size() - _mediaFile.Cursor()) <(2 * chunkSize + 1))
return true;
if (!GetByteAt(_chunkSizeDetectionCount, byte)) {
FATAL("Unable to read byte at offset %"PRIu32, _chunkSizeDetectionCount);
return false;
}
if (byte != 0x47)
return true;
if (!GetByteAt(_chunkSizeDetectionCount + chunkSize, byte)) {
FATAL("Unable to read byte at offset %"PRIu32, _chunkSizeDetectionCount + chunkSize);
return false;
}
if (byte != 0x47)
return true;
if (!GetByteAt(_chunkSizeDetectionCount + 2 * chunkSize, byte)) {
FATAL("Unable to read byte at offset %"PRIu32, _chunkSizeDetectionCount + 2 * chunkSize);
return false;
}
if (byte != 0x47)
return true;
_chunkSize = chunkSize;
return true;
}
#endif /* HAS_MEDIA_TS */
| 6,602
|
C++
|
.cpp
| 217
| 27.976959
| 93
| 0.724622
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,331
|
iotimer.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/kqueue/iotimer.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_KQUEUE
#include "netio/kqueue/iotimer.h"
#include "protocols/baseprotocol.h"
#include "netio/kqueue/iohandlermanager.h"
int32_t IOTimer::_idGenerator;
IOTimer::IOTimer()
: IOHandler(0, 0, IOHT_TIMER) {
_outboundFd = _inboundFd = ++_idGenerator;
}
IOTimer::~IOTimer() {
IOHandlerManager::DisableTimer(this, true);
}
bool IOTimer::SignalOutputData() {
ASSERT("Operation not supported");
return false;
}
bool IOTimer::OnEvent(struct kevent &event) {
switch (event.filter) {
case EVFILT_TIMER:
{
if (!_pProtocol->IsEnqueueForDelete()) {
if (!_pProtocol->TimePeriodElapsed()) {
FATAL("Unable to handle TimeElapsed event");
IOHandlerManager::EnqueueForDelete(this);
return false;
}
}
return true;
}
default:
{
ASSERT("Invalid state: %hu", event.filter);
return false;
}
}
}
bool IOTimer::EnqueueForTimeEvent(uint32_t seconds) {
return IOHandlerManager::EnableTimer(this, seconds);
}
bool IOTimer::EnqueueForHighGranularityTimeEvent(uint32_t milliseconds) {
return IOHandlerManager::EnableHighGranularityTimer(this, milliseconds);
}
void IOTimer::GetStats(Variant &info, uint32_t namespaceId) {
}
#endif /* NET_KQUEUE */
| 1,969
|
C++
|
.cpp
| 63
| 28.857143
| 73
| 0.746434
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,332
|
tcpcarrier.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/kqueue/tcpcarrier.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_KQUEUE
#include "netio/kqueue/tcpcarrier.h"
#include "netio/kqueue/iohandlermanager.h"
#include "protocols/baseprotocol.h"
#define ENABLE_WRITE_DATA \
if (!_writeDataEnabled) { \
_writeDataEnabled = true; \
IOHandlerManager::EnableWriteData(this); \
} \
_enableWriteDataCalled=true;
#define DISABLE_WRITE_DATA \
if (_writeDataEnabled) { \
_enableWriteDataCalled=false; \
_pProtocol->ReadyForSend(); \
if(!_enableWriteDataCalled) { \
if(_pProtocol->GetOutputBuffer()==NULL) {\
_writeDataEnabled = false; \
IOHandlerManager::DisableWriteData(this); \
} \
} \
}
TCPCarrier::TCPCarrier(int32_t fd)
: IOHandler(fd, fd, IOHT_TCP_CARRIER) {
IOHandlerManager::EnableReadData(this);
_writeDataEnabled = false;
_enableWriteDataCalled = false;
memset(&_farAddress, 0, sizeof (sockaddr_in));
_farIp = "";
_farPort = 0;
memset(&_nearAddress, 0, sizeof (sockaddr_in));
_nearIp = "";
_nearPort = 0;
GetEndpointsInfo();
_rx = 0;
_tx = 0;
_ioAmount = 0;
_lastRecvError = 0;
_lastSendError = 0;
Variant stats;
GetStats(stats);
}
TCPCarrier::~TCPCarrier() {
Variant stats;
GetStats(stats);
CLOSE_SOCKET(_inboundFd);
}
bool TCPCarrier::OnEvent(struct kevent &event) {
//3. Do the I/O
switch (event.filter) {
case EVFILT_READ:
{
IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
o_assert(pInputBuffer != NULL);
if (!pInputBuffer->ReadFromTCPFd(event.ident, event.data, _ioAmount,
_lastRecvError)) {
FATAL("Unable to read data from connection: %s. Error was (%d): %s",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", _lastRecvError,
strerror(_lastRecvError));
return false;
}
_rx += _ioAmount;
ADD_IN_BYTES_MANAGED(_type, _ioAmount);
if (!_pProtocol->SignalInputData(_ioAmount)) {
FATAL("Unable to read data from connection: %s. Signaling upper protocols failed",
(_pProtocol != NULL) ? STR(*_pProtocol) : "");
return false;
}
return true;
}
case EVFILT_WRITE:
{
IOBuffer *pOutputBuffer = NULL;
if ((pOutputBuffer = _pProtocol->GetOutputBuffer()) != NULL) {
if (!pOutputBuffer->WriteToTCPFd(event.ident, event.data,
_ioAmount, _lastSendError)) {
FATAL("Unable to write data on connection: %s. Error was (%d): %s",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", _lastSendError,
strerror(_lastSendError));
IOHandlerManager::EnqueueForDelete(this);
return false;
}
_tx += _ioAmount;
ADD_OUT_BYTES_MANAGED(_type, _ioAmount);
if (GETAVAILABLEBYTESCOUNT(*pOutputBuffer) == 0) {
DISABLE_WRITE_DATA;
}
} else {
DISABLE_WRITE_DATA;
}
return true;
}
default:
{
FATAL("Unable to read/write data from/to connection: %s. Invalid event type: %d",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", event.filter);
return false;
}
}
}
bool TCPCarrier::SignalOutputData() {
ENABLE_WRITE_DATA;
return true;
}
void TCPCarrier::GetStats(Variant &info, uint32_t namespaceId) {
if (!GetEndpointsInfo()) {
FATAL("Unable to get endpoints info");
info = "unable to get endpoints info";
return;
}
info["type"] = "IOHT_TCP_CARRIER";
info["farIP"] = _farIp;
info["farPort"] = _farPort;
info["nearIP"] = _nearIp;
info["nearPort"] = _nearPort;
info["rx"] = _rx;
info["tx"] = _tx;
}
sockaddr_in &TCPCarrier::GetFarEndpointAddress() {
if ((_farIp == "") || (_farPort == 0))
GetEndpointsInfo();
return _farAddress;
}
string TCPCarrier::GetFarEndpointAddressIp() {
if (_farIp != "")
return _farIp;
GetEndpointsInfo();
return _farIp;
}
uint16_t TCPCarrier::GetFarEndpointPort() {
if (_farPort != 0)
return _farPort;
GetEndpointsInfo();
return _farPort;
}
sockaddr_in &TCPCarrier::GetNearEndpointAddress() {
if ((_nearIp == "") || (_nearPort == 0))
GetEndpointsInfo();
return _nearAddress;
}
string TCPCarrier::GetNearEndpointAddressIp() {
if (_nearIp != "")
return _nearIp;
GetEndpointsInfo();
return _nearIp;
}
uint16_t TCPCarrier::GetNearEndpointPort() {
if (_nearPort != 0)
return _nearPort;
GetEndpointsInfo();
return _nearPort;
}
bool TCPCarrier::GetEndpointsInfo() {
if ((_farIp != "")
&& (_farPort != 0)
&& (_nearIp != "")
&& (_nearPort != 0)) {
return true;
}
socklen_t len = sizeof (sockaddr);
if (getpeername(_inboundFd, (sockaddr *) & _farAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_farIp = format("%s", inet_ntoa(((sockaddr_in *) & _farAddress)->sin_addr));
_farPort = ENTOHS(((sockaddr_in *) & _farAddress)->sin_port); //----MARKED-SHORT----
if (getsockname(_inboundFd, (sockaddr *) & _nearAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_nearIp = format("%s", inet_ntoa(((sockaddr_in *) & _nearAddress)->sin_addr));
_nearPort = ENTOHS(((sockaddr_in *) & _nearAddress)->sin_port); //----MARKED-SHORT----
return true;
}
#endif /* NET_KQUEUE */
| 5,664
|
C++
|
.cpp
| 192
| 26.75
| 87
| 0.683052
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,333
|
udpcarrier.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/kqueue/udpcarrier.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_KQUEUE
#include "netio/kqueue/udpcarrier.h"
#include "netio/kqueue/iohandlermanager.h"
#include "protocols/baseprotocol.h"
UDPCarrier::UDPCarrier(int32_t fd)
: IOHandler(fd, fd, IOHT_UDP_CARRIER) {
memset(&_peerAddress, 0, sizeof (sockaddr_in));
memset(&_nearAddress, 0, sizeof (sockaddr_in));
_nearIp = "";
_nearPort = 0;
_rx = 0;
_tx = 0;
_ioAmount = 0;
Variant stats;
GetStats(stats);
}
UDPCarrier::~UDPCarrier() {
Variant stats;
GetStats(stats);
CLOSE_SOCKET(_inboundFd);
}
bool UDPCarrier::OnEvent(struct kevent &event) {
//3. Do the I/O
switch (event.filter) {
case EVFILT_READ:
{
IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
o_assert(pInputBuffer != NULL);
if (!pInputBuffer->ReadFromUDPFd(event.ident, _ioAmount, _peerAddress)) {
FATAL("Unable to read data");
return false;
}
_rx += _ioAmount;
ADD_IN_BYTES_MANAGED(_type, _ioAmount);
return _pProtocol->SignalInputData(_ioAmount, &_peerAddress);
}
case EVFILT_WRITE:
{
_pProtocol->ReadyForSend();
return true;
}
default:
{
ASSERT("Invalid state: %hu", event.filter);
return false;
}
}
}
bool UDPCarrier::SignalOutputData() {
NYIR;
}
void UDPCarrier::GetStats(Variant &info, uint32_t namespaceId) {
if (!GetEndpointsInfo()) {
FATAL("Unable to get endpoints info");
info = "unable to get endpoints info";
return;
}
info["type"] = "IOHT_UDP_CARRIER";
info["nearIP"] = _nearIp;
info["nearPort"] = _nearPort;
info["rx"] = _rx;
}
Variant &UDPCarrier::GetParameters() {
return _parameters;
}
void UDPCarrier::SetParameters(Variant parameters) {
_parameters = parameters;
}
bool UDPCarrier::StartAccept() {
return IOHandlerManager::EnableReadData(this);
}
string UDPCarrier::GetFarEndpointAddress() {
ASSERT("Operation not supported");
return "";
}
uint16_t UDPCarrier::GetFarEndpointPort() {
ASSERT("Operation not supported");
return 0;
}
string UDPCarrier::GetNearEndpointAddress() {
if (_nearIp != "")
return _nearIp;
GetEndpointsInfo();
return _nearIp;
}
uint16_t UDPCarrier::GetNearEndpointPort() {
if (_nearPort != 0)
return _nearPort;
GetEndpointsInfo();
return _nearPort;
}
UDPCarrier* UDPCarrier::Create(string bindIp, uint16_t bindPort, uint16_t ttl,
uint16_t tos, string ssmIp) {
//1. Create the socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if ((sock < 0) || (!setFdCloseOnExec(sock))) {
int err = errno;
FATAL("Unable to create socket: (%d) %s", err, strerror(err));
return NULL;
}
//2. fd options
if (!setFdOptions(sock, true)) {
FATAL("Unable to set fd options");
CLOSE_SOCKET(sock);
return NULL;
}
if (tos <= 255) {
if (!setFdTOS(sock, (uint8_t) tos)) {
FATAL("Unable to set tos");
CLOSE_SOCKET(sock);
return NULL;
}
}
//3. Bind
if (bindIp == "") {
bindIp = "0.0.0.0";
bindPort = 0;
}
sockaddr_in bindAddress;
memset(&bindAddress, 0, sizeof (bindAddress));
bindAddress.sin_family = PF_INET;
bindAddress.sin_addr.s_addr = inet_addr(STR(bindIp));
bindAddress.sin_port = EHTONS(bindPort); //----MARKED-SHORT----
if (bindAddress.sin_addr.s_addr == INADDR_NONE) {
FATAL("Unable to bind on address %s:%hu", STR(bindIp), bindPort);
CLOSE_SOCKET(sock);
return NULL;
}
uint32_t testVal = EHTONL(bindAddress.sin_addr.s_addr);
if ((testVal > 0xe0000000) && (testVal < 0xefffffff)) {
INFO("Subscribe to multicast %s:%"PRIu16, STR(bindIp), bindPort);
int activateBroadcast = 1;
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &activateBroadcast,
sizeof (activateBroadcast)) != 0) {
int err = errno;
FATAL("Unable to activate SO_BROADCAST on the socket: (%d) %s",
err, strerror(err));
return NULL;
}
if (ttl <= 255) {
if (!setFdMulticastTTL(sock, (uint8_t) ttl)) {
FATAL("Unable to set ttl");
CLOSE_SOCKET(sock);
return NULL;
}
}
} else {
if (ttl <= 255) {
if (!setFdTTL(sock, (uint8_t) ttl)) {
FATAL("Unable to set ttl");
CLOSE_SOCKET(sock);
return NULL;
}
}
}
if (bind(sock, (sockaddr *) & bindAddress, sizeof (sockaddr)) != 0) {
int err = errno;
FATAL("Unable to bind on address: udp://%s:%"PRIu16"; Error was: (%d) %s",
STR(bindIp), bindPort, err, strerror(err));
CLOSE_SOCKET(sock);
return NULL;
}
if ((testVal > 0xe0000000) && (testVal < 0xefffffff)) {
if (!setFdJoinMulticast(sock, bindIp, bindPort, ssmIp)) {
FATAL("Adding multicast failed");
CLOSE_SOCKET(sock);
return NULL;
}
}
//4. Create the carrier
UDPCarrier *pResult = new UDPCarrier(sock);
pResult->_nearAddress = bindAddress;
return pResult;
}
UDPCarrier* UDPCarrier::Create(string bindIp, uint16_t bindPort,
BaseProtocol *pProtocol, uint16_t ttl, uint16_t tos, string ssmIp) {
if (pProtocol == NULL) {
FATAL("Protocol can't be null");
return NULL;
}
UDPCarrier *pResult = Create(bindIp, bindPort, ttl, tos, ssmIp);
if (pResult == NULL) {
FATAL("Unable to create UDP carrier");
return NULL;
}
pResult->SetProtocol(pProtocol->GetFarEndpoint());
pProtocol->GetFarEndpoint()->SetIOHandler(pResult);
return pResult;
}
bool UDPCarrier::Setup(Variant &settings) {
NYIR;
}
bool UDPCarrier::GetEndpointsInfo() {
socklen_t len = sizeof (sockaddr);
if (getsockname(_inboundFd, (sockaddr *) & _nearAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_nearIp = format("%s", inet_ntoa(((sockaddr_in *) & _nearAddress)->sin_addr));
_nearPort = ENTOHS(((sockaddr_in *) & _nearAddress)->sin_port); //----MARKED-SHORT----
return true;
}
#endif /* NET_KQUEUE */
| 6,314
|
C++
|
.cpp
| 221
| 26.00905
| 87
| 0.697575
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,334
|
tcpacceptor.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/kqueue/tcpacceptor.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_KQUEUE
#include "netio/kqueue/tcpacceptor.h"
#include "netio/kqueue/iohandlermanager.h"
#include "protocols/protocolfactorymanager.h"
#include "protocols/tcpprotocol.h"
#include "netio/kqueue/tcpcarrier.h"
#include "application/baseclientapplication.h"
TCPAcceptor::TCPAcceptor(string ipAddress, uint16_t port, Variant parameters,
vector<uint64_t>/*&*/ protocolChain)
: IOHandler(0, 0, IOHT_ACCEPTOR) {
_pApplication = NULL;
memset(&_address, 0, sizeof (sockaddr_in));
_address.sin_family = PF_INET;
_address.sin_addr.s_addr = inet_addr(STR(ipAddress));
o_assert(_address.sin_addr.s_addr != INADDR_NONE);
_address.sin_port = EHTONS(port); //----MARKED-SHORT----
_protocolChain = protocolChain;
_parameters = parameters;
_enabled = false;
_acceptedCount = 0;
_droppedCount = 0;
_ipAddress = ipAddress;
_port = port;
}
TCPAcceptor::~TCPAcceptor() {
CLOSE_SOCKET(_inboundFd);
}
bool TCPAcceptor::Bind() {
_inboundFd = _outboundFd = (int) socket(PF_INET, SOCK_STREAM, 0); //NOINHERIT
if (_inboundFd < 0) {
int err = errno;
FATAL("Unable to create socket: (%d) %s", err, strerror(err));
return false;
}
if (!setFdOptions(_inboundFd, false)) {
FATAL("Unable to set socket options");
return false;
}
if (bind(_inboundFd, (sockaddr *) & _address, sizeof (sockaddr)) != 0) {
int err = errno;
FATAL("Unable to bind on address: tcp://%s:%hu; Error was: (%d) %s",
inet_ntoa(((sockaddr_in *) & _address)->sin_addr),
ENTOHS(((sockaddr_in *) & _address)->sin_port),
err,
strerror(err));
return false;
}
if (_port == 0) {
socklen_t tempSize = sizeof (sockaddr);
if (getsockname(_inboundFd, (sockaddr *) & _address, &tempSize) != 0) {
FATAL("Unable to extract the random port");
return false;
}
_parameters[CONF_PORT] = (uint16_t) ENTOHS(_address.sin_port);
}
if (listen(_inboundFd, 100) != 0) {
FATAL("Unable to put the socket in listening mode");
return false;
}
_enabled = true;
return true;
}
void TCPAcceptor::SetApplication(BaseClientApplication *pApplication) {
o_assert(_pApplication == NULL);
_pApplication = pApplication;
}
bool TCPAcceptor::StartAccept() {
return IOHandlerManager::EnableAcceptConnections(this);
}
bool TCPAcceptor::SignalOutputData() {
ASSERT("Operation not supported");
return false;
}
bool TCPAcceptor::OnEvent(struct kevent &event) {
if (!OnConnectionAvailable(event))
return IsAlive();
else
return true;
}
bool TCPAcceptor::OnConnectionAvailable(struct kevent &event) {
if (_pApplication == NULL)
return Accept();
return _pApplication->AcceptTCPConnection(this);
}
bool TCPAcceptor::Accept() {
sockaddr address;
memset(&address, 0, sizeof (sockaddr));
socklen_t len = sizeof (sockaddr);
int32_t fd;
//1. Accept the connection
fd = accept(_inboundFd, &address, &len);
if ((fd < 0) || (!setFdCloseOnExec(fd))) {
int err = errno;
FATAL("Unable to accept client connection: (%d) %s", err, strerror(err));
return false;
}
if (!_enabled) {
CLOSE_SOCKET(fd);
_droppedCount++;
WARN("Acceptor is not enabled. Client dropped: %s:%"PRIu16" -> %s:%"PRIu16,
inet_ntoa(((sockaddr_in *) & address)->sin_addr),
ENTOHS(((sockaddr_in *) & address)->sin_port),
STR(_ipAddress),
_port);
return true;
}
if (!setFdOptions(fd, false)) {
FATAL("Unable to set socket options");
CLOSE_SOCKET(fd);
return false;
}
//4. Create the chain
BaseProtocol *pProtocol = ProtocolFactoryManager::CreateProtocolChain(
_protocolChain, _parameters);
if (pProtocol == NULL) {
FATAL("Unable to create protocol chain");
CLOSE_SOCKET(fd);
return false;
}
//5. Create the carrier and bind it
TCPCarrier *pTCPCarrier = new TCPCarrier(fd);
pTCPCarrier->SetProtocol(pProtocol->GetFarEndpoint());
pProtocol->GetFarEndpoint()->SetIOHandler(pTCPCarrier);
//6. Register the protocol stack with an application
if (_pApplication != NULL) {
pProtocol = pProtocol->GetNearEndpoint();
pProtocol->SetApplication(_pApplication);
}
if (pProtocol->GetNearEndpoint()->GetOutputBuffer() != NULL)
pProtocol->GetNearEndpoint()->EnqueueForOutbound();
_acceptedCount++;
INFO("Inbound connection accepted: %s", STR(*(pProtocol->GetNearEndpoint())));
//7. Done
return true;
}
bool TCPAcceptor::Drop() {
sockaddr address;
memset(&address, 0, sizeof (sockaddr));
socklen_t len = sizeof (sockaddr);
//1. Accept the connection
int32_t fd = accept(_inboundFd, &address, &len);
if ((fd < 0) || (!setFdCloseOnExec(fd))) {
int err = errno;
if (err != EWOULDBLOCK)
WARN("Accept failed. Error code was: (%d) %s", err, strerror(err));
return false;
}
//2. Drop it now
CLOSE_SOCKET(fd);
_droppedCount++;
INFO("Client explicitly dropped: %s:%"PRIu16" -> %s:%"PRIu16,
inet_ntoa(((sockaddr_in *) & address)->sin_addr),
ENTOHS(((sockaddr_in *) & address)->sin_port),
STR(_ipAddress),
_port);
return true;
}
Variant & TCPAcceptor::GetParameters() {
return _parameters;
}
BaseClientApplication *TCPAcceptor::GetApplication() {
return _pApplication;
}
vector<uint64_t> &TCPAcceptor::GetProtocolChain() {
return _protocolChain;
}
void TCPAcceptor::GetStats(Variant &info, uint32_t namespaceId) {
info = _parameters;
info["id"] = (((uint64_t) namespaceId) << 32) | GetId();
info["enabled"] = (bool)_enabled;
info["acceptedConnectionsCount"] = _acceptedCount;
info["droppedConnectionsCount"] = _droppedCount;
if (_pApplication != NULL) {
info["appId"] = (((uint64_t) namespaceId) << 32) | _pApplication->GetId();
info["appName"] = _pApplication->GetName();
} else {
info["appId"] = (((uint64_t) namespaceId) << 32);
info["appName"] = "";
}
}
bool TCPAcceptor::Enable() {
return _enabled;
}
void TCPAcceptor::Enable(bool enabled) {
_enabled = enabled;
}
bool TCPAcceptor::IsAlive() {
//TODO: Implement this. It must return true
//if this acceptor is operational
NYI;
return true;
}
#endif /* NET_KQUEUE */
| 6,686
|
C++
|
.cpp
| 211
| 29.317536
| 79
| 0.711222
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,335
|
iohandlermanager.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/kqueue/iohandlermanager.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_KQUEUE
#include "netio/kqueue/iohandlermanager.h"
#include "netio/kqueue/iohandler.h"
#define INITIAL_EVENTS_SIZE 1024
vector<IOHandlerManagerToken *> IOHandlerManager::_tokensVector1;
vector<IOHandlerManagerToken *> IOHandlerManager::_tokensVector2;
vector<IOHandlerManagerToken *> *IOHandlerManager::_pAvailableTokens;
vector<IOHandlerManagerToken *> *IOHandlerManager::_pRecycledTokens;
map<uint32_t, IOHandler *> IOHandlerManager::_activeIOHandlers;
map<uint32_t, IOHandler *> IOHandlerManager::_deadIOHandlers;
int32_t IOHandlerManager::_kq = 0;
struct kevent *IOHandlerManager::_pDetectedEvents = NULL;
struct kevent *IOHandlerManager::_pPendingEvents = NULL;
int32_t IOHandlerManager::_pendingEventsCount = 0;
int32_t IOHandlerManager::_eventsSize = 0;
FdStats IOHandlerManager::_fdStats;
#ifndef HAS_KQUEUE_TIMERS
struct timespec IOHandlerManager::_timeout = {1, 0};
TimersManager *IOHandlerManager::_pTimersManager = NULL;
struct kevent IOHandlerManager::_dummy = {0, EVFILT_TIMER, 0, 0, 0, NULL};
#endif /* HAS_KQUEUE_TIMERS */
void IOHandlerManager::SetupToken(IOHandler *pIOHandler) {
IOHandlerManagerToken *pResult = NULL;
if (_pAvailableTokens->size() == 0) {
pResult = new IOHandlerManagerToken();
} else {
pResult = (*_pAvailableTokens)[0];
_pAvailableTokens->erase(_pAvailableTokens->begin());
}
pResult->pPayload = pIOHandler;
pResult->validPayload = true;
pIOHandler->SetIOHandlerManagerToken(pResult);
}
void IOHandlerManager::FreeToken(IOHandler *pIOHandler) {
IOHandlerManagerToken *pToken = pIOHandler->GetIOHandlerManagerToken();
pIOHandler->SetIOHandlerManagerToken(NULL);
pToken->pPayload = NULL;
pToken->validPayload = false;
ADD_VECTOR_END((*_pRecycledTokens), pToken);
}
bool IOHandlerManager::RegisterEvent(int32_t fd, int16_t filter, uint16_t flags,
uint32_t fflags, uint32_t data, IOHandlerManagerToken *pToken, bool ignoreError) {
if (_pendingEventsCount >= _eventsSize) {
ResizeEvents();
}
EV_SET(&_pPendingEvents[_pendingEventsCount], fd, filter, flags, fflags,
data, pToken);
_pendingEventsCount++;
return true;
}
map<uint32_t, IOHandler *> & IOHandlerManager::GetActiveHandlers() {
return _activeIOHandlers;
}
map<uint32_t, IOHandler *> & IOHandlerManager::GetDeadHandlers() {
return _deadIOHandlers;
}
FdStats &IOHandlerManager::GetStats(bool updateSpeeds) {
#ifdef GLOBALLY_ACCOUNT_BYTES
if (updateSpeeds)
_fdStats.UpdateSpeeds();
#endif /* GLOBALLY_ACCOUNT_BYTES */
return _fdStats;
}
void IOHandlerManager::Initialize() {
_fdStats.Reset();
_kq = 0;
_pAvailableTokens = &_tokensVector1;
_pRecycledTokens = &_tokensVector2;
#ifndef HAS_KQUEUE_TIMERS
_pTimersManager = new TimersManager(ProcessTimer);
#endif /* HAS_KQUEUE_TIMERS */
ResizeEvents();
}
void IOHandlerManager::Start() {
_kq = kqueue();
o_assert(_kq > 0);
}
void IOHandlerManager::SignalShutdown() {
close(_kq);
}
void IOHandlerManager::ShutdownIOHandlers() {
FOR_MAP(_activeIOHandlers, uint32_t, IOHandler *, i) {
EnqueueForDelete(MAP_VAL(i));
}
}
void IOHandlerManager::Shutdown() {
close(_kq);
for (uint32_t i = 0; i < _tokensVector1.size(); i++)
delete _tokensVector1[i];
_tokensVector1.clear();
_pAvailableTokens = &_tokensVector1;
for (uint32_t i = 0; i < _tokensVector2.size(); i++)
delete _tokensVector2[i];
_tokensVector2.clear();
_pRecycledTokens = &_tokensVector2;
#ifndef HAS_KQUEUE_TIMERS
delete _pTimersManager;
_pTimersManager = NULL;
#endif /* HAS_KQUEUE_TIMERS */
free(_pPendingEvents);
_pPendingEvents = NULL;
free(_pDetectedEvents);
_pDetectedEvents = NULL;
_pendingEventsCount = 0;
_eventsSize = 0;
if (_activeIOHandlers.size() != 0 || _deadIOHandlers.size() != 0) {
FATAL("Incomplete shutdown!");
}
}
void IOHandlerManager::RegisterIOHandler(IOHandler* pIOHandler) {
if (MAP_HAS1(_activeIOHandlers, pIOHandler->GetId())) {
ASSERT("IOHandler already registered");
}
size_t before = _activeIOHandlers.size();
_activeIOHandlers[pIOHandler->GetId()] = pIOHandler;
SetupToken(pIOHandler);
_fdStats.RegisterManaged(pIOHandler->GetType());
DEBUG("Handlers count changed: %"PRIz"u->%"PRIz"u %s", before, before + 1,
STR(IOHandler::IOHTToString(pIOHandler->GetType())));
}
void IOHandlerManager::UnRegisterIOHandler(IOHandler *pIOHandler) {
if (MAP_HAS1(_activeIOHandlers, pIOHandler->GetId())) {
_fdStats.UnRegisterManaged(pIOHandler->GetType());
FreeToken(pIOHandler);
size_t before = _activeIOHandlers.size();
_activeIOHandlers.erase(pIOHandler->GetId());
DEBUG("Handlers count changed: %"PRIz"u->%"PRIz"u %s", before, before - 1,
STR(IOHandler::IOHTToString(pIOHandler->GetType())));
}
}
int IOHandlerManager::CreateRawUDPSocket() {
int result = socket(AF_INET, SOCK_DGRAM, 0);
if ((result >= 0)&&(setFdCloseOnExec(result))) {
_fdStats.RegisterRawUdp();
} else {
int err = errno;
FATAL("Unable to create raw udp socket. Error code was: (%d) %s",
err, strerror(err));
}
return result;
}
void IOHandlerManager::CloseRawUDPSocket(int socket) {
if (socket > 0) {
_fdStats.UnRegisterRawUdp();
}
CLOSE_SOCKET(socket);
}
#ifdef GLOBALLY_ACCOUNT_BYTES
void IOHandlerManager::AddInBytesManaged(IOHandlerType type, uint64_t bytes) {
_fdStats.AddInBytesManaged(type, bytes);
}
void IOHandlerManager::AddOutBytesManaged(IOHandlerType type, uint64_t bytes) {
_fdStats.AddOutBytesManaged(type, bytes);
}
void IOHandlerManager::AddInBytesRawUdp(uint64_t bytes) {
_fdStats.AddInBytesRawUdp(bytes);
}
void IOHandlerManager::AddOutBytesRawUdp(uint64_t bytes) {
_fdStats.AddOutBytesRawUdp(bytes);
}
#endif /* GLOBALLY_ACCOUNT_BYTES */
bool IOHandlerManager::EnableReadData(IOHandler *pIOHandler) {
return RegisterEvent(pIOHandler->GetInboundFd(), EVFILT_READ,
EV_ADD | EV_ENABLE, 0, 0,
pIOHandler->GetIOHandlerManagerToken());
}
bool IOHandlerManager::DisableReadData(IOHandler *pIOHandler, bool ignoreError) {
return RegisterEvent(pIOHandler->GetInboundFd(), EVFILT_READ,
EV_ADD | EV_DISABLE, 0, 0,
pIOHandler->GetIOHandlerManagerToken(), ignoreError);
}
bool IOHandlerManager::EnableWriteData(IOHandler *pIOHandler) {
return RegisterEvent(pIOHandler->GetOutboundFd(), EVFILT_WRITE,
EV_ADD | EV_ENABLE, 0, 0,
pIOHandler->GetIOHandlerManagerToken());
}
bool IOHandlerManager::DisableWriteData(IOHandler *pIOHandler, bool ignoreError) {
return RegisterEvent(pIOHandler->GetOutboundFd(), EVFILT_WRITE,
EV_ADD | EV_DISABLE, 0, 0,
pIOHandler->GetIOHandlerManagerToken(), ignoreError);
}
bool IOHandlerManager::EnableAcceptConnections(IOHandler *pIOHandler) {
return RegisterEvent(pIOHandler->GetInboundFd(), EVFILT_READ,
EV_ADD | EV_ENABLE, 0, 0,
pIOHandler->GetIOHandlerManagerToken());
}
bool IOHandlerManager::DisableAcceptConnections(IOHandler *pIOHandler, bool ignoreError) {
return RegisterEvent(pIOHandler->GetInboundFd(), EVFILT_READ,
EV_ADD | EV_DISABLE, 0, 0,
pIOHandler->GetIOHandlerManagerToken(), ignoreError);
}
bool IOHandlerManager::EnableTimer(IOHandler *pIOHandler, uint32_t seconds) {
#ifdef HAS_KQUEUE_TIMERS
return RegisterEvent(pIOHandler->GetId(), EVFILT_TIMER,
EV_ADD | EV_ENABLE, NOTE_USECONDS,
seconds*KQUEUE_TIMER_MULTIPLIER, pIOHandler->GetIOHandlerManagerToken());
#else /* HAS_KQUEUE_TIMERS */
TimerEvent event = {0, 0, 0, 0};
event.id = pIOHandler->GetId();
event.period = seconds * 1000;
event.pUserData = pIOHandler->GetIOHandlerManagerToken();
_pTimersManager->AddTimer(event);
return true;
#endif /* HAS_KQUEUE_TIMERS */
}
bool IOHandlerManager::EnableHighGranularityTimer(IOHandler *pIOHandler, uint32_t milliseconds) {
#ifdef HAS_KQUEUE_TIMERS
return RegisterEvent(pIOHandler->GetId(), EVFILT_TIMER,
EV_ADD | EV_ENABLE, NOTE_USECONDS,
milliseconds * (KQUEUE_TIMER_MULTIPLIER / 1000), pIOHandler->GetIOHandlerManagerToken());
#else /* HAS_KQUEUE_TIMERS */
TimerEvent event = {0, 0, 0, 0};
event.id = pIOHandler->GetId();
event.period = milliseconds;
event.pUserData = pIOHandler->GetIOHandlerManagerToken();
_pTimersManager->AddTimer(event);
return true;
#endif /* HAS_KQUEUE_TIMERS */
}
bool IOHandlerManager::DisableTimer(IOHandler *pIOHandler, bool ignoreError) {
#ifdef HAS_KQUEUE_TIMERS
return RegisterEvent(pIOHandler->GetId(), EVFILT_TIMER,
EV_DELETE, 0, 0,
pIOHandler->GetIOHandlerManagerToken(), ignoreError);
#else /* HAS_KQUEUE_TIMERS */
_pTimersManager->RemoveTimer(pIOHandler->GetId());
return true;
#endif /* HAS_KQUEUE_TIMERS */
}
void IOHandlerManager::EnqueueForDelete(IOHandler *pIOHandler) {
DisableAcceptConnections(pIOHandler, true);
DisableReadData(pIOHandler, true);
DisableWriteData(pIOHandler, true);
DisableTimer(pIOHandler, true);
if (!MAP_HAS1(_deadIOHandlers, pIOHandler->GetId()))
_deadIOHandlers[pIOHandler->GetId()] = pIOHandler;
}
uint32_t IOHandlerManager::DeleteDeadHandlers() {
uint32_t result = 0;
while (_deadIOHandlers.size() > 0) {
IOHandler *pIOHandler = MAP_VAL(_deadIOHandlers.begin());
_deadIOHandlers.erase(pIOHandler->GetId());
delete pIOHandler;
result++;
}
return result;
}
bool IOHandlerManager::Pulse() {
int32_t result = 0;
#ifdef HAS_KQUEUE_TIMERS
result = kevent(_kq, _pPendingEvents, _pendingEventsCount,
_pDetectedEvents, _eventsSize, NULL);
#else /* HAS_KQUEUE_TIMERS */
result = kevent(_kq, _pPendingEvents, _pendingEventsCount,
_pDetectedEvents, _eventsSize, &_timeout);
int32_t nextVal = _pTimersManager->TimeElapsed();
_timeout.tv_sec = nextVal / 1000;
_timeout.tv_nsec = (nextVal * 1000000) % 1000000000;
#endif /* HAS_KQUEUE_TIMERS */
if (result < 0) {
int err = errno;
if (err == EINTR)
return true;
FATAL("kevent failed: (%d) %s", err, strerror(err));
return false;
}
_pendingEventsCount = 0;
for (int32_t i = 0; i < result; i++) {
IOHandlerManagerToken *pToken =
(IOHandlerManagerToken *) _pDetectedEvents[i].udata;
if ((_pDetectedEvents[i].flags & EV_ERROR) != 0) {
if (pToken->validPayload) {
//DEBUG("***Event handler ERROR: %p", (IOHandler *) pToken->pPayload);
IOHandlerManager::EnqueueForDelete((IOHandler *) pToken->pPayload);
}
continue;
}
if (pToken->validPayload) {
if (!((IOHandler *) pToken->pPayload)->OnEvent(_pDetectedEvents[i])) {
EnqueueForDelete((IOHandler *) pToken->pPayload);
}
if ((_pDetectedEvents[i].flags & EV_EOF) != 0) {
//DEBUG("***Event handler EOF: %p", (IOHandler *) pToken->pPayload);
IOHandlerManager::EnqueueForDelete((IOHandler *) pToken->pPayload);
}
}
// else {
// FATAL("Invalid token");
// }
}
if (_tokensVector1.size() > _tokensVector2.size()) {
_pAvailableTokens = &_tokensVector1;
_pRecycledTokens = &_tokensVector2;
} else {
_pAvailableTokens = &_tokensVector2;
_pRecycledTokens = &_tokensVector1;
}
return true;
}
#ifndef HAS_KQUEUE_TIMERS
bool IOHandlerManager::ProcessTimer(TimerEvent &event) {
IOHandlerManagerToken *pToken =
(IOHandlerManagerToken *) event.pUserData;
if (pToken->validPayload) {
if (!((IOHandler *) pToken->pPayload)->OnEvent(_dummy)) {
EnqueueForDelete((IOHandler *) pToken->pPayload);
return false;
}
return true;
} else {
FATAL("Invalid token");
return false;
}
}
#endif /* HAS_KQUEUE_TIMERS */
inline void IOHandlerManager::ResizeEvents() {
_eventsSize += INITIAL_EVENTS_SIZE;
_pPendingEvents = (struct kevent *) realloc(_pPendingEvents,
_eventsSize * sizeof (struct kevent));
_pDetectedEvents = (struct kevent *) realloc(_pDetectedEvents,
_eventsSize * sizeof (struct kevent));
WARN("Event size resized: %d->%d", _eventsSize - INITIAL_EVENTS_SIZE,
_eventsSize);
}
#endif /* NET_KQUEUE */
| 12,348
|
C++
|
.cpp
| 343
| 33.763848
| 97
| 0.751568
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,336
|
iotimer.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/select/iotimer.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_SELECT
#include "netio/select/iotimer.h"
#include "protocols/baseprotocol.h"
#include "netio/select/iohandlermanager.h"
int32_t IOTimer::_idGenerator;
IOTimer::IOTimer()
: IOHandler(0, 0, IOHT_TIMER) {
_outboundFd = _inboundFd = ++_idGenerator;
}
IOTimer::~IOTimer() {
IOHandlerManager::DisableTimer(this);
}
bool IOTimer::SignalOutputData() {
ASSERT("Operation not supported");
return false;
}
bool IOTimer::OnEvent(select_event &event) {
if (!_pProtocol->IsEnqueueForDelete()) {
if (!_pProtocol->TimePeriodElapsed()) {
FATAL("Unable to handle TimeElapsed event");
IOHandlerManager::EnqueueForDelete(this);
return false;
}
}
return true;
}
bool IOTimer::EnqueueForTimeEvent(uint32_t seconds) {
return IOHandlerManager::EnableTimer(this, seconds);
}
bool IOTimer::EnqueueForHighGranularityTimeEvent(uint32_t milliseconds) {
return IOHandlerManager::EnableHighGranularityTimer(this, milliseconds);
}
void IOTimer::GetStats(Variant &info, uint32_t namespaceId) {
}
#endif /* NET_SELECT */
| 1,805
|
C++
|
.cpp
| 53
| 32.09434
| 73
| 0.762644
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,337
|
tcpcarrier.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/select/tcpcarrier.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_SELECT
#include "netio/select/tcpcarrier.h"
#include "netio/select/iohandlermanager.h"
#include "protocols/baseprotocol.h"
#define ENABLE_WRITE_DATA \
if (!_writeDataEnabled) { \
_writeDataEnabled = true; \
IOHandlerManager::EnableWriteData(this); \
} \
_enableWriteDataCalled=true;
#define DISABLE_WRITE_DATA \
if (_writeDataEnabled) { \
_enableWriteDataCalled=false; \
_pProtocol->ReadyForSend(); \
if(!_enableWriteDataCalled) { \
if(_pProtocol->GetOutputBuffer()==NULL) {\
_writeDataEnabled = false; \
IOHandlerManager::DisableWriteData(this); \
} \
} \
}
TCPCarrier::TCPCarrier(int32_t fd)
: IOHandler(fd, fd, IOHT_TCP_CARRIER) {
IOHandlerManager::EnableReadData(this);
_writeDataEnabled = false;
_enableWriteDataCalled = false;
memset(&_farAddress, 0, sizeof (sockaddr_in));
_farIp = "";
_farPort = 0;
memset(&_nearAddress, 0, sizeof (sockaddr_in));
_nearIp = "";
_nearPort = 0;
_sendBufferSize = 1024 * 1024 * 8;
_recvBufferSize = 1024 * 256;
GetEndpointsInfo();
_rx = 0;
_tx = 0;
_ioAmount = 0;
_lastRecvError = 0;
_lastSendError = 0;
Variant stats;
GetStats(stats);
EventLogger::GetDefaultLogger()->LogCarrierCreated(stats);
}
TCPCarrier::~TCPCarrier() {
Variant stats;
GetStats(stats);
EventLogger::GetDefaultLogger()->LogCarrierClosed(stats);
CLOSE_SOCKET(_inboundFd);
}
bool TCPCarrier::OnEvent(select_event &event) {
//3. Do the I/O
switch (event.type) {
case SET_READ:
{
IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
o_assert(pInputBuffer != NULL);
if (!pInputBuffer->ReadFromTCPFd(_inboundFd,
_recvBufferSize, _ioAmount, _lastRecvError)) {
FATAL("Unable to read data from connection: %s. Error was (%d): %s",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", _lastRecvError,
strerror(_lastRecvError));
return false;
}
_rx += _ioAmount;
ADD_IN_BYTES_MANAGED(_type, _ioAmount);
if (!_pProtocol->SignalInputData(_ioAmount)) {
FATAL("Unable to read data from connection: %s. Signaling upper protocols failed",
(_pProtocol != NULL) ? STR(*_pProtocol) : "");
return false;
}
return true;
}
case SET_WRITE:
{
IOBuffer *pOutputBuffer = NULL;
while ((pOutputBuffer = _pProtocol->GetOutputBuffer()) != NULL) {
if (!pOutputBuffer->WriteToTCPFd(_outboundFd,
_sendBufferSize, _ioAmount, _lastSendError)) {
FATAL("Unable to write data on connection: %s. Error was (%d): %s",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", _lastSendError,
strerror(_lastSendError));
IOHandlerManager::EnqueueForDelete(this);
return false;
}
_tx += _ioAmount;
ADD_OUT_BYTES_MANAGED(_type, _ioAmount);
if (GETAVAILABLEBYTESCOUNT(*pOutputBuffer) > 0) {
ENABLE_WRITE_DATA;
break;
}
}
if (pOutputBuffer == NULL) {
DISABLE_WRITE_DATA;
}
return true;
}
default:
{
FATAL("Unable to read/write data from/to connection: %s. Invalid event type: %d",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", event.type);
return false;
}
}
}
bool TCPCarrier::SignalOutputData() {
ENABLE_WRITE_DATA;
return true;
}
void TCPCarrier::GetStats(Variant &info, uint32_t namespaceId) {
if (!GetEndpointsInfo()) {
FATAL("Unable to get endpoints info");
info = "unable to get endpoints info";
return;
}
info["type"] = "IOHT_TCP_CARRIER";
info["farIP"] = _farIp;
info["farPort"] = _farPort;
info["nearIP"] = _nearIp;
info["nearPort"] = _nearPort;
info["rx"] = _rx;
info["tx"] = _tx;
}
sockaddr_in &TCPCarrier::GetFarEndpointAddress() {
if ((_farIp == "") || (_farPort == 0))
GetEndpointsInfo();
return _farAddress;
}
string TCPCarrier::GetFarEndpointAddressIp() {
if (_farIp != "")
return _farIp;
GetEndpointsInfo();
return _farIp;
}
uint16_t TCPCarrier::GetFarEndpointPort() {
if (_farPort != 0)
return _farPort;
GetEndpointsInfo();
return _farPort;
}
sockaddr_in &TCPCarrier::GetNearEndpointAddress() {
if ((_nearIp == "") || (_nearPort == 0))
GetEndpointsInfo();
return _nearAddress;
}
string TCPCarrier::GetNearEndpointAddressIp() {
if (_nearIp != "")
return _nearIp;
GetEndpointsInfo();
return _nearIp;
}
uint16_t TCPCarrier::GetNearEndpointPort() {
if (_nearPort != 0)
return _nearPort;
GetEndpointsInfo();
return _nearPort;
}
bool TCPCarrier::GetEndpointsInfo() {
if ((_farIp != "")
&& (_farPort != 0)
&& (_nearIp != "")
&& (_nearPort != 0)) {
return true;
}
socklen_t len = sizeof (sockaddr);
if (getpeername(_inboundFd, (sockaddr *) & _farAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_farIp = format("%s", inet_ntoa(((sockaddr_in *) & _farAddress)->sin_addr));
_farPort = ENTOHS(((sockaddr_in *) & _farAddress)->sin_port); //----MARKED-SHORT----
if (getsockname(_inboundFd, (sockaddr *) & _nearAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_nearIp = format("%s", inet_ntoa(((sockaddr_in *) & _nearAddress)->sin_addr));
_nearPort = ENTOHS(((sockaddr_in *) & _nearAddress)->sin_port); //----MARKED-SHORT----
return true;
}
#endif /* NET_SELECT */
| 5,887
|
C++
|
.cpp
| 198
| 26.969697
| 87
| 0.685427
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,338
|
udpcarrier.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/select/udpcarrier.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_SELECT
#include "netio/select/udpcarrier.h"
#include "netio/select/iohandlermanager.h"
#include "protocols/baseprotocol.h"
UDPCarrier::UDPCarrier(int32_t fd)
: IOHandler(fd, fd, IOHT_UDP_CARRIER) {
memset(&_peerAddress, 0, sizeof (sockaddr_in));
memset(&_nearAddress, 0, sizeof (sockaddr_in));
_nearIp = "";
_nearPort = 0;
_rx = 0;
_tx = 0;
_ioAmount = 0;
Variant stats;
GetStats(stats);
}
UDPCarrier::~UDPCarrier() {
Variant stats;
GetStats(stats);
CLOSE_SOCKET(_inboundFd);
}
bool UDPCarrier::OnEvent(select_event &event) {
//3. Do the I/O
switch (event.type) {
case SET_READ:
{
IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
o_assert(pInputBuffer != NULL);
if (!pInputBuffer->ReadFromUDPFd(_inboundFd, _ioAmount, _peerAddress)) {
FATAL("Unable to read data");
return false;
}
_rx += _ioAmount;
ADD_IN_BYTES_MANAGED(_type, _ioAmount);
return _pProtocol->SignalInputData(_ioAmount, &_peerAddress);
}
case SET_WRITE:
{
_pProtocol->ReadyForSend();
return true;
}
default:
{
ASSERT("Invalid state: %hhu", event.type);
return false;
}
}
}
bool UDPCarrier::SignalOutputData() {
NYIR;
}
void UDPCarrier::GetStats(Variant &info, uint32_t namespaceId) {
if (!GetEndpointsInfo()) {
FATAL("Unable to get endpoints info");
info = "unable to get endpoints info";
return;
}
info["type"] = "IOHT_UDP_CARRIER";
info["nearIP"] = _nearIp;
info["nearPort"] = _nearPort;
info["rx"] = _rx;
}
Variant &UDPCarrier::GetParameters() {
return _parameters;
}
void UDPCarrier::SetParameters(Variant parameters) {
_parameters = parameters;
}
bool UDPCarrier::StartAccept() {
return IOHandlerManager::EnableReadData(this);
}
string UDPCarrier::GetFarEndpointAddress() {
ASSERT("Operation not supported");
return "";
}
uint16_t UDPCarrier::GetFarEndpointPort() {
ASSERT("Operation not supported");
return 0;
}
string UDPCarrier::GetNearEndpointAddress() {
if (_nearIp != "")
return _nearIp;
GetEndpointsInfo();
return _nearIp;
}
uint16_t UDPCarrier::GetNearEndpointPort() {
if (_nearPort != 0)
return _nearPort;
GetEndpointsInfo();
return _nearPort;
}
UDPCarrier* UDPCarrier::Create(string bindIp, uint16_t bindPort, uint16_t ttl,
uint16_t tos, string ssmIp) {
//1. Create the socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if ((sock < 0) || (!setFdCloseOnExec(sock))) {
int err = LASTSOCKETERROR;
FATAL("Unable to create socket: %d", err);
return NULL;
}
//2. fd options
if (!setFdOptions(sock, true)) {
FATAL("Unable to set fd options");
CLOSE_SOCKET(sock);
return NULL;
}
if (tos <= 255) {
if (!setFdTOS(sock, (uint8_t) tos)) {
FATAL("Unable to set tos");
CLOSE_SOCKET(sock);
return NULL;
}
}
//3. Bind
if (bindIp == "") {
bindIp = "0.0.0.0";
bindPort = 0;
}
sockaddr_in bindAddress;
memset(&bindAddress, 0, sizeof (bindAddress));
bindAddress.sin_family = PF_INET;
bindAddress.sin_addr.s_addr = inet_addr(STR(bindIp));
bindAddress.sin_port = EHTONS(bindPort); //----MARKED-SHORT----
if (bindAddress.sin_addr.s_addr == INADDR_NONE) {
FATAL("Unable to bind on address %s:%hu", STR(bindIp), bindPort);
CLOSE_SOCKET(sock);
return NULL;
}
uint32_t testVal = EHTONL(bindAddress.sin_addr.s_addr);
if ((testVal > 0xe0000000) && (testVal < 0xefffffff)) {
INFO("Subscribe to multicast %s:%"PRIu16, STR(bindIp), bindPort);
int activateBroadcast = 1;
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &activateBroadcast,
sizeof (activateBroadcast)) != 0) {
int err = LASTSOCKETERROR;
FATAL("Unable to activate SO_BROADCAST on the socket: %d", err);
return NULL;
}
if (ttl <= 255) {
if (!setFdMulticastTTL(sock, (uint8_t) ttl)) {
FATAL("Unable to set ttl");
CLOSE_SOCKET(sock);
return NULL;
}
}
} else {
if (ttl <= 255) {
if (!setFdTTL(sock, (uint8_t) ttl)) {
FATAL("Unable to set ttl");
CLOSE_SOCKET(sock);
return NULL;
}
}
}
if (bind(sock, (sockaddr *) & bindAddress, sizeof (sockaddr)) != 0) {
int err = LASTSOCKETERROR;
FATAL("Unable to bind on address: udp://%s:%"PRIu16"; Error was: %d",
STR(bindIp), bindPort, err);
CLOSE_SOCKET(sock);
return NULL;
}
if ((testVal > 0xe0000000) && (testVal < 0xefffffff)) {
if (!setFdJoinMulticast(sock, bindIp, bindPort, ssmIp)) {
FATAL("Adding multicast failed");
CLOSE_SOCKET(sock);
return NULL;
}
}
//4. Create the carrier
UDPCarrier *pResult = new UDPCarrier(sock);
pResult->_nearAddress = bindAddress;
return pResult;
}
UDPCarrier* UDPCarrier::Create(string bindIp, uint16_t bindPort,
BaseProtocol *pProtocol, uint16_t ttl, uint16_t tos, string ssmIp) {
if (pProtocol == NULL) {
FATAL("Protocol can't be null");
return NULL;
}
UDPCarrier *pResult = Create(bindIp, bindPort, ttl, tos, ssmIp);
if (pResult == NULL) {
FATAL("Unable to create UDP carrier");
return NULL;
}
pResult->SetProtocol(pProtocol->GetFarEndpoint());
pProtocol->GetFarEndpoint()->SetIOHandler(pResult);
return pResult;
}
bool UDPCarrier::Setup(Variant &settings) {
NYIR;
}
bool UDPCarrier::GetEndpointsInfo() {
socklen_t len = sizeof (sockaddr);
if (getsockname(_inboundFd, (sockaddr *) & _nearAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_nearIp = format("%s", inet_ntoa(((sockaddr_in *) & _nearAddress)->sin_addr));
_nearPort = ENTOHS(((sockaddr_in *) & _nearAddress)->sin_port); //----MARKED-SHORT----
return true;
}
#endif /* NET_SELECT */
| 6,268
|
C++
|
.cpp
| 220
| 25.945455
| 87
| 0.699967
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,339
|
tcpacceptor.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/select/tcpacceptor.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_SELECT
#include "netio/select/tcpacceptor.h"
#include "netio/select/iohandlermanager.h"
#include "protocols/protocolfactorymanager.h"
#include "protocols/tcpprotocol.h"
#include "netio/select/tcpcarrier.h"
#include "application/baseclientapplication.h"
TCPAcceptor::TCPAcceptor(string ipAddress, uint16_t port, Variant parameters,
vector<uint64_t>/*&*/ protocolChain)
: IOHandler(0, 0, IOHT_ACCEPTOR) {
_pApplication = NULL;
memset(&_address, 0, sizeof (sockaddr_in));
_address.sin_family = PF_INET;
_address.sin_addr.s_addr = inet_addr(STR(ipAddress));
o_assert(_address.sin_addr.s_addr != INADDR_NONE);
_address.sin_port = EHTONS(port); //----MARKED-SHORT----
_protocolChain = protocolChain;
_parameters = parameters;
_enabled = false;
_acceptedCount = 0;
_droppedCount = 0;
_ipAddress = ipAddress;
_port = port;
}
TCPAcceptor::~TCPAcceptor() {
CLOSE_SOCKET(_inboundFd);
}
bool TCPAcceptor::Bind() {
_inboundFd = _outboundFd = (int) socket(PF_INET, SOCK_STREAM, 0); //NOINHERIT
if (_inboundFd < 0) {
int err = LASTSOCKETERROR;
FATAL("Unable to create socket: %d", err);
return false;
}
if (!setFdOptions(_inboundFd, false)) {
FATAL("Unable to set socket options");
return false;
}
if (bind(_inboundFd, (sockaddr *) & _address, sizeof (sockaddr)) != 0) {
int err = LASTSOCKETERROR;
FATAL("Unable to bind on address: tcp://%s:%hu; Error was: %d",
inet_ntoa(((sockaddr_in *) & _address)->sin_addr),
ENTOHS(((sockaddr_in *) & _address)->sin_port),
err);
return false;
}
if (_port == 0) {
socklen_t tempSize = sizeof (sockaddr);
if (getsockname(_inboundFd, (sockaddr *) & _address, &tempSize) != 0) {
FATAL("Unable to extract the random port");
return false;
}
_parameters[CONF_PORT] = (uint16_t) ENTOHS(_address.sin_port);
}
if (listen(_inboundFd, 100) != 0) {
FATAL("Unable to put the socket in listening mode");
return false;
}
_enabled = true;
return true;
}
void TCPAcceptor::SetApplication(BaseClientApplication *pApplication) {
o_assert(_pApplication == NULL);
_pApplication = pApplication;
}
bool TCPAcceptor::StartAccept() {
return IOHandlerManager::EnableAcceptConnections(this);
}
bool TCPAcceptor::SignalOutputData() {
ASSERT("Operation not supported");
return false;
}
bool TCPAcceptor::OnEvent(select_event &event) {
if (!OnConnectionAvailable(event))
return IsAlive();
else
return true;
}
bool TCPAcceptor::OnConnectionAvailable(select_event &event) {
if (_pApplication == NULL)
return Accept();
return _pApplication->AcceptTCPConnection(this);
}
bool TCPAcceptor::Accept() {
sockaddr address;
memset(&address, 0, sizeof (sockaddr));
socklen_t len = sizeof (sockaddr);
int32_t fd;
//1. Accept the connection
fd = accept(_inboundFd, &address, &len);
if ((fd < 0) || (!setFdCloseOnExec(fd))) {
int err = LASTSOCKETERROR;
FATAL("Unable to accept client connection: %d", err);
return false;
}
if (!_enabled) {
CLOSE_SOCKET(fd);
_droppedCount++;
WARN("Acceptor is not enabled. Client dropped: %s:%"PRIu16" -> %s:%"PRIu16,
inet_ntoa(((sockaddr_in *) & address)->sin_addr),
ENTOHS(((sockaddr_in *) & address)->sin_port),
STR(_ipAddress),
_port);
return true;
}
if (!setFdOptions(fd, false)) {
FATAL("Unable to set socket options");
CLOSE_SOCKET(fd);
return false;
}
//4. Create the chain
BaseProtocol *pProtocol = ProtocolFactoryManager::CreateProtocolChain(
_protocolChain, _parameters);
if (pProtocol == NULL) {
FATAL("Unable to create protocol chain");
CLOSE_SOCKET(fd);
return false;
}
//5. Create the carrier and bind it
TCPCarrier *pTCPCarrier = new TCPCarrier(fd);
pTCPCarrier->SetProtocol(pProtocol->GetFarEndpoint());
pProtocol->GetFarEndpoint()->SetIOHandler(pTCPCarrier);
//6. Register the protocol stack with an application
if (_pApplication != NULL) {
pProtocol = pProtocol->GetNearEndpoint();
pProtocol->SetApplication(_pApplication);
}
if (pProtocol->GetNearEndpoint()->GetOutputBuffer() != NULL)
pProtocol->GetNearEndpoint()->EnqueueForOutbound();
_acceptedCount++;
INFO("Inbound connection accepted: %s", STR(*(pProtocol->GetNearEndpoint())));
//7. Done
return true;
}
bool TCPAcceptor::Drop() {
sockaddr address;
memset(&address, 0, sizeof (sockaddr));
socklen_t len = sizeof (sockaddr);
//1. Accept the connection
int32_t fd = accept(_inboundFd, &address, &len);
if ((fd < 0) || (!setFdCloseOnExec(fd))) {
int err = LASTSOCKETERROR;
WARN("Accept failed. Error code was: %d", err);
return false;
}
//2. Drop it now
CLOSE_SOCKET(fd);
_droppedCount++;
INFO("Client explicitly dropped: %s:%"PRIu16" -> %s:%"PRIu16,
inet_ntoa(((sockaddr_in *) & address)->sin_addr),
ENTOHS(((sockaddr_in *) & address)->sin_port),
STR(_ipAddress),
_port);
return true;
}
Variant & TCPAcceptor::GetParameters() {
return _parameters;
}
BaseClientApplication *TCPAcceptor::GetApplication() {
return _pApplication;
}
vector<uint64_t> &TCPAcceptor::GetProtocolChain() {
return _protocolChain;
}
void TCPAcceptor::GetStats(Variant &info, uint32_t namespaceId) {
info = _parameters;
info["id"] = (((uint64_t) namespaceId) << 32) | GetId();
info["enabled"] = (bool)_enabled;
info["acceptedConnectionsCount"] = _acceptedCount;
info["droppedConnectionsCount"] = _droppedCount;
if (_pApplication != NULL) {
info["appId"] = (((uint64_t) namespaceId) << 32) | _pApplication->GetId();
info["appName"] = _pApplication->GetName();
} else {
info["appId"] = (((uint64_t) namespaceId) << 32);
info["appName"] = "";
}
}
bool TCPAcceptor::Enable() {
return _enabled;
}
void TCPAcceptor::Enable(bool enabled) {
_enabled = enabled;
}
bool TCPAcceptor::IsAlive() {
//TODO: Implement this. It must return true
//if this acceptor is operational
NYI;
return true;
}
#endif /* NET_SELECT */
| 6,613
|
C++
|
.cpp
| 209
| 29.291866
| 79
| 0.715072
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,340
|
iohandlermanager.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/select/iohandlermanager.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_SELECT
#include "netio/select/iohandlermanager.h"
#include "netio/select/iohandler.h"
#define FDSTATE_READ_ENABLED 0x01
#define FDSTATE_WRITE_ENABLED 0x02
map<uint32_t, IOHandler *> IOHandlerManager::_activeIOHandlers;
map<uint32_t, IOHandler *> IOHandlerManager::_deadIOHandlers;
fd_set IOHandlerManager::_readFds;
fd_set IOHandlerManager::_writeFds;
fd_set IOHandlerManager::_readFdsCopy;
fd_set IOHandlerManager::_writeFdsCopy;
map<int32_t, map<uint32_t, uint8_t> > IOHandlerManager::_fdState;
struct timeval IOHandlerManager::_timeout = {1, 0};
TimersManager *IOHandlerManager::_pTimersManager = NULL;
select_event IOHandlerManager::_currentEvent = {0};
bool IOHandlerManager::_isShuttingDown = false;
FdStats IOHandlerManager::_fdStats;
map<uint32_t, IOHandler *> & IOHandlerManager::GetActiveHandlers() {
return _activeIOHandlers;
}
map<uint32_t, IOHandler *> & IOHandlerManager::GetDeadHandlers() {
return _deadIOHandlers;
}
FdStats &IOHandlerManager::GetStats(bool updateSpeeds) {
#ifdef GLOBALLY_ACCOUNT_BYTES
if (updateSpeeds)
_fdStats.UpdateSpeeds();
#endif /* GLOBALLY_ACCOUNT_BYTES */
return _fdStats;
}
void IOHandlerManager::Initialize() {
_fdStats.Reset();
FD_ZERO(&_readFds);
FD_ZERO(&_writeFds);
_pTimersManager = new TimersManager(ProcessTimer);
_isShuttingDown = false;
}
void IOHandlerManager::Start() {
}
void IOHandlerManager::SignalShutdown() {
_isShuttingDown = true;
}
void IOHandlerManager::ShutdownIOHandlers() {
FOR_MAP(_activeIOHandlers, uint32_t, IOHandler *, i) {
EnqueueForDelete(MAP_VAL(i));
}
}
void IOHandlerManager::Shutdown() {
_isShuttingDown = false;
delete _pTimersManager;
_pTimersManager = NULL;
if (_activeIOHandlers.size() != 0 || _deadIOHandlers.size() != 0) {
FATAL("Incomplete shutdown!");
}
}
void IOHandlerManager::RegisterIOHandler(IOHandler* pIOHandler) {
if (MAP_HAS1(_activeIOHandlers, pIOHandler->GetId())) {
ASSERT("IOHandler already registered");
}
size_t before = _activeIOHandlers.size();
_activeIOHandlers[pIOHandler->GetId()] = pIOHandler;
_fdStats.RegisterManaged(pIOHandler->GetType());
DEBUG("Handlers count changed: %"PRIz"u->%"PRIz"u %s", before, before + 1,
STR(IOHandler::IOHTToString(pIOHandler->GetType())));
}
void IOHandlerManager::UnRegisterIOHandler(IOHandler *pIOHandler) {
DisableAcceptConnections(pIOHandler);
DisableReadData(pIOHandler);
DisableWriteData(pIOHandler);
DisableTimer(pIOHandler);
if (MAP_HAS1(_activeIOHandlers, pIOHandler->GetId())) {
_fdStats.UnRegisterManaged(pIOHandler->GetType());
size_t before = _activeIOHandlers.size();
_activeIOHandlers.erase(pIOHandler->GetId());
DEBUG("Handlers count changed: %"PRIz"u->%"PRIz"u %s", before, before - 1,
STR(IOHandler::IOHTToString(pIOHandler->GetType())));
}
}
int IOHandlerManager::CreateRawUDPSocket() {
int result = socket(AF_INET, SOCK_DGRAM, 0);
if ((result >= 0)&&(setFdCloseOnExec(result))) {
_fdStats.RegisterRawUdp();
} else {
int err = LASTSOCKETERROR;
FATAL("Unable to create raw udp socket. Error code was: %d", err);
}
return result;
}
void IOHandlerManager::CloseRawUDPSocket(int socket) {
if (socket > 0) {
_fdStats.UnRegisterRawUdp();
}
CLOSE_SOCKET(socket);
}
#ifdef GLOBALLY_ACCOUNT_BYTES
void IOHandlerManager::AddInBytesManaged(IOHandlerType type, uint64_t bytes) {
_fdStats.AddInBytesManaged(type, bytes);
}
void IOHandlerManager::AddOutBytesManaged(IOHandlerType type, uint64_t bytes) {
_fdStats.AddOutBytesManaged(type, bytes);
}
void IOHandlerManager::AddInBytesRawUdp(uint64_t bytes) {
_fdStats.AddInBytesRawUdp(bytes);
}
void IOHandlerManager::AddOutBytesRawUdp(uint64_t bytes) {
_fdStats.AddOutBytesRawUdp(bytes);
}
#endif /* GLOBALLY_ACCOUNT_BYTES */
bool IOHandlerManager::EnableReadData(IOHandler *pIOHandler) {
_fdState[pIOHandler->GetInboundFd()][pIOHandler->GetId()] |= FDSTATE_READ_ENABLED;
return UpdateFdSets(pIOHandler->GetInboundFd());
}
bool IOHandlerManager::DisableReadData(IOHandler *pIOHandler) {
_fdState[pIOHandler->GetInboundFd()][pIOHandler->GetId()] &= ~FDSTATE_READ_ENABLED;
return UpdateFdSets(pIOHandler->GetInboundFd());
}
bool IOHandlerManager::EnableWriteData(IOHandler *pIOHandler) {
_fdState[pIOHandler->GetOutboundFd()][pIOHandler->GetId()] |= FDSTATE_WRITE_ENABLED;
return UpdateFdSets(pIOHandler->GetOutboundFd());
}
bool IOHandlerManager::DisableWriteData(IOHandler *pIOHandler) {
_fdState[pIOHandler->GetOutboundFd()][pIOHandler->GetId()] &= ~FDSTATE_WRITE_ENABLED;
return UpdateFdSets(pIOHandler->GetOutboundFd());
}
bool IOHandlerManager::EnableAcceptConnections(IOHandler *pIOHandler) {
_fdState[pIOHandler->GetInboundFd()][pIOHandler->GetId()] |= FDSTATE_READ_ENABLED;
return UpdateFdSets(pIOHandler->GetInboundFd());
}
bool IOHandlerManager::DisableAcceptConnections(IOHandler *pIOHandler) {
_fdState[pIOHandler->GetInboundFd()][pIOHandler->GetId()] &= ~FDSTATE_READ_ENABLED;
return UpdateFdSets(pIOHandler->GetInboundFd());
}
bool IOHandlerManager::EnableTimer(IOHandler *pIOHandler, uint32_t seconds) {
TimerEvent event = {0, 0, 0};
event.id = pIOHandler->GetId();
event.period = seconds;
_pTimersManager->AddTimer(event);
return true;
}
bool IOHandlerManager::EnableHighGranularityTimer(IOHandler *pIOHandler, uint32_t milliseconds) {
uint32_t seconds = ((milliseconds % 1000) == 0) ? (milliseconds / 1000) : (milliseconds / 1000 + 1);
if (seconds == 0)
seconds = 1;
TimerEvent event = {0, 0, 0};
event.id = pIOHandler->GetId();
event.period = seconds;
_pTimersManager->AddTimer(event);
return true;
}
bool IOHandlerManager::DisableTimer(IOHandler *pIOHandler) {
_pTimersManager->RemoveTimer(pIOHandler->GetId());
return true;
}
void IOHandlerManager::EnqueueForDelete(IOHandler *pIOHandler) {
DisableAcceptConnections(pIOHandler);
DisableReadData(pIOHandler);
DisableWriteData(pIOHandler);
DisableTimer(pIOHandler);
if (!MAP_HAS1(_deadIOHandlers, pIOHandler->GetId())) {
_deadIOHandlers[pIOHandler->GetId()] = pIOHandler;
}
}
uint32_t IOHandlerManager::DeleteDeadHandlers() {
uint32_t result = 0;
while (_deadIOHandlers.size() > 0) {
IOHandler *pIOHandler = MAP_VAL(_deadIOHandlers.begin());
_deadIOHandlers.erase(pIOHandler->GetId());
delete pIOHandler;
result++;
}
return result;
}
bool IOHandlerManager::Pulse() {
if (_isShuttingDown)
return false;
//1. Create a copy of all fd sets
FD_ZERO(&_readFdsCopy);
FD_ZERO(&_writeFdsCopy);
FD_ZERO(&_writeFdsCopy);
FD_COPY(&_readFds, &_readFdsCopy);
FD_COPY(&_writeFds, &_writeFdsCopy);
//2. compute the max fd
if (_activeIOHandlers.size() == 0)
return true;
//3. do the select
RESET_TIMER(_timeout, 1, 0);
int32_t count = select(MAP_KEY(--_fdState.end()) + 1, &_readFdsCopy, &_writeFdsCopy, NULL, &_timeout);
if (count < 0) {
int err = LASTSOCKETERROR;
if (err == EINTR)
return true;
FATAL("Unable to do select: %d", err);
return false;
}
int32_t nextVal = _pTimersManager->TimeElapsed();
_timeout.tv_sec = nextVal / 1000;
_timeout.tv_usec = (nextVal * 1000000) % 1000000000;
if (count == 0) {
return true;
}
//4. Start crunching the sets
FOR_MAP(_activeIOHandlers, uint32_t, IOHandler *, i) {
if (FD_ISSET(MAP_VAL(i)->GetInboundFd(), &_readFdsCopy)) {
_currentEvent.type = SET_READ;
if (!MAP_VAL(i)->OnEvent(_currentEvent))
EnqueueForDelete(MAP_VAL(i));
}
if (FD_ISSET(MAP_VAL(i)->GetOutboundFd(), &_writeFdsCopy)) {
_currentEvent.type = SET_WRITE;
if (!MAP_VAL(i)->OnEvent(_currentEvent))
EnqueueForDelete(MAP_VAL(i));
}
}
return true;
}
bool IOHandlerManager::UpdateFdSets(int32_t fd) {
if (fd == 0)
return true;
uint8_t state = 0;
FOR_MAP(_fdState[fd], uint32_t, uint8_t, i) {
state |= MAP_VAL(i);
}
if ((state & FDSTATE_READ_ENABLED) != 0)
FD_SET(fd, &_readFds);
else
FD_CLR(fd, &_readFds);
if ((state & FDSTATE_WRITE_ENABLED) != 0)
FD_SET(fd, &_writeFds);
else
FD_CLR(fd, &_writeFds);
if (state == 0)
_fdState.erase(fd);
return true;
}
bool IOHandlerManager::ProcessTimer(TimerEvent &event) {
_currentEvent.type = SET_TIMER;
if (MAP_HAS1(_activeIOHandlers, event.id)) {
if (!_activeIOHandlers[event.id]->OnEvent(_currentEvent)) {
EnqueueForDelete(_activeIOHandlers[event.id]);
return false;
}
return true;
} else {
return false;
}
}
#endif /* NET_SELECT */
| 9,084
|
C++
|
.cpp
| 265
| 32.150943
| 103
| 0.749629
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,341
|
iotimer.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/epoll/iotimer.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_EPOLL
#include "netio/epoll/iotimer.h"
#include "netio/epoll/iohandlermanager.h"
#include "protocols/baseprotocol.h"
#ifdef HAS_EPOLL_TIMERS
#include <sys/timerfd.h>
#else /* HAS_EPOLL_TIMERS */
int32_t IOTimer::_idGenerator;
#endif /* HAS_EPOLL_TIMERS */
IOTimer::IOTimer()
: IOHandler(0, 0, IOHT_TIMER) {
#ifdef HAS_EPOLL_TIMERS
_count = 0;
_inboundFd = _outboundFd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
if (_inboundFd < 0) {
int err = errno;
ASSERT("timerfd_create failed with error (%d) %s", err, strerror(err));
}
#else /* HAS_EPOLL_TIMERS */
_inboundFd = _outboundFd = ++_idGenerator;
#endif /* HAS_EPOLL_TIMERS */
}
IOTimer::~IOTimer() {
IOHandlerManager::DisableTimer(this, true);
#ifdef HAS_EPOLL_TIMERS
CLOSE_SOCKET(_inboundFd);
#endif /* HAS_EPOLL_TIMERS */
}
bool IOTimer::SignalOutputData() {
ASSERT("Operation not supported");
return false;
}
bool IOTimer::OnEvent(struct epoll_event &/*ignored*/) {
#ifdef HAS_EPOLL_TIMERS
if (read(_inboundFd, &_count, 8) != 8) {
FATAL("Timer failed!");
return false;
}
#endif /* HAS_EPOLL_TIMERS */
if (!_pProtocol->IsEnqueueForDelete()) {
if (!_pProtocol->TimePeriodElapsed()) {
FATAL("Unable to handle TimeElapsed event");
IOHandlerManager::EnqueueForDelete(this);
return false;
}
}
return true;
}
bool IOTimer::EnqueueForTimeEvent(uint32_t seconds) {
return IOHandlerManager::EnableTimer(this, seconds);
}
bool IOTimer::EnqueueForHighGranularityTimeEvent(uint32_t milliseconds) {
return IOHandlerManager::EnableHighGranularityTimer(this, milliseconds);
}
void IOTimer::GetStats(Variant &info, uint32_t namespaceId) {
}
#endif /* NET_EPOLL */
| 2,439
|
C++
|
.cpp
| 75
| 30.64
| 74
| 0.741922
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,342
|
tcpcarrier.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/epoll/tcpcarrier.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_EPOLL
#include "netio/epoll/tcpcarrier.h"
#include "netio/epoll/iohandlermanager.h"
#include "protocols/baseprotocol.h"
#define ENABLE_WRITE_DATA \
if (!_writeDataEnabled) { \
_writeDataEnabled = true; \
IOHandlerManager::EnableWriteData(this); \
} \
_enableWriteDataCalled=true;
#define DISABLE_WRITE_DATA \
if (_writeDataEnabled) { \
_enableWriteDataCalled=false; \
_pProtocol->ReadyForSend(); \
if(!_enableWriteDataCalled) { \
if(_pProtocol->GetOutputBuffer()==NULL) {\
_writeDataEnabled = false; \
IOHandlerManager::DisableWriteData(this); \
} \
} \
}
TCPCarrier::TCPCarrier(int32_t fd)
: IOHandler(fd, fd, IOHT_TCP_CARRIER) {
IOHandlerManager::EnableReadData(this);
_writeDataEnabled = false;
_enableWriteDataCalled = false;
memset(&_farAddress, 0, sizeof (sockaddr_in));
_farIp = "";
_farPort = 0;
memset(&_nearAddress, 0, sizeof (sockaddr_in));
_nearIp = "";
_nearPort = 0;
_sendBufferSize = 1024 * 1024 * 8;
_recvBufferSize = 1024 * 256;
GetEndpointsInfo();
_rx = 0;
_tx = 0;
_ioAmount = 0;
_lastRecvError = 0;
_lastSendError = 0;
Variant stats;
GetStats(stats);
}
TCPCarrier::~TCPCarrier() {
Variant stats;
GetStats(stats);
CLOSE_SOCKET(_inboundFd);
}
bool TCPCarrier::OnEvent(struct epoll_event &event) {
//1. Read data
if ((event.events & EPOLLIN) != 0) {
IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
o_assert(pInputBuffer != NULL);
if (!pInputBuffer->ReadFromTCPFd(_inboundFd, _recvBufferSize, _ioAmount,
_lastRecvError)) {
FATAL("Unable to read data from connection: %s. Error was (%d): %s",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", _lastRecvError,
strerror(_lastRecvError));
return false;
}
_rx += _ioAmount;
ADD_IN_BYTES_MANAGED(_type, _ioAmount);
if (!_pProtocol->SignalInputData(_ioAmount)) {
FATAL("Unable to read data from connection: %s. Signaling upper protocols failed",
(_pProtocol != NULL) ? STR(*_pProtocol) : "");
return false;
}
}
//2. Write data
if ((event.events & EPOLLOUT) != 0) {
IOBuffer *pOutputBuffer = NULL;
if ((pOutputBuffer = _pProtocol->GetOutputBuffer()) != NULL) {
if (!pOutputBuffer->WriteToTCPFd(_inboundFd, _sendBufferSize, _ioAmount,
_lastSendError)) {
FATAL("Unable to write data on connection: %s. Error was (%d): %s",
(_pProtocol != NULL) ? STR(*_pProtocol) : "", _lastSendError,
strerror(_lastSendError));
IOHandlerManager::EnqueueForDelete(this);
return false;
}
_tx += _ioAmount;
ADD_OUT_BYTES_MANAGED(_type, _ioAmount);
if (GETAVAILABLEBYTESCOUNT(*pOutputBuffer) == 0) {
DISABLE_WRITE_DATA;
}
} else {
DISABLE_WRITE_DATA;
}
}
return true;
}
bool TCPCarrier::SignalOutputData() {
ENABLE_WRITE_DATA;
return true;
}
void TCPCarrier::GetStats(Variant &info, uint32_t namespaceId) {
if (!GetEndpointsInfo()) {
FATAL("Unable to get endpoints info");
info = "unable to get endpoints info";
return;
}
info["type"] = "IOHT_TCP_CARRIER";
info["farIP"] = _farIp;
info["farPort"] = _farPort;
info["nearIP"] = _nearIp;
info["nearPort"] = _nearPort;
info["rx"] = _rx;
info["tx"] = _tx;
}
sockaddr_in &TCPCarrier::GetFarEndpointAddress() {
if ((_farIp == "") || (_farPort == 0))
GetEndpointsInfo();
return _farAddress;
}
string TCPCarrier::GetFarEndpointAddressIp() {
if (_farIp != "")
return _farIp;
GetEndpointsInfo();
return _farIp;
}
uint16_t TCPCarrier::GetFarEndpointPort() {
if (_farPort != 0)
return _farPort;
GetEndpointsInfo();
return _farPort;
}
sockaddr_in &TCPCarrier::GetNearEndpointAddress() {
if ((_nearIp == "") || (_nearPort == 0))
GetEndpointsInfo();
return _nearAddress;
}
string TCPCarrier::GetNearEndpointAddressIp() {
if (_nearIp != "")
return _nearIp;
GetEndpointsInfo();
return _nearIp;
}
uint16_t TCPCarrier::GetNearEndpointPort() {
if (_nearPort != 0)
return _nearPort;
GetEndpointsInfo();
return _nearPort;
}
bool TCPCarrier::GetEndpointsInfo() {
if ((_farIp != "")
&& (_farPort != 0)
&& (_nearIp != "")
&& (_nearPort != 0)) {
return true;
}
socklen_t len = sizeof (sockaddr);
if (getpeername(_inboundFd, (sockaddr *) & _farAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_farIp = format("%s", inet_ntoa(((sockaddr_in *) & _farAddress)->sin_addr));
_farPort = ENTOHS(((sockaddr_in *) & _farAddress)->sin_port); //----MARKED-SHORT----
if (getsockname(_inboundFd, (sockaddr *) & _nearAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_nearIp = format("%s", inet_ntoa(((sockaddr_in *) & _nearAddress)->sin_addr));
_nearPort = ENTOHS(((sockaddr_in *) & _nearAddress)->sin_port); //----MARKED-SHORT----
return true;
}
#endif /* NET_EPOLL */
| 5,518
|
C++
|
.cpp
| 184
| 27.48913
| 87
| 0.689136
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,343
|
udpcarrier.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/epoll/udpcarrier.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_EPOLL
#include "netio/epoll/udpcarrier.h"
#include "netio/epoll/iohandlermanager.h"
#include "protocols/baseprotocol.h"
#define SOCKET_READ_CHUNK 65536
#define SOCKET_WRITE_CHUNK SOCKET_READ_CHUNK
UDPCarrier::UDPCarrier(int32_t fd)
: IOHandler(fd, fd, IOHT_UDP_CARRIER) {
memset(&_peerAddress, 0, sizeof (sockaddr_in));
memset(&_nearAddress, 0, sizeof (sockaddr_in));
_nearIp = "";
_nearPort = 0;
_rx = 0;
_tx = 0;
_ioAmount = 0;
Variant stats;
GetStats(stats);
}
UDPCarrier::~UDPCarrier() {
Variant stats;
GetStats(stats);
CLOSE_SOCKET(_inboundFd);
}
bool UDPCarrier::OnEvent(struct epoll_event &event) {
//1. Read data
if ((event.events & EPOLLIN) != 0) {
IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
o_assert(pInputBuffer != NULL);
if (!pInputBuffer->ReadFromUDPFd(_inboundFd, _ioAmount, _peerAddress)) {
FATAL("Unable to read data");
return false;
}
if (_ioAmount == 0) {
FATAL("Connection closed");
return false;
}
_rx += _ioAmount;
ADD_IN_BYTES_MANAGED(_type, _ioAmount);
if (!_pProtocol->SignalInputData(_ioAmount, &_peerAddress)) {
FATAL("Unable to signal data available");
return false;
}
}
//2. Write data
if ((event.events & EPOLLOUT) != 0) {
_pProtocol->ReadyForSend();
return true;
}
return true;
}
bool UDPCarrier::SignalOutputData() {
NYIR;
}
void UDPCarrier::GetStats(Variant &info, uint32_t namespaceId) {
if (!GetEndpointsInfo()) {
FATAL("Unable to get endpoints info");
info = "unable to get endpoints info";
return;
}
info["type"] = "IOHT_UDP_CARRIER";
info["nearIP"] = _nearIp;
info["nearPort"] = _nearPort;
info["rx"] = _rx;
}
Variant &UDPCarrier::GetParameters() {
return _parameters;
}
void UDPCarrier::SetParameters(Variant parameters) {
_parameters = parameters;
}
bool UDPCarrier::StartAccept() {
return IOHandlerManager::EnableReadData(this);
}
string UDPCarrier::GetFarEndpointAddress() {
ASSERT("Operation not supported");
return "";
}
uint16_t UDPCarrier::GetFarEndpointPort() {
ASSERT("Operation not supported");
return 0;
}
string UDPCarrier::GetNearEndpointAddress() {
if (_nearIp != "")
return _nearIp;
GetEndpointsInfo();
return _nearIp;
}
uint16_t UDPCarrier::GetNearEndpointPort() {
if (_nearPort != 0)
return _nearPort;
GetEndpointsInfo();
return _nearPort;
}
UDPCarrier* UDPCarrier::Create(string bindIp, uint16_t bindPort, uint16_t ttl,
uint16_t tos, string ssmIp) {
//1. Create the socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if ((sock < 0) || (!setFdCloseOnExec(sock))) {
int err = errno;
FATAL("Unable to create socket: (%d) %s", err, strerror(err));
return NULL;
}
//2. fd options
if (!setFdOptions(sock, true)) {
FATAL("Unable to set fd options");
CLOSE_SOCKET(sock);
return NULL;
}
if (tos <= 255) {
if (!setFdTOS(sock, (uint8_t) tos)) {
FATAL("Unable to set tos");
CLOSE_SOCKET(sock);
return NULL;
}
}
//3. Bind
if (bindIp == "") {
bindIp = "0.0.0.0";
bindPort = 0;
}
sockaddr_in bindAddress;
memset(&bindAddress, 0, sizeof (bindAddress));
bindAddress.sin_family = PF_INET;
bindAddress.sin_addr.s_addr = inet_addr(STR(bindIp));
bindAddress.sin_port = EHTONS(bindPort); //----MARKED-SHORT----
if (bindAddress.sin_addr.s_addr == INADDR_NONE) {
FATAL("Unable to bind on address %s:%hu", STR(bindIp), bindPort);
CLOSE_SOCKET(sock);
return NULL;
}
uint32_t testVal = EHTONL(bindAddress.sin_addr.s_addr);
if ((testVal > 0xe0000000) && (testVal < 0xefffffff)) {
INFO("Subscribe to multicast %s:%"PRIu16, STR(bindIp), bindPort);
int activateBroadcast = 1;
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &activateBroadcast,
sizeof (activateBroadcast)) != 0) {
int err = errno;
FATAL("Unable to activate SO_BROADCAST on the socket: (%d) %s", err, strerror(err));
return NULL;
}
if (ttl <= 255) {
if (!setFdMulticastTTL(sock, (uint8_t) ttl)) {
FATAL("Unable to set ttl");
CLOSE_SOCKET(sock);
return NULL;
}
}
} else {
if (ttl <= 255) {
if (!setFdTTL(sock, (uint8_t) ttl)) {
FATAL("Unable to set ttl");
CLOSE_SOCKET(sock);
return NULL;
}
}
}
if (bind(sock, (sockaddr *) & bindAddress, sizeof (sockaddr)) != 0) {
int err = errno;
FATAL("Unable to bind on address: udp://%s:%"PRIu16"; Error was: (%d) %s",
STR(bindIp), bindPort, err, strerror(err));
CLOSE_SOCKET(sock);
return NULL;
}
if ((testVal > 0xe0000000) && (testVal < 0xefffffff)) {
if (!setFdJoinMulticast(sock, bindIp, bindPort, ssmIp)) {
FATAL("Adding multicast failed");
CLOSE_SOCKET(sock);
return NULL;
}
}
//4. Create the carrier
UDPCarrier *pResult = new UDPCarrier(sock);
pResult->_nearAddress = bindAddress;
return pResult;
}
UDPCarrier* UDPCarrier::Create(string bindIp, uint16_t bindPort,
BaseProtocol *pProtocol, uint16_t ttl, uint16_t tos, string ssmIp) {
if (pProtocol == NULL) {
FATAL("Protocol can't be null");
return NULL;
}
UDPCarrier *pResult = Create(bindIp, bindPort, ttl, tos, ssmIp);
if (pResult == NULL) {
FATAL("Unable to create UDP carrier");
return NULL;
}
pResult->SetProtocol(pProtocol->GetFarEndpoint());
pProtocol->GetFarEndpoint()->SetIOHandler(pResult);
return pResult;
}
bool UDPCarrier::Setup(Variant &settings) {
NYIR;
}
bool UDPCarrier::GetEndpointsInfo() {
socklen_t len = sizeof (sockaddr);
if (getsockname(_inboundFd, (sockaddr *) & _nearAddress, &len) != 0) {
FATAL("Unable to get peer's address");
return false;
}
_nearIp = format("%s", inet_ntoa(((sockaddr_in *) & _nearAddress)->sin_addr));
_nearPort = ENTOHS(((sockaddr_in *) & _nearAddress)->sin_port); //----MARKED-SHORT----
return true;
}
#endif /* NET_EPOLL */
| 6,466
|
C++
|
.cpp
| 222
| 26.635135
| 87
| 0.699259
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,344
|
tcpacceptor.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/epoll/tcpacceptor.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "protocols/rtmp/amf0serializer.h"
#ifdef NET_EPOLL
#include "netio/epoll/tcpacceptor.h"
#include "netio/epoll/iohandlermanager.h"
#include "protocols/protocolfactorymanager.h"
#include "protocols/tcpprotocol.h"
#include "netio/epoll/tcpcarrier.h"
#include "application/baseclientapplication.h"
TCPAcceptor::TCPAcceptor(string ipAddress, uint16_t port, Variant parameters,
vector<uint64_t>/*&*/ protocolChain)
: IOHandler(0, 0, IOHT_ACCEPTOR) {
_pApplication = NULL;
memset(&_address, 0, sizeof (sockaddr_in));
_address.sin_family = PF_INET;
_address.sin_addr.s_addr = inet_addr(STR(ipAddress));
o_assert(_address.sin_addr.s_addr != INADDR_NONE);
_address.sin_port = EHTONS(port); //----MARKED-SHORT----
_protocolChain = protocolChain;
_parameters = parameters;
_enabled = false;
_acceptedCount = 0;
_droppedCount = 0;
_ipAddress = ipAddress;
_port = port;
}
TCPAcceptor::~TCPAcceptor() {
CLOSE_SOCKET(_inboundFd);
}
bool TCPAcceptor::Bind() {
_inboundFd = _outboundFd = (int) socket(PF_INET, SOCK_STREAM, 0); //NOINHERIT
if (_inboundFd < 0) {
int err = errno;
FATAL("Unable to create socket: (%d) %s", err, strerror(err));
return false;
}
if (!setFdOptions(_inboundFd, false)) {
FATAL("Unable to set socket options");
return false;
}
if (bind(_inboundFd, (sockaddr *) & _address, sizeof (sockaddr)) != 0) {
int err = errno;
FATAL("Unable to bind on address: tcp://%s:%hu; Error was: (%d) %s",
inet_ntoa(((sockaddr_in *) & _address)->sin_addr),
ENTOHS(((sockaddr_in *) & _address)->sin_port),
err,
strerror(err));
return false;
}
if (_port == 0) {
socklen_t tempSize = sizeof (sockaddr);
if (getsockname(_inboundFd, (sockaddr *) & _address, &tempSize) != 0) {
FATAL("Unable to extract the random port");
return false;
}
_parameters[CONF_PORT] = (uint16_t) ENTOHS(_address.sin_port);
}
if (listen(_inboundFd, 100) != 0) {
FATAL("Unable to put the socket in listening mode");
return false;
}
_enabled = true;
return true;
}
void TCPAcceptor::SetApplication(BaseClientApplication *pApplication) {
o_assert(_pApplication == NULL);
_pApplication = pApplication;
}
bool TCPAcceptor::StartAccept() {
return IOHandlerManager::EnableAcceptConnections(this);
}
bool TCPAcceptor::SignalOutputData() {
ASSERT("Operation not supported");
return false;
}
bool TCPAcceptor::OnEvent(struct epoll_event &event) {
//we should not return false here, because the acceptor will simply go down.
//Instead, after the connection accepting routine failed, check to
//see if the acceptor socket is stil in the business
if (!OnConnectionAvailable(event))
return IsAlive();
else
return true;
}
bool TCPAcceptor::OnConnectionAvailable(struct epoll_event &event) {
if (_pApplication == NULL)
return Accept();
return _pApplication->AcceptTCPConnection(this);
}
bool TCPAcceptor::Accept() {
sockaddr address;
memset(&address, 0, sizeof (sockaddr));
socklen_t len = sizeof (sockaddr);
int32_t fd;
//1. Accept the connection
fd = accept(_inboundFd, &address, &len);
if ((fd < 0) || (!setFdCloseOnExec(fd))) {
int err = errno;
FATAL("Unable to accept client connection: (%d) %s", err, strerror(err));
return false;
}
if (!_enabled) {
CLOSE_SOCKET(fd);
_droppedCount++;
WARN("Acceptor is not enabled. Client dropped: %s:%"PRIu16" -> %s:%"PRIu16,
inet_ntoa(((sockaddr_in *) & address)->sin_addr),
ENTOHS(((sockaddr_in *) & address)->sin_port),
STR(_ipAddress),
_port);
return true;
}
if (!setFdOptions(fd, false)) {
FATAL("Unable to set socket options");
CLOSE_SOCKET(fd);
return false;
}
//4. Create the chain
BaseProtocol *pProtocol = ProtocolFactoryManager::CreateProtocolChain(_protocolChain, _parameters);
if (pProtocol == NULL) {
FATAL("Unable to create protocol chain");
CLOSE_SOCKET(fd);
return false;
}
//5. Create the carrier and bind it
TCPCarrier *pTCPCarrier = new TCPCarrier(fd);
pTCPCarrier->SetProtocol(pProtocol->GetFarEndpoint());
pProtocol->GetFarEndpoint()->SetIOHandler(pTCPCarrier);
//6. Register the protocol stack with an application
if (_pApplication != NULL) {
pProtocol = pProtocol->GetNearEndpoint();
pProtocol->SetApplication(_pApplication);
// EventLogger *pEvtLog = _pApplication->GetEventLogger();
// if (pEvtLog != NULL) {
// pEvtLog->LogInboundConnectionStart(_ipAddress, _port, STR(*(pProtocol->GetFarEndpoint())));
// pTCPCarrier->SetEventLogger(pEvtLog);
// }
}
if (pProtocol->GetNearEndpoint()->GetOutputBuffer() != NULL)
pProtocol->GetNearEndpoint()->EnqueueForOutbound();
_acceptedCount++;
INFO("Inbound connection accepted: %s", STR(*(pProtocol->GetNearEndpoint())));
//7. Done
return true;
}
bool TCPAcceptor::Drop() {
sockaddr address;
memset(&address, 0, sizeof (sockaddr));
socklen_t len = sizeof (sockaddr);
//1. Accept the connection
int32_t fd = accept(_inboundFd, &address, &len);
if ((fd < 0) || (!setFdCloseOnExec(fd))) {
int err = errno;
if (err != EWOULDBLOCK)
WARN("Accept failed. Error code was: (%d) %s", err, strerror(err));
return false;
}
//2. Drop it now
CLOSE_SOCKET(fd);
_droppedCount++;
INFO("Client explicitly dropped: %s:%"PRIu16" -> %s:%"PRIu16,
inet_ntoa(((sockaddr_in *) & address)->sin_addr),
ENTOHS(((sockaddr_in *) & address)->sin_port),
STR(_ipAddress),
_port);
return true;
}
Variant & TCPAcceptor::GetParameters() {
return _parameters;
}
BaseClientApplication *TCPAcceptor::GetApplication() {
return _pApplication;
}
vector<uint64_t> &TCPAcceptor::GetProtocolChain() {
return _protocolChain;
}
void TCPAcceptor::GetStats(Variant &info, uint32_t namespaceId) {
info = _parameters;
info["id"] = (((uint64_t) namespaceId) << 32) | GetId();
info["enabled"] = (bool)_enabled;
info["acceptedConnectionsCount"] = _acceptedCount;
info["droppedConnectionsCount"] = _droppedCount;
if (_pApplication != NULL) {
info["appId"] = (((uint64_t) namespaceId) << 32) | _pApplication->GetId();
info["appName"] = _pApplication->GetName();
} else {
info["appId"] = (((uint64_t) namespaceId) << 32);
info["appName"] = "";
}
}
bool TCPAcceptor::Enable() {
return _enabled;
}
void TCPAcceptor::Enable(bool enabled) {
_enabled = enabled;
}
bool TCPAcceptor::IsAlive() {
//TODO: Implement this. It must return true
//if this acceptor is operational
NYI;
return true;
}
#endif /* NET_EPOLL */
| 7,176
|
C++
|
.cpp
| 219
| 30.388128
| 100
| 0.713004
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,345
|
iohandlermanager.cpp
|
shiretu_crtmpserver/sources/thelib/src/netio/epoll/iohandlermanager.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef NET_EPOLL
#include "netio/epoll/iohandlermanager.h"
#include "netio/epoll/iohandler.h"
#ifdef HAS_EPOLL_TIMERS
#include <sys/timerfd.h>
#endif /* HAS_EPOLL_TIMERS */
int32_t IOHandlerManager::_eq = 0;
map<uint32_t, IOHandler *> IOHandlerManager::_activeIOHandlers;
map<uint32_t, IOHandler *> IOHandlerManager::_deadIOHandlers;
struct epoll_event IOHandlerManager::_query[EPOLL_QUERY_SIZE];
vector<IOHandlerManagerToken *> IOHandlerManager::_tokensVector1;
vector<IOHandlerManagerToken *> IOHandlerManager::_tokensVector2;
vector<IOHandlerManagerToken *> *IOHandlerManager::_pAvailableTokens;
vector<IOHandlerManagerToken *> *IOHandlerManager::_pRecycledTokens;
int32_t IOHandlerManager::_nextWaitPeriod = 1000;
#ifndef HAS_EPOLL_TIMERS
TimersManager *IOHandlerManager::_pTimersManager = NULL;
#endif /* HAS_EPOLL_TIMERS */
FdStats IOHandlerManager::_fdStats;
struct epoll_event IOHandlerManager::_dummy = {0,
{0}};
map<uint32_t, IOHandler *> & IOHandlerManager::GetActiveHandlers() {
return _activeIOHandlers;
}
map<uint32_t, IOHandler *> & IOHandlerManager::GetDeadHandlers() {
return _deadIOHandlers;
}
FdStats &IOHandlerManager::GetStats(bool updateSpeeds) {
#ifdef GLOBALLY_ACCOUNT_BYTES
if (updateSpeeds)
_fdStats.UpdateSpeeds();
#endif /* GLOBALLY_ACCOUNT_BYTES */
return _fdStats;
}
void IOHandlerManager::Initialize() {
_fdStats.Reset();
_eq = 0;
_pAvailableTokens = &_tokensVector1;
_pRecycledTokens = &_tokensVector2;
#ifndef HAS_EPOLL_TIMERS
_pTimersManager = new TimersManager(ProcessTimer);
#endif /* HAS_EPOLL_TIMERS */
memset(&_dummy, 0, sizeof (_dummy));
}
void IOHandlerManager::Start() {
_eq = epoll_create(EPOLL_QUERY_SIZE);
o_assert(_eq > 0);
}
void IOHandlerManager::SignalShutdown() {
close(_eq);
}
void IOHandlerManager::ShutdownIOHandlers() {
FOR_MAP(_activeIOHandlers, uint32_t, IOHandler *, i) {
EnqueueForDelete(MAP_VAL(i));
}
}
void IOHandlerManager::Shutdown() {
close(_eq);
for (uint32_t i = 0; i < _tokensVector1.size(); i++)
delete _tokensVector1[i];
_tokensVector1.clear();
_pAvailableTokens = &_tokensVector1;
for (uint32_t i = 0; i < _tokensVector2.size(); i++)
delete _tokensVector2[i];
_tokensVector2.clear();
_pRecycledTokens = &_tokensVector2;
#ifndef HAS_EPOLL_TIMERS
delete _pTimersManager;
_pTimersManager = NULL;
#endif /* HAS_EPOLL_TIMERS */
if (_activeIOHandlers.size() != 0 || _deadIOHandlers.size() != 0) {
FATAL("Incomplete shutdown!");
}
}
void IOHandlerManager::RegisterIOHandler(IOHandler* pIOHandler) {
if (MAP_HAS1(_activeIOHandlers, pIOHandler->GetId())) {
ASSERT("IOHandler already registered");
}
SetupToken(pIOHandler);
size_t before = _activeIOHandlers.size();
_activeIOHandlers[pIOHandler->GetId()] = pIOHandler;
_fdStats.RegisterManaged(pIOHandler->GetType());
DEBUG("Handlers count changed: %"PRIz"u->%"PRIz"u %s", before, before + 1,
STR(IOHandler::IOHTToString(pIOHandler->GetType())));
}
void IOHandlerManager::UnRegisterIOHandler(IOHandler *pIOHandler) {
if (MAP_HAS1(_activeIOHandlers, pIOHandler->GetId())) {
_fdStats.UnRegisterManaged(pIOHandler->GetType());
FreeToken(pIOHandler);
size_t before = _activeIOHandlers.size();
_activeIOHandlers.erase(pIOHandler->GetId());
DEBUG("Handlers count changed: %"PRIz"u->%"PRIz"u %s", before, before - 1,
STR(IOHandler::IOHTToString(pIOHandler->GetType())));
}
}
int IOHandlerManager::CreateRawUDPSocket() {
int result = socket(AF_INET, SOCK_DGRAM, 0);
if ((result >= 0)&&(setFdCloseOnExec(result))) {
_fdStats.RegisterRawUdp();
} else {
int err = errno;
FATAL("Unable to create raw udp socket. Error code was: (%d) %s",
err, strerror(err));
}
return result;
}
void IOHandlerManager::CloseRawUDPSocket(int socket) {
if (socket > 0) {
_fdStats.UnRegisterRawUdp();
}
CLOSE_SOCKET(socket);
}
#ifdef GLOBALLY_ACCOUNT_BYTES
void IOHandlerManager::AddInBytesManaged(IOHandlerType type, uint64_t bytes) {
_fdStats.AddInBytesManaged(type, bytes);
}
void IOHandlerManager::AddOutBytesManaged(IOHandlerType type, uint64_t bytes) {
_fdStats.AddOutBytesManaged(type, bytes);
}
void IOHandlerManager::AddInBytesRawUdp(uint64_t bytes) {
_fdStats.AddInBytesRawUdp(bytes);
}
void IOHandlerManager::AddOutBytesRawUdp(uint64_t bytes) {
_fdStats.AddOutBytesRawUdp(bytes);
}
#endif /* GLOBALLY_ACCOUNT_BYTES */
bool IOHandlerManager::EnableReadData(IOHandler *pIOHandler) {
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_ADD, pIOHandler->GetInboundFd(), &evt) != 0) {
int err = errno;
FATAL("Unable to enable read data: (%d) %s", err, strerror(err));
return false;
}
return true;
}
bool IOHandlerManager::DisableReadData(IOHandler *pIOHandler, bool ignoreError) {
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_DEL, pIOHandler->GetInboundFd(), &evt) != 0) {
if (!ignoreError) {
int err = errno;
FATAL("Unable to disable read data: (%d) %s", err, strerror(err));
return false;
}
}
return true;
}
bool IOHandlerManager::EnableWriteData(IOHandler *pIOHandler) {
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN | EPOLLOUT;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_MOD, pIOHandler->GetOutboundFd(), &evt) != 0) {
int err = errno;
if (err == ENOENT) {
if (epoll_ctl(_eq, EPOLL_CTL_ADD, pIOHandler->GetOutboundFd(), &evt) != 0) {
err = errno;
FATAL("Unable to enable read data: (%d) %s", err, strerror(err));
return false;
}
} else {
FATAL("Unable to enable read data: (%d) %s", err, strerror(err));
return false;
}
}
return true;
}
bool IOHandlerManager::DisableWriteData(IOHandler *pIOHandler, bool ignoreError) {
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_MOD, pIOHandler->GetOutboundFd(), &evt) != 0) {
if (!ignoreError) {
int err = errno;
FATAL("Unable to disable write data: (%d) %s", err, strerror(err));
return false;
}
}
return true;
}
bool IOHandlerManager::EnableAcceptConnections(IOHandler *pIOHandler) {
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_ADD, pIOHandler->GetInboundFd(), &evt) != 0) {
int err = errno;
if (err == EEXIST)
return true;
FATAL("Unable to enable accept connections: (%d) %s", err, strerror(err));
return false;
}
return true;
}
bool IOHandlerManager::DisableAcceptConnections(IOHandler *pIOHandler, bool ignoreError) {
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_DEL, pIOHandler->GetInboundFd(), &evt) != 0) {
if (!ignoreError) {
int err = errno;
FATAL("Unable to disable accept connections: (%d) %s", err, strerror(err));
return false;
}
}
return true;
}
bool IOHandlerManager::EnableTimer(IOHandler *pIOHandler, uint32_t seconds) {
#ifdef HAS_EPOLL_TIMERS
itimerspec tmp;
itimerspec dummy;
memset(&tmp, 0, sizeof (tmp));
tmp.it_interval.tv_nsec = 0;
tmp.it_interval.tv_sec = seconds;
tmp.it_value.tv_nsec = 0;
tmp.it_value.tv_sec = seconds;
if (timerfd_settime(pIOHandler->GetInboundFd(), 0, &tmp, &dummy) != 0) {
int err = errno;
FATAL("timerfd_settime failed with error (%d) %s", err, strerror(err));
return false;
}
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_ADD, pIOHandler->GetInboundFd(), &evt) != 0) {
int err = errno;
FATAL("Unable to enable read data: (%d) %s", err, strerror(err));
return false;
}
return true;
#else /* HAS_EPOLL_TIMERS */
TimerEvent event = {0, 0, 0, 0};
event.id = pIOHandler->GetId();
event.period = seconds * 1000;
event.pUserData = pIOHandler->GetIOHandlerManagerToken();
_pTimersManager->AddTimer(event);
return true;
#endif /* HAS_EPOLL_TIMERS */
}
#ifdef HAS_EPOLL_TIMERS
string dumpTimerStruct(itimerspec &ts) {
return format("it_interval\n\ttv_sec: %"PRIz"u\n\ttv_nsec: %ld\nit_value\n\ttv_sec: %"PRIz"u\n\ttv_nsec: %ld",
ts.it_interval.tv_sec,
ts.it_interval.tv_nsec,
ts.it_value.tv_sec,
ts.it_value.tv_nsec);
}
#endif /* HAS_EPOLL_TIMERS */
bool IOHandlerManager::EnableHighGranularityTimer(IOHandler *pIOHandler, uint32_t milliseconds) {
#ifdef HAS_EPOLL_TIMERS
itimerspec tmp;
itimerspec dummy;
memset(&tmp, 0, sizeof (tmp));
tmp.it_interval.tv_nsec = (milliseconds % 1000)*1000000;
tmp.it_interval.tv_sec = milliseconds / 1000;
tmp.it_value.tv_nsec = (milliseconds % 1000)*1000000;
tmp.it_value.tv_sec = milliseconds / 1000;
// ASSERT("milliseconds: %"PRIu32"\n%s",
// milliseconds,
// STR(dumpTimerStruct(tmp)));
if (timerfd_settime(pIOHandler->GetInboundFd(), 0, &tmp, &dummy) != 0) {
int err = errno;
FATAL("timerfd_settime failed with error (%d) %s", err, strerror(err));
return false;
}
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_ADD, pIOHandler->GetInboundFd(), &evt) != 0) {
int err = errno;
FATAL("Unable to enable read data: (%d) %s", err, strerror(err));
return false;
}
return true;
#else /* HAS_EPOLL_TIMERS */
TimerEvent event = {0, 0, 0, 0};
event.id = pIOHandler->GetId();
event.period = milliseconds;
event.pUserData = pIOHandler->GetIOHandlerManagerToken();
_pTimersManager->AddTimer(event);
return true;
#endif /* HAS_EPOLL_TIMERS */
}
bool IOHandlerManager::DisableTimer(IOHandler *pIOHandler, bool ignoreError) {
#ifdef HAS_EPOLL_TIMERS
itimerspec tmp;
itimerspec dummy;
memset(&tmp, 0, sizeof (tmp));
timerfd_settime(pIOHandler->GetInboundFd(), 0, &tmp, &dummy);
struct epoll_event evt = {0,
{0}};
evt.events = EPOLLIN;
evt.data.ptr = pIOHandler->GetIOHandlerManagerToken();
if (epoll_ctl(_eq, EPOLL_CTL_DEL, pIOHandler->GetInboundFd(), &evt) != 0) {
if (!ignoreError) {
int err = errno;
FATAL("Unable to disable read data: (%d) %s", err, strerror(err));
return false;
}
}
return true;
#else /* HAS_EPOLL_TIMERS */
_pTimersManager->RemoveTimer(pIOHandler->GetId());
return true;
#endif /* HAS_EPOLL_TIMERS */
}
void IOHandlerManager::EnqueueForDelete(IOHandler *pIOHandler) {
DisableWriteData(pIOHandler, true);
DisableAcceptConnections(pIOHandler, true);
DisableReadData(pIOHandler, true);
DisableTimer(pIOHandler, true);
if (!MAP_HAS1(_deadIOHandlers, pIOHandler->GetId()))
_deadIOHandlers[pIOHandler->GetId()] = pIOHandler;
}
uint32_t IOHandlerManager::DeleteDeadHandlers() {
uint32_t result = 0;
while (_deadIOHandlers.size() > 0) {
IOHandler *pIOHandler = MAP_VAL(_deadIOHandlers.begin());
_deadIOHandlers.erase(pIOHandler->GetId());
delete pIOHandler;
result++;
}
return result;
}
bool IOHandlerManager::Pulse() {
int32_t eventsCount = 0;
#ifdef HAS_EPOLL_TIMERS
if ((eventsCount = epoll_wait(_eq, _query, EPOLL_QUERY_SIZE, -1)) < 0) {
int err = errno;
if (err == EINTR)
return true;
FATAL("Unable to execute epoll_wait: (%d) %s", err, strerror(err));
return false;
}
#else /* HAS_EPOLL_TIMERS */
if ((eventsCount = epoll_wait(_eq, _query, EPOLL_QUERY_SIZE, _nextWaitPeriod)) < 0) {
int err = errno;
if (err == EINTR)
return true;
FATAL("Unable to execute epoll_wait: (%d) %s", err, strerror(err));
return false;
}
_nextWaitPeriod = _pTimersManager->TimeElapsed();
#endif /* HAS_EPOLL_TIMERS */
for (int32_t i = 0; i < eventsCount; i++) {
//1. Get the token
IOHandlerManagerToken *pToken =
(IOHandlerManagerToken *) _query[i].data.ptr;
//2. Test the fd
if ((_query[i].events & EPOLLERR) != 0) {
if (pToken->validPayload) {
if ((_query[i].events & EPOLLHUP) != 0) {
//DEBUG("***Event handler HUP: %p", (IOHandler *) pToken->pPayload);
((IOHandler *) pToken->pPayload)->OnEvent(_query[i]);
}
// else {
// DEBUG("***Event handler ERR: %p", (IOHandler *) pToken->pPayload);
// }
IOHandlerManager::EnqueueForDelete((IOHandler *) pToken->pPayload);
}
continue;
}
//3. Do the damage
if (pToken->validPayload) {
if (!((IOHandler *) pToken->pPayload)->OnEvent(_query[i])) {
EnqueueForDelete((IOHandler *) pToken->pPayload);
}
}
// else {
// FATAL("Invalid token");
// }
}
if (_tokensVector1.size() > _tokensVector2.size()) {
_pAvailableTokens = &_tokensVector1;
_pRecycledTokens = &_tokensVector2;
} else {
_pAvailableTokens = &_tokensVector2;
_pRecycledTokens = &_tokensVector1;
}
return true;
}
void IOHandlerManager::SetupToken(IOHandler *pIOHandler) {
IOHandlerManagerToken *pResult = NULL;
if (_pAvailableTokens->size() == 0) {
pResult = new IOHandlerManagerToken();
} else {
pResult = (*_pAvailableTokens)[0];
_pAvailableTokens->erase(_pAvailableTokens->begin());
}
pResult->pPayload = pIOHandler;
pResult->validPayload = true;
pIOHandler->SetIOHandlerManagerToken(pResult);
}
void IOHandlerManager::FreeToken(IOHandler *pIOHandler) {
IOHandlerManagerToken *pToken = pIOHandler->GetIOHandlerManagerToken();
pIOHandler->SetIOHandlerManagerToken(NULL);
pToken->pPayload = NULL;
pToken->validPayload = false;
ADD_VECTOR_END((*_pRecycledTokens), pToken);
}
#ifndef HAS_EPOLL_TIMERS
bool IOHandlerManager::ProcessTimer(TimerEvent &event) {
IOHandlerManagerToken *pToken =
(IOHandlerManagerToken *) event.pUserData;
_dummy.data.ptr = &event;
if (pToken->validPayload) {
if (!((IOHandler *) pToken->pPayload)->OnEvent(_dummy)) {
EnqueueForDelete((IOHandler *) pToken->pPayload);
return false;
}
return true;
} else {
FATAL("Invalid token");
return false;
}
}
#endif /* HAS_EPOLL_TIMERS */
#endif /* NET_EPOLL */
| 14,688
|
C++
|
.cpp
| 445
| 30.678652
| 111
| 0.719431
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,346
|
main.cpp
|
shiretu_crtmpserver/sources/tests/src/main.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "commontestssuite.h"
#include "varianttestssuite.h"
#include "thelibtestssuite.h"
int main(void) {
TS_PRINT("Begin tests...\n");
EXECUTE_SUITE(CommonTestsSuite);
EXECUTE_SUITE(VariantTestsSuite);
EXECUTE_SUITE(TheLibTestsSuite);
TS_PRINT("A total of %d tests completed successfuly\n", BaseTestsSuite::_testsCount);
return 0;
}
| 1,117
|
C++
|
.cpp
| 29
| 36.655172
| 86
| 0.757827
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,347
|
commontestssuite.cpp
|
shiretu_crtmpserver/sources/tests/src/commontestssuite.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "commontestssuite.h"
CommonTestsSuite::CommonTestsSuite()
: BaseTestsSuite() {
}
CommonTestsSuite::~CommonTestsSuite() {
}
void CommonTestsSuite::Run() {
test_Endianess();
test_isNumeric();
test_lowerCase();
test_upperCase();
test_ltrim();
test_rtrim();
test_trim();
test_replace();
test_split();
test_mapping();
test_format();
test_splitFileName();
test_generateRandomString();
test_GetHostByName();
test_md5();
test_HMACsha256();
test_b64();
test_unb64();
test_unhex();
test_ParseURL();
test_setFdOptions();
}
void CommonTestsSuite::test_Endianess() {
uint16_t ui16 = 0x0102;
uint32_t ui32 = 0x01020304;
uint64_t ui64 = 0x0102030405060708LL;
double d = 123.456;
//host to network
uint8_t *pBuffer = NULL;
ui16 = EHTONS(ui16);
pBuffer = (uint8_t *) & ui16;
TS_ASSERT(pBuffer[0] == 0x01);
TS_ASSERT(pBuffer[1] == 0x02);
pBuffer = NULL;
ui32 = EHTONL(ui32);
pBuffer = (uint8_t *) & ui32;
TS_ASSERT(pBuffer[0] == 0x01);
TS_ASSERT(pBuffer[1] == 0x02);
TS_ASSERT(pBuffer[2] == 0x03);
TS_ASSERT(pBuffer[3] == 0x04);
pBuffer = NULL;
ui32 = 0x01020304;
ui32 = EHTONA(ui32);
pBuffer = (uint8_t *) & ui32;
TS_ASSERT(pBuffer[0] == 0x02);
TS_ASSERT(pBuffer[1] == 0x03);
TS_ASSERT(pBuffer[2] == 0x04);
TS_ASSERT(pBuffer[3] == 0x01);
pBuffer = NULL;
ui64 = EHTONLL(ui64);
pBuffer = (uint8_t *) & ui64;
TS_ASSERT(pBuffer[0] == 0x01);
TS_ASSERT(pBuffer[1] == 0x02);
TS_ASSERT(pBuffer[2] == 0x03);
TS_ASSERT(pBuffer[3] == 0x04);
TS_ASSERT(pBuffer[4] == 0x05);
TS_ASSERT(pBuffer[5] == 0x06);
TS_ASSERT(pBuffer[6] == 0x07);
TS_ASSERT(pBuffer[7] == 0x08);
pBuffer = NULL;
EHTOND(d, ui64);
pBuffer = (uint8_t *) & ui64;
TS_ASSERT(pBuffer[0] == 0x40);
TS_ASSERT(pBuffer[1] == 0x5e);
TS_ASSERT(pBuffer[2] == 0xdd);
TS_ASSERT(pBuffer[3] == 0x2f);
TS_ASSERT(pBuffer[4] == 0x1a);
TS_ASSERT(pBuffer[5] == 0x9f);
TS_ASSERT(pBuffer[6] == 0xbe);
TS_ASSERT(pBuffer[7] == 0x77);
//network to host pointer
char buffer[] = {
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f
};
ui16 = ENTOHSP(buffer);
TS_ASSERT(ui16 == 0x0001);
ui16 = ENTOHSP(buffer + 1);
TS_ASSERT(ui16 == 0x0102);
ui16 = ENTOHSP(buffer + 2);
TS_ASSERT(ui16 == 0x0203);
ui16 = ENTOHSP(buffer + 3);
TS_ASSERT(ui16 == 0x0304);
ui16 = ENTOHSP(buffer + 4);
TS_ASSERT(ui16 == 0x0405);
ui16 = ENTOHSP(buffer + 5);
TS_ASSERT(ui16 == 0x0506);
ui16 = ENTOHSP(buffer + 6);
TS_ASSERT(ui16 == 0x0607);
ui16 = ENTOHSP(buffer + 7);
TS_ASSERT(ui16 == 0x0708);
ui16 = ENTOHSP(buffer + 8);
TS_ASSERT(ui16 == 0x0809);
ui16 = ENTOHSP(buffer + 9);
TS_ASSERT(ui16 == 0x090a);
ui16 = ENTOHSP(buffer + 10);
TS_ASSERT(ui16 == 0x0a0b);
ui16 = ENTOHSP(buffer + 11);
TS_ASSERT(ui16 == 0x0b0c);
ui16 = ENTOHSP(buffer + 12);
TS_ASSERT(ui16 == 0x0c0d);
ui16 = ENTOHSP(buffer + 13);
TS_ASSERT(ui16 == 0x0d0e);
ui16 = ENTOHSP(buffer + 14);
TS_ASSERT(ui16 == 0x0e0f);
ui32 = ENTOHLP(buffer);
TS_ASSERT(ui32 == 0x00010203);
ui32 = ENTOHLP(buffer + 1);
TS_ASSERT(ui32 == 0x01020304);
ui32 = ENTOHLP(buffer + 2);
TS_ASSERT(ui32 == 0x02030405);
ui32 = ENTOHLP(buffer + 3);
TS_ASSERT(ui32 == 0x03040506);
ui32 = ENTOHLP(buffer + 4);
TS_ASSERT(ui32 == 0x04050607);
ui32 = ENTOHLP(buffer + 5);
TS_ASSERT(ui32 == 0x05060708);
ui32 = ENTOHLP(buffer + 6);
TS_ASSERT(ui32 == 0x06070809);
ui32 = ENTOHLP(buffer + 7);
TS_ASSERT(ui32 == 0x0708090a);
ui32 = ENTOHLP(buffer + 8);
TS_ASSERT(ui32 == 0x08090a0b);
ui32 = ENTOHLP(buffer + 9);
TS_ASSERT(ui32 == 0x090a0b0c);
ui32 = ENTOHLP(buffer + 10);
TS_ASSERT(ui32 == 0x0a0b0c0d);
ui32 = ENTOHLP(buffer + 11);
TS_ASSERT(ui32 == 0x0b0c0d0e);
ui32 = ENTOHLP(buffer + 12);
TS_ASSERT(ui32 == 0x0c0d0e0f);
ui32 = ENTOHAP(buffer);
TS_ASSERT(ui32 == 0x03000102);
ui32 = ENTOHAP(buffer + 1);
TS_ASSERT(ui32 == 0x04010203);
ui32 = ENTOHAP(buffer + 2);
TS_ASSERT(ui32 == 0x05020304);
ui32 = ENTOHAP(buffer + 3);
TS_ASSERT(ui32 == 0x06030405);
ui32 = ENTOHAP(buffer + 4);
TS_ASSERT(ui32 == 0x07040506);
ui32 = ENTOHAP(buffer + 5);
TS_ASSERT(ui32 == 0x08050607);
ui32 = ENTOHAP(buffer + 6);
TS_ASSERT(ui32 == 0x09060708);
ui32 = ENTOHAP(buffer + 7);
TS_ASSERT(ui32 == 0x0a070809);
ui32 = ENTOHAP(buffer + 8);
TS_ASSERT(ui32 == 0x0b08090a);
ui32 = ENTOHAP(buffer + 9);
TS_ASSERT(ui32 == 0x0c090a0b);
ui32 = ENTOHAP(buffer + 10);
TS_ASSERT(ui32 == 0x0d0a0b0c);
ui32 = ENTOHAP(buffer + 11);
TS_ASSERT(ui32 == 0x0e0b0c0d);
ui32 = ENTOHAP(buffer + 12);
TS_ASSERT(ui32 == 0x0f0c0d0e);
ui64 = ENTOHLLP(buffer);
TS_ASSERT(ui64 == 0x0001020304050607LL);
ui64 = ENTOHLLP(buffer + 1);
TS_ASSERT(ui64 == 0x0102030405060708LL);
ui64 = ENTOHLLP(buffer + 2);
TS_ASSERT(ui64 == 0x0203040506070809LL);
ui64 = ENTOHLLP(buffer + 3);
TS_ASSERT(ui64 == 0x030405060708090aLL);
ui64 = ENTOHLLP(buffer + 4);
TS_ASSERT(ui64 == 0x0405060708090a0bLL);
ui64 = ENTOHLLP(buffer + 5);
TS_ASSERT(ui64 == 0x05060708090a0b0cLL);
ui64 = ENTOHLLP(buffer + 6);
TS_ASSERT(ui64 == 0x060708090a0b0c0dLL);
ui64 = ENTOHLLP(buffer + 7);
TS_ASSERT(ui64 == 0x0708090a0b0c0d0eLL);
ui64 = ENTOHLLP(buffer + 8);
TS_ASSERT(ui64 == 0x08090a0b0c0d0e0fLL);
char *pTempBuffer = new char[64 + 8];
unsigned char rawDouble[] = {0x40, 0x5E, 0xDD, 0x2F, 0x1A, 0x9F, 0xBE, 0x77};
double tempDoubleVal = 0;
for (int i = 0; i <= 64; i++) {
memset(pTempBuffer, 0, i);
memcpy(pTempBuffer + i, rawDouble, 8);
memset(pTempBuffer + i + 8, 0, 64 + 8 - i - 8);
ENTOHDP((pTempBuffer + i), tempDoubleVal);
TS_ASSERT(d == tempDoubleVal);
}
delete[] pTempBuffer;
//network to host
#ifdef LITTLE_ENDIAN_BYTE_ALIGNED
TS_ASSERT(ENTOHA(0x01040302) == 0x01020304);
TS_ASSERT(ENTOHLL(0x0807060504030201LL) == 0x0102030405060708LL);
ENTOHD(0x77BE9F1A2FDD5E40LL, tempDoubleVal);
TS_ASSERT(d == tempDoubleVal);
#endif /* LITTLE_ENDIAN_BYTE_ALIGNED */
#ifdef LITTLE_ENDIAN_SHORT_ALIGNED
TS_ASSERT(ENTOHA(0x01040302) == 0x01020304);
TS_ASSERT(ENTOHLL(0x0807060504030201LL) == 0x0102030405060708LL);
ENTOHD(0x77BE9F1A2FDD5E40LL, tempDoubleVal);
TS_ASSERT(d == tempDoubleVal);
#endif /* LITTLE_ENDIAN_SHORT_ALIGNED */
#ifdef BIG_ENDIAN_BYTE_ALIGNED
TS_ASSERT(ENTOHA(0x02030401) == 0x01020304);
TS_ASSERT(ENTOHLL(0x0102030405060708LL) == 0x0102030405060708LL);
ENTOHD(0x405EDD2F1A9FBE77LL, tempDoubleVal);
TS_ASSERT(d == tempDoubleVal);
#endif /* BIG_ENDIAN_BYTE_ALIGNED */
#ifdef BIG_ENDIAN_SHORT_ALIGNED
#error BIG_ENDIAN_SHORT_ALIGNED set of tests not yet implemented! Please take care of this first!
#endif /* BIG_ENDIAN_SHORT_ALIGNED */
//double mirror
TS_ASSERT(ENTOHS(EHTONS(0x0102)) == 0x0102);
TS_ASSERT(EHTONS(ENTOHS(0x0102)) == 0x0102);
TS_ASSERT(ENTOHL(EHTONL(0x01020304)) == 0x01020304);
TS_ASSERT(EHTONL(ENTOHL(0x01020304)) == 0x01020304);
TS_ASSERT(ENTOHLL(EHTONLL(0x0102030405060708LL)) == 0x0102030405060708LL);
TS_ASSERT(EHTONLL(ENTOHLL(0x0102030405060708LL)) == 0x0102030405060708LL);
//EHTOND/ENTOHD are different. Requires 2 parameters. So, no double mirror
TS_ASSERT(ENTOHA(EHTONA(0x01020304)) == 0x01020304);
TS_ASSERT(EHTONA(ENTOHA(0x01020304)) == 0x01020304);
// Buffer Put routines
for (int i = 0; i < 16; i++) {
EHTONSP(buffer + i, 0x0102);
TS_ASSERT(ENTOHSP(buffer + i) == 0x0102);
EHTONLP(buffer + i, 0x01020304);
TS_ASSERT(ENTOHLP(buffer + i) == 0x01020304);
EHTONLLP(buffer + i, 0x0102030405060708LL);
TS_ASSERT(ENTOHLLP(buffer + i) == 0x0102030405060708LL);
EHTONDP(d, (buffer + i));
ENTOHDP(buffer + i, tempDoubleVal);
TS_ASSERT(d == tempDoubleVal);
}
}
void CommonTestsSuite::test_isNumeric() {
TS_ASSERT(!isNumeric(""));
TS_ASSERT(!isNumeric(" "));
TS_ASSERT(!isNumeric("sdfsdfsd"));
TS_ASSERT(!isNumeric("0x1234"));
TS_ASSERT(!isNumeric("4294967294"));
TS_ASSERT(!isNumeric("4294967295"));
TS_ASSERT(!isNumeric("4294967296"));
TS_ASSERT(!isNumeric("2147483648"));
TS_ASSERT(!isNumeric("-4294967294"));
TS_ASSERT(!isNumeric("-4294967295"));
TS_ASSERT(!isNumeric("-4294967296"));
TS_ASSERT(isNumeric("2147483647"));
TS_ASSERT(isNumeric("2147483646"));
TS_ASSERT(isNumeric("1234"));
TS_ASSERT(isNumeric("0"));
TS_ASSERT(isNumeric("-1234"));
TS_ASSERT(isNumeric("-2147483647"));
TS_ASSERT(isNumeric("-2147483648"));
}
void CommonTestsSuite::test_lowerCase() {
TS_ASSERT(lowerCase("TeXt") == "text");
TS_ASSERT(lowerCase("TEXT") == "text");
TS_ASSERT(lowerCase("text") == "text");
TS_ASSERT(lowerCase("") == "");
TS_ASSERT(lowerCase(" ") == " ");
string testString;
for (int c = -128; c <= 255; c++)
testString += (char) c;
string lowerString;
for (int c = -128; c <= 255; c++) {
if (c >= 65 && c <= 90)
lowerString += (char) (c + 32);
else
lowerString += (char) c;
}
TS_ASSERT(testString != lowerString);
TS_ASSERT(lowerCase(testString) == lowerString);
}
void CommonTestsSuite::test_upperCase() {
TS_ASSERT(upperCase("TeXt") == "TEXT");
TS_ASSERT(upperCase("TEXT") == "TEXT");
TS_ASSERT(upperCase("text") == "TEXT");
TS_ASSERT(upperCase("") == "");
TS_ASSERT(upperCase(" ") == " ");
string testString;
for (int c = -128; c <= 255; c++)
testString += (char) c;
string upperString;
for (int c = -128; c <= 255; c++) {
if (c >= 97 && c <= 122)
upperString += (char) (c - 32);
else
upperString += (char) c;
}
TS_ASSERT(testString != upperString);
TS_ASSERT(upperCase(testString) == upperString);
}
void CommonTestsSuite::test_ltrim() {
string str;
str = "";
lTrim(str);
TS_ASSERT(str == "");
str = " ";
lTrim(str);
TS_ASSERT(str == "");
str = " b";
lTrim(str);
TS_ASSERT(str == "b");
str = " bb";
lTrim(str);
TS_ASSERT(str == "bb");
str = " bb ";
lTrim(str);
TS_ASSERT(str == "bb ");
str = " bb b";
lTrim(str);
TS_ASSERT(str == "bb b");
str = " bb b ";
lTrim(str);
TS_ASSERT(str == "bb b ");
}
void CommonTestsSuite::test_rtrim() {
string str;
str = "";
rTrim(str);
TS_ASSERT(str == "");
str = " ";
rTrim(str);
TS_ASSERT(str == "");
str = " b";
rTrim(str);
TS_ASSERT(str == " b");
str = " bb";
rTrim(str);
TS_ASSERT(str == " bb");
str = " bb ";
rTrim(str);
TS_ASSERT(str == " bb");
str = " bb b";
rTrim(str);
TS_ASSERT(str == " bb b");
str = " bb b ";
rTrim(str);
TS_ASSERT(str == " bb b");
}
void CommonTestsSuite::test_trim() {
string str;
str = "";
trim(str);
TS_ASSERT(str == "");
str = " ";
trim(str);
TS_ASSERT(str == "");
str = " b";
trim(str);
TS_ASSERT(str == "b");
str = " bb";
trim(str);
TS_ASSERT(str == "bb");
str = " bb ";
trim(str);
TS_ASSERT(str == "bb");
str = " bb b";
trim(str);
TS_ASSERT(str == "bb b");
str = " bb b ";
trim(str);
TS_ASSERT(str == "bb b");
}
void CommonTestsSuite::test_replace() {
string str;
str = "";
replace(str, "", "");
TS_ASSERT(str == "");
str = "";
replace(str, "test", "");
TS_ASSERT(str == "");
str = "";
replace(str, "test", "TEST");
TS_ASSERT(str == "");
str = "";
replace(str, "", "TEST");
TS_ASSERT(str == "");
str = "test string ";
replace(str, "test", "");
TS_ASSERT(str == " string ");
str = "test string ";
replace(str, "test", "TEST");
TS_ASSERT(str == "TEST string ");
str = "test string ";
replace(str, "", "TEST");
TS_ASSERT(str == "test string ");
str = "aaa";
replace(str, "a", "aa");
TS_ASSERT(str == "aaaaaa");
str = "aaaaa";
replace(str, "aa", "a");
TS_ASSERT(str == "aaa");
str = "aaa";
replace(str, "aa", "a");
TS_ASSERT(str == "aa");
}
void CommonTestsSuite::test_split() {
string input = "some::string:with:::a lot of : ::";
vector<string> parts;
split(input, ":", parts);
TS_ASSERT(parts.size() == 10);
TS_ASSERT(parts[0] == "some");
TS_ASSERT(parts[1] == "");
TS_ASSERT(parts[2] == "string");
TS_ASSERT(parts[3] == "with");
TS_ASSERT(parts[4] == "");
TS_ASSERT(parts[5] == "");
TS_ASSERT(parts[6] == "a lot of ");
TS_ASSERT(parts[7] == " ");
TS_ASSERT(parts[8] == "");
TS_ASSERT(parts[9] == "");
input = "some string split with s and g text...sg...";
split(input, "sg", parts);
TS_ASSERT(parts.size() == 2);
TS_ASSERT(parts[0] == "some string split with s and g text...");
TS_ASSERT(parts[1] == "...");
input = "some string split with s and g text...sg";
split(input, "sg", parts);
TS_ASSERT(parts.size() == 2);
TS_ASSERT(parts[0] == "some string split with s and g text...");
TS_ASSERT(parts[1] == "");
input = "some string split with s and g text...";
split(input, "sg", parts);
TS_ASSERT(parts.size() == 1);
TS_ASSERT(parts[0] == "some string split with s and g text...");
input = "::";
split(input, ":", parts);
TS_ASSERT(parts.size() == 3);
TS_ASSERT(parts[0] == "");
TS_ASSERT(parts[1] == "");
TS_ASSERT(parts[2] == "");
input = ":";
split(input, ":", parts);
TS_ASSERT(parts.size() == 2);
TS_ASSERT(parts[0] == "");
TS_ASSERT(parts[1] == "");
input = "aaaa";
split(input, ":", parts);
TS_ASSERT(parts.size() == 1);
TS_ASSERT(parts[0] == "aaaa");
input = "";
split(input, ":", parts);
TS_ASSERT(parts.size() == 1);
TS_ASSERT(parts[0] == "");
}
void CommonTestsSuite::test_mapping() {
string line = "name1=value1;name2=value2;=value3;name4=;";
map<string, string> m = mapping(line, ";", "=", false);
TS_ASSERT(m.size() == 4);
TS_ASSERT(m["name1"] == "value1");
TS_ASSERT(m["name2"] == "value2");
TS_ASSERT(m[""] == "value3");
TS_ASSERT(m["name4"] == "");
TS_ASSERT(m.size() == 4);
line = "name1=value1;name2=value2;=value3;name4=";
m = mapping(line, ";", "=", false);
TS_ASSERT(m.size() == 4);
TS_ASSERT(m["name1"] == "value1");
TS_ASSERT(m["name2"] == "value2");
TS_ASSERT(m[""] == "value3");
TS_ASSERT(m["name4"] == "");
TS_ASSERT(m.size() == 4);
line = "name1=value1;name2=value2;=value3;name4=;;;";
m = mapping(line, ";", "=", false);
TS_ASSERT(m.size() == 4);
TS_ASSERT(m["name1"] == "value1");
TS_ASSERT(m["name2"] == "value2");
TS_ASSERT(m[""] == "value3");
TS_ASSERT(m["name4"] == "");
TS_ASSERT(m.size() == 4);
line = "name1=value1;name2=value2;=value3;name4=;;;name1=value11;";
m = mapping(line, ";", "=", false);
TS_ASSERT(m.size() == 4);
TS_ASSERT(m["name1"] == "value11");
TS_ASSERT(m["name2"] == "value2");
TS_ASSERT(m[""] == "value3");
TS_ASSERT(m["name4"] == "");
TS_ASSERT(m.size() == 4);
line = ";=;";
m = mapping(line, ";", "=", false);
TS_ASSERT(m.size() == 1);
TS_ASSERT(m[""] == "");
TS_ASSERT(m.size() == 1);
line = "=;=";
m = mapping(line, ";", "=", false);
TS_ASSERT(m.size() == 1);
TS_ASSERT(m[""] == "");
TS_ASSERT(m.size() == 1);
line = "aa = b b ; = ";
m = mapping(line, ";", "=", true);
TS_ASSERT(m.size() == 2);
TS_ASSERT(m["aa"] == "b b");
TS_ASSERT(m[""] == "");
TS_ASSERT(m.size() == 2);
}
void CommonTestsSuite::test_format() {
TS_ASSERT(format("%s%d%.2f", "test", -1, 123.45) == "test-1123.45");
}
void CommonTestsSuite::test_splitFileName() {
string name;
string extension;
name = extension = "dummy";
splitFileName("", name, extension);
TS_ASSERT(name == "");
TS_ASSERT(extension == "");
name = extension = "dummy";
splitFileName("/path/", name, extension);
TS_ASSERT(name == "/path/");
TS_ASSERT(extension == "");
name = extension = "dummy";
splitFileName("/path/file", name, extension);
TS_ASSERT(name == "/path/file");
TS_ASSERT(extension == "");
name = extension = "dummy";
splitFileName("/path/file.", name, extension);
TS_ASSERT(name == "/path/file");
TS_ASSERT(extension == "");
name = extension = "dummy";
splitFileName("/path/file.ext", name, extension);
TS_ASSERT(name == "/path/file");
TS_ASSERT(extension == "ext");
name = extension = "dummy";
splitFileName("/path/.ext", name, extension);
TS_ASSERT(name == "/path/");
TS_ASSERT(extension == "ext");
name = extension = "dummy";
splitFileName("/path/.", name, extension);
TS_ASSERT(name == "/path/");
TS_ASSERT(extension == "");
name = extension = "dummy";
splitFileName(".", name, extension);
TS_ASSERT(name == "");
TS_ASSERT(extension == "");
}
void CommonTestsSuite::test_generateRandomString() {
map<string, string> strings;
for (uint32_t i = 0; i < 16384; i++) {
string randString = generateRandomString(16);
//we don't want to increment tests count
//That is why we use TS_ASSERT_NO_INCREMENT
TS_ASSERT_NO_INCREMENT(randString != "");
if (strings.find(randString) != strings.end()) {
TS_ASSERT(false);
}
strings[randString];
}
//Ok, treat all this 16384 tests as one test by doing a dummy test
TS_ASSERT(true);
}
void CommonTestsSuite::test_GetHostByName() {
//TS_ASSERT(GetHostByName("___this_should_not_exist___") == "");
//TS_ASSERT(GetHostByName("localhost") == "127.0.0.1");
//TS_ASSERT(GetHostByName("127.0.0.1") == "127.0.0.1");
//TS_ASSERT(GetHostByName("rtmpd.com") == "89.149.7.54");
}
void CommonTestsSuite::test_md5() {
TS_ASSERT(md5("MD5 test string", true) == "da42a8cd6c584e577a85dd796ae75eef");
}
void CommonTestsSuite::test_HMACsha256() {
string plain = "This is a test";
string key = "test_key";
uint8_t hash[32] = {0};
uint8_t wanted[] = {
0xA7, 0x97, 0x3B, 0x48, 0xB2, 0x92, 0x5A, 0x81,
0xFD, 0x93, 0x41, 0x95, 0x48, 0x51, 0x91, 0x88,
0xE4, 0xC5, 0xFB, 0xAE, 0x63, 0xD1, 0xF6, 0xF3,
0x1F, 0x16, 0xF7, 0xC0, 0x9A, 0xD3, 0xC4, 0x07
};
HMACsha256(STR(plain), (uint32_t) plain.length(), STR(key), (uint32_t) key.length(), hash);
for (uint32_t i = 0; i < 32; i++) {
TS_ASSERT(hash[i] == wanted[i]);
}
}
void CommonTestsSuite::test_b64() {
TS_ASSERT(b64("this is a test1") == "dGhpcyBpcyBhIHRlc3Qx");
TS_ASSERT(b64("this is a test") == "dGhpcyBpcyBhIHRlc3Q=");
TS_ASSERT(b64("this is a tes") == "dGhpcyBpcyBhIHRlcw==");
TS_ASSERT(b64("") == "");
}
void CommonTestsSuite::test_unb64() {
TS_ASSERT(unb64("dGhpcyBpcyBhIHRlc3Qx") == "this is a test1");
TS_ASSERT(unb64("dGhpcyBpcyBhIHRlc3Q=") == "this is a test");
TS_ASSERT(unb64("dGhpcyBpcyBhIHRlcw==") == "this is a tes");
TS_ASSERT(unb64("") == "");
}
void CommonTestsSuite::test_unhex() {
string hexString;
string bin;
hexString = "";
bin = unhex(hexString);
TS_ASSERT(bin == "");
hexString = "1";
bin = unhex(hexString);
TS_ASSERT(bin == "");
hexString = "1non_permitted_characters";
bin = unhex(hexString);
TS_ASSERT(bin == "");
hexString = "1non_permitted_characters1";
bin = unhex(hexString);
TS_ASSERT(bin == "");
for (uint32_t i = 0; i <= 255; i++) {
hexString = format("%02x", i);
bin = unhex(hexString);
TS_ASSERT(bin.length() == 1);
TS_ASSERT((uint8_t) bin[0] == i);
}
for (uint32_t i = 1; i <= 255; i++) {
hexString = "";
for (uint32_t j = 0; j < i; j++) {
hexString += format("%02x", j);
}
bin = unhex(hexString);
if (bin.length() != i) {
TS_ASSERT(bin.length() == i);
}
for (uint32_t j = 0; j < i; j++) {
if ((uint8_t) bin[j] != j) {
TS_ASSERT((uint8_t) bin[j] == j);
}
}
}
}
void CommonTestsSuite::test_ParseURL() {
// URI uri;
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("sjdhfkjsdhfjksdh", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http:/gigi/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("htt://gigi/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://:gigi/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://gigi:gfgf/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://gigi:123456/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://:@gigi/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://aaa:ddd@gigi/stiintza", false, uri) == true);
// TS_ASSERT(uri.host == "gigi");
// TS_ASSERT(uri.port == 80);
// TS_ASSERT(uri.userName == "aaa");
// TS_ASSERT(uri.password == "ddd");
// TS_ASSERT(uri.fullDocumentPath == "/stiintza");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://gigi/stiintza", false, uri) == true);
// TS_ASSERT(uri.host == "gigi");
// TS_ASSERT(uri.port == 80);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "/stiintza");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://@gigi/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://:@gigi/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://gigi:/stiintza", false, uri) == false);
// TS_ASSERT(uri.host == "");
// TS_ASSERT(uri.port == 0);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "");
//
// uri.Reset();
// uri.port = 9999;
// TS_ASSERT(URI::FromString("http://gigi:1234/stiintza", false, uri) == true);
// TS_ASSERT(uri.host == "gigi");
// TS_ASSERT(uri.port == 1234);
// TS_ASSERT(uri.userName == "");
// TS_ASSERT(uri.password == "");
// TS_ASSERT(uri.fullDocumentPath == "/stiintza");
}
void CommonTestsSuite::test_setFdOptions() {
InitNetworking();
SOCKET fd = socket(AF_INET, SOCK_STREAM, 0); //NOINHERIT
TS_ASSERT(fd > 0);
TS_ASSERT(setFdNoSIGPIPE(fd));
TS_ASSERT(setFdNonBlock(fd));
TS_ASSERT(setFdNoNagle(fd, false));
TS_ASSERT(setFdKeepAlive(fd, false));
TS_ASSERT(setFdReuseAddress(fd));
CLOSE_SOCKET(fd);
fd = (SOCKET) - 1;
fd = socket(AF_INET, SOCK_STREAM, 0); //NOINHERIT
TS_ASSERT(fd > 0);
TS_ASSERT(setFdOptions(fd, false));
CLOSE_SOCKET(fd);
}
| 24,908
|
C++
|
.cpp
| 821
| 28.159562
| 97
| 0.638862
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,348
|
iobuffer.cpp
|
shiretu_crtmpserver/sources/common/src/utils/buffering/iobuffer.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils/buffering/iobuffer.h"
#include "utils/logging/logging.h"
#ifdef WITH_SANITY_INPUT_BUFFER
#define SANITY_INPUT_BUFFER \
o_assert(_consumed<=_published); \
o_assert(_published<=_size);
#else
#define SANITY_INPUT_BUFFER
#endif
//#define TRACK_ALLOCATIONS
/*
#include <execinfo.h>
void *array[100]; \
int arraySize = backtrace(array, 100); \
char **messages = backtrace_symbols(array, arraySize); \
for (int i = 0; i < arraySize && messages != NULL; ++i) \
{ \
fprintf(stderr, "[bt]: (%d) %s\n", i, messages[i]); \
} \
map<DWORD,pair<uint32_t,string> > gBackTrace;
PVOID *gpTrace=NULL;
#include <Dbghelp.h>
void CaptureBacktrace(){
if(gpTrace==NULL){
SymSetOptions ( SYMOPT_DEFERRED_LOADS | SYMOPT_INCLUDE_32BIT_MODULES | SYMOPT_UNDNAME );
if (!::SymInitialize( ::GetCurrentProcess(), "http://msdl.microsoft.com/download/symbols", TRUE ))
return;
gpTrace=new PVOID[65536];
}
DWORD hash;
DWORD captured=CaptureStackBackTrace(1,65535,gpTrace,&hash);
map<DWORD,pair<uint32_t,string> >::iterator found=gBackTrace.find(hash);
if(found!=gBackTrace.end()){
found->second.first++;
if((found->second.first%1000)==0){
fprintf(stderr,"--------------------------\n");
fprintf(stderr,"%"PRIu32"\n",found->second.first);
fprintf(stderr,"%"PRIu32"\n%s\n",found->first,STR(found->second.second));
}
} else {
string stack="";
for(DWORD i=0;i<captured&&i<65536;i++){
IMAGEHLP_LINE64 fileLine={0};
ULONG64 buffer[ (sizeof( SYMBOL_INFO ) + 1024 + sizeof( ULONG64 ) - 1) / sizeof( ULONG64 ) ] = { 0 };
SYMBOL_INFO *info = (SYMBOL_INFO *)buffer;
info->SizeOfStruct = sizeof( SYMBOL_INFO );
info->MaxNameLen = 1024;
DWORD64 displacement1 = 0;
DWORD displacement2 = 0;
if ((SymFromAddr( ::GetCurrentProcess(), (DWORD64)gpTrace[ i ], &displacement1, info ))
&&(SymGetLineFromAddr64( ::GetCurrentProcess(), (DWORD64)gpTrace[ i ], &displacement2,&fileLine))){
stack+=string(info->Name,info->NameLen);
stack+=format(" %s:%"PRIu32"\n",fileLine.FileName,fileLine.LineNumber);
}
}
if(stack.find("le_ba.cpp")==string::npos){
pair<uint32_t,string> p=pair<uint32_t,string>(1,stack);
gBackTrace[hash]=p;
}
}
}
*/
#ifdef TRACK_ALLOCATIONS
uint64_t gAllocated = 0;
uint64_t gDeallocated = 0;
uint64_t gAllocationCount = 0;
uint64_t gDeallocationCount = 0;
uint64_t gIOBuffConstructorCount = 0;
uint64_t gIOBuffDestructorCount = 0;
uint64_t gLastAllocatedSize = 0;
uint64_t gLastDeallocatedSize = 0;
uint64_t gMaxSize = 0;
uint64_t gMemcpySize = 0;
uint64_t gMemcpyCount = 0;
uint64_t gSmartCopy = 0;
uint64_t gNormalCopy = 0;
#define DUMP_ALLOCATIONS_TRACKING(kind, pointer) \
do { \
fprintf(stderr,"%p %s A/D Amounts (MB): %.2f/%.2f (%.2f); %"PRIu64"/%"PRIu64" (%"PRIu64"); %"PRIu64"/%"PRIu64" (%"PRIu64") A/D/M %"PRIu64"/%"PRIu64"/%"PRIu64" %.2f(%"PRIu64") %"PRIu64"/%"PRIu64"\n", \
pointer, \
kind, \
(double)gAllocated/(1024.0*1024.0), \
(double)gDeallocated/(1024.0*1024.0), \
(double)(gAllocated-gDeallocated)/(1024.0*1024.0), \
gAllocationCount, \
gDeallocationCount, \
gAllocationCount-gDeallocationCount, \
gIOBuffConstructorCount, \
gIOBuffDestructorCount, \
gIOBuffConstructorCount-gIOBuffDestructorCount, \
gLastAllocatedSize, \
gLastDeallocatedSize, \
gMaxSize, \
(double)gMemcpySize/(1024.0*1024.0), \
gMemcpyCount, \
gSmartCopy, \
gNormalCopy \
); \
fflush(stderr); \
}while(0)
#define TRACK_NEW(size,pointer) \
do { \
gAllocated+=(size); \
gAllocationCount++; \
gLastAllocatedSize=(size); \
gMaxSize=gMaxSize<(size)?(size):gMaxSize; \
DUMP_ALLOCATIONS_TRACKING(" new",pointer); \
}while(0)
#define TRACK_DELETE(size,pointer) \
do { \
gDeallocated+=(size); \
gDeallocationCount++; \
gLastDeallocatedSize=(size); \
DUMP_ALLOCATIONS_TRACKING("delete",pointer); \
}while(0)
#define TRACK_IOBUFFER_CONSTRUCTOR(pointer) \
do { \
gIOBuffConstructorCount++; \
DUMP_ALLOCATIONS_TRACKING("constr",pointer); \
}while(0)
#define TRACK_IOBUFFER_DESTRUCTOR(pointer) \
do { \
gIOBuffConstructorCount++; \
DUMP_ALLOCATIONS_TRACKING(" destr",pointer); \
}while(0)
#define TRACK_IOBUFFER_MEMCPY(size,pointer) \
do { \
gMemcpyCount++; \
gMemcpySize+=(size); \
if((gMemcpyCount%100)==0) \
DUMP_ALLOCATIONS_TRACKING("memcpy",pointer); \
}while(0)
#define TRACK_SMART_COPY(pointer,smart) \
do { \
if(smart) \
gSmartCopy++; \
else \
gNormalCopy++; \
if(((gSmartCopy+gNormalCopy)%100)==0) \
DUMP_ALLOCATIONS_TRACKING(" copy",pointer); \
}while(0)
#else /* TRACK_ALLOCATIONS */
#define DUMP_ALLOCATIONS_TRACKING(kind, pointer)
#define TRACK_NEW(size,pointer)
#define TRACK_DELETE(size,pointer)
#define TRACK_IOBUFFER_CONSTRUCTOR(pointer)
#define TRACK_IOBUFFER_DESTRUCTOR(pointer)
#define TRACK_IOBUFFER_MEMCPY(size,pointer)
#define TRACK_SMART_COPY(pointer,smart)
#endif /* TRACK_ALLOCATIONS */
IOBuffer::IOBuffer() {
_pBuffer = NULL;
_size = 0;
_published = 0;
_consumed = 0;
_minChunkSize = 4096;
_dummy = sizeof (sockaddr_in);
_sendLimit = 0xffffffff;
SANITY_INPUT_BUFFER;
TRACK_IOBUFFER_CONSTRUCTOR(this);
}
IOBuffer::~IOBuffer() {
SANITY_INPUT_BUFFER;
Cleanup();
SANITY_INPUT_BUFFER;
TRACK_IOBUFFER_DESTRUCTOR(this);
}
void IOBuffer::Initialize(uint32_t expected) {
if ((_pBuffer != NULL) ||
(_size != 0) ||
(_published != 0) ||
(_consumed != 0))
ASSERT("This buffer was used before. Please initialize it before using");
EnsureSize(expected);
}
bool IOBuffer::ReadFromTCPFd(int32_t fd, uint32_t expected, int32_t &recvAmount, int &err) {
SANITY_INPUT_BUFFER;
if (expected == 0) {
err = SOCKERROR_ECONNRESET;
SANITY_INPUT_BUFFER;
return false;
}
if (_published + expected > _size) {
if (!EnsureSize(expected)) {
SANITY_INPUT_BUFFER;
return false;
}
}
recvAmount = recv(fd, (char *) (_pBuffer + _published), expected, MSG_NOSIGNAL);
if (recvAmount > 0) {
_published += (uint32_t) recvAmount;
SANITY_INPUT_BUFFER;
return true;
} else {
err = recvAmount == 0 ? SOCKERROR_ECONNRESET : LASTSOCKETERROR;
if ((err != SOCKERROR_EAGAIN)&&(err != SOCKERROR_EINPROGRESS)) {
SANITY_INPUT_BUFFER;
return false;
}
return true;
}
}
bool IOBuffer::ReadFromUDPFd(int32_t fd, int32_t &recvAmount, sockaddr_in &peerAddress) {
SANITY_INPUT_BUFFER;
if (_published + 65536 > _size) {
if (!EnsureSize(65536)) {
SANITY_INPUT_BUFFER;
return false;
}
}
recvAmount = recvfrom(fd, (char *) (_pBuffer + _published), 65536,
MSG_NOSIGNAL, (sockaddr *) & peerAddress, &_dummy);
if (recvAmount > 0) {
_published += (uint32_t) recvAmount;
SANITY_INPUT_BUFFER;
return true;
} else {
int err = LASTSOCKETERROR;
#ifdef WIN32
if (err == SOCKERROR_ECONNRESET) {
WARN("Windows is stupid enough to issue a CONNRESET on a UDP socket. See http://support.microsoft.com/?kbid=263823 for details");
SANITY_INPUT_BUFFER;
return true;
}
#endif /* WIN32 */
FATAL("Unable to read data from UDP socket. Error was: %d", err);
SANITY_INPUT_BUFFER;
return false;
}
}
bool IOBuffer::ReadFromStdio(int32_t fd, uint32_t expected, int32_t &recvAmount) {
SANITY_INPUT_BUFFER;
if (_published + expected > _size) {
if (!EnsureSize(expected)) {
SANITY_INPUT_BUFFER;
return false;
}
}
recvAmount = READ_FD(fd, (char *) (_pBuffer + _published), expected);
if (recvAmount > 0) {
_published += (uint32_t) recvAmount;
SANITY_INPUT_BUFFER;
return true;
} else {
SANITY_INPUT_BUFFER;
return false;
}
}
bool IOBuffer::ReadFromFs(File &file, uint32_t size) {
SANITY_INPUT_BUFFER;
if (size == 0) {
SANITY_INPUT_BUFFER;
return true;
}
if (_published + size > _size) {
if (!EnsureSize(size)) {
SANITY_INPUT_BUFFER;
return false;
}
}
if (!file.ReadBuffer(_pBuffer + _published, size)) {
SANITY_INPUT_BUFFER;
return false;
}
_published += size;
SANITY_INPUT_BUFFER;
return true;
}
#ifdef HAS_MMAP
bool IOBuffer::ReadFromFs(MmapFile &file, uint32_t size) {
SANITY_INPUT_BUFFER;
if (size == 0) {
SANITY_INPUT_BUFFER;
return true;
}
if (_published + size > _size) {
if (!EnsureSize(size)) {
SANITY_INPUT_BUFFER;
return false;
}
}
if (!file.ReadBuffer(_pBuffer + _published, size)) {
SANITY_INPUT_BUFFER;
return false;
}
_published += size;
SANITY_INPUT_BUFFER;
return true;
}
#endif /* HAS_MMAP */
bool IOBuffer::ReadFromBuffer(const uint8_t *pBuffer, const uint32_t size) {
SANITY_INPUT_BUFFER;
if (!EnsureSize(size)) {
SANITY_INPUT_BUFFER;
return false;
}
memcpy(_pBuffer + _published, pBuffer, size);
TRACK_IOBUFFER_MEMCPY(size, this);
_published += size;
SANITY_INPUT_BUFFER;
return true;
}
void IOBuffer::ReadFromInputBuffer(IOBuffer *pInputBuffer, uint32_t start, uint32_t size) {
SANITY_INPUT_BUFFER;
ReadFromBuffer(GETIBPOINTER(*pInputBuffer) + start, size);
SANITY_INPUT_BUFFER;
}
bool IOBuffer::ReadFromInputBuffer(const IOBuffer &buffer, uint32_t size) {
SANITY_INPUT_BUFFER;
if (!ReadFromBuffer(buffer._pBuffer + buffer._consumed, size)) {
SANITY_INPUT_BUFFER;
return false;
}
SANITY_INPUT_BUFFER;
return true;
}
bool IOBuffer::ReadFromInputBufferWithIgnore(IOBuffer &src) {
SANITY_INPUT_BUFFER;
if (((_published - _consumed) == 0)
&&((src._published - src._consumed) != 0)
&&(_sendLimit == 0xffffffff)
&&(src._sendLimit == 0xffffffff)
) {
//this is the ideal case in which "this" (the destiantion) doesn't
//have anything inside it and bot the source and the destination
//don't have any send limit. We just swap the guts
uint8_t *_pTempBuffer = src._pBuffer;
src._pBuffer = _pBuffer;
_pBuffer = _pTempBuffer;
uint32_t _tempSize = src._size;
src._size = _size;
_size = _tempSize;
uint32_t _tempPublished = src._published;
src._published = _published;
_published = _tempPublished;
uint32_t _tempConsumed = src._consumed;
src._consumed = _consumed;
_consumed = _tempConsumed;
SANITY_INPUT_BUFFER;
TRACK_SMART_COPY(this, true);
return true;
} else {
//here we have either some bytes in the destination (this) or the source
//has a send limit. We just copy the data and than call ignore
//on the source which MUST take care of _sendLimit accordingly
if ((src._published == src._consumed) || (src._sendLimit == 0)) {
SANITY_INPUT_BUFFER;
return true;
}
uint32_t ceil = min(GETAVAILABLEBYTESCOUNT(src), GETIBSENDLIMIT(src));
if (!ReadFromBuffer(GETIBPOINTER(src), ceil)) {
FATAL("Unable to copy data");
SANITY_INPUT_BUFFER;
return false;
}
if (!src.Ignore(ceil)) {
FATAL("Unable to ignore data");
SANITY_INPUT_BUFFER;
return false;
}
SANITY_INPUT_BUFFER;
TRACK_SMART_COPY(this, false);
return true;
}
}
bool IOBuffer::ReadFromString(string binary) {
SANITY_INPUT_BUFFER;
if (!ReadFromBuffer((uint8_t *) binary.data(), (uint32_t) binary.length())) {
SANITY_INPUT_BUFFER;
return false;
}
SANITY_INPUT_BUFFER;
return true;
}
void IOBuffer::ReadFromByte(uint8_t byte) {
SANITY_INPUT_BUFFER;
EnsureSize(1);
_pBuffer[_published] = byte;
_published++;
SANITY_INPUT_BUFFER;
}
bool IOBuffer::ReadFromBIO(BIO *pBIO) {
SANITY_INPUT_BUFFER;
if (pBIO == NULL) {
SANITY_INPUT_BUFFER;
return true;
}
int32_t bioAvailable = BIO_pending(pBIO);
if (bioAvailable < 0) {
FATAL("BIO_pending failed");
SANITY_INPUT_BUFFER;
return false;
}
if (bioAvailable == 0) {
SANITY_INPUT_BUFFER;
return true;
}
EnsureSize((uint32_t) bioAvailable);
int32_t written = BIO_read(pBIO, _pBuffer + _published, bioAvailable);
_published += written;
SANITY_INPUT_BUFFER;
return true;
}
void IOBuffer::ReadFromRepeat(uint8_t byte, uint32_t size) {
SANITY_INPUT_BUFFER;
EnsureSize(size);
memset(_pBuffer + _published, byte, size);
_published += size;
SANITY_INPUT_BUFFER;
}
bool IOBuffer::WriteToTCPFd(int32_t fd, uint32_t size, int32_t &sentAmount, int &err) {
SANITY_INPUT_BUFFER;
bool result = true;
if (_sendLimit != 0xffffffff) {
size = size > _sendLimit ? _sendLimit : size;
}
if (size == 0)
return true;
sentAmount = send(fd, (char *) (_pBuffer + _consumed),
//_published - _consumed,
size > _published - _consumed ? _published - _consumed : size,
MSG_NOSIGNAL);
if (sentAmount < 0) {
err = LASTSOCKETERROR;
if ((err != SOCKERROR_EAGAIN)&&(err != SOCKERROR_EINPROGRESS)) {
FATAL("Unable to send %"PRIu32" bytes of data data. Size advertised by network layer was %"PRIu32". Permanent error (%d): %s",
_published - _consumed, size, err, strerror(err));
result = false;
}
} else {
_consumed += sentAmount;
if (_sendLimit != 0xffffffff)
_sendLimit -= sentAmount;
}
if (result)
Recycle();
SANITY_INPUT_BUFFER;
return result;
}
bool IOBuffer::WriteToStdio(int32_t fd, uint32_t size, int32_t &sentAmount) {
SANITY_INPUT_BUFFER;
bool result = true;
sentAmount = WRITE_FD(fd, (char *) (_pBuffer + _consumed),
_published - _consumed);
//size > _published - _consumed ? _published - _consumed : size,
int err = errno;
if (sentAmount < 0) {
FATAL("Unable to send %"PRIu32" bytes of data data. Size advertised by network layer was %"PRIu32". Permanent error: (%d) %s",
_published - _consumed, size, err, strerror(err));
result = false;
} else {
_consumed += sentAmount;
}
if (result)
Recycle();
SANITY_INPUT_BUFFER;
return result;
}
uint32_t IOBuffer::GetMinChunkSize() {
return _minChunkSize;
}
void IOBuffer::SetMinChunkSize(uint32_t minChunkSize) {
o_assert(minChunkSize > 0 && minChunkSize < 16 * 1024 * 1024);
_minChunkSize = minChunkSize;
}
uint32_t IOBuffer::GetCurrentWritePosition() {
return _published;
}
uint8_t *IOBuffer::GetPointer() {
return _pBuffer;
}
bool IOBuffer::Ignore(uint32_t size) {
SANITY_INPUT_BUFFER;
_consumed += size;
if (_sendLimit != 0xffffffff)
_sendLimit -= size;
Recycle();
SANITY_INPUT_BUFFER;
return true;
}
bool IOBuffer::IgnoreAll() {
SANITY_INPUT_BUFFER;
_consumed = _published;
_sendLimit = 0xffffffff;
Recycle();
SANITY_INPUT_BUFFER;
return true;
}
bool IOBuffer::MoveData() {
SANITY_INPUT_BUFFER;
if (_published - _consumed <= _consumed) {
memcpy(_pBuffer, _pBuffer + _consumed, _published - _consumed);
TRACK_IOBUFFER_MEMCPY(_published - _consumed, this);
_published = _published - _consumed;
_consumed = 0;
}
SANITY_INPUT_BUFFER;
return true;
}
#define OUTSTANDING (_published - _consumed)
#define AVAILABLE (_size - _published)
#define TOTAL_AVAILABLE (AVAILABLE+_consumed)
#define NEEDED (OUTSTANDING + expected)
bool IOBuffer::EnsureSize(uint32_t expected) {
SANITY_INPUT_BUFFER;
//1. Is the trailing free space enough?
if (AVAILABLE >= expected) {
SANITY_INPUT_BUFFER;
return true;
}
//2. Is the total free space enough?
if (TOTAL_AVAILABLE >= expected) {
//3. Yes, move data to consolidate free space
MoveData();
//4. Is the consolidated free space enough this time? (should be)
if (AVAILABLE >= expected) {
SANITY_INPUT_BUFFER;
return true;
}
}
//5. Nope! So, let's get busy with making a brand new buffer...
//We are going to make the buffer at least 1.3*_size and make sure
//is not lower than _minChunkSize
if (NEEDED < (_size * 1.3)) {
expected = (uint32_t) (_size * 1.3) - OUTSTANDING;
}
if (NEEDED < _minChunkSize) {
expected = _minChunkSize - OUTSTANDING;
}
//6. Allocate the required memory
uint8_t *pTempBuffer = new uint8_t[NEEDED];
TRACK_NEW(NEEDED, this);
//7. Copy existing data if necessary and switch buffers
if (_pBuffer != NULL) {
memcpy(pTempBuffer, _pBuffer + _consumed, OUTSTANDING);
TRACK_IOBUFFER_MEMCPY(OUTSTANDING, this);
delete[] _pBuffer;
TRACK_DELETE(_size, this);
}
_pBuffer = pTempBuffer;
//8. Update the size & indices
_size = NEEDED;
_published = OUTSTANDING;
_consumed = 0;
SANITY_INPUT_BUFFER;
return true;
}
string IOBuffer::DumpBuffer(const uint8_t *pBuffer, uint32_t length) {
IOBuffer temp;
temp.ReadFromBuffer(pBuffer, length);
return temp.ToString();
}
string IOBuffer::DumpBuffer(MSGHDR &message, uint32_t limit) {
IOBuffer temp;
for (MSGHDR_MSG_IOVLEN_TYPE i = 0; i < message.MSGHDR_MSG_IOVLEN; i++) {
temp.ReadFromBuffer((uint8_t *) message.MSGHDR_MSG_IOV[i].IOVEC_IOV_BASE,
message.MSGHDR_MSG_IOV[i].IOVEC_IOV_LEN);
}
return temp.ToString(0, limit);
}
string IOBuffer::ToString(uint32_t startIndex, uint32_t limit) {
SANITY_INPUT_BUFFER;
string allowedCharacters = " 1234567890-=qwertyuiop[]asdfghjkl;'\\`zxcvbnm";
allowedCharacters += ",./!@#$%^&*()_+QWERTYUIOP{}ASDFGHJKL:\"|~ZXCVBNM<>?";
stringstream ss;
ss << "Size: " << _size << endl;
ss << "Published: " << _published << endl;
ss << "Consumed: " << _consumed << endl;
if (_sendLimit == 0xffffffff)
ss << "Send limit: unlimited" << endl;
else
ss << "Send limit: " << _sendLimit << endl;
ss << format("Address: %p", _pBuffer) << endl;
if (limit != 0) {
ss << format("Limited to %u bytes", limit) << endl;
}
string address = "";
string part1 = "";
string part2 = "";
string hr = "";
limit = (limit == 0) ? _published : limit;
for (uint32_t i = startIndex; i < limit; i++) {
if (((i % 16) == 0) && (i > 0)) {
ss << address << " " << part1 << " " << part2 << " " << hr << endl;
part1 = "";
part2 = "";
hr = "";
}
address = format("%08u", i - (i % 16));
if ((i % 16) < 8) {
part1 += format("%02hhx", _pBuffer[i]);
part1 += " ";
} else {
part2 += format("%02hhx", _pBuffer[i]);
part2 += " ";
}
if (allowedCharacters.find(_pBuffer[i], 0) != string::npos)
hr += _pBuffer[i];
else
hr += '.';
}
if (part1 != "") {
part1 += string(24 - part1.size(), ' ');
part2 += string(24 - part2.size(), ' ');
hr += string(16 - hr.size(), ' ');
ss << address << " " << part1 << " " << part2 << " " << hr << endl;
}
SANITY_INPUT_BUFFER;
return ss.str();
}
IOBuffer::operator string() {
return ToString(0, 0);
}
void IOBuffer::ReleaseDoublePointer(char ***pppPointer) {
char **ppPointer = *pppPointer;
if (ppPointer == NULL)
return;
for (uint32_t i = 0;; i++) {
if (ppPointer[i] == NULL)
break;
delete[] ppPointer[i];
ppPointer[i] = NULL;
}
delete[] ppPointer;
ppPointer = NULL;
*pppPointer = NULL;
}
void IOBuffer::Cleanup() {
if (_pBuffer != NULL) {
delete[] _pBuffer;
TRACK_DELETE(_size, this);
_pBuffer = NULL;
}
_size = 0;
_published = 0;
_consumed = 0;
}
void IOBuffer::Recycle() {
if (_consumed != _published)
return;
SANITY_INPUT_BUFFER;
_consumed = 0;
_published = 0;
SANITY_INPUT_BUFFER;
}
| 19,171
|
C++
|
.cpp
| 663
| 26.502262
| 201
| 0.694098
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,350
|
timersmanager.cpp
|
shiretu_crtmpserver/sources/common/src/utils/misc/timersmanager.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils/misc/timersmanager.h"
#include "utils/logging/logging.h"
TimerEvent::operator string() {
return format("id: %4"PRIu32"; period: %6"PRIu32"; nextRun: %"PRIu64,
id, period, triggerTime);
}
TimersManager::TimersManager(ProcessTimerEvent processTimerEvent) {
_processTimerEvent = processTimerEvent;
_lastTime = 0;
_currentTime = 0;
_processResult = false;
_processing = false;
}
TimersManager::~TimersManager() {
map<uint64_t, map<uint32_t, TimerEvent *> >::iterator i;
for (i = _timers.begin(); i != _timers.end(); i++) {
FOR_MAP(MAP_VAL(i), uint32_t, TimerEvent *, j) {
delete MAP_VAL(j);
}
}
_timers.clear();
}
void TimersManager::AddTimer(TimerEvent &evt) {
TimerEvent *pTemp = new TimerEvent;
memcpy(pTemp, &evt, sizeof (TimerEvent));
GETMILLISECONDS(_currentTime);
pTemp->triggerTime = _currentTime + pTemp->period;
_timers[pTemp->triggerTime][pTemp->id] = pTemp;
}
void TimersManager::RemoveTimer(uint32_t eventTimerId) {
map<uint64_t, map<uint32_t, TimerEvent *> >::iterator i;
for (i = _timers.begin(); i != _timers.end(); i++) {
map<uint32_t, TimerEvent *>::iterator found = MAP_VAL(i).find(eventTimerId);
if (found != MAP_VAL(i).end()) {
TimerEvent *pTemp = MAP_VAL(found);
if (pTemp != NULL) {
delete pTemp;
}
if (_processing) {
MAP_VAL(i)[eventTimerId] = NULL;
} else {
MAP_VAL(i).erase(found);
if (MAP_VAL(i).size() == 0)
_timers.erase(MAP_KEY(i));
}
return;
}
}
}
int32_t TimersManager::TimeElapsed() {
_processing = true;
int32_t result = 1000;
GETMILLISECONDS(_currentTime);
if (_lastTime > _currentTime) {
WARN("Clock skew detected. Re-adjusting the timers");
_lastTime = _currentTime;
map<uint64_t, map<uint32_t, TimerEvent *> > timers;
map<uint64_t, map<uint32_t, TimerEvent *> >::iterator i;
for (i = _timers.begin(); i != _timers.end(); i++) {
FOR_MAP(MAP_VAL(i), uint32_t, TimerEvent *, j) {
TimerEvent *pTemp = MAP_VAL(j);
if (pTemp != NULL) {
pTemp->triggerTime = _currentTime + pTemp->period;
timers[pTemp->triggerTime][pTemp->id] = pTemp;
}
}
}
_timers = timers;
return 1;
}
_lastTime = _currentTime;
_processResult = false;
map<uint64_t, map<uint32_t, TimerEvent *> >::iterator i = _timers.begin();
while (i != _timers.end()) {
if (MAP_KEY(i) > _currentTime) {
result = (int32_t) (MAP_KEY(i) - _currentTime);
break;
}
FOR_MAP(MAP_VAL(i), uint32_t, TimerEvent *, j) {
TimerEvent *pTemp = MAP_VAL(j);
if (pTemp != NULL) {
_processResult = _processTimerEvent(*pTemp);
if (_processResult) {
pTemp->triggerTime += pTemp->period;
_timers[pTemp->triggerTime][pTemp->id] = pTemp;
} else {
pTemp = MAP_VAL(j);
MAP_VAL(i)[MAP_KEY(j)] = NULL;
if (pTemp != NULL) {
delete pTemp;
}
}
}
}
_timers.erase(i);
i = _timers.begin();
}
_processing = false;
return result;
}
string TimersManager::DumpTimers() {
string result = "";
map<uint64_t, map<uint32_t, TimerEvent *> >::iterator i;
for (i = _timers.begin(); i != _timers.end(); i++) {
result += format("%"PRIu64"\n", MAP_KEY(i));
FOR_MAP(MAP_VAL(i), uint32_t, TimerEvent *, j) {
if (MAP_VAL(j) != NULL)
result += "\t" + MAP_VAL(j)->operator string() + "\n";
else
result += format("\tid: %4"PRIu32"; NULL\n", MAP_KEY(j));
}
if (MAP_VAL(i).size() == 0)
result += "\n";
}
return result;
}
| 4,191
|
C++
|
.cpp
| 134
| 28.238806
| 78
| 0.658832
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,351
|
format.cpp
|
shiretu_crtmpserver/sources/common/src/utils/misc/format.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common.h"
string format(const char *pFormat, ...) {
char *pBuffer = NULL;
va_list arguments;
va_start(arguments, pFormat);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif /* __clang__ */
if (vasprintf(&pBuffer, pFormat, arguments) == -1) {
va_end(arguments);
o_assert(false);
return "";
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif /* __clang__ */
va_end(arguments);
string result;
if (pBuffer != NULL) {
result = pBuffer;
free(pBuffer);
}
return result;
}
string vFormat(const char *pFormat, va_list args) {
char *pBuffer = NULL;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif /* __clang__ */
if (vasprintf(&pBuffer, pFormat, args) == -1) {
o_assert(false);
return "";
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif /* __clang__ */
string result;
if (pBuffer != NULL) {
result = pBuffer;
free(pBuffer);
}
return result;
}
| 1,785
|
C++
|
.cpp
| 63
| 26.460317
| 72
| 0.716114
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
750,352
|
file.cpp
|
shiretu_crtmpserver/sources/common/src/utils/misc/file.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils/buffering/iobuffer.h"
#include "utils/logging/logging.h"
File::File() {
_path = "";
_truncate = false;
_append = false;
_pFile = NULL;
_suppressLogErrorsOnInit = false;
}
File::~File() {
Close();
}
void File::SuppressLogErrorsOnInit() {
_suppressLogErrorsOnInit = true;
}
bool File::Initialize(string path) {
return Initialize(path, FILE_OPEN_MODE_READ);
}
bool File::Initialize(string path, FILE_OPEN_MODE mode) {
Close();
_path = path;
string openMode = "";
switch (mode) {
case FILE_OPEN_MODE_READ:
{
openMode = "rb";
break;
}
case FILE_OPEN_MODE_WRITE:
{
openMode = "r+b";
break;
}
case FILE_OPEN_MODE_TRUNCATE:
{
openMode = "w+b";
break;
}
case FILE_OPEN_MODE_APPEND:
{
openMode = "a+b";
break;
}
default:
{
FATAL("Invalid open mode");
return false;
}
}
_pFile = fopen(STR(_path), STR(openMode)); //NOINHERIT
if (_pFile == NULL) {
int err = errno;
if (!_suppressLogErrorsOnInit)
FATAL("Unable to open file %s with mode `%s`. Error was: (%d) %s",
STR(_path), STR(openMode), err, strerror(err));
return false;
}
if (!SeekEnd())
return false;
_size = ftell64(_pFile);
if (!SeekBegin())
return false;
return true;
}
void File::Close() {
if (_pFile != NULL) {
fflush(_pFile);
fclose(_pFile);
_pFile = NULL;
}
_size = 0;
_path = "";
_truncate = false;
_append = false;
}
uint64_t File::Size() {
if (_pFile == NULL) {
WARN("File not opened");
return 0;
}
return _size;
}
uint64_t File::Cursor() {
if (_pFile == NULL) {
WARN("File not opened");
return 0;
}
return (uint64_t) ftell64(_pFile);
}
bool File::IsEOF() {
if (_pFile == NULL) {
WARN("File not opened");
return true;
}
return (feof(_pFile) != 0);
}
string File::GetPath() {
return _path;
}
bool File::IsOpen() {
if (_pFile == NULL)
return false;
return (ferror(_pFile) == 0);
}
bool File::SeekBegin() {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
if (fseek64(_pFile, 0, SEEK_SET) != 0) {
FATAL("Unable to seek to the beginning of file");
return false;
}
return true;
}
bool File::SeekEnd() {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
if (fseek64(_pFile, 0, SEEK_END) != 0) {
FATAL("Unable to seek to the end of file");
return false;
}
return true;
}
bool File::SeekAhead(int64_t count) {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
if (count < 0) {
FATAL("Invalid count");
return false;
}
if (count + Cursor() > _size) {
FATAL("End of file will be reached");
return false;
}
if (fseek64(_pFile, (PIOFFT) count, SEEK_CUR) != 0) {
FATAL("Unable to seek ahead %"PRId64" bytes", count);
return false;
}
return true;
}
bool File::SeekBehind(int64_t count) {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
if (count < 0) {
FATAL("Invalid count");
return false;
}
if (Cursor() < (uint64_t) count) {
FATAL("End of file will be reached");
return false;
}
if (fseek64(_pFile, (PIOFFT) (-1 * count), SEEK_CUR) != 0) {
FATAL("Unable to seek behind %"PRId64" bytes", count);
return false;
}
return true;
}
bool File::SeekTo(uint64_t position) {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
if (_size < position) {
FATAL("End of file will be reached");
return false;
}
if (fseek64(_pFile, (PIOFFT) position, SEEK_SET) != 0) {
FATAL("Unable to seek to position %"PRIu64, position);
return false;
}
return true;
}
bool File::ReadI8(int8_t *pValue) {
return ReadBuffer((uint8_t *) pValue, 1);
}
bool File::ReadI16(int16_t *pValue, bool networkOrder) {
if (!ReadBuffer((uint8_t *) pValue, 2))
return false;
if (networkOrder)
*pValue = ENTOHS(*pValue); //----MARKED-SHORT----
return true;
}
bool File::ReadI24(int32_t *pValue, bool networkOrder) {
*pValue = 0;
if (!ReadBuffer((uint8_t *) pValue, 3))
return false;
if (networkOrder)
*pValue = ENTOHL(*pValue) >> 8; //----MARKED-LONG---
else
*pValue = ((*pValue) << 8) >> 8;
return true;
}
bool File::ReadI32(int32_t *pValue, bool networkOrder) {
if (!ReadBuffer((uint8_t *) pValue, 4))
return false;
if (networkOrder)
*pValue = ENTOHL(*pValue); //----MARKED-LONG---
return true;
}
bool File::ReadSI32(int32_t *pValue) {
if (!ReadI32(pValue, false))
return false;
*pValue = ENTOHA(*pValue); //----MARKED-LONG---
return true;
}
bool File::ReadI64(int64_t *pValue, bool networkOrder) {
if (!ReadBuffer((uint8_t *) pValue, 8))
return false;
if (networkOrder)
*pValue = ENTOHLL(*pValue);
return true;
}
bool File::ReadUI8(uint8_t *pValue) {
return ReadI8((int8_t *) pValue);
}
bool File::ReadUI16(uint16_t *pValue, bool networkOrder) {
return ReadI16((int16_t *) pValue, networkOrder);
}
bool File::ReadUI24(uint32_t *pValue, bool networkOrder) {
return ReadI24((int32_t *) pValue, networkOrder);
}
bool File::ReadUI32(uint32_t *pValue, bool networkOrder) {
return ReadI32((int32_t *) pValue, networkOrder);
}
bool File::ReadSUI32(uint32_t *pValue) {
return ReadSI32((int32_t *) pValue);
}
bool File::ReadUI64(uint64_t *pValue, bool networkOrder) {
return ReadI64((int64_t *) pValue, networkOrder);
}
bool File::ReadBuffer(uint8_t *pBuffer, uint64_t count) {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
if (count == 0)
return true;
if (count > 0xffffffffLL) {
FATAL("Can't read more than 4GB of data at once");
return false;
}
if (fread(pBuffer, (uint32_t) count, 1, _pFile) != 1) {
int err = errno;
FATAL("Unable to read %"PRIu64" bytes from the file. Cursor: %"PRIu64" (0x%"PRIx64"); (%d) %s",
count, Cursor(), Cursor(), err, strerror(err));
return false;
}
return true;
}
bool File::ReadAll(string &str) {
str = "";
if (Size() >= 0xffffffff) {
FATAL("ReadAll can only be done on files smaller than 2^32 bytes (4GB)");
return false;
}
if (Size() == 0) {
return true;
}
if (!SeekBegin()) {
FATAL("Unable to seek to begin");
return false;
}
uint8_t *pBuffer = new uint8_t[(uint32_t) Size()];
if (!ReadBuffer(pBuffer, Size())) {
FATAL("Unable to read data");
delete[] pBuffer;
return false;
}
str = string((char *) pBuffer, (uint32_t) Size());
delete[] pBuffer;
return true;
}
bool File::PeekI8(int8_t *pValue) {
if (!ReadI8(pValue))
return false;
return SeekBehind(1);
}
bool File::PeekI16(int16_t *pValue, bool networkOrder) {
if (!ReadI16(pValue, networkOrder))
return false;
return SeekBehind(2);
}
bool File::PeekI24(int32_t *pValue, bool networkOrder) {
if (!ReadI24(pValue, networkOrder))
return false;
return SeekBehind(3);
}
bool File::PeekI32(int32_t *pValue, bool networkOrder) {
if (!ReadI32(pValue, networkOrder))
return false;
return SeekBehind(4);
}
bool File::PeekSI32(int32_t *pValue) {
if (!ReadSI32(pValue))
return false;
return SeekBehind(4);
}
bool File::PeekI64(int64_t *pValue, bool networkOrder) {
if (!ReadI64(pValue, networkOrder))
return false;
return SeekBehind(8);
}
bool File::PeekUI8(uint8_t *pValue) {
return PeekI8((int8_t *) pValue);
}
bool File::PeekUI16(uint16_t *pValue, bool networkOrder) {
return PeekI16((int16_t *) pValue, networkOrder);
}
bool File::PeekUI24(uint32_t *pValue, bool networkOrder) {
return PeekI24((int32_t *) pValue, networkOrder);
}
bool File::PeekUI32(uint32_t *pValue, bool networkOrder) {
return PeekI32((int32_t *) pValue, networkOrder);
}
bool File::PeekSUI32(uint32_t *pValue) {
return PeekSI32((int32_t *) pValue);
}
bool File::PeekUI64(uint64_t *pValue, bool networkOrder) {
return PeekI64((int64_t *) pValue, networkOrder);
}
bool File::PeekBuffer(uint8_t *pBuffer, uint64_t count) {
if (!ReadBuffer(pBuffer, count))
return false;
return SeekBehind(count);
}
bool File::WriteI8(int8_t value) {
return WriteBuffer((uint8_t *) & value, 1);
}
bool File::WriteI16(int16_t value, bool networkOrder) {
if (networkOrder)
value = EHTONS(value); //----MARKED-SHORT----
return WriteBuffer((uint8_t *) & value, 2);
}
bool File::WriteI24(int32_t value, bool networkOrder) {
if (networkOrder)
value = EHTONL(value << 8);
return WriteBuffer((uint8_t *) & value, 3);
}
bool File::WriteI32(int32_t value, bool networkOrder) {
if (networkOrder)
value = EHTONL(value);
return WriteBuffer((uint8_t *) & value, 4);
}
bool File::WriteSI32(int32_t value) {
if (!WriteI24(value, true))
return false;
if (!WriteI8(value >> 24))
return false;
return true;
}
bool File::WriteI64(int64_t value, bool networkOrder) {
if (networkOrder)
value = EHTONLL(value);
return WriteBuffer((uint8_t *) & value, 8);
}
bool File::WriteUI8(uint8_t value) {
return WriteI8((int8_t) value);
}
bool File::WriteUI16(uint16_t value, bool networkOrder) {
return WriteI16((int16_t) value, networkOrder);
}
bool File::WriteUI24(uint32_t value, bool networkOrder) {
return WriteI24((int32_t) value, networkOrder);
}
bool File::WriteUI32(uint32_t value, bool networkOrder) {
return WriteI32((int32_t) value, networkOrder);
}
bool File::WriteSUI32(uint32_t value) {
return WriteSI32((int32_t) value);
}
bool File::WriteUI64(uint64_t value, bool networkOrder) {
return WriteI64((int64_t) value, networkOrder);
}
bool File::WriteString(string &value) {
return WriteBuffer((uint8_t *) STR(value), value.length());
}
bool File::WriteBuffer(const uint8_t *pBuffer, uint64_t count) {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
if (count == 0)
return true;
if (count > 0xffffffffLL) {
FATAL("Can't write more than 4GB of data at once");
return false;
}
if (fwrite(pBuffer, (uint32_t) count, 1, _pFile) != 1) {
FATAL("Unable to write %"PRIu64" bytes to file", count);
return false;
}
_size += count;
return true;
}
bool File::Flush() {
if (_pFile == NULL) {
FATAL("File not opened");
return false;
}
fflush(_pFile);
return IsOpen();
}
| 10,654
|
C++
|
.cpp
| 427
| 22.728337
| 97
| 0.686669
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,358
|
syslogloglocation.cpp
|
shiretu_crtmpserver/sources/common/src/utils/logging/syslogloglocation.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_SYSLOG
#include "utils/logging/syslogloglocation.h"
#include "utils/logging/formatter.h"
#include "common.h"
#include <syslog.h>
SyslogLogLocation::SyslogLogLocation(Variant &configuration, string identifier, bool appendSourceFileLine, int32_t specificLevel)
: BaseLogLocation(configuration) {
_appendSourceFileLine = appendSourceFileLine;
_identifier = identifier;
_priorities[_FINEST_] = LOG_DEBUG;
_priorities[_FINE_] = LOG_DEBUG;
_priorities[_DEBUG_] = LOG_DEBUG;
_priorities[_INFO_] = LOG_INFO;
_priorities[_WARNING_] = LOG_WARNING;
_priorities[_ERROR_] = LOG_ERR;
_priorities[_FATAL_] = LOG_ERR;
_priorities[_PROD_ACCESS_] = LOG_ERR;
_priorities[_PROD_ERROR_] = LOG_ERR;
_specificLevel = specificLevel;
_enforceLoggerName = (_configuration[CONF_LOG_APPENDER_NAME] != "");
_pDefualtFormatter = NULL;
InitFormatters();
}
SyslogLogLocation::~SyslogLogLocation() {
if (_pDefualtFormatter != NULL) {
delete _pDefualtFormatter;
_pDefualtFormatter = NULL;
}
FOR_MAP(_formatters, string, Formatter *, i) {
delete MAP_VAL(i);
}
_formatters.clear();
}
void SyslogLogLocation::Log(int32_t level, string fileName, uint32_t lineNumber,
string functionName, string message) {
return;
}
void SyslogLogLocation::Log(int32_t level, string fileName, uint32_t lineNumber,
string functionName, Variant &le) {
if (_specificLevel != 0) {
if (_specificLevel != level) {
return;
}
} else {
if (_level < 0 || level > _level) {
return;
}
}
if (_enforceLoggerName) {
if (_configuration[CONF_LOG_APPENDER_NAME] != le["loggerName"]) {
return;
}
}
string finalMessage = ComputeMessage(le);
if (finalMessage == "")
return;
int priority = (MAP_HAS1(_priorities, level) ? _priorities[level] : LOG_DEBUG) | LOG_USER;
if (_appendSourceFileLine) {
syslog(priority, "%s %s:%"PRIu32":%s %s",
STR(le["loggerName"]),
STR(fileName),
lineNumber,
STR(functionName),
STR(finalMessage));
} else {
syslog(priority, "%s %s",
STR(le["loggerName"]),
STR(finalMessage));
}
}
void SyslogLogLocation::InitFormatters() {
if (!_configuration.HasKeyChain(V_MAP, false, 1, CONF_LOG_APPENDER_FORMAT))
return;
string defaultFormatter = "";
if (_configuration[CONF_LOG_APPENDER_FORMAT][(uint32_t) 1] == V_STRING) {
defaultFormatter = (string) _configuration[CONF_LOG_APPENDER_FORMAT][(uint32_t) 1];
}
_configuration[CONF_LOG_APPENDER_FORMAT].RemoveAt(1);
if (defaultFormatter != "") {
_pDefualtFormatter = Formatter::GetInstance(defaultFormatter);
}
FOR_MAP(_configuration[CONF_LOG_APPENDER_FORMAT], string, Variant, i) {
if ((MAP_VAL(i) != V_STRING)
|| (MAP_VAL(i) == ""))
continue;
Formatter *pTemp = Formatter::GetInstance(MAP_VAL(i));
_formatters[MAP_KEY(i)] = pTemp;
}
}
string SyslogLogLocation::ComputeMessage(Variant &le) {
Formatter *pFormatter = NULL;
if (MAP_HAS1(_formatters, (string) le["operation"]))
pFormatter = _formatters[(string) le["operation"]];
else
pFormatter = _pDefualtFormatter;
if (pFormatter == NULL)
return "";
return pFormatter->Format(le);
}
void SyslogLogLocation::SignalFork() {
}
#endif /* HAS_SYSLOG */
| 3,925
|
C++
|
.cpp
| 120
| 30.266667
| 129
| 0.721268
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,359
|
logger.cpp
|
shiretu_crtmpserver/sources/common/src/utils/logging/logger.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils/logging/logger.h"
#include "utils/logging/baseloglocation.h"
#include "version.h"
Logger *Logger::_pLogger = NULL;
string Version::GetBuildNumber() {
#ifdef CRTMPSERVER_VERSION_BUILD_NUMBER
return CRTMPSERVER_VERSION_BUILD_NUMBER;
#else /* CRTMPSERVER_VERSION_BUILD_NUMBER */
return "";
#endif /* CRTMPSERVER_VERSION_BUILD_NUMBER */
}
uint64_t Version::GetBuildDate() {
#ifdef CRTMPSERVER_VERSION_BUILD_DATE
return CRTMPSERVER_VERSION_BUILD_DATE;
#else /* CRTMPSERVER_VERSION_BUILD_DATE */
return 0;
#endif /* CRTMPSERVER_VERSION_BUILD_DATE */
}
string Version::GetBuildDateString() {
time_t buildDate = (time_t) GetBuildDate();
if (buildDate == 0) {
return "";
}
Timestamp *pTs = gmtime(&buildDate);
Variant v(*pTs);
return (string) v;
}
string Version::GetReleaseNumber() {
#ifdef CRTMPSERVER_VERSION_RELEASE_NUMBER
return CRTMPSERVER_VERSION_RELEASE_NUMBER;
#else /* CRTMPSERVER_VERSION_RELEASE_NUMBER */
return "";
#endif /* CRTMPSERVER_VERSION_RELEASE_NUMBER */
}
string Version::GetCodeName() {
#ifdef CRTMPSERVER_VERSION_CODE_NAME
return CRTMPSERVER_VERSION_CODE_NAME;
#else /* CRTMPSERVER_VERSION_CODE_NAME */
return "";
#endif /* CRTMPSERVER_VERSION_CODE_NAME */
}
string Version::GetBuilderOSName() {
#ifdef CRTMPSERVER_VERSION_BUILDER_OS_NAME
return CRTMPSERVER_VERSION_BUILDER_OS_NAME;
#else /* CRTMPSERVER_VERSION_BUILDER_OS_NAME */
return "";
#endif /* CRTMPSERVER_VERSION_BUILDER_OS_NAME */
}
string Version::GetBuilderOSVersion() {
#ifdef CRTMPSERVER_VERSION_BUILDER_OS_VERSION
return CRTMPSERVER_VERSION_BUILDER_OS_VERSION;
#else /* CRTMPSERVER_VERSION_BUILDER_OS_VERSION */
return "";
#endif /* CRTMPSERVER_VERSION_BUILDER_OS_VERSION */
}
string Version::GetBuilderOSArch() {
#ifdef CRTMPSERVER_VERSION_BUILDER_OS_ARCH
return CRTMPSERVER_VERSION_BUILDER_OS_ARCH;
#else /* CRTMPSERVER_VERSION_BUILDER_OS_ARCH */
return "";
#endif /* CRTMPSERVER_VERSION_BUILDER_OS_ARCH */
}
string Version::GetBuilderOSUname() {
#ifdef CRTMPSERVER_VERSION_BUILDER_OS_UNAME
return CRTMPSERVER_VERSION_BUILDER_OS_UNAME;
#else /* CRTMPSERVER_VERSION_BUILDER_OS_UNAME */
return "";
#endif /* CRTMPSERVER_VERSION_BUILDER_OS_UNAME */
}
string Version::GetBuilderOS() {
if (GetBuilderOSName() == "")
return "";
string result = GetBuilderOSName();
if (GetBuilderOSVersion() != "") {
result += "-" + GetBuilderOSVersion();
}
if (GetBuilderOSArch() != "") {
result += "-" + GetBuilderOSArch();
}
return result;
}
string Version::GetBanner() {
string result = HTTP_HEADERS_SERVER_US;
if (GetReleaseNumber() != "")
result += " version " + GetReleaseNumber();
result += " build " + GetBuildNumber();
if (GetCodeName() != "")
result += " - " + GetCodeName();
if (GetBuilderOS() != "") {
result += " - (built for " + GetBuilderOS() + " on " + GetBuildDateString() + ")";
} else {
result += " - (built on " + GetBuildDateString() + ")";
}
return result;
}
Variant Version::GetAll() {
Variant result;
result["buildNumber"] = (string) GetBuildNumber();
result["buildDate"] = (uint64_t) GetBuildDate();
result["releaseNumber"] = (string) GetReleaseNumber();
result["codeName"] = (string) GetCodeName();
result["banner"] = (string) GetBanner();
return result;
}
Variant Version::GetBuilder() {
Variant result;
result["name"] = (string) GetBuilderOSName();
result["version"] = (string) GetBuilderOSVersion();
result["arch"] = (string) GetBuilderOSArch();
result["uname"] = (string) GetBuilderOSUname();
return result;
}
#ifdef HAS_SAFE_LOGGER
pthread_mutex_t *Logger::_pMutex = NULL;
class LogLocker {
private:
pthread_mutex_t *_pMutex;
public:
LogLocker(pthread_mutex_t *pMutex) {
if (pMutex == NULL) {
printf("Logger not initialized\n");
o_assert(false);
}
_pMutex = pMutex;
if (pthread_mutex_lock(_pMutex) != 0) {
printf("Unable to lock the logger");
o_assert(false);
}
};
virtual ~LogLocker() {
if (pthread_mutex_unlock(_pMutex) != 0) {
printf("Unable to unlock the logger");
o_assert(false);
}
}
};
#define LOCK LogLocker __LogLocker__(Logger::_pMutex);
#else
#define LOCK
#endif /* HAS_SAFE_LOGGER */
Logger::Logger() {
LOCK;
_freeAppenders = false;
}
Logger::~Logger() {
LOCK;
if (_freeAppenders) {
FOR_VECTOR(_logLocations, i) {
delete _logLocations[i];
}
_logLocations.clear();
}
}
void Logger::Init() {
#ifdef HAS_SAFE_LOGGER
if (_pMutex != NULL) {
printf("logger already initialized");
o_assert(false);
}
_pMutex = new pthread_mutex_t;
if (pthread_mutex_init(_pMutex, NULL)) {
printf("Unable to init the logger mutex");
o_assert(false);
}
#else
if (_pLogger != NULL)
return;
#endif /* HAS_SAFE_LOGGER */
_pLogger = new Logger();
}
void Logger::Free(bool freeAppenders) {
LOCK;
if (_pLogger != NULL) {
_pLogger->_freeAppenders = freeAppenders;
delete _pLogger;
_pLogger = NULL;
}
}
void Logger::Log(int32_t level, const char *pFileName, uint32_t lineNumber,
const char *pFunctionName, const char *pFormatString, ...) {
LOCK;
if (_pLogger == NULL)
return;
va_list arguments;
va_start(arguments, pFormatString);
string message = vFormat(pFormatString, arguments);
va_end(arguments);
FOR_VECTOR(_pLogger->_logLocations, i) {
if (_pLogger->_logLocations[i]->EvalLogLevel(level, pFileName, lineNumber,
pFunctionName))
_pLogger->_logLocations[i]->Log(level, pFileName,
lineNumber, pFunctionName, message);
}
}
bool Logger::AddLogLocation(BaseLogLocation *pLogLocation) {
LOCK;
if (_pLogger == NULL)
return false;
if (!pLogLocation->Init())
return false;
ADD_VECTOR_END(_pLogger->_logLocations, pLogLocation);
return true;
}
void Logger::SignalFork() {
LOCK;
if (_pLogger == NULL)
return;
FOR_VECTOR(_pLogger->_logLocations, i) {
_pLogger->_logLocations[i]->SignalFork();
}
}
void Logger::SetLevel(int32_t level) {
LOCK;
if (_pLogger == NULL)
return;
FOR_VECTOR(_pLogger->_logLocations, i) {
_pLogger->_logLocations[i]->SetLevel(level);
}
}
| 6,737
|
C++
|
.cpp
| 237
| 26.405063
| 84
| 0.721707
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,363
|
baseplatform.cpp
|
shiretu_crtmpserver/sources/common/src/platform/baseplatform.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common.h"
BasePlatform::BasePlatform() {
}
BasePlatform::~BasePlatform() {
}
#if defined FREEBSD || defined LINUX || defined OSX || defined SOLARIS
void GetFinishedProcesses(vector<pid_t> &pids, bool &noMorePids) {
pids.clear();
noMorePids = false;
int statLoc = 0;
while (true) {
pid_t pid = waitpid(-1, &statLoc, WNOHANG);
if (pid < 0) {
int err = errno;
if (err != ECHILD)
WARN("waitpid failed %d %s", err, strerror(err));
noMorePids = true;
break;
}
if (pid == 0)
break;
ADD_VECTOR_END(pids, pid);
}
}
bool LaunchProcess(string fullBinaryPath, vector<string> &arguments, vector<string> &envVars, pid_t &pid) {
char **_ppArgs = NULL;
char **_ppEnv = NULL;
ADD_VECTOR_BEGIN(arguments, fullBinaryPath);
_ppArgs = new char*[arguments.size() + 1];
for (uint32_t i = 0; i < arguments.size(); i++) {
_ppArgs[i] = new char[arguments[i].size() + 1];
strcpy(_ppArgs[i], arguments[i].c_str());
}
_ppArgs[arguments.size()] = NULL;
if (envVars.size() > 0) {
_ppEnv = new char*[envVars.size() + 1];
for (uint32_t i = 0; i < envVars.size(); i++) {
_ppEnv[i] = new char[envVars[i].size() + 1];
strcpy(_ppEnv[i], envVars[i].c_str());
}
_ppEnv[envVars.size()] = NULL;
}
if (posix_spawn(&pid, STR(fullBinaryPath), NULL, NULL, _ppArgs, _ppEnv) != 0) {
int err = errno;
FATAL("posix_spawn failed %d %s", err, strerror(err));
IOBuffer::ReleaseDoublePointer(&_ppArgs);
IOBuffer::ReleaseDoublePointer(&_ppEnv);
return false;
}
IOBuffer::ReleaseDoublePointer(&_ppArgs);
IOBuffer::ReleaseDoublePointer(&_ppEnv);
return true;
}
bool setFdCloseOnExec(int fd) {
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
int err = errno;
FATAL("fcntl failed %d %s", err, strerror(err));
return false;
}
return true;
}
void killProcess(pid_t pid) {
kill(pid, SIGKILL);
}
#endif /* defined FREEBSD || defined LINUX || defined OSX || defined SOLARIS */
| 2,693
|
C++
|
.cpp
| 83
| 30.036145
| 107
| 0.687982
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,366
|
freebsdplatform.cpp
|
shiretu_crtmpserver/sources/common/src/platform/freebsd/freebsdplatform.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef FREEBSD
#include "common.h"
string alowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
static map<int, SignalFnc> _signalHandlers;
FreeBSDPlatform::FreeBSDPlatform() {
}
FreeBSDPlatform::~FreeBSDPlatform() {
}
string GetEnvVariable(const char *pEnvVarName) {
char *pTemp = getenv(pEnvVarName);
if (pTemp != NULL)
return pTemp;
return "";
}
void replace(string &target, string search, string replacement) {
if (search == replacement)
return;
if (search == "")
return;
string::size_type i = string::npos;
string::size_type lastPos = 0;
while ((i = target.find(search, lastPos)) != string::npos) {
target.replace(i, search.length(), replacement);
lastPos = i + replacement.length();
}
}
bool fileExists(string path) {
struct stat fileInfo;
if (stat(STR(path), &fileInfo) == 0) {
return true;
} else {
return false;
}
}
string lowerCase(string value) {
return changeCase(value, true);
}
string upperCase(string value) {
return changeCase(value, false);
}
string changeCase(string &value, bool lowerCase) {
string result = "";
for (string::size_type i = 0; i < value.length(); i++) {
if (lowerCase)
result += tolower(value[i]);
else
result += toupper(value[i]);
}
return result;
}
string tagToString(uint64_t tag) {
string result;
for (uint32_t i = 0; i < 8; i++) {
uint8_t v = (tag >> ((7 - i)*8)&0xff);
if (v == 0)
break;
result += (char) v;
}
return result;
}
bool setMaxFdCount(uint32_t ¤t, uint32_t &max) {
//1. reset stuff
current = 0;
max = 0;
struct rlimit limits;
memset(&limits, 0, sizeof (limits));
//2. get the current value
if (getrlimit(RLIMIT_NOFILE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
current = (uint32_t) limits.rlim_cur;
max = (uint32_t) limits.rlim_max;
//3. Set the current value to max value
limits.rlim_cur = limits.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
int err = errno;
FATAL("setrlimit failed: (%d) %s", err, strerror(err));
return false;
}
//4. Try to get it back
memset(&limits, 0, sizeof (limits));
if (getrlimit(RLIMIT_NOFILE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
current = (uint32_t) limits.rlim_cur;
max = (uint32_t) limits.rlim_max;
return true;
}
bool enableCoreDumps() {
struct rlimit limits;
memset(&limits, 0, sizeof (limits));
memset(&limits, 0, sizeof (limits));
if (getrlimit(RLIMIT_CORE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
limits.rlim_cur = limits.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &limits) != 0) {
int err = errno;
FATAL("setrlimit failed: (%d) %s", err, strerror(err));
return false;
}
memset(&limits, 0, sizeof (limits));
if (getrlimit(RLIMIT_CORE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
return limits.rlim_cur == RLIM_INFINITY;
}
bool setFdJoinMulticast(SOCKET sock, string bindIp, uint16_t bindPort, string ssmIp) {
if (ssmIp == "") {
struct ip_mreq group;
group.imr_multiaddr.s_addr = inet_addr(STR(bindIp));
group.imr_interface.s_addr = INADDR_ANY;
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char *) &group, sizeof (group)) < 0) {
int err = errno;
FATAL("Adding multicast failed. Error was: (%d) %s", err, strerror(err));
return false;
}
return true;
} else {
struct group_source_req multicast;
struct sockaddr_in *pGroup = (struct sockaddr_in*) &multicast.gsr_group;
struct sockaddr_in *pSource = (struct sockaddr_in*) &multicast.gsr_source;
memset(&multicast, 0, sizeof (multicast));
//Setup the group we want to join
pGroup->sin_family = AF_INET;
pGroup->sin_addr.s_addr = inet_addr(STR(bindIp));
pGroup->sin_port = EHTONS(bindPort);
//setup the source we want to listen
pSource->sin_family = AF_INET;
pSource->sin_addr.s_addr = inet_addr(STR(ssmIp));
if (pSource->sin_addr.s_addr == INADDR_NONE) {
FATAL("Unable to SSM on address %s", STR(ssmIp));
return false;
}
pSource->sin_port = 0;
INFO("Try to SSM on ip %s", STR(ssmIp));
if (setsockopt(sock, IPPROTO_IP, MCAST_JOIN_SOURCE_GROUP, &multicast,
sizeof (multicast)) < 0) {
int err = errno;
FATAL("Adding multicast failed. Error was: (%d) %s", err,
strerror(err));
return false;
}
return true;
}
}
bool setFdNonBlock(SOCKET fd) {
int32_t arg;
if ((arg = fcntl(fd, F_GETFL, NULL)) < 0) {
int err = errno;
FATAL("Unable to get fd flags: (%d) %s", err, strerror(err));
return false;
}
arg |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, arg) < 0) {
int err = errno;
FATAL("Unable to set fd flags: (%d) %s", err, strerror(err));
return false;
}
return true;
}
bool setFdNoSIGPIPE(SOCKET fd) {
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE,
(const char*) & one, sizeof (one)) != 0) {
FATAL("Unable to set SO_NOSIGPIPE");
return false;
}
return true;
}
bool setFdKeepAlive(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
(const char*) & one, sizeof (one)) != 0) {
FATAL("Unable to set SO_NOSIGPIPE");
return false;
}
return true;
}
bool setFdNoNagle(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
int32_t one = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) & one, sizeof (one)) != 0) {
return false;
}
return true;
}
bool setFdReuseAddress(SOCKET fd) {
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) & one, sizeof (one)) != 0) {
FATAL("Unable to reuse address");
return false;
}
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *) & one, sizeof (one)) != 0) {
FATAL("Unable to reuse port");
return false;
}
return true;
}
bool setFdTTL(SOCKET fd, uint8_t ttl) {
int temp = ttl;
if (setsockopt(fd, IPPROTO_IP, IP_TTL, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_TTL: %"PRIu8"; error was (%d) %s", ttl, err, strerror(err));
}
return true;
}
bool setFdMulticastTTL(SOCKET fd, uint8_t ttl) {
int temp = ttl;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_MULTICAST_TTL: %"PRIu8"; error was (%d) %s", ttl, err, strerror(err));
}
return true;
}
bool setFdTOS(SOCKET fd, uint8_t tos) {
int temp = tos;
if (setsockopt(fd, IPPROTO_IP, IP_TOS, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_TOS: %"PRIu8"; error was (%d) %s", tos, err, strerror(err));
}
return true;
}
int32_t __maxSndBufValUdp = 0;
int32_t __maxRcvBufValUdp = 0;
int32_t __maxSndBufValTcp = 0;
int32_t __maxRcvBufValTcp = 0;
SOCKET __maxSndBufSocket = -1;
bool DetermineMaxRcvSndBuff(int option, bool isUdp) {
int32_t &maxVal = isUdp ?
((option == SO_SNDBUF) ? __maxSndBufValUdp : __maxRcvBufValUdp)
: ((option == SO_SNDBUF) ? __maxSndBufValTcp : __maxRcvBufValTcp);
CLOSE_SOCKET(__maxSndBufSocket);
__maxSndBufSocket = -1;
__maxSndBufSocket = socket(AF_INET, isUdp ? SOCK_DGRAM : SOCK_STREAM, 0);
if (__maxSndBufSocket < 0) {
FATAL("Unable to create testing socket");
return false;
}
int32_t known = 0;
int32_t testing = 0x7fffffff;
int32_t prevTesting = testing;
// FINEST("---- isUdp: %d; option: %s ----", isUdp, (option == SO_SNDBUF ? "SO_SNDBUF" : "SO_RCVBUF"));
while (known != testing) {
// assert(known <= testing);
// assert(known <= prevTesting);
// assert(testing <= prevTesting);
// FINEST("%"PRId32" (%"PRId32") %"PRId32, known, testing, prevTesting);
if (setsockopt(__maxSndBufSocket, SOL_SOCKET, option, (const char*) & testing,
sizeof (testing)) == 0) {
known = testing;
testing = known + (prevTesting - known) / 2;
//FINEST("---------");
} else {
prevTesting = testing;
testing = known + (testing - known) / 2;
}
}
CLOSE_SOCKET(__maxSndBufSocket);
__maxSndBufSocket = -1;
maxVal = known;
// FINEST("%s maxVal: %"PRId32, (option == SO_SNDBUF ? "SO_SNDBUF" : "SO_RCVBUF"), maxVal);
return maxVal > 0;
}
bool setFdMaxSndRcvBuff(SOCKET fd, bool isUdp) {
int32_t &maxSndBufVal = isUdp ? __maxSndBufValUdp : __maxSndBufValTcp;
int32_t &maxRcvBufVal = isUdp ? __maxRcvBufValUdp : __maxRcvBufValTcp;
if (maxSndBufVal == 0) {
if (!DetermineMaxRcvSndBuff(SO_SNDBUF, isUdp)) {
FATAL("Unable to determine maximum value for SO_SNDBUF");
return false;
}
}
if (maxRcvBufVal == 0) {
if (!DetermineMaxRcvSndBuff(SO_RCVBUF, isUdp)) {
FATAL("Unable to determine maximum value for SO_SNDBUF");
return false;
}
}
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*) & maxSndBufVal,
sizeof (maxSndBufVal)) != 0) {
FATAL("Unable to set SO_SNDBUF");
return false;
}
if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*) & maxRcvBufVal,
sizeof (maxSndBufVal)) != 0) {
FATAL("Unable to set SO_RCVBUF");
return false;
}
return true;
}
bool setFdOptions(SOCKET fd, bool isUdp) {
if (!isUdp) {
if (!setFdNonBlock(fd)) {
FATAL("Unable to set non block");
return false;
}
}
if (!setFdNoSIGPIPE(fd)) {
FATAL("Unable to set no SIGPIPE");
return false;
}
if (!setFdKeepAlive(fd, isUdp)) {
FATAL("Unable to set keep alive");
return false;
}
if (!setFdNoNagle(fd, isUdp)) {
WARN("Unable to disable Nagle algorithm");
}
if (!setFdReuseAddress(fd)) {
FATAL("Unable to enable reuse address");
return false;
}
if (!setFdMaxSndRcvBuff(fd, isUdp)) {
FATAL("Unable to set max SO_SNDBUF on UDP socket");
return false;
}
return true;
}
bool deleteFile(string path) {
if (remove(STR(path)) != 0) {
FATAL("Unable to delete file `%s`", STR(path));
return false;
}
return true;
}
bool deleteFolder(string path, bool force) {
if (!force) {
return deleteFile(path);
} else {
string command = format("rm -rf %s", STR(path));
if (system(STR(command)) != 0) {
FATAL("Unable to delete folder %s", STR(path));
return false;
}
return true;
}
}
bool createFolder(string path, bool recursive) {
string command = format("mkdir %s %s",
recursive ? "-p" : "",
STR(path));
if (system(STR(command)) != 0) {
FATAL("Unable to create folder %s", STR(path));
return false;
}
return true;
}
string getHostByName(string name) {
struct hostent *pHostEnt = gethostbyname(STR(name));
if (pHostEnt == NULL)
return "";
if (pHostEnt->h_length <= 0)
return "";
string result = format("%hhu.%hhu.%hhu.%hhu",
(uint8_t) pHostEnt->h_addr_list[0][0],
(uint8_t) pHostEnt->h_addr_list[0][1],
(uint8_t) pHostEnt->h_addr_list[0][2],
(uint8_t) pHostEnt->h_addr_list[0][3]);
return result;
}
bool isNumeric(string value) {
return value == format("%d", atoi(STR(value)));
}
void split(string str, string separator, vector<string> &result) {
result.clear();
string::size_type position = str.find(separator);
string::size_type lastPosition = 0;
uint32_t separatorLength = separator.length();
while (position != str.npos) {
ADD_VECTOR_END(result, str.substr(lastPosition, position - lastPosition));
lastPosition = position + separatorLength;
position = str.find(separator, lastPosition);
}
ADD_VECTOR_END(result, str.substr(lastPosition, string::npos));
}
uint64_t getTagMask(uint64_t tag) {
uint64_t result = 0xffffffffffffffffLL;
for (int8_t i = 56; i >= 0; i -= 8) {
if (((tag >> i)&0xff) == 0)
break;
result = result >> 8;
}
return ~result;
}
string generateRandomString(uint32_t length) {
string result = "";
for (uint32_t i = 0; i < length; i++)
result += alowedCharacters[rand() % alowedCharacters.length()];
return result;
}
void lTrim(string &value) {
string::size_type i = 0;
for (i = 0; i < value.length(); i++) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(i);
}
void rTrim(string &value) {
int32_t i = 0;
for (i = (int32_t) value.length() - 1; i >= 0; i--) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(0, i + 1);
}
void trim(string &value) {
lTrim(value);
rTrim(value);
}
int8_t getCPUCount() {
NYI;
return 0;
}
map<string, string> mapping(string str, string separator1, string separator2, bool trimStrings) {
map<string, string> result;
vector<string> pairs;
split(str, separator1, pairs);
FOR_VECTOR_ITERATOR(string, pairs, i) {
if (VECTOR_VAL(i) != "") {
if (VECTOR_VAL(i).find(separator2) != string::npos) {
string key = VECTOR_VAL(i).substr(0, VECTOR_VAL(i).find(separator2));
string value = VECTOR_VAL(i).substr(VECTOR_VAL(i).find(separator2) + 1);
if (trimStrings) {
trim(key);
trim(value);
}
result[key] = value;
} else {
if (trimStrings) {
trim(VECTOR_VAL(i));
}
result[VECTOR_VAL(i)] = "";
}
}
}
return result;
}
void splitFileName(string fileName, string &name, string & extension, char separator) {
size_t dotPosition = fileName.find_last_of(separator);
if (dotPosition == string::npos) {
name = fileName;
extension = "";
return;
}
name = fileName.substr(0, dotPosition);
extension = fileName.substr(dotPosition + 1);
}
double getFileModificationDate(string path) {
struct stat s;
if (stat(STR(path), &s) != 0) {
FATAL("Unable to stat file %s", STR(path));
return 0;
}
return (double) s.st_mtimespec.tv_sec + (double) s.st_mtimespec.tv_nsec / 1000000000.0;
}
string normalizePath(string base, string file) {
char dummy1[PATH_MAX];
char dummy2[PATH_MAX];
char *pBase = realpath(STR(base), dummy1);
char *pFile = realpath(STR(base + file), dummy2);
if (pBase != NULL) {
base = pBase;
} else {
base = "";
}
if (pFile != NULL) {
file = pFile;
} else {
file = "";
}
if (file == "" || base == "") {
return "";
}
if (file.find(base) != 0) {
return "";
} else {
if (!fileExists(file)) {
return "";
} else {
return file;
}
}
}
bool listFolder(string path, vector<string> &result, bool normalizeAllPaths,
bool includeFolders, bool recursive) {
if (path == "")
path = ".";
if (path[path.size() - 1] != PATH_SEPARATOR)
path += PATH_SEPARATOR;
DIR *pDir = NULL;
pDir = opendir(STR(path));
if (pDir == NULL) {
int err = errno;
FATAL("Unable to open folder: %s (%d) %s", STR(path), err, strerror(err));
return false;
}
struct dirent *pDirent = NULL;
while ((pDirent = readdir(pDir)) != NULL) {
string entry = pDirent->d_name;
if ((entry == ".")
|| (entry == "..")) {
continue;
}
if (normalizeAllPaths) {
entry = normalizePath(path, entry);
} else {
entry = path + entry;
}
if (entry == "")
continue;
if (pDirent->d_type == DT_UNKNOWN) {
struct stat temp;
if (stat(STR(entry), &temp) != 0) {
WARN("Unable to stat entry %s", STR(entry));
continue;
}
pDirent->d_type = ((temp.st_mode & S_IFDIR) == S_IFDIR) ? DT_DIR : DT_REG;
}
switch (pDirent->d_type) {
case DT_DIR:
{
if (includeFolders) {
ADD_VECTOR_END(result, entry);
}
if (recursive) {
if (!listFolder(entry, result, normalizeAllPaths, includeFolders, recursive)) {
FATAL("Unable to list folder");
closedir(pDir);
return false;
}
}
break;
}
case DT_REG:
{
ADD_VECTOR_END(result, entry);
break;
}
default:
{
WARN("Invalid dir entry detected");
break;
}
}
}
closedir(pDir);
return true;
}
bool moveFile(string src, string dst) {
if (rename(STR(src), STR(dst)) != 0) {
FATAL("Unable to move file from `%s` to `%s`",
STR(src), STR(dst));
return false;
}
return true;
}
bool isAbsolutePath(string &path) {
return (bool)((path.size() > 0) && (path[0] == PATH_SEPARATOR));
}
void signalHandler(int sig) {
if (!MAP_HAS1(_signalHandlers, sig))
return;
_signalHandlers[sig]();
}
void installSignal(int sig, SignalFnc pSignalFnc) {
_signalHandlers[sig] = pSignalFnc;
struct sigaction action;
action.sa_handler = signalHandler;
action.sa_flags = 0;
if (sigemptyset(&action.sa_mask) != 0) {
ASSERT("Unable to install the quit signal");
return;
}
if (sigaction(sig, &action, NULL) != 0) {
ASSERT("Unable to install the quit signal");
return;
}
}
void installQuitSignal(SignalFnc pQuitSignalFnc) {
installSignal(SIGTERM, pQuitSignalFnc);
}
void installConfRereadSignal(SignalFnc pConfRereadSignalFnc) {
installSignal(SIGHUP, pConfRereadSignalFnc);
}
static time_t _gUTCOffset = -1;
void computeUTCOffset() {
time_t now = time(NULL);
struct tm *pTemp = localtime(&now);
_gUTCOffset = pTemp->tm_gmtoff;
}
time_t getlocaltime() {
if (_gUTCOffset == -1)
computeUTCOffset();
return getutctime() + _gUTCOffset;
}
time_t gettimeoffset() {
if (_gUTCOffset == -1)
computeUTCOffset();
return _gUTCOffset;
}
#endif /* FREEBSD */
| 17,683
|
C++
|
.cpp
| 639
| 25.039124
| 104
| 0.667611
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,367
|
osxplatform.cpp
|
shiretu_crtmpserver/sources/common/src/platform/osx/osxplatform.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef OSX
#include "platform/osx/osxplatform.h"
#include "common.h"
string alowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
static map<int, SignalFnc> _signalHandlers;
OSXPlatform::OSXPlatform() {
}
OSXPlatform::~OSXPlatform() {
}
string GetEnvVariable(const char *pEnvVarName) {
char *pTemp = getenv(pEnvVarName);
if (pTemp != NULL)
return pTemp;
return "";
}
void replace(string &target, string search, string replacement) {
if (search == replacement)
return;
if (search == "")
return;
string::size_type i = string::npos;
string::size_type lastPos = 0;
while ((i = target.find(search, lastPos)) != string::npos) {
target.replace(i, search.length(), replacement);
lastPos = i + replacement.length();
}
}
bool fileExists(string path) {
struct stat fileInfo;
if (stat(STR(path), &fileInfo) == 0) {
return true;
} else {
return false;
}
}
string lowerCase(string value) {
return changeCase(value, true);
}
string upperCase(string value) {
return changeCase(value, false);
}
string changeCase(string &value, bool lowerCase) {
string result = "";
for (string::size_type i = 0; i < value.length(); i++) {
if (lowerCase)
result += tolower(value[i]);
else
result += toupper(value[i]);
}
return result;
}
string tagToString(uint64_t tag) {
string result;
for (uint32_t i = 0; i < 8; i++) {
uint8_t v = (tag >> ((7 - i)*8)&0xff);
if (v == 0)
break;
result += (char) v;
}
return result;
}
bool setMaxFdCount(uint32_t ¤t, uint32_t &max) {
//1. reset stuff
current = 0;
max = 0;
struct rlimit limits;
memset(&limits, 0, sizeof (limits));
//2. get the current value
if (getrlimit(RLIMIT_NOFILE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
current = (uint32_t) limits.rlim_cur;
max = (uint32_t) limits.rlim_max;
//3. Set the current value to max value
limits.rlim_cur = OPEN_MAX < limits.rlim_max ? OPEN_MAX : limits.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
int err = errno;
FATAL("setrlimit failed: (%d) %s", err, strerror(err));
return false;
}
//4. Try to get it back
memset(&limits, 0, sizeof (limits));
if (getrlimit(RLIMIT_NOFILE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
current = (uint32_t) limits.rlim_cur;
max = (uint32_t) limits.rlim_max;
return true;
}
bool enableCoreDumps() {
struct rlimit limits;
memset(&limits, 0, sizeof (limits));
memset(&limits, 0, sizeof (limits));
if (getrlimit(RLIMIT_CORE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
limits.rlim_cur = limits.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &limits) != 0) {
int err = errno;
FATAL("setrlimit failed: (%d) %s", err, strerror(err));
return false;
}
memset(&limits, 0, sizeof (limits));
if (getrlimit(RLIMIT_CORE, &limits) != 0) {
int err = errno;
FATAL("getrlimit failed: (%d) %s", err, strerror(err));
return false;
}
return limits.rlim_cur == RLIM_INFINITY;
}
bool setFdJoinMulticast(SOCKET sock, string bindIp, uint16_t bindPort, string ssmIp) {
WARN("Mac OS X doesn't have SSM support");
ssmIp = "";
if (ssmIp == "") {
struct ip_mreq group;
group.imr_multiaddr.s_addr = inet_addr(STR(bindIp));
group.imr_interface.s_addr = INADDR_ANY;
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char *) &group, sizeof (group)) < 0) {
int err = errno;
FATAL("Adding multicast failed. Error was: (%d) %s", err, strerror(err));
return false;
}
return true;
} else {
struct group_source_req multicast;
struct sockaddr_in *pGroup = (struct sockaddr_in*) &multicast.gsr_group;
struct sockaddr_in *pSource = (struct sockaddr_in*) &multicast.gsr_source;
memset(&multicast, 0, sizeof (multicast));
//Setup the group we want to join
pGroup->sin_family = AF_INET;
pGroup->sin_addr.s_addr = inet_addr(STR(bindIp));
pGroup->sin_port = EHTONS(bindPort);
//setup the source we want to listen
pSource->sin_family = AF_INET;
pSource->sin_addr.s_addr = inet_addr(STR(ssmIp));
if (pSource->sin_addr.s_addr == INADDR_NONE) {
FATAL("Unable to SSM on address %s", STR(ssmIp));
return false;
}
pSource->sin_port = 0;
INFO("Try to SSM on ip %s", STR(ssmIp));
if (setsockopt(sock, IPPROTO_IP, MCAST_JOIN_SOURCE_GROUP, &multicast,
sizeof (multicast)) < 0) {
int err = errno;
FATAL("Adding multicast failed. Error was: (%d) %s", err,
strerror(err));
return false;
}
return true;
}
}
bool setFdNonBlock(SOCKET fd) {
int32_t arg;
if ((arg = fcntl(fd, F_GETFL, NULL)) < 0) {
int err = errno;
FATAL("Unable to get fd flags: (%d) %s", err, strerror(err));
return false;
}
arg |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, arg) < 0) {
int err = errno;
FATAL("Unable to set fd flags: (%d) %s", err, strerror(err));
return false;
}
return true;
}
bool setFdNoSIGPIPE(SOCKET fd) {
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE,
(const char*) & one, sizeof (one)) != 0) {
FATAL("Unable to set SO_NOSIGPIPE");
return false;
}
return true;
}
bool setFdKeepAlive(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
(const char*) & one, sizeof (one)) != 0) {
FATAL("Unable to set SO_NOSIGPIPE");
return false;
}
return true;
}
bool setFdNoNagle(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
int32_t one = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) & one, sizeof (one)) != 0) {
return false;
}
return true;
}
bool setFdReuseAddress(SOCKET fd) {
int32_t one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) & one, sizeof (one)) != 0) {
FATAL("Unable to reuse address");
return false;
}
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *) & one, sizeof (one)) != 0) {
FATAL("Unable to reuse port");
return false;
}
return true;
}
bool setFdTTL(SOCKET fd, uint8_t ttl) {
int temp = ttl;
if (setsockopt(fd, IPPROTO_IP, IP_TTL, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_TTL: %"PRIu8"; error was (%d) %s", ttl, err, strerror(err));
}
return true;
}
bool setFdMulticastTTL(SOCKET fd, uint8_t ttl) {
int temp = ttl;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_MULTICAST_TTL: %"PRIu8"; error was (%d) %s", ttl, err, strerror(err));
}
return true;
}
bool setFdTOS(SOCKET fd, uint8_t tos) {
int temp = tos;
if (setsockopt(fd, IPPROTO_IP, IP_TOS, &temp, sizeof (temp)) != 0) {
int err = errno;
WARN("Unable to set IP_TOS: %"PRIu8"; error was (%d) %s", tos, err, strerror(err));
}
return true;
}
int32_t __maxSndBufValUdp = 0;
int32_t __maxRcvBufValUdp = 0;
int32_t __maxSndBufValTcp = 0;
int32_t __maxRcvBufValTcp = 0;
SOCKET __maxSndBufSocket = -1;
bool DetermineMaxRcvSndBuff(int option, bool isUdp) {
int32_t &maxVal = isUdp ?
((option == SO_SNDBUF) ? __maxSndBufValUdp : __maxRcvBufValUdp)
: ((option == SO_SNDBUF) ? __maxSndBufValTcp : __maxRcvBufValTcp);
CLOSE_SOCKET(__maxSndBufSocket);
__maxSndBufSocket = -1;
__maxSndBufSocket = socket(AF_INET, isUdp ? SOCK_DGRAM : SOCK_STREAM, 0);
if (__maxSndBufSocket < 0) {
FATAL("Unable to create testing socket");
return false;
}
int32_t known = 0;
int32_t testing = 0x7fffffff;
int32_t prevTesting = testing;
// FINEST("---- isUdp: %d; option: %s ----", isUdp, (option == SO_SNDBUF ? "SO_SNDBUF" : "SO_RCVBUF"));
while (known != testing) {
// assert(known <= testing);
// assert(known <= prevTesting);
// assert(testing <= prevTesting);
// FINEST("%"PRId32" (%"PRId32") %"PRId32, known, testing, prevTesting);
if (setsockopt(__maxSndBufSocket, SOL_SOCKET, option, (const char*) & testing,
sizeof (testing)) == 0) {
known = testing;
testing = known + (prevTesting - known) / 2;
//FINEST("---------");
} else {
prevTesting = testing;
testing = known + (testing - known) / 2;
}
}
CLOSE_SOCKET(__maxSndBufSocket);
__maxSndBufSocket = -1;
maxVal = known;
// FINEST("%s maxVal: %"PRId32, (option == SO_SNDBUF ? "SO_SNDBUF" : "SO_RCVBUF"), maxVal);
return maxVal > 0;
}
bool setFdMaxSndRcvBuff(SOCKET fd, bool isUdp) {
int32_t &maxSndBufVal = isUdp ? __maxSndBufValUdp : __maxSndBufValTcp;
int32_t &maxRcvBufVal = isUdp ? __maxRcvBufValUdp : __maxRcvBufValTcp;
if (maxSndBufVal == 0) {
if (!DetermineMaxRcvSndBuff(SO_SNDBUF, isUdp)) {
FATAL("Unable to determine maximum value for SO_SNDBUF");
return false;
}
}
if (maxRcvBufVal == 0) {
if (!DetermineMaxRcvSndBuff(SO_RCVBUF, isUdp)) {
FATAL("Unable to determine maximum value for SO_SNDBUF");
return false;
}
}
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*) & maxSndBufVal,
sizeof (maxSndBufVal)) != 0) {
FATAL("Unable to set SO_SNDBUF");
return false;
}
if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*) & maxRcvBufVal,
sizeof (maxSndBufVal)) != 0) {
FATAL("Unable to set SO_RCVBUF");
return false;
}
return true;
}
bool setFdOptions(SOCKET fd, bool isUdp) {
if (!isUdp) {
if (!setFdNonBlock(fd)) {
FATAL("Unable to set non block");
return false;
}
}
if (!setFdNoSIGPIPE(fd)) {
FATAL("Unable to set no SIGPIPE");
return false;
}
if (!setFdKeepAlive(fd, isUdp)) {
FATAL("Unable to set keep alive");
return false;
}
if (!setFdNoNagle(fd, isUdp)) {
WARN("Unable to disable Nagle algorithm");
}
if (!setFdReuseAddress(fd)) {
FATAL("Unable to enable reuse address");
return false;
}
if (!setFdMaxSndRcvBuff(fd, isUdp)) {
FATAL("Unable to set max SO_SNDBUF on UDP socket");
return false;
}
return true;
}
bool deleteFile(string path) {
if (remove(STR(path)) != 0) {
FATAL("Unable to delete file `%s`", STR(path));
return false;
}
return true;
}
bool deleteFolder(string path, bool force) {
if (!force) {
return deleteFile(path);
} else {
string command = format("rm -rf %s", STR(path));
if (system(STR(command)) != 0) {
FATAL("Unable to delete folder %s", STR(path));
return false;
}
return true;
}
}
bool createFolder(string path, bool recursive) {
string command = format("mkdir %s %s",
recursive ? "-p" : "",
STR(path));
if (system(STR(command)) != 0) {
FATAL("Unable to create folder %s", STR(path));
return false;
}
return true;
}
string getHostByName(string name) {
struct hostent *pHostEnt = gethostbyname(STR(name));
if (pHostEnt == NULL)
return "";
if (pHostEnt->h_length <= 0)
return "";
string result = format("%hhu.%hhu.%hhu.%hhu",
(uint8_t) pHostEnt->h_addr_list[0][0],
(uint8_t) pHostEnt->h_addr_list[0][1],
(uint8_t) pHostEnt->h_addr_list[0][2],
(uint8_t) pHostEnt->h_addr_list[0][3]);
return result;
}
bool isNumeric(string value) {
return value == format("%d", atoi(STR(value)));
}
void split(string str, string separator, vector<string> &result) {
result.clear();
string::size_type position = str.find(separator);
string::size_type lastPosition = 0;
uint32_t separatorLength = separator.length();
while (position != str.npos) {
ADD_VECTOR_END(result, str.substr(lastPosition, position - lastPosition));
lastPosition = position + separatorLength;
position = str.find(separator, lastPosition);
}
ADD_VECTOR_END(result, str.substr(lastPosition, string::npos));
}
uint64_t getTagMask(uint64_t tag) {
uint64_t result = 0xffffffffffffffffLL;
for (int8_t i = 56; i >= 0; i -= 8) {
if (((tag >> i)&0xff) == 0)
break;
result = result >> 8;
}
return ~result;
}
string generateRandomString(uint32_t length) {
string result = "";
for (uint32_t i = 0; i < length; i++)
result += alowedCharacters[rand() % alowedCharacters.length()];
return result;
}
void lTrim(string &value) {
string::size_type i = 0;
for (i = 0; i < value.length(); i++) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(i);
}
void rTrim(string &value) {
int32_t i = 0;
for (i = (int32_t) value.length() - 1; i >= 0; i--) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(0, i + 1);
}
void trim(string &value) {
lTrim(value);
rTrim(value);
}
int8_t getCPUCount() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
map<string, string> mapping(string str, string separator1, string separator2, bool trimStrings) {
map<string, string> result;
vector<string> pairs;
split(str, separator1, pairs);
FOR_VECTOR_ITERATOR(string, pairs, i) {
if (VECTOR_VAL(i) != "") {
if (VECTOR_VAL(i).find(separator2) != string::npos) {
string key = VECTOR_VAL(i).substr(0, VECTOR_VAL(i).find(separator2));
string value = VECTOR_VAL(i).substr(VECTOR_VAL(i).find(separator2) + 1);
if (trimStrings) {
trim(key);
trim(value);
}
result[key] = value;
} else {
if (trimStrings) {
trim(VECTOR_VAL(i));
}
result[VECTOR_VAL(i)] = "";
}
}
}
return result;
}
void splitFileName(string fileName, string &name, string & extension, char separator) {
size_t dotPosition = fileName.find_last_of(separator);
if (dotPosition == string::npos) {
name = fileName;
extension = "";
return;
}
name = fileName.substr(0, dotPosition);
extension = fileName.substr(dotPosition + 1);
}
double getFileModificationDate(string path) {
struct stat s;
if (stat(STR(path), &s) != 0) {
FATAL("Unable to stat file %s", STR(path));
return 0;
}
return (double) s.st_mtimespec.tv_sec + (double) s.st_mtimespec.tv_nsec / 1000000000.0;
}
string normalizePath(string base, string file) {
if (base == "")
base = ".";
if (base[base.size() - 1] != PATH_SEPARATOR)
base += PATH_SEPARATOR;
char dummy1[PATH_MAX];
char dummy2[PATH_MAX];
char *pBase = realpath(STR(base), dummy1);
char *pFile = realpath(STR(base + file), dummy2);
if (pBase != NULL) {
base = pBase;
} else {
base = "";
}
if (pFile != NULL) {
file = pFile;
} else {
file = "";
}
if (file == "" || base == "") {
return "";
}
if (file.find(base) != 0) {
return "";
} else {
if (!fileExists(file)) {
return "";
} else {
return file;
}
}
}
bool listFolder(string path, vector<string> &result, bool normalizeAllPaths,
bool includeFolders, bool recursive) {
if (path == "")
path = ".";
if (path[path.size() - 1] != PATH_SEPARATOR)
path += PATH_SEPARATOR;
DIR *pDir = NULL;
pDir = opendir(STR(path));
if (pDir == NULL) {
int err = errno;
FATAL("Unable to open folder: %s (%d) %s", STR(path), err, strerror(err));
return false;
}
struct dirent *pDirent = NULL;
while ((pDirent = readdir(pDir)) != NULL) {
string entry = pDirent->d_name;
if ((entry == ".")
|| (entry == "..")) {
continue;
}
if (normalizeAllPaths) {
entry = normalizePath(path, entry);
} else {
entry = path + entry;
}
if (entry == "")
continue;
if (pDirent->d_type == DT_UNKNOWN) {
struct stat temp;
if (stat(STR(entry), &temp) != 0) {
WARN("Unable to stat entry %s", STR(entry));
continue;
}
pDirent->d_type = ((temp.st_mode & S_IFDIR) == S_IFDIR) ? DT_DIR : DT_REG;
}
switch (pDirent->d_type) {
case DT_DIR:
{
if (includeFolders) {
ADD_VECTOR_END(result, entry);
}
if (recursive) {
if (!listFolder(entry, result, normalizeAllPaths, includeFolders, recursive)) {
FATAL("Unable to list folder");
closedir(pDir);
return false;
}
}
break;
}
case DT_REG:
{
ADD_VECTOR_END(result, entry);
break;
}
default:
{
WARN("Invalid dir entry detected");
break;
}
}
}
closedir(pDir);
return true;
}
bool moveFile(string src, string dst) {
if (rename(STR(src), STR(dst)) != 0) {
FATAL("Unable to move file from `%s` to `%s`",
STR(src), STR(dst));
return false;
}
return true;
}
bool isAbsolutePath(string &path) {
return (bool)((path.size() > 0) && (path[0] == PATH_SEPARATOR));
}
void signalHandler(int sig) {
if (!MAP_HAS1(_signalHandlers, sig))
return;
_signalHandlers[sig]();
}
void installSignal(int sig, SignalFnc pSignalFnc) {
_signalHandlers[sig] = pSignalFnc;
struct sigaction action;
action.sa_handler = signalHandler;
action.sa_flags = 0;
if (sigemptyset(&action.sa_mask) != 0) {
ASSERT("Unable to install the quit signal");
return;
}
if (sigaction(sig, &action, NULL) != 0) {
ASSERT("Unable to install the quit signal");
return;
}
}
void installQuitSignal(SignalFnc pQuitSignalFnc) {
installSignal(SIGTERM, pQuitSignalFnc);
}
void installConfRereadSignal(SignalFnc pConfRereadSignalFnc) {
installSignal(SIGHUP, pConfRereadSignalFnc);
}
static time_t _gUTCOffset = -1;
void computeUTCOffset() {
time_t now = time(NULL);
struct tm *pTemp = localtime(&now);
_gUTCOffset = pTemp->tm_gmtoff;
}
time_t getlocaltime() {
if (_gUTCOffset == -1)
computeUTCOffset();
return getutctime() + _gUTCOffset;
}
time_t gettimeoffset() {
if (_gUTCOffset == -1)
computeUTCOffset();
return _gUTCOffset;
}
#endif /* OSX */
| 17,919
|
C++
|
.cpp
| 645
| 25.151938
| 104
| 0.666997
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,368
|
timegm.cpp
|
shiretu_crtmpserver/sources/common/src/platform/android/timegm.cpp
|
/*
* Copyright (c) 1997 Kungliga Tekniska H�gskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the Institute 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 INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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.
*/
#ifdef ANDROID
#include "platform/platform.h"
#include <time64.h>
time_t timegm(struct tm * const t) {
// time_t is signed on Android.
static const time_t kTimeMax = ~(1 << (sizeof (time_t) * CHAR_BIT - 1));
static const time_t kTimeMin = (1 << (sizeof (time_t) * CHAR_BIT - 1));
time64_t result = timegm64(t);
if (result < kTimeMin || result > kTimeMax)
return -1;
return result;
}
#endif /* ANDROID */
| 2,056
|
C++
|
.cpp
| 45
| 43.711111
| 77
| 0.756231
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,370
|
win32platform.cpp
|
shiretu_crtmpserver/sources/common/src/platform/windows/win32platform.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef WIN32
#include "platform/platform.h"
#include "utils/logging/logging.h"
#include <Strsafe.h>
#include <stdio.h>
#include <TlHelp32.h>
static map<uint32_t, SignalFnc> _signalHandlers;
static vector<pid_t> _pids;
string GetEnvVariable(const char *pEnvVarName) {
string result = "";
size_t len = 0;
char *pEnv = NULL;
_dupenv_s(&pEnv, &len, pEnvVarName);
if (pEnv != NULL) {
result = pEnv;
free(pEnv);
pEnv = NULL;
}
return result;
}
int vasprintf(char **strp, const char *fmt, va_list ap, int size) {
*strp = (char *) malloc(size);
int result = 0;
if ((result = vsnprintf(*strp, size, fmt, ap)) == -1) {
free(*strp);
return vasprintf(strp, fmt, ap, size + size / 2);
} else {
return result;
}
}
bool fileExists(string path) {
#ifdef UNICODE
//TODO: Add the unicode implementation here
NYIR;
#else
if (PathFileExists(STR(path)))
return true;
else
return false;
#endif /* UNICODE */
}
string tagToString(uint64_t tag) {
string result;
for (uint32_t i = 0; i < 8; i++) {
uint8_t v = (tag >> ((7 - i)*8)&0xff);
if (v == 0)
break;
result += (char) v;
}
return result;
}
uint64_t getTagMask(uint64_t tag) {
uint64_t result = 0xffffffffffffffffULL;
for (int8_t i = 56; i >= 0; i -= 8) {
if (((tag >> i)&0xff) == 0)
break;
result = result >> 8;
}
return ~result;
}
bool isNumeric(string value) {
return value == format("%d", atoi(STR(value)));
}
string lowerCase(string value) {
return changeCase(value, true);
}
string upperCase(string value) {
return changeCase(value, false);
}
void lTrim(string &value) {
string::size_type i = 0;
for (i = 0; i < value.length(); i++) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(i);
}
void rTrim(string &value) {
int32_t i = 0;
for (i = (int32_t) value.length() - 1; i >= 0; i--) {
if (value[i] != ' ' &&
value[i] != '\t' &&
value[i] != '\n' &&
value[i] != '\r')
break;
}
value = value.substr(0, i + 1);
}
void trim(string &value) {
lTrim(value);
rTrim(value);
}
int8_t getCPUCount() {
WARN("Windows doesn't support multiple instances");
return 0;
}
void replace(string &target, string search, string replacement) {
if (search == replacement)
return;
if (search == "")
return;
string::size_type i = string::npos;
string::size_type lastPos = 0;
while ((i = target.find(search, lastPos)) != string::npos) {
target.replace(i, search.length(), replacement);
lastPos = i + replacement.length();
}
}
void split(string str, string separator, vector<string> &result) {
result.clear();
string::size_type position = str.find(separator);
string::size_type lastPosition = 0;
uint32_t separatorLength = (uint32_t) separator.length();
while (position != str.npos) {
ADD_VECTOR_END(result, str.substr(lastPosition, position - lastPosition));
lastPosition = position + separatorLength;
position = str.find(separator, lastPosition);
}
ADD_VECTOR_END(result, str.substr(lastPosition, string::npos));
}
map<string, string> mapping(string str, string separator1, string separator2, bool trimStrings) {
map<string, string> result;
vector<string> pairs;
split(str, separator1, pairs);
FOR_VECTOR_ITERATOR(string, pairs, i) {
if (VECTOR_VAL(i) != "") {
if (VECTOR_VAL(i).find(separator2) != string::npos) {
string key = VECTOR_VAL(i).substr(0, VECTOR_VAL(i).find(separator2));
string value = VECTOR_VAL(i).substr(VECTOR_VAL(i).find(separator2) + 1);
if (trimStrings) {
trim(key);
trim(value);
}
result[key] = value;
} else {
if (trimStrings) {
trim(VECTOR_VAL(i));
}
result[VECTOR_VAL(i)] = "";
}
}
}
return result;
}
string changeCase(string &value, bool lowerCase) {
//int32_t len = (int32_t)value.length();
string newvalue(value);
for (string::size_type i = 0, l = newvalue.length(); i < l; ++i)
newvalue[i] = (char) (lowerCase ? tolower(newvalue[i]) : toupper(newvalue[i]));
return newvalue;
}
int gettimeofday(struct timeval *tv, void* tz) {
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
uint64_t value = ((uint64_t) ft.dwHighDateTime << 32) | ft.dwLowDateTime;
tv->tv_usec = (long) ((value / 10LL) % 1000000LL);
tv->tv_sec = (long) ((value - 116444736000000000LL) / 10000000LL);
return (0);
}
bool HandlerRoutine(uint32_t dwCtrlType) {
if (MAP_HAS1(_signalHandlers, dwCtrlType)) {
_signalHandlers[dwCtrlType]();
return true;
}
return false;
}
void installConfRereadSignal(SignalFnc pConfRereadSignalFnc) {
_signalHandlers[CTRL_BREAK_EVENT] = pConfRereadSignalFnc;
SetConsoleCtrlHandler((PHANDLER_ROUTINE) HandlerRoutine, TRUE);
}
void installQuitSignal(SignalFnc pQuitSignalFnc) {
_signalHandlers[CTRL_C_EVENT] = pQuitSignalFnc;
SetConsoleCtrlHandler((PHANDLER_ROUTINE) HandlerRoutine, TRUE);
}
double getFileModificationDate(string path) {
struct _stat64 s;
if (_stat64(STR(path), &s) != 0) {
FATAL("Unable to stat file %s", STR(path));
return 0;
}
return (double) s.st_mtime;
}
void InitNetworking() {
WSADATA wsa;
memset(&wsa, 0, sizeof (wsa));
WSAStartup(0, &wsa);
WSAStartup(wsa.wHighVersion, &wsa);
}
HMODULE UnicodeLoadLibrary(string fileName) {
return LoadLibrary(STR(fileName));
}
int inet_aton(const char *pStr, struct in_addr *pRes) {
pRes->S_un.S_addr = inet_addr(pStr);
return true;
}
bool setMaxFdCount(uint32_t ¤t, uint32_t &max) {
//1. Get the current values
current = (uint32_t) _getmaxstdio();
max = 2048;
//2. Set the current value to the max value
if (_setmaxstdio(2048) != 2048) {
int err = errno;
FATAL("_setmaxstdio failed: %d (%s)", err, strerror(err));
return false;
}
//3. Get back the current value
current = (uint32_t) _getmaxstdio();
return true;
}
bool enableCoreDumps() {
return true;
}
bool setFdJoinMulticast(SOCKET sock, string bindIp, uint16_t bindPort, string ssmIp) {
if (ssmIp == "") {
struct ip_mreq group;
group.imr_multiaddr.s_addr = inet_addr(STR(bindIp));
group.imr_interface.s_addr = INADDR_ANY;
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char *) &group, sizeof (group)) < 0) {
int err = LASTSOCKETERROR;
FATAL("Adding multicast failed. Error was: %d", err);
return false;
}
return true;
} else {
struct group_source_req multicast;
struct sockaddr_in *pGroup = (struct sockaddr_in*) &multicast.gsr_group;
struct sockaddr_in *pSource = (struct sockaddr_in*) &multicast.gsr_source;
memset(&multicast, 0, sizeof (multicast));
//Setup the group we want to join
pGroup->sin_family = AF_INET;
pGroup->sin_addr.s_addr = inet_addr(STR(bindIp));
pGroup->sin_port = EHTONS(bindPort);
//setup the source we want to listen
pSource->sin_family = AF_INET;
pSource->sin_addr.s_addr = inet_addr(STR(ssmIp));
if (pSource->sin_addr.s_addr == INADDR_NONE) {
FATAL("Unable to SSM on address %s", STR(ssmIp));
return false;
}
pSource->sin_port = 0;
INFO("Try to SSM on ip %s", STR(ssmIp));
if (setsockopt(sock, IPPROTO_IP, MCAST_JOIN_SOURCE_GROUP, (char *) &multicast,
sizeof (multicast)) < 0) {
int err = LASTSOCKETERROR;
FATAL("Adding multicast failed. Error was: (%d)", err);
return false;
}
return true;
}
}
bool setFdCloseOnExec(int fd) {
return true;
}
bool setFdNonBlock(SOCKET fd) {
u_long iMode = 1; // 0 for blocking, anything else for nonblocking
if (ioctlsocket(fd, FIONBIO, &iMode) < 0) {
int err = LASTSOCKETERROR;
FATAL("Unable to set fd flags: %d", err);
return false;
}
return true;
}
bool setFdNoSIGPIPE(SOCKET fd) {
return true;
}
bool setFdKeepAlive(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
int value = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char *) &value, sizeof (int)) != 0) {
DWORD err = WSAGetLastError();
FATAL("setsockopt failed with error %"PRIu32, err);
return false;
}
return true;
}
bool setFdNoNagle(SOCKET fd, bool isUdp) {
if (isUdp)
return true;
BOOL value = TRUE;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &value, sizeof (BOOL)) == SOCKET_ERROR) {
DWORD err = WSAGetLastError();
FATAL("Unable to disable Nagle algorithm. Error was: %"PRIu32, err);
return false;
}
return true;
}
bool setFdReuseAddress(SOCKET fd) {
BOOL value = TRUE;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &value, sizeof (BOOL)) == SOCKET_ERROR) {
FATAL("Error #%u", WSAGetLastError());
return false;
}
return true;
}
bool setFdTTL(SOCKET fd, uint8_t ttl) {
NYI;
return true;
}
bool setFdMulticastTTL(SOCKET fd, uint8_t ttl) {
NYI
return true;
}
bool setFdTOS(SOCKET fd, uint8_t tos) {
NYI
return true;
}
int32_t __maxSndBufValUdp = 0;
int32_t __maxRcvBufValUdp = 0;
int32_t __maxSndBufValTcp = 0;
int32_t __maxRcvBufValTcp = 0;
SOCKET __maxSndBufSocket = (SOCKET) - 1;
bool testSetsockopt(int option, int32_t testing) {
if (setsockopt(__maxSndBufSocket, SOL_SOCKET, option, (const char*) & testing, sizeof (testing)) != 0)
return false;
int32_t retValue = 0;
int retValueSize = sizeof (retValue);
if (getsockopt(__maxSndBufSocket, SOL_SOCKET, option, (char*) & retValue, &retValueSize) != 0)
return false;
return retValue == testing;
}
bool DetermineMaxRcvSndBuff(int option, bool isUdp) {
int32_t &maxVal = isUdp ?
((option == SO_SNDBUF) ? __maxSndBufValUdp : __maxRcvBufValUdp)
: ((option == SO_SNDBUF) ? __maxSndBufValTcp : __maxRcvBufValTcp);
CLOSE_SOCKET(__maxSndBufSocket);
__maxSndBufSocket = (SOCKET) - 1;
__maxSndBufSocket = socket(AF_INET, isUdp ? SOCK_DGRAM : SOCK_STREAM, 0);
if (__maxSndBufSocket < 0) {
FATAL("Unable to create testing socket");
return false;
}
int32_t known = 0;
int32_t testing = 1024 * 1024 * 16;
int32_t prevTesting = testing;
// FINEST("---- isUdp: %d; option: %s ----", isUdp, (option == SO_SNDBUF ? "SO_SNDBUF" : "SO_RCVBUF"));
while (known != testing) {
// assert(known <= testing);
// assert(known <= prevTesting);
// assert(testing <= prevTesting);
// FINEST("%"PRId32" (%"PRId32") %"PRId32, known, testing, prevTesting);
if (testSetsockopt(option, testing)) {
known = testing;
testing = known + (prevTesting - known) / 2;
//FINEST("---------");
} else {
prevTesting = testing;
testing = known + (testing - known) / 2;
}
}
CLOSE_SOCKET(__maxSndBufSocket);
__maxSndBufSocket = (SOCKET) - 1;
maxVal = known;
// FINEST("%s maxVal: %"PRId32, (option == SO_SNDBUF ? "SO_SNDBUF" : "SO_RCVBUF"), maxVal);
return maxVal > 0;
}
bool setFdMaxSndRcvBuff(SOCKET fd, bool isUdp) {
int32_t &maxSndBufVal = isUdp ? __maxSndBufValUdp : __maxSndBufValTcp;
int32_t &maxRcvBufVal = isUdp ? __maxRcvBufValUdp : __maxRcvBufValTcp;
if (maxSndBufVal == 0) {
if (!DetermineMaxRcvSndBuff(SO_SNDBUF, isUdp)) {
FATAL("Unable to determine maximum value for SO_SNDBUF");
return false;
}
}
if (maxRcvBufVal == 0) {
if (!DetermineMaxRcvSndBuff(SO_RCVBUF, isUdp)) {
FATAL("Unable to determine maximum value for SO_SNDBUF");
return false;
}
}
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*) & maxSndBufVal,
sizeof (maxSndBufVal)) != 0) {
FATAL("Unable to set SO_SNDBUF");
return false;
}
if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*) & maxRcvBufVal,
sizeof (maxSndBufVal)) != 0) {
FATAL("Unable to set SO_RCVBUF");
return false;
}
return true;
}
bool setFdOptions(SOCKET fd, bool isUdp) {
if (!isUdp) {
if (!setFdNonBlock(fd)) {
FATAL("Unable to set non block");
return false;
}
}
if (!setFdNoSIGPIPE(fd)) {
FATAL("Unable to set no SIGPIPE");
return false;
}
if (!setFdKeepAlive(fd, isUdp)) {
FATAL("Unable to set keep alive");
return false;
}
if (!setFdNoNagle(fd, isUdp)) {
WARN("Unable to disable Nagle algorithm");
}
if (!setFdReuseAddress(fd)) {
FATAL("Unable to enable reuse address");
return false;
}
if (!setFdMaxSndRcvBuff(fd, isUdp)) {
FATAL("Unable to set max SO_SNDBUF on UDP socket");
return false;
}
return true;
}
void killProcess(pid_t pid) {
//1. the the process snapshoot
HANDLE hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
FATAL("processes enumeration failed: %"PRIu32, err);
return;
}
//2. Prepare the info structure
PROCESSENTRY32 pe;
memset(&pe, 0, sizeof (PROCESSENTRY32));
pe.dwSize = sizeof (PROCESSENTRY32);
//3. cycle over all processes and see which one has this one as parent
if (Process32First(hSnap, &pe)) {
do {
if (pe.th32ParentProcessID == (DWORD) pid)
killProcess(pe.th32ProcessID);
} while (Process32Next(hSnap, &pe));
}
//4. Kill the process
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, (DWORD) pid);
if (hProcess == NULL) {
FATAL("Cannot access process id = %"PRId32, pid);
return;
}
if (!TerminateProcess(hProcess, 0)) {
FATAL("Cannot terminate process id = %"PRId32, pid);
}
CloseHandle(hProcess);
}
string alowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
string generateRandomString(uint32_t length) {
string result = "";
for (uint32_t i = 0; i < length; i++)
result += alowedCharacters[rand() % alowedCharacters.length()];
return result;
}
string getHostByName(string name) {
struct hostent *pHostEnt = gethostbyname(STR(name));
if (pHostEnt == NULL)
return "";
if (pHostEnt->h_length <= 0)
return "";
string result = format("%hhu.%hhu.%hhu.%hhu",
(uint8_t) pHostEnt->h_addr_list[0][0],
(uint8_t) pHostEnt->h_addr_list[0][1],
(uint8_t) pHostEnt->h_addr_list[0][2],
(uint8_t) pHostEnt->h_addr_list[0][3]);
return result;
}
void splitFileName(string fileName, string &name, string & extension, char separator) {
size_t dotPosition = fileName.find_last_of(separator);
if (dotPosition == string::npos) {
name = fileName;
extension = "";
return;
}
name = fileName.substr(0, dotPosition);
extension = fileName.substr(dotPosition + 1);
}
string normalizePath(string base, string file) {
char dummy1[MAX_PATH ];
char dummy2[MAX_PATH ];
if (GetFullPathName(STR(base), MAX_PATH, dummy1, NULL) == 0)
return "";
if (GetFullPathName(STR(base + file), MAX_PATH, dummy2, NULL) == 0)
return "";
base = dummy1;
file = dummy2;
if (file == "" || base == "") {
return "";
}
if (file.find(base) != 0) {
return "";
} else {
if (!fileExists(file)) {
return "";
} else {
return file;
}
}
}
bool listFolder(string path, vector<string> &result, bool normalizeAllPaths,
bool includeFolders, bool recursive) {
WIN32_FIND_DATA ffd;
TCHAR szDir[MAX_PATH];
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError = 0;
// Check that the input path plus 3 is not longer than MAX_PATH.
// Three characters are for the "\*" plus NULL appended below.
if (path.size() > (MAX_PATH - 3)) {
WARN("Directory path is too long: %s.", STR(path));
return false;
}
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, STR(path));
StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
// Find the first file in the directory.
hFind = FindFirstFile(szDir, &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
FATAL("Unable to open folder %s", STR(path));
return false;
}
do {
string entry = ffd.cFileName;
if ((entry == ".") || (entry == "..")) {
continue;
}
if (normalizeAllPaths) {
entry = normalizePath(path, entry);
} else {
entry = path + entry;
}
if (entry == "")
continue;
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (includeFolders) {
ADD_VECTOR_END(result, entry);
}
if (recursive) {
if (!listFolder(entry, result, normalizeAllPaths, includeFolders, recursive)) {
FATAL("Unable to list folder");
FindClose(hFind);
return false;
}
}
} else {
ADD_VECTOR_END(result, entry);
}
} while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) {
WARN("Unable to find first file");
FindClose(hFind);
return false;
}
FindClose(hFind);
return true;
}
bool deleteFile(string path) {
if (remove(STR(path)) != 0) {
FATAL("Unable to delete file `%s`", STR(path));
return false;
}
return true;
}
bool deleteFolder(string path, bool force) {
string fileFound;
WIN32_FIND_DATA info;
HANDLE hp;
fileFound = format("%s\\*.*", STR(path));
hp = FindFirstFile(STR(fileFound), &info);
// Check first if we have a valid handle!
if (hp == INVALID_HANDLE_VALUE) {
WARN("Files to be deleted were already removed: %s", STR(fileFound));
return true;
}
do {
if (!((strcmp(info.cFileName, ".") == 0) ||
(strcmp(info.cFileName, "..") == 0))) {
if ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
FILE_ATTRIBUTE_DIRECTORY) {
string subFolder = path;
subFolder.append("\\");
subFolder.append(info.cFileName);
if (!deleteFolder(subFolder, true)) {
FATAL("Unable to delete subfolder %s", STR(subFolder));
return false;
}
if (!RemoveDirectory(STR(subFolder))) {
FATAL("Unable to delete subfolder %s", STR(subFolder));
return false;
}
} else {
fileFound = format("%s\\%s", STR(path), info.cFileName);
if (!DeleteFile(STR(fileFound))) {
FATAL("Unable to delete file %s", STR(fileFound));
return false;
}
}
}
} while (FindNextFile(hp, &info));
FindClose(hp);
return true;
}
bool createFolder(string path, bool recursive) {
char DirName[256];
const char* p = path.c_str();
char* q = DirName;
while (*p) {
if (('\\' == *p) || ('/' == *p)) {
if (':' != *(p - 1)) {
CreateDirectory(DirName, NULL);
}
}
*q++ = *p++;
*q = '\0';
}
CreateDirectory(DirName, NULL);
return true;
}
bool moveFile(string src, string dst) {
if (rename(STR(src), STR(dst)) != 0) {
FATAL("Unable to move file from `%s` to `%s`",
STR(src), STR(dst));
return false;
}
return true;
}
bool isAbsolutePath(string &path) {
if (path.size() < 4)
return false;
return (((path[0] >= 'A')&&(path[0] <= 'Z')) || ((path[0] >= 'a')&&(path[0] <= 'z')))
&&(path[1] == ':')
&&(path[2] == '\\');
}
static time_t _gUTCOffset = -1;
void computeUTCOffset() {
//time_t now = time(NULL);
//struct tm *pTemp = localtime(&now);
//_gUTCOffset = pTemp->tm_gmtoff;
NYIA;
}
time_t getlocaltime() {
if (_gUTCOffset == -1)
computeUTCOffset();
return getutctime() + _gUTCOffset;
}
time_t gettimeoffset() {
if (_gUTCOffset == -1)
computeUTCOffset();
return _gUTCOffset;
}
void GetFinishedProcesses(vector<pid_t> &pids, bool &noMorePids) {
//1. set parameters to defaults
pids.clear();
noMorePids = true;
// if pid cache is empty, bail out;
if (_pids.size() == 0)
return;
//2. prepare handles of pids
uint32_t pidCount = (uint32_t) _pids.size();
HANDLE *hProcs = new HANDLE[pidCount];
uint8_t i = 0;
uint8_t truePidCount = 0;
while (truePidCount != _pids.size()) {
DWORD currProcId = _pids.back();
hProcs[i] = OpenProcess(PROCESS_ALL_ACCESS, false, currProcId);
if (hProcs[i] == 0) {
ADD_VECTOR_END(pids, currProcId);
} else {
i++;
truePidCount++;
ADD_VECTOR_BEGIN(_pids, currProcId);
}
_pids.pop_back();
}
//3. catch any terminated process handles
while (truePidCount) {
pid_t procId = 0;
DWORD resp = WaitForMultipleObjects(truePidCount, hProcs, FALSE, 0);
if (resp == WAIT_TIMEOUT) // break when there is no terminated processes
break;
noMorePids = false;
if (resp == WAIT_FAILED) {
//ASSERT("Failed to get finished processes");
WARN("Failed to get process status. Err: %"PRIu32, GetLastError());
break;
} else {
//4. get process id from process handle and dump it into the pid param
HANDLE hProcess = hProcs[resp];
procId = GetProcessId(hProcess);
CloseHandle(hProcess);
}
//5. refresh pid cache
FOR_VECTOR_ITERATOR(pid_t, _pids, i) {
if (VECTOR_VAL(i) == procId) {
_pids.erase(i);
break;
}
}
pids.push_back(procId);
//6. update handle array and close unused handle
truePidCount--;
memmove(&hProcs[resp], &hProcs[resp + 1], pidCount * sizeof (HANDLE));
};
}
bool LaunchProcess(string fullBinaryPath, vector<string> &arguments, vector<string> &envVars, pid_t &pid) {
// Wrap fullBinaryPath within qoutes so that spaces will be honored
fullBinaryPath = "\"" + fullBinaryPath + "\"";
// For arguments, qoute as needed as well
FOR_VECTOR(arguments, i) {
fullBinaryPath += " \"" + arguments[i] + "\"";
}
// Actual number of characters to be reserved for the environment variables
size_t blockSize = 1;
// Before creating the envVars, we need to copy the environment variables from the parent
static vector<string> parentVars;
static bool gotParentsVar = false;
static uint32_t pvSize = 0;
if (gotParentsVar == false) {
// Populate it first
parentVars.clear();
const char* pVars = GetEnvironmentStrings();
uint32_t prev = 0;
pvSize = 0;
do {
if (pVars[pvSize] == '\0') {
parentVars.push_back(string(pVars + prev, pVars + pvSize));
// Skip the null terminator
prev = pvSize + 1;
if (pVars[pvSize + 1] == '\0') {
pvSize += 1; // consider the last null terminator
break;
}
}
pvSize++;
} while (pvSize < 0x0FFFFFFFF);
// Toggle the field since we already got it from the parent
//TODO: what if the client updated the environment and EMS was already called with launchProcess?
gotParentsVar = true;
}
// Add the passed env variables to the size to be reserved
FOR_VECTOR(envVars, i) {
blockSize += envVars[i].length() + 1;
}
char *envBlock = NULL;
// Sanity check: if limit reached
if ((pvSize == 0x0FFFFFFFF) || ((uint32_t) (pvSize + blockSize) < pvSize)) {
WARN("Passed environment variables will not be considered.");
} else {
// Add to the target blocksize
blockSize += pvSize;
// Create envVars block (null-terminated block of null-terminated key-value pair strings
// format should be: name1=value1\0name2=value2\0\0
if (envVars.size() != 0) {
envBlock = new char[blockSize];
memset(envBlock, 0, blockSize);
char *p = envBlock;
// First the parent
FOR_VECTOR(parentVars, i) {
memcpy(p, parentVars[i].c_str(), parentVars[i].length());
p += parentVars[i].length() + 1;
}
// Then append the passed envVars
FOR_VECTOR(envVars, i) {
memcpy(p, envVars[i].c_str(), envVars[i].length());
p += envVars[i].length() + 1;
}
}
}
//FINEST("blockSize: %"PRIu32, blockSize);
// Create the process
STARTUPINFO si = {0};
si.cb = sizeof (si);
PROCESS_INFORMATION pi = {0};
char *pTemp = new char[fullBinaryPath.size() + 1];
memset(pTemp, 0, fullBinaryPath.size() + 1);
memcpy(pTemp, fullBinaryPath.data(), fullBinaryPath.size());
//FINEST("pTemp: `%s`",pTemp);
if (!CreateProcess(NULL, pTemp, NULL, NULL, false, 0, envBlock, NULL, &si, &pi)) {
DWORD error = GetLastError();
FATAL("Unable to launch proces. Error: %"PRIu32, error);
delete[] pTemp;
if (envBlock != NULL)
delete envBlock;
return false;
}
// Cleanup
delete[] pTemp;
if (envBlock != NULL)
delete envBlock;
pid = pi.dwProcessId;
_pids.push_back(pid);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return true;
}
#endif /* WIN32 */
| 24,919
|
C++
|
.cpp
| 813
| 26.800738
| 108
| 0.657464
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
750,371
|
rtmpappprotocolhandler.cpp
|
shiretu_crtmpserver/sources/applications/flvplayback/src/rtmpappprotocolhandler.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#include "rtmpappprotocolhandler.h"
#include "protocols/rtmp/basertmpprotocol.h"
#include "protocols/rtmp/messagefactories/messagefactories.h"
#include "application/baseclientapplication.h"
#include "streaming/baseinnetstream.h"
#include "streaming/streamstypes.h"
using namespace app_flvplayback;
RTMPAppProtocolHandler::RTMPAppProtocolHandler(Variant &configuration)
: BaseRTMPAppProtocolHandler(configuration) {
}
RTMPAppProtocolHandler::~RTMPAppProtocolHandler() {
}
bool RTMPAppProtocolHandler::ProcessInvokeGeneric(BaseRTMPProtocol *pFrom,
Variant &request) {
string functionName = M_INVOKE_FUNCTION(request);
if (functionName == "getAvailableFlvs") {
return ProcessGetAvailableFlvs(pFrom, request);
} else if (functionName == "insertMetadata") {
return ProcessInsertMetadata(pFrom, request);
} else {
return BaseRTMPAppProtocolHandler::ProcessInvokeGeneric(pFrom, request);
}
}
bool RTMPAppProtocolHandler::ProcessGetAvailableFlvs(BaseRTMPProtocol *pFrom, Variant &request) {
Variant parameters;
parameters.PushToArray(Variant());
parameters.PushToArray(Variant());
map<uint32_t, BaseStream *> allInboundStreams =
GetApplication()->GetStreamsManager()->FindByType(ST_IN_NET, true);
FOR_MAP(allInboundStreams, uint32_t, BaseStream *, i) {
parameters[(uint32_t) 1].PushToArray(MAP_VAL(i)->GetName());
}
Variant message = GenericMessageFactory::GetInvoke(3, 0, 0, false, 0,
"SetAvailableFlvs", parameters);
return SendRTMPMessage(pFrom, message);
}
bool RTMPAppProtocolHandler::ProcessInsertMetadata(BaseRTMPProtocol *pFrom, Variant &request) {
NYIR;
}
#endif /* HAS_PROTOCOL_RTMP */
| 2,430
|
C++
|
.cpp
| 59
| 39.152542
| 97
| 0.78829
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,372
|
tsappprotocolhandler.cpp
|
shiretu_crtmpserver/sources/applications/flvplayback/src/tsappprotocolhandler.cpp
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_TS
#include "tsappprotocolhandler.h"
#include "application/baseclientapplication.h"
#include "protocols/rtmp/sharedobjects/so.h"
#include "protocols/rtmp/sharedobjects/somanager.h"
#include "protocols/rtmp/basertmpappprotocolhandler.h"
#include "protocols/protocoltypes.h"
using namespace app_flvplayback;
TSAppProtocolHandler::TSAppProtocolHandler(Variant &configuration)
: BaseTSAppProtocolHandler(configuration) {
}
TSAppProtocolHandler::~TSAppProtocolHandler() {
}
#endif /* HAS_PROTOCOL_TS */
| 1,298
|
C++
|
.cpp
| 32
| 38.8125
| 72
| 0.784127
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,375
|
protocoltypes.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/protocoltypes.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PROTOCOLTYPES_H
#define _PROTOCOLTYPES_H
#include "common.h"
//carrier protocols
#define PT_TCP MAKE_TAG3('T','C','P')
#define PT_UDP MAKE_TAG3('U','D','P')
//variant protocols
#define PT_BIN_VAR MAKE_TAG4('B','V','A','R')
#define PT_XML_VAR MAKE_TAG4('X','V','A','R')
#define PT_JSON_VAR MAKE_TAG4('J','V','A','R')
//RTMP protocols
#define PT_INBOUND_RTMP MAKE_TAG2('I','R')
#define PT_INBOUND_RTMPS_DISC MAKE_TAG3('I','R','S')
#define PT_OUTBOUND_RTMP MAKE_TAG2('O','R')
//encryption protocols
#define PT_RTMPE MAKE_TAG2('R','E')
#define PT_INBOUND_SSL MAKE_TAG4('I','S','S','L')
#define PT_OUTBOUND_SSL MAKE_TAG4('O','S','S','L')
//MPEG-TS protocol
#define PT_INBOUND_TS MAKE_TAG3('I','T','S')
//HTTP protocols
#define PT_INBOUND_HTTP MAKE_TAG4('I','H','T','T')
#define PT_INBOUND_HTTP_FOR_RTMP MAKE_TAG4('I','H','4','R')
#define PT_OUTBOUND_HTTP MAKE_TAG4('O','H','T','T')
#define PT_OUTBOUND_HTTP_FOR_RTMP MAKE_TAG4('O','H','4','R')
//Timer protocol
#define PT_TIMER MAKE_TAG3('T','M','R')
//Live FLV protocols
#define PT_INBOUND_LIVE_FLV MAKE_TAG4('I','L','F','L')
#define PT_OUTBOUND_LIVE_FLV MAKE_TAG4('O','L','F','L')
//RTP/RTPS protocols
#define PT_RTSP MAKE_TAG4('R','T','S','P')
#define PT_RTCP MAKE_TAG4('R','T','C','P')
#define PT_INBOUND_RTP MAKE_TAG4('I','R','T','P')
#define PT_OUTBOUND_RTP MAKE_TAG4('O','R','T','P')
#define PT_RTP_NAT_TRAVERSAL MAKE_TAG5('R','N','A','T','T')
//CLI protocols
#define PT_INBOUND_JSONCLI MAKE_TAG8('I','J','S','O','N','C','L','I')
#define PT_HTTP_4_CLI MAKE_TAG3('H','4','C')
//pass through protocol
#define PT_PASSTHROUGH MAKE_TAG2('P','T')
#endif /* _PROTOCOLTYPES_H */
| 2,474
|
C++
|
.h
| 60
| 39.666667
| 72
| 0.66917
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,376
|
baseprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/baseprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEPROTOCOL_H
#define _BASEPROTOCOL_H
#include "common.h"
#include "protocols/protocoltypes.h"
#include "utils/readyforsendinterface.h"
class IOBuffer;
class IOHandler;
class BaseClientApplication;
/*!
@class BaseProtocol
@brief The base class on which all atomic protocols must derive from.
*/
class DLLEXP BaseProtocol
: public ReadyForSendInterface {
private:
static uint32_t _idGenerator;
uint32_t _id;
BaseClientApplication *_pApplication;
uint32_t _lastKnownApplicationId;
protected:
uint64_t _type;
BaseProtocol *_pFarProtocol;
BaseProtocol *_pNearProtocol;
bool _deleteFar;
bool _deleteNear;
bool _enqueueForDelete;
bool _gracefullyEnqueueForDelete;
Variant _customParameters;
double _creationTimestamp;
public:
BaseProtocol(uint64_t type);
virtual ~BaseProtocol();
//
//general purpose, fixed methods
//
/*!
@abstract Returns the type of the protocol
*/
uint64_t GetType();
/*!
@brief Returns the id of the protocol. Each protocol instance has an id. The id is unique across all protocols, no matter the type
*/
uint32_t GetId();
/*!
@brief Returns the creation timestamp expressed in milliseconds for 1970 epoch
*/
double GetSpawnTimestamp();
/*!
@brief Gets the far protocol
*/
BaseProtocol *GetFarProtocol();
/*!
@brief Sets the far protocol
@param pProtocol
*/
void SetFarProtocol(BaseProtocol *pProtocol);
/*!
@brief Break the far side of the protocol chain by making far protocol NULL
*/
void ResetFarProtocol();
/*!
@brief Gets the near protocol
*/
BaseProtocol *GetNearProtocol();
/*!
@brief Sets the near protocol
@param pProtocol
*/
void SetNearProtocol(BaseProtocol *pProtocol);
/*!
@brief Break the near side of the protocol chain by making near protocol NULL
*/
void ResetNearProtocol();
//Normally, if this protocol will be deleted, all the stack will be deleted
//Using the next 2 functions we can tell where the protocol deletion will stop
/*!
@brief Deletes the protocol
@param deleteNear: Indicates which protocol to delete.
@discussion Normally, if this protocol will be deleted, all the stack will be deleted. Using the DeleteNearProtocol and DeleteFarProtocol, we can tell where the protocol deletion will stop.
*/
void DeleteNearProtocol(bool deleteNear);
/*!
@brief Deletes the protocol
@param deleteNear: Indicates which protocol to delete.
@discussion Normally, if this protocol will be deleted, all the stack will be deleted. Using the DeleteNearProtocol and DeleteFarProtocol, we can tell where the protocol deletion will stop.
*/
void DeleteFarProtocol(bool deleteFar);
/*!
@brief Gets the far-most protocol in the protocl chain.
@discussion Far-end protocol - is the one close to the transport layer
*/
BaseProtocol *GetFarEndpoint();
/*!
@brief Gets the near-most protocol in the protocl chain.
@discussion Near-end protocol - is the one close to the business rules layer
*/
BaseProtocol *GetNearEndpoint();
/*!
@brief Tests to see if the protocol is enqueued for delete
*/
bool IsEnqueueForDelete();
/*!
@brief Gets the protocol's application
*/
BaseClientApplication * GetApplication();
/*!
@brief Gets the protocol's last known application. Same as GetApplication if the protocol is currently bound to any application
*/
BaseClientApplication * GetLastKnownApplication();
//This are functions for set/get the costom parameters
//in case of outbound protocols
/*!
@brief Sets the custom parameters in case of outbound protocols
@param customParameters: Variant contaitning the custom parameters
*/
void SetOutboundConnectParameters(Variant &customParameters);
/*!
@brief Gets the custom parameters
*/
Variant &GetCustomParameters();
/*!
@brief This will return complete information about all protocols in the current stack, including the carrier if available.
@param info
*/
void GetStackStats(Variant &info, uint32_t namespaceId = 0);
//utility functions
operator string();
//
//virtuals
//
/*!
@brief This is called to initialize internal resources specific to each protocol. This is called before adding the protocol to the stack.
@param parameters
*/
virtual bool Initialize(Variant ¶meters);
/*!
@brief Enqueues the protocol to the delete queue imediatly. All transport related routines called from now on, will be ignored.
*/
virtual void EnqueueForDelete();
/*!
@brief Enqueues the protocol to the delete queue if there is no outstanding outbound data.
@param fromFarSide
*/
virtual void GracefullyEnqueueForDelete(bool fromFarSide = true);
/*!
@brief Returns the IO handler of the protocol chain.
*/
virtual IOHandler *GetIOHandler();
/*!
@brief Sets the IO Handler of the protocol chain.
@param pCarrier
*/
virtual void SetIOHandler(IOHandler *pCarrier);
/*!
@brief Gets the input buffers
*/
virtual IOBuffer * GetInputBuffer();
/*!
@brief Gets the output buffers
*/
virtual IOBuffer * GetOutputBuffer();
/*!
@brief Get the total amount of bytes that this protocol transported (raw bytes).
*/
virtual uint64_t GetDecodedBytesCount();
/*!
@brief This function can be called by anyone who wants to signal the transport layer that there is data ready to be sent. pExtraParameters usually is a pointer to an OutboundBuffer, but this depends on the protocol type.
*/
virtual bool EnqueueForOutbound();
/*!
@brief Enqueue the current protocol stack for timed event
@param seconds
*/
virtual bool EnqueueForTimeEvent(uint32_t seconds);
/*!
@brief This is invoked by the framework when the protocol is enqueued for timing oprrations
*/
virtual bool TimePeriodElapsed();
/*!
@brief This is invoked by the framework when the underlaying system is ready to send more data
*/
virtual void ReadyForSend();
/*!
@brief Sets the protocol's application
@param application
*/
virtual void SetApplication(BaseClientApplication *pApplication);
/*!
@brief This is called by the framework when data is available for processing, when making use of connection-less protocols
@param buffer
@param pPeerAddress
*/
virtual bool SignalInputData(IOBuffer &buffer, sockaddr_in *pPeerAddress);
/*!
@brief This is called by the framework when data is available for processing, directly from the network i/o layer
@brief recvAmount
@param pPeerAddress
*/
virtual bool SignalInputData(int32_t recvAmount, sockaddr_in *pPeerAddress);
/*!
@brief This will return a Variant containing various statistic information. This should be overridden if more/less info is desired
@param info
*/
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
//
//must be implemented by the class that inherits this class
//
/*!
@brief Should return true if this protocol can be linked with a far protocol of type 'type'. Otherwise should return false
@param type
@discussion This function must be implemented by the class that inherits this class
*/
virtual bool AllowFarProtocol(uint64_t type) = 0;
/*!
@brief Should return true if this protocol can be linked with a near protocol of type 'type'. Otherwise should return false
@param type
@discussion This function must be implemented by the class that inherits this class
*/
virtual bool AllowNearProtocol(uint64_t type) = 0;
/*!
@brief This is called by the framework when data is available for processing, directly from the network i/o layer
@param recvAmount
@discussion This function must be implemented by the class that inherits this class
*/
virtual bool SignalInputData(int32_t recvAmount) = 0;
/*!
@brief This is called by the framework when data is available for processing, from the underlaying protocol (NOT i/o layer)
@param buffer
@discussion This function must be implemented by the class that inherits this class
*/
virtual bool SignalInputData(IOBuffer &buffer) = 0;
private:
//utility function
string ToString(uint32_t currentId);
};
#endif /* _BASEPROTOCOL_H */
| 8,806
|
C++
|
.h
| 254
| 32.102362
| 222
| 0.769539
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,377
|
basetimerprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/timer/basetimerprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASETIMERPROTOCOL_H
#define _BASETIMERPROTOCOL_H
#include "protocols/baseprotocol.h"
class IOTimer;
class DLLEXP BaseTimerProtocol
: public BaseProtocol {
private:
IOTimer *_pTimer;
uint32_t _milliseconds;
protected:
string _name;
public:
BaseTimerProtocol();
virtual ~BaseTimerProtocol();
string GetName();
uint32_t GetTimerPeriodInMilliseconds();
double GetTimerPeriodInSeconds();
virtual IOHandler *GetIOHandler();
virtual void SetIOHandler(IOHandler *pIOHandler);
virtual bool EnqueueForTimeEvent(uint32_t seconds);
virtual bool EnqueueForHighGranularityTimeEvent(uint32_t milliseconds);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer);
};
#endif /* _BASETIMERPROTOCOL_H */
| 1,630
|
C++
|
.h
| 45
| 34.222222
| 72
| 0.788303
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,378
|
passthroughprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/passthrough/passthroughprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PASSTHROUGHPROTOCOL_H
#define _PASSTHROUGHPROTOCOL_H
#include "protocols/baseprotocol.h"
#include "streaming/basestream.h"
class InNetPassThroughStream;
class OutNetPassThroughStream;
class DLLEXP PassThroughProtocol
: public BaseProtocol {
private:
IOBuffer _inputBuffer;
IOBuffer _outputBuffer;
BaseStream *_pDummyStream;
public:
PassThroughProtocol();
virtual ~PassThroughProtocol();
virtual IOBuffer * GetOutputBuffer();
virtual void GetStats(Variant &info, uint32_t namespaceId);
virtual bool Initialize(Variant ¶meters);
void SetDummyStream(BaseStream *pDummyStream);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer);
virtual bool SignalInputData(IOBuffer &buffer, sockaddr_in *pPeerAddress);
bool SendTCPData(string &data);
private:
void CloseStream();
};
#endif /* _PASSTHROUGHPROTOCOL_H */
| 1,747
|
C++
|
.h
| 47
| 35.361702
| 75
| 0.79174
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,379
|
passthroughappprotocolhandler.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/passthrough/passthroughappprotocolhandler.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PASSTHROUGHAPPPROTOCOLHANDLER_H
#define _PASSTHROUGHAPPPROTOCOLHANDLER_H
#include "application/baseappprotocolhandler.h"
#define SCHEME_MPEGTSUDP "mpegtsudp"
#define SCHEME_MPEGTSTCP "mpegtstcp"
#define SCHEME_DEEP_MPEGTSUDP "dmpegtsudp"
#define SCHEME_DEEP_MPEGTSTCP "dmpegtstcp"
class DLLEXP PassThroughAppProtocolHandler
: public BaseAppProtocolHandler {
public:
PassThroughAppProtocolHandler(Variant &configuration);
virtual ~PassThroughAppProtocolHandler();
virtual void RegisterProtocol(BaseProtocol *pProtocol);
virtual void UnRegisterProtocol(BaseProtocol *pProtocol);
};
#endif /* _PASSTHROUGHAPPPROTOCOLHANDLER_H */
| 1,417
|
C++
|
.h
| 34
| 39.911765
| 72
| 0.796807
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,380
|
basevariantappprotocolhandler.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/variant/basevariantappprotocolhandler.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_VAR
#ifndef _BASEVARIANTAPPPROTOCOLHANDLER_H
#define _BASEVARIANTAPPPROTOCOLHANDLER_H
#include "application/baseappprotocolhandler.h"
class BaseVariantProtocol;
typedef enum {
VariantSerializer_BIN,
VariantSerializer_XML,
VariantSerializer_JSON
} VariantSerializer;
class DLLEXP BaseVariantAppProtocolHandler
: public BaseAppProtocolHandler {
private:
Variant _urlCache;
vector<uint64_t> _outboundHttpBinVariant;
vector<uint64_t> _outboundHttpXmlVariant;
vector<uint64_t> _outboundHttpJsonVariant;
vector<uint64_t> _outboundHttpsBinVariant;
vector<uint64_t> _outboundHttpsXmlVariant;
vector<uint64_t> _outboundHttpsJsonVariant;
vector<uint64_t> _outboundBinVariant;
vector<uint64_t> _outboundXmlVariant;
vector<uint64_t> _outboundJsonVariant;
public:
BaseVariantAppProtocolHandler(Variant &configuration);
virtual ~BaseVariantAppProtocolHandler();
virtual void RegisterProtocol(BaseProtocol *pProtocol);
virtual void UnRegisterProtocol(BaseProtocol *pProtocol);
//opens an OUTBOUNDXMLVARIANT or an OUTBOUNDBINVARIANT
//and sends the variant
bool Send(string ip, uint16_t port, Variant &variant,
VariantSerializer serializer = VariantSerializer_XML);
//opens an OUTBOUNDHTTPXMLVARIANT or an OUTBOUNDHTTPBINVARIANT
//and sends the variant (with optional client certificate setting)
bool Send(string url, Variant &variant,
VariantSerializer serializer = VariantSerializer_XML,
string serverCertificate = "", string clientCertificate = "",
string clientCertificateKey = "");
//used internally
static bool SignalProtocolCreated(BaseProtocol *pProtocol, Variant ¶meters);
virtual void ConnectionFailed(Variant ¶meters);
//this is called whenever a message is received
virtual bool ProcessMessage(BaseVariantProtocol *pProtocol,
Variant &lastSent, Variant &lastReceived);
private:
Variant &GetScaffold(string &uriString);
vector<uint64_t> &GetTransport(VariantSerializer serializerType, bool isHttp, bool isSsl);
};
#endif /* _BASEVARIANTAPPPROTOCOLHANDLER_H */
#endif /* HAS_PROTOCOL_VAR */
| 2,845
|
C++
|
.h
| 68
| 39.720588
| 91
| 0.806732
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,381
|
inboundjsoncliprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/cli/inboundjsoncliprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_CLI
#ifndef _INBOUNDJSONCLIPROTOCOL_H
#define _INBOUNDJSONCLIPROTOCOL_H
#include "protocols/cli/inboundbasecliprotocol.h"
class DLLEXP InboundJSONCLIProtocol
: public InboundBaseCLIProtocol {
private:
bool _useLengthPadding;
public:
InboundJSONCLIProtocol();
virtual ~InboundJSONCLIProtocol();
virtual bool Initialize(Variant ¶meters);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Woverloaded-virtual"
#endif /* __clang__ */
virtual bool SignalInputData(IOBuffer &buffer);
#ifdef __clang__
#pragma clang diagnostic pop
#endif /* __clang__ */
virtual bool SendMessage(Variant &message);
private:
bool ParseCommand(string &command);
};
#endif /* _INBOUNDJSONCLIPROTOCOL_H */
#endif /* HAS_PROTOCOL_CLI */
| 1,551
|
C++
|
.h
| 44
| 33.545455
| 72
| 0.772667
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,382
|
basertmpprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/basertmpprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _BASERTMPPROTOCOL_H
#define _BASERTMPPROTOCOL_H
#include "protocols/baseprotocol.h"
#include "protocols/rtmp/channel.h"
#include "protocols/rtmp/rtmpprotocolserializer.h"
#include "streaming/rtmpstream.h"
#include "mediaformats/readers/streammetadataresolver.h"
#define RECEIVED_BYTES_COUNT_REPORT_CHUNK 131072
#define MAX_CHANNELS_COUNT (64+255)
#define MAX_STREAMS_COUNT 256
#define MIN_AV_CHANNLES 20
#define MAX_AV_CHANNLES MAX_CHANNELS_COUNT
typedef enum {
RTMP_STATE_NOT_INITIALIZED,
RTMP_STATE_CLIENT_REQUEST_RECEIVED,
RTMP_STATE_CLIENT_REQUEST_SENT,
RTMP_STATE_SERVER_RESPONSE_SENT,
RTMP_STATE_DONE
} RTMPState;
class BaseStream;
class BaseOutStream;
class BaseOutNetRTMPStream;
class InFileRTMPStream;
class InNetRTMPStream;
class BaseRTMPAppProtocolHandler;
class ClientSO;
class DLLEXP BaseRTMPProtocol
: public BaseProtocol {
protected:
static uint8_t genuineFMSKey[];
static uint8_t genuineFPKey[];
bool _handshakeCompleted;
RTMPState _rtmpState;
IOBuffer _outputBuffer;
uint64_t _nextReceivedBytesCountReport;
uint32_t _winAckSize;
Channel _channels[MAX_CHANNELS_COUNT];
int32_t _selectedChannel;
uint32_t _inboundChunkSize;
uint32_t _outboundChunkSize;
BaseRTMPAppProtocolHandler *_pProtocolHandler;
RTMPProtocolSerializer _rtmpProtocolSerializer;
BaseStream *_streams[MAX_STREAMS_COUNT];
vector<uint32_t> _channelsPool;
LinkedListNode<BaseOutNetRTMPStream *> *_pSignaledRTMPOutNetStream;
map<InFileRTMPStream *, InFileRTMPStream *> _inFileStreams;
uint64_t _rxInvokes;
uint64_t _txInvokes;
map<string, ClientSO *> _sos;
public:
BaseRTMPProtocol(uint64_t protocolType);
virtual ~BaseRTMPProtocol();
ClientSO *GetSO(string &name);
bool CreateSO(string &name);
void SignalBeginSOProcess(string &name);
bool HandleSOPrimitive(string &name, Variant &primitive);
void SignalEndSOProcess(string &name, uint32_t versionNumber);
bool ClientSOSend(string &name, Variant ¶meters);
bool ClientSOSetProperty(string &soName, string &propName, Variant &propValue);
void SignalOutBufferFull(uint32_t outstanding, uint32_t maxValue);
virtual bool Initialize(Variant ¶meters);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual IOBuffer * GetOutputBuffer();
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer);
virtual bool TimePeriodElapsed();
virtual void ReadyForSend();
virtual void SetApplication(BaseClientApplication *pApplication);
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
bool ResetChannel(uint32_t channelId);
bool SendMessage(Variant &message);
bool SendRawData(Header &header, Channel &channel, uint8_t *pData, uint32_t length);
bool SendRawData(uint8_t *pData, uint32_t length);
void SetWinAckSize(uint32_t winAckSize);
uint32_t GetOutboundChunkSize();
bool SetInboundChunkSize(uint32_t chunkSize);
void TrySetOutboundChunkSize(uint32_t chunkSize);
BaseStream * GetRTMPStream(uint32_t rtmpStreamId);
bool CloseStream(uint32_t streamId, bool createNeutralStream);
RTMPStream * CreateNeutralStream(uint32_t &streamId);
InNetRTMPStream * CreateINS(uint32_t channelId, uint32_t streamId, string streamName);
BaseOutNetRTMPStream * CreateONS(uint32_t streamId, string streamName,
uint64_t inStreamType, uint32_t &clientSideBuffer);
void SignalONS(BaseOutNetRTMPStream *pONS);
InFileRTMPStream * CreateIFS(Metadata &metadata, bool hasTimer);
void RemoveIFS(InFileRTMPStream *pIFS);
Channel *ReserveChannel();
void ReleaseChannel(Channel *pChannel);
virtual bool EnqueueForTimeEvent(uint32_t seconds);
protected:
virtual bool PerformHandshake(IOBuffer &buffer) = 0;
uint32_t GetDHOffset(uint8_t *pBuffer, uint8_t schemeNumber);
uint32_t GetDigestOffset(uint8_t *pBuffer, uint8_t schemeNumber);
private:
uint32_t GetDHOffset0(uint8_t *pBuffer);
uint32_t GetDHOffset1(uint8_t *pBuffer);
uint32_t GetDigestOffset0(uint8_t *pBuffer);
uint32_t GetDigestOffset1(uint8_t *pBuffer);
bool ProcessBytes(IOBuffer &buffer);
};
#endif /* _BASERTMPPROTOCOL_H */
#endif /* HAS_PROTOCOL_RTMP */
| 4,913
|
C++
|
.h
| 122
| 38.327869
| 87
| 0.807676
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,383
|
basertmpappprotocolhandler.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/basertmpappprotocolhandler.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _BASERTMPAPPPROTOCOLHANDLER_H
#define _BASERTMPAPPPROTOCOLHANDLER_H
#include "application/baseappprotocolhandler.h"
#include "protocols/rtmp/header.h"
#include "protocols/rtmp/rtmpprotocolserializer.h"
#include "protocols/rtmp/sharedobjects/somanager.h"
#include "mediaformats/readers/streammetadataresolver.h"
class OutboundRTMPProtocol;
class BaseRTMPProtocol;
class ClientSO;
class DLLEXP BaseRTMPAppProtocolHandler
: public BaseAppProtocolHandler {
protected:
RTMPProtocolSerializer _rtmpProtocolSerializer;
SOManager _soManager;
bool _validateHandshake;
bool _enableCheckBandwidth;
Variant _onBWCheckMessage;
Variant _onBWCheckStrippedMessage;
map<uint32_t, BaseRTMPProtocol *> _connections;
map<uint32_t, uint32_t> _nextInvokeId;
map<uint32_t, map<uint32_t, Variant > > _resultMessageTracking;
Variant _adobeAuthSettings;
string _authMethod;
string _adobeAuthSalt;
double _lastUsersFileUpdate;
Variant _users;
public:
BaseRTMPAppProtocolHandler(Variant &configuration);
virtual ~BaseRTMPAppProtocolHandler();
virtual bool ParseAuthenticationNode(Variant &node, Variant &result);
/*
* This will return true if the application has the validateHandshake flag
* */
bool ValidateHandshake();
/*
* This will return the shared objects manager for this particular application
* */
SOManager *GetSOManager();
virtual void SignalClientSOConnected(BaseRTMPProtocol *pFrom, ClientSO *pClientSO);
virtual void SignalClientSOUpdated(BaseRTMPProtocol *pFrom, ClientSO *pClientSO);
virtual void SignalClientSOSend(BaseRTMPProtocol *pFrom, ClientSO *pClientSO,
Variant ¶meters);
virtual void SignalOutBufferFull(BaseRTMPProtocol *pFrom,
uint32_t outstanding, uint32_t maxValue);
/*
* (Un)Register connection. This is called by the framework
* each time a connections is going up or down
* pProtocol - the conection which is going up or down
* */
virtual void RegisterProtocol(BaseProtocol *pProtocol);
virtual void UnRegisterProtocol(BaseProtocol *pProtocol);
/*
* This is called by the framework when a stream needs to be pulled in
* Basically, this will open a RTMP client and start playback a stream
* */
virtual bool PullExternalStream(URI uri, Variant streamConfig);
virtual bool PullExternalStream(URI &uri, BaseRTMPProtocol *pFrom,
string &sourceName, string &destName);
/*
* This is called by the framework when a stream needs to be pushed forward
* Basically, this will open a RTMP client and start publishing a stream
* */
virtual bool PushLocalStream(Variant streamConfig);
virtual bool PushLocalStream(BaseRTMPProtocol *pFrom, string sourceName,
string destName);
/*
* This is called bt the framework when an outbound connection was established
* */
virtual bool OutboundConnectionEstablished(OutboundRTMPProtocol *pFrom);
/*
* This is called by the framework when authentication is needed upon
* connect invoke.
* pFrom - the connection requesting authentication
* request - full connect request
* */
virtual bool AuthenticateInbound(BaseRTMPProtocol *pFrom, Variant &request,
Variant &authState);
/*
* This is called by the framework when outstanding data is ready for processing
* pFrom - the connection that has data ready for processing
* inputBuffer - raw data
* */
virtual bool InboundMessageAvailable(BaseRTMPProtocol *pFrom, Header &header,
IOBuffer &inputBuffer);
/*
* This is called by the framework when a new message was successfully deserialized
* and is ready for processing
* pFrom - the connection that has data ready for processing
* request - complete request ready for processing
* */
virtual bool InboundMessageAvailable(BaseRTMPProtocol *pFrom, Variant &request);
//TODO: Commenting ou the protected section bellow is a quite nasty hack
//It is done to support virtual machines and out-of-hierarchy calls
//for the base class. This should be definitely removed and re-factored
//properly. I will leave it here for the time being
//protected:
/*
* The following list of functions are called when the corresponding
* message is received. All of them have the same parameters
* pFrom - the origin of the request
* request - the complete request
* */
virtual bool ProcessAbortMessage(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessWinAckSize(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessPeerBW(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessAck(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessChunkSize(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessUsrCtrl(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessNotify(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessFlexStreamSend(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessSharedObject(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessInvoke(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessInvokeConnect(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessInvokeClose(BaseRTMPProtocol *pFrom, Variant &request);
virtual bool ProcessInvokeCreateStream(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokePublish(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeSeek(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokePlay(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokePauseRaw(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokePause(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeCloseStream(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeReleaseStream(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeDeleteStream(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeOnStatus(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeFCPublish(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeFCSubscribe(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeGetStreamLength(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeOnBWDone(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeOnFCPublish(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeOnFCUnpublish(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeCheckBandwidth(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeGeneric(BaseRTMPProtocol *pFrom,
Variant &request);
virtual bool ProcessInvokeResult(BaseRTMPProtocol *pFrom,
Variant &result);
/*
* The following functions are called by the framework when a result
* is received from the distant peer (server made the request, and we just
* got a response). All of them have the same parameters
* pFrom - the connection which sent us the response
* request - the initial request
* response - the response
* */
virtual bool ProcessInvokeResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
virtual bool ProcessInvokeConnectResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
virtual bool ProcessInvokeReleaseStreamResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
virtual bool ProcessInvokeFCPublishStreamResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
virtual bool ProcessInvokeCreateStreamResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
virtual bool ProcessInvokeFCSubscribeResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
virtual bool ProcessInvokeOnBWCheckResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
virtual bool ProcessInvokeGenericResult(BaseRTMPProtocol *pFrom,
Variant &request, Variant &response);
/*
* Adobe authentication method used by FMLE.
* */
virtual bool AuthenticateInboundAdobe(BaseRTMPProtocol *pFrom, Variant &request,
Variant &authState);
/*
* This will return the password assigned to the specified user
* */
virtual string GetAuthPassword(string user);
/*
* Used to send generi RTMP messages
* pTo - target connection
* message - complete RTMP message
* trackResponse - if true, a response is expected after sending this message
* if one becomes available, ProcessInvokeResult will be called
* if false, no response is expected
* */
bool SendRTMPMessage(BaseRTMPProtocol *pTo, Variant message,
bool trackResponse = false);
/*
* Opens a client-side connection for a shared object
* */
bool OpenClientSharedObject(BaseRTMPProtocol *pFrom, string soName);
/*!
* Called by the framework when the RTMP connection is a dissector.
* Should be ONLY re-implemented in dissectors
*/
virtual bool FeedAVData(BaseRTMPProtocol *pFrom, uint8_t *pData,
uint32_t dataLength, uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
/*!
* Called by the framework when the RTMP connection is a dissector.
* Should be ONLY re-implemented in dissectors
*/
virtual bool FeedAVDataAggregate(BaseRTMPProtocol *pFrom, uint8_t *pData,
uint32_t dataLength, uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
private:
/*
* Will clear any leftovers from failed authentication attempts
*/
void ClearAuthenticationInfo(BaseProtocol *pFrom);
/*
* Tries to create an outbound stream and link it to the live inbound stream
* streamName - the name of the live inbound stream
* linked - will be set to true if the linking succeeded. Otherwise it will
* be set to false
* returns true if process returned successfully, or false otherwise
* */
bool TryLinkToLiveStream(BaseRTMPProtocol *pFrom, uint32_t streamId,
string streamName, bool &linked, string &aliasName);
/*
* Tries to create an outbound stream and link it to the file inbound stream
* streamName - the name of the file inbound stream
* linked - will be set to true if the linking succeeded. Otherwise it will
* be set to false
* returns true if process returned successfully, or false otherwise
* */
bool TryLinkToFileStream(BaseRTMPProtocol *pFrom, uint32_t streamId,
Metadata &metadata, string streamName, double startTime,
double length, bool &linked, string &aliasName);
/*
* This will return true if the connection is an outbound connection
* which needs to pull in a stream
* */
bool NeedsToPullExternalStream(BaseRTMPProtocol *pFrom);
/*
* This will return true if the connection is an outbound connection
* which is used to export a local stream
* */
bool NeedsToPushLocalStream(BaseRTMPProtocol *pFrom);
/*
* Initiate the stream pulling sequence: connect->createStream->Play
* */
bool PullExternalStream(BaseRTMPProtocol *pFrom);
/*
* Initiate the stream pushing sequence: connect->createStream->Publish
* */
bool PushLocalStream(BaseRTMPProtocol *pFrom);
/*
* Send the initial connect invoke
* */
bool ConnectForPullPush(BaseRTMPProtocol *pFrom, string uriPath,
Variant &config, bool isPull);
/*
* Log Event
**/
//Variant& CreateLogEventInvoke(BaseRTMPProtocol *pFrom, Variant &request);
Variant GetInvokeConnect(string appName,
string tcUrl,
double audioCodecs,
double capabilities,
string flashVer,
bool fPad,
string pageUrl,
string swfUrl,
double videoCodecs,
double videoFunction,
double objectEncoding,
Variant &streamConfig,
string &uriPath);
Variant GetInvokeConnectAuthAdobe(string appName,
string tcUrl,
double audioCodecs,
double capabilities,
string flashVer,
bool fPad,
string pageUrl,
string swfUrl,
double videoCodecs,
double videoFunction,
double objectEncoding,
Variant &streamConfig,
string &uriPath);
};
#endif /* _BASERTMPAPPPROTOCOLHANDLER_H */
#endif /* HAS_PROTOCOL_RTMP */
| 12,854
|
C++
|
.h
| 313
| 38.297125
| 84
| 0.787651
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,384
|
outboundrtmpprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/outboundrtmpprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _OUTBOUNDRTMPPROTOCOL_H
#define _OUTBOUNDRTMPPROTOCOL_H
#include "protocols/rtmp/basertmpprotocol.h"
class DHWrapper;
class DLLEXP OutboundRTMPProtocol
: public BaseRTMPProtocol {
private:
uint8_t *_pClientPublicKey;
uint8_t *_pOutputBuffer;
uint8_t *_pClientDigest;
RC4_KEY* _pKeyIn;
RC4_KEY* _pKeyOut;
DHWrapper *_pDHWrapper;
uint8_t _usedScheme;
bool _encrypted;
public:
OutboundRTMPProtocol();
virtual ~OutboundRTMPProtocol();
protected:
virtual bool PerformHandshake(IOBuffer &buffer);
public:
static bool Connect(string ip, uint16_t port, Variant customParameters);
static bool SignalProtocolCreated(BaseProtocol *pProtocol, Variant customParameters);
private:
bool PerformHandshakeStage1(bool encrypted);
bool VerifyServer(IOBuffer &inputBuffer);
bool PerformHandshakeStage2(IOBuffer &inputBuffer, bool encrypted);
};
#endif /* _OUTBOUNDRTMPPROTOCOL_H */
#endif /* HAS_PROTOCOL_RTMP */
| 1,723
|
C++
|
.h
| 49
| 33.326531
| 86
| 0.785714
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,385
|
inboundrtmpprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/inboundrtmpprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _INBOUNDRTMPPROTOCOL_H
#define _INBOUNDRTMPPROTOCOL_H
#include "protocols/rtmp/basertmpprotocol.h"
class DLLEXP InboundRTMPProtocol
: public BaseRTMPProtocol {
private:
RC4_KEY*_pKeyIn;
RC4_KEY*_pKeyOut;
uint8_t *_pOutputBuffer;
uint32_t _currentFPVersion;
uint8_t _usedScheme;
public:
InboundRTMPProtocol();
virtual ~InboundRTMPProtocol();
protected:
virtual bool PerformHandshake(IOBuffer &buffer);
private:
bool ValidateClient(IOBuffer &inputBuffer);
bool ValidateClientScheme(IOBuffer &inputBuffer, uint8_t scheme);
bool PerformHandshake(IOBuffer &buffer, bool encrypted);
bool PerformSimpleHandshake(IOBuffer &buffer);
bool PerformComplexHandshake(IOBuffer &buffer, bool encrypted);
};
#endif /* _INBOUNDRTMPPROTOCOL_H */
#endif /* HAS_PROTOCOL_RTMP */
| 1,583
|
C++
|
.h
| 44
| 34.159091
| 72
| 0.782779
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,386
|
rtmpoutputchecks.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/rtmpoutputchecks.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _MONITORRTMPPROTOCOL_H
#define _MONITORRTMPPROTOCOL_H
#include "protocols/baseprotocol.h"
#include "protocols/rtmp/channel.h"
#include "protocols/rtmp/rtmpprotocolserializer.h"
#include "streaming/rtmpstream.h"
class DLLEXP RTMPOutputChecks
: public BaseProtocol {
protected:
Channel *_channels;
int32_t _selectedChannel;
uint32_t _inboundChunkSize;
RTMPProtocolSerializer _rtmpProtocolSerializer;
IOBuffer _input;
uint32_t _maxStreamCount;
uint32_t _maxChannelsCount;
public:
RTMPOutputChecks(uint32_t maxStreamIndex, uint32_t maxChannelIndex);
virtual ~RTMPOutputChecks();
virtual bool Initialize(Variant ¶meters);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer);
bool SetInboundChunkSize(uint32_t chunkSize);
bool Feed(IOBuffer &buffer);
private:
bool ProcessBytes(IOBuffer &buffer);
};
#endif /* _MONITORRTMPPROTOCOL_H */
#endif /* HAS_PROTOCOL_RTMP */
| 1,838
|
C++
|
.h
| 50
| 34.84
| 72
| 0.790541
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,387
|
outfilertmpflvstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/streaming/outfilertmpflvstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _OUTFILERTMPFLVSTREAM_H
#define _OUTFILERTMPFLVSTREAM_H
#include "streaming/baseoutfilestream.h"
class DLLEXP OutFileRTMPFLVStream
: public BaseOutFileStream {
private:
File _file;
double _timeBase;
IOBuffer _audioBuffer;
IOBuffer _videoBuffer;
uint32_t _prevTagSize;
string _filename;
public:
OutFileRTMPFLVStream(BaseProtocol *pProtocol, string name, string filename);
virtual ~OutFileRTMPFLVStream();
void Initialize();
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual bool IsCompatibleWithType(uint64_t type);
virtual void SignalAttachedToInStream();
virtual void SignalDetachedFromInStream();
virtual void SignalStreamCompleted();
virtual void SignalAudioStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, AudioCodecInfo *pOld,
AudioCodecInfo *pNew);
virtual void SignalVideoStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, VideoCodecInfo *pOld,
VideoCodecInfo *pNew);
protected:
virtual bool PushVideoData(IOBuffer &buffer, double pts, double dts,
bool isKeyFrame);
virtual bool PushAudioData(IOBuffer &buffer, double pts, double dts);
virtual bool IsCodecSupported(uint64_t codec);
};
#endif /* _OUTFILERTMPFLVSTREAM_H */
#endif /* HAS_PROTOCOL_RTMP */
| 2,324
|
C++
|
.h
| 61
| 35.95082
| 77
| 0.791131
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,388
|
infilertmpstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/streaming/infilertmpstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _INFILERTMPSTREAM_H
#define _INFILERTMPSTREAM_H
#include "streaming/baseinfilestream.h"
#include "protocols/rtmp/header.h"
#include "protocols/rtmp/amf0serializer.h"
#include "mediaformats/readers/streammetadataresolver.h"
class BaseRTMPProtocol;
class StreamsManager;
class DLLEXP InFileRTMPStream
: public BaseInFileStream {
private:
class BaseBuilder {
public:
BaseBuilder();
virtual ~BaseBuilder();
virtual bool BuildFrame(MediaFile *pFile, MediaFrame &mediaFrame,
IOBuffer &buffer) = 0;
};
class AVCBuilder : public BaseBuilder {
private:
uint8_t _videoCodecHeaderInit[5];
uint8_t _videoCodecHeaderKeyFrame[2];
uint8_t _videoCodecHeader[2];
public:
AVCBuilder();
virtual ~AVCBuilder();
virtual bool BuildFrame(MediaFile *pFile, MediaFrame &mediaFrame,
IOBuffer &buffer);
};
class AACBuilder : public BaseBuilder {
private:
uint8_t _audioCodecHeaderInit[2];
uint8_t _audioCodecHeader[2];
public:
AACBuilder();
virtual ~AACBuilder();
virtual bool BuildFrame(MediaFile *pFile, MediaFrame &mediaFrame,
IOBuffer &buffer);
};
class MP3Builder : public BaseBuilder {
private:
public:
MP3Builder();
virtual ~MP3Builder();
virtual bool BuildFrame(MediaFile *pFile, MediaFrame &mediaFrame,
IOBuffer &buffer);
};
class PassThroughBuilder : public BaseBuilder {
public:
PassThroughBuilder();
virtual ~PassThroughBuilder();
virtual bool BuildFrame(MediaFile *pFile, MediaFrame &mediaFrame,
IOBuffer &buffer);
};
private:
BaseBuilder *_pAudioBuilder;
BaseBuilder *_pVideoBuilder;
IOBuffer _metadataBuffer;
AMF0Serializer _amfSerializer;
string _metadataName;
Variant _metadataParameters;
Variant _tempVariant;
protected:
Metadata _completeMetadata;
uint32_t _chunkSize;
public:
InFileRTMPStream(BaseProtocol *pProtocol,uint64_t type, string name);
virtual ~InFileRTMPStream();
virtual bool Initialize(Metadata &metadata, TimerType timerType,
uint32_t granularity);
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual bool IsCompatibleWithType(uint64_t type);
uint32_t GetChunkSize();
static InFileRTMPStream *GetInstance(BaseRTMPProtocol *pRTMPProtocol,
StreamsManager *pStreamsManager, Metadata &metadata);
void SetCompleteMetadata(Metadata &completeMetadata);
Metadata &GetCompleteMetadata();
virtual void SignalOutStreamAttached(BaseOutStream *pOutStream);
virtual void SignalOutStreamDetached(BaseOutStream *pOutStream);
virtual bool BuildFrame(MediaFile *pFile, MediaFrame &mediaFrame,
IOBuffer &buffer);
virtual bool FeedMetaData(MediaFile *pFile, MediaFrame &mediaFrame);
};
#endif /* _INFILERTMPSTREAM_H */
#endif /* HAS_PROTOCOL_RTMP */
| 3,584
|
C++
|
.h
| 106
| 31.339623
| 72
| 0.786335
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,389
|
outnetrtmp4tsstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/streaming/outnetrtmp4tsstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _OUTNETRTMP4TSSTREAM_H
#define _OUTNETRTMP4TSSTREAM_H
#include "protocols/rtmp/streaming/baseoutnetrtmpstream.h"
class DLLEXP OutNetRTMP4TSStream
: public BaseOutNetRTMPStream {
public:
OutNetRTMP4TSStream(BaseProtocol *pProtocol, string name, uint32_t rtmpStreamId,
uint32_t chunkSize);
virtual ~OutNetRTMP4TSStream();
virtual bool IsCompatibleWithType(uint64_t type);
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
protected:
virtual bool FinishInitialization(
GenericProcessDataSetup *pGenericProcessDataSetup);
virtual bool PushVideoData(IOBuffer &buffer, double pts, double dts,
bool isKeyFrame);
virtual bool PushAudioData(IOBuffer &buffer, double pts, double dts);
virtual bool IsCodecSupported(uint64_t codec);
};
#endif /* _OUTNETRTMP4TSSTREAM_H */
#endif /* HAS_PROTOCOL_RTMP */
| 1,726
|
C++
|
.h
| 42
| 38.928571
| 81
| 0.783881
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,390
|
innetrtmpstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/streaming/innetrtmpstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _INNETRTMPSTREAM_H
#define _INNETRTMPSTREAM_H
#include "streaming/baseinnetstream.h"
#include "streaming/streamcapabilities.h"
#include "mediaformats/readers/streammetadataresolver.h"
class BaseRTMPProtocol;
class BaseOutStream;
class DLLEXP InNetRTMPStream
: public BaseInNetStream {
private:
uint32_t _rtmpStreamId;
uint32_t _chunkSize;
uint32_t _channelId;
string _clientId;
int32_t _videoCts;
bool _dummy;
uint8_t _lastAudioCodec;
uint8_t _lastVideoCodec;
StreamCapabilities _streamCapabilities;
IOBuffer _aggregate;
public:
InNetRTMPStream(BaseProtocol *pProtocol, string name, uint32_t rtmpStreamId,
uint32_t chunkSize, uint32_t channelId);
virtual ~InNetRTMPStream();
virtual StreamCapabilities * GetCapabilities();
virtual void ReadyForSend();
virtual bool IsCompatibleWithType(uint64_t type);
uint32_t GetRTMPStreamId();
uint32_t GetChunkSize();
void SetChunkSize(uint32_t chunkSize);
bool SendStreamMessage(Variant &message);
virtual bool SendStreamMessage(string functionName, Variant ¶meters);
bool SendOnStatusStreamPublished();
bool RecordFLV(Metadata &meta, bool append);
bool RecordMP4(Metadata &meta);
virtual void SignalOutStreamAttached(BaseOutStream *pOutStream);
virtual void SignalOutStreamDetached(BaseOutStream *pOutStream);
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
virtual bool FeedDataAggregate(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
static bool InitializeAudioCapabilities(BaseInStream *pStream,
StreamCapabilities &streamCapabilities,
bool &capabilitiesInitialized, uint8_t *pData, uint32_t length);
static bool InitializeVideoCapabilities(BaseInStream *pStream,
StreamCapabilities &streamCapabilities,
bool &capabilitiesInitialized, uint8_t *pData, uint32_t length);
virtual uint32_t GetInputVideoTimescale();
virtual uint32_t GetInputAudioTimescale();
private:
string GetRecordedFileName(Metadata &meta);
BaseRTMPProtocol *GetRTMPProtocol();
};
#endif /* _INNETRTMPSTREAM_H */
#endif /* HAS_PROTOCOL_RTMP */
| 3,195
|
C++
|
.h
| 81
| 37.234568
| 77
| 0.799225
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,391
|
outnetrtmp4rtmpstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/streaming/outnetrtmp4rtmpstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _OUTNETRTMP4RTMPSTREAM_H
#define _OUTNETRTMP4RTMPSTREAM_H
#include "protocols/rtmp/streaming/baseoutnetrtmpstream.h"
class DLLEXP OutNetRTMP4RTMPStream
: public BaseOutNetRTMPStream {
public:
OutNetRTMP4RTMPStream(BaseProtocol *pProtocol, string name,
uint32_t rtmpStreamId, uint32_t chunkSize);
virtual ~OutNetRTMP4RTMPStream();
virtual bool IsCompatibleWithType(uint64_t type);
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
protected:
virtual bool PushVideoData(IOBuffer &buffer, double pts, double dts,
bool isKeyFrame);
virtual bool PushAudioData(IOBuffer &buffer, double pts, double dts);
virtual bool IsCodecSupported(uint64_t codec);
};
#endif /* _OUTNETRTMP4RTMPSTREAM_H */
#endif /* HAS_PROTOCOL_RTMP */
| 1,647
|
C++
|
.h
| 40
| 39.05
| 72
| 0.78035
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,392
|
baseoutnetrtmpstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/streaming/baseoutnetrtmpstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _BASEOUTNETRTMPSTREAM_H
#define _BASEOUTNETRTMPSTREAM_H
#include "streaming/baseoutnetstream.h"
#include "protocols/rtmp/header.h"
#include "protocols/rtmp/channel.h"
#include "mediaformats/readers/streammetadataresolver.h"
class BaseRTMPProtocol;
class DLLEXP BaseOutNetRTMPStream
: public BaseOutNetStream {
private:
uint32_t _rtmpStreamId;
uint32_t _chunkSize;
BaseRTMPProtocol *_pRTMPProtocol;
double _seekTime;
double _start;
uint32_t _isFirstVideoFrame;
Header _videoHeader;
IOBuffer _videoBucket;
uint32_t _isFirstAudioFrame;
Header _audioHeader;
IOBuffer _audioBucket;
Channel *_pChannelAudio;
Channel *_pChannelVideo;
Channel *_pChannelCommands;
uint32_t _feederChunkSize;
bool _canDropFrames;
bool _audioCurrentFrameDropped;
bool _videoCurrentFrameDropped;
uint32_t _maxBufferSize;
uint64_t _attachedStreamType;
string _clientId;
bool _paused;
bool _sendOnStatusPlayMessages;
PublicMetadata _metadata;
uint64_t _metaFileSize;
double _metaFileDuration;
bool _absoluteTimestamps;
protected:
BaseOutNetRTMPStream(BaseProtocol *pProtocol, uint64_t type, string name,
uint32_t rtmpStreamId, uint32_t chunkSize);
public:
static BaseOutNetRTMPStream *GetInstance(BaseProtocol *pProtocol,
StreamsManager *pStreamsManager,
string name, uint32_t rtmpStreamId,
uint32_t chunkSize,
uint64_t inStreamType);
virtual ~BaseOutNetRTMPStream();
uint32_t GetRTMPStreamId();
uint32_t GetCommandsChannelId();
void SetChunkSize(uint32_t chunkSize);
uint32_t GetChunkSize();
void SetFeederChunkSize(uint32_t feederChunkSize);
bool CanDropFrames();
void CanDropFrames(bool canDropFrames);
void SetSendOnStatusPlayMessages(bool value);
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
virtual bool SendStreamMessage(Variant &message);
virtual void SignalAttachedToInStream();
virtual void SignalDetachedFromInStream();
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
virtual void SignalStreamCompleted();
virtual void SignalAudioStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, AudioCodecInfo *pOld,
AudioCodecInfo *pNew);
virtual void SignalVideoStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, VideoCodecInfo *pOld,
VideoCodecInfo *pNew);
protected:
virtual bool InternalFeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double dts, bool isAudio);
bool FeedAudioCodecBytes(StreamCapabilities *pCapabilities, double dts, bool isAbsolute);
bool FeedVideoCodecBytes(StreamCapabilities *pCapabilities, double dts, bool isAbsolute);
private:
bool ChunkAndSend(uint8_t *pData, uint32_t length, IOBuffer &bucket,
Header &header, Channel &channel);
bool AllowExecution(uint32_t totalProcessed, uint32_t dataLength, bool isAudio);
void InternalReset();
void GetMetadata();
bool SendOnMetadata();
};
#endif /* _BASEOUTNETRTMPSTREAM_H */
#endif /* HAS_PROTOCOL_RTMP */
| 3,876
|
C++
|
.h
| 106
| 34.349057
| 90
| 0.804371
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,393
|
rtmpstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/streaming/rtmpstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _RTMPSTREAM_H
#define _RTMPSTREAM_H
#include "streaming/basestream.h"
class DLLEXP RTMPStream
: public BaseStream {
private:
uint32_t _rtmpStreamId;
uint32_t _clientSideBufer;
public:
RTMPStream(BaseProtocol *pProtocol, uint32_t rtmpStreamId);
virtual ~RTMPStream();
virtual StreamCapabilities * GetCapabilities();
void SetClientSideBuffer(uint32_t value);
uint32_t GetClientSideBuffer();
virtual bool Play(double dts, double length);
virtual bool Pause();
virtual bool Resume();
virtual bool Seek(double dts);
virtual bool Stop();
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual void ReadyForSend();
virtual bool IsCompatibleWithType(uint64_t type);
};
#endif /* _RTMPSTREAM_H */
#endif /* HAS_PROTOCOL_RTMP */
| 1,835
|
C++
|
.h
| 51
| 33.960784
| 72
| 0.769577
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,394
|
streammessagefactory.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtmp/messagefactories/streammessagefactory.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTMP
#ifndef _STREAMMESSAGEFACTORY_H
#define _STREAMMESSAGEFACTORY_H
#include "protocols/rtmp/messagefactories/genericmessagefactory.h"
class DLLEXP StreamMessageFactory {
public:
//stream control
static Variant GetUserControlStream(uint16_t operation, uint32_t streamId);
static Variant GetUserControlStreamBegin(uint32_t streamId);
static Variant GetUserControlStreamEof(uint32_t streamId);
static Variant GetUserControlStreamDry(uint32_t streamId);
static Variant GetUserControlStreamIsRecorded(uint32_t streamId);
static Variant GetUserControlStreamSetBufferlength(uint32_t streamId,
uint32_t value);
//management requests
static Variant GetInvokeCreateStream();
static Variant GetInvokeReleaseStream(string streamName);
static Variant GetInvokeCloseStream(uint32_t channelId, uint32_t streamId);
static Variant GetInvokeDeleteStream(uint32_t channelId, uint32_t streamId);
static Variant GetInvokePublish(uint32_t channelId, uint32_t streamId,
string streamName, string mode = "live");
static Variant GetInvokePlay(uint32_t channelId, uint32_t streamId,
string streamName, double start, double length);
static Variant GetInvokeFCSubscribe(string streamName);
static Variant GetInvokeFCPublish(string streamName);
//management responses
static Variant GetInvokeCreateStreamResult(Variant &request,
double createdStreamId);
static Variant GetInvokeCreateStreamResult(uint32_t channelId,
uint32_t streamId, uint32_t requestId, double createdStreamId);
static Variant GetInvokeReleaseStreamResult(uint32_t channelId,
uint32_t streamId, uint32_t requestId, double releasedStreamId);
static Variant GetInvokeReleaseStreamErrorNotFound(Variant &request);
static Variant GetInvokeOnFCPublish(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string code, string description);
static Variant GetInvokeOnFCSubscribe(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string code, string description);
//event notifications
static Variant GetInvokeOnStatusStreamPublishBadName(Variant &request,
string streamName);
static Variant GetInvokeOnStatusStreamPublishBadName(uint32_t channelId,
uint32_t streamId, double requestId, string streamName);
static Variant GetInvokeOnStatusStreamPublished(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string level, string code, string description,
string details, string clientId);
static Variant GetInvokeOnStatusStreamPlayFailed(Variant &request,
string streamName);
static Variant GetInvokeOnStatusStreamPlayFailed(uint32_t channelId,
uint32_t streamId, double requestId, string streamName);
static Variant GetInvokeOnStatusStreamPlayReset(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string description, string details, string clientId);
static Variant GetInvokeOnStatusStreamPlayStart(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string description, string details, string clientId);
static Variant GetInvokeOnStatusStreamPlayStop(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string description, string details, string clientId);
static Variant GetInvokeOnStatusStreamPlayUnpublishNotify(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string description, string clientId);
static Variant GetInvokeOnStatusStreamSeekNotify(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string description, string details, string clientId);
static Variant GetInvokeOnStatusStreamPauseNotify(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string description, string details, string clientId);
static Variant GetInvokeOnStatusStreamUnpauseNotify(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double requestId, string description, string details, string clientId);
static Variant GetNotifyRtmpSampleAccess(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
bool unknown1, bool unknown2);
static Variant GetNotifyOnMetaData(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
Variant metadata, bool dataKeyFrame);
static Variant GetNotifyOnPlayStatusPlayComplete(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute,
double bytes, double duration);
static Variant GetNotifyOnStatusDataStart(uint32_t channelId,
uint32_t streamId, double timeStamp, bool isAbsolute);
//generic stream send
static Variant GetFlexStreamSend(uint32_t channelId, uint32_t streamId,
double timeStamp, bool isAbsolute, string function,
Variant ¶meters);
};
#endif /* _STREAMMESSAGEFACTORY_H */
#endif /* HAS_PROTOCOL_RTMP */
| 5,784
|
C++
|
.h
| 109
| 50.321101
| 78
| 0.820268
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,395
|
inboundtsprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/ts/inboundtsprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined HAS_PROTOCOL_TS && defined HAS_MEDIA_TS
#ifndef _INBOUNDTSPROTOCOL_H
#define _INBOUNDTSPROTOCOL_H
#include "protocols/baseprotocol.h"
#include "mediaformats/readers/ts/pidtypes.h"
#include "mediaformats/readers/ts/tspacketheader.h"
#include "mediaformats/readers/ts/piddescriptor.h"
#include "mediaformats/readers/ts/tsparsereventsink.h"
#define TS_CHUNK_188 188
#define TS_CHUNK_204 204
#define TS_CHUNK_208 208
class TSParser;
class BaseTSAppProtocolHandler;
class InNetTSStream;
class DLLEXP InboundTSProtocol
: public BaseProtocol, TSParserEventsSink {
private:
uint32_t _chunkSizeDetectionCount;
uint32_t _chunkSize;
BaseTSAppProtocolHandler *_pProtocolHandler;
TSParser *_pParser;
InNetTSStream *_pInStream;
public:
InboundTSProtocol();
virtual ~InboundTSProtocol();
virtual bool Initialize(Variant ¶meters);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer, sockaddr_in *pPeerAddress);
virtual bool SignalInputData(IOBuffer &buffer);
virtual void SetApplication(BaseClientApplication *pApplication);
BaseTSAppProtocolHandler *GetProtocolHandler();
uint32_t GetChunkSize();
virtual BaseInStream *GetInStream();
virtual void SignalResetChunkSize();
virtual void SignalPAT(TSPacketPAT *pPAT);
virtual void SignalPMT(TSPacketPMT *pPMT);
virtual void SignalPMTComplete();
virtual bool SignalStreamsPIDSChanged(map<uint16_t, TSStreamInfo> &streams);
virtual bool SignalStreamPIDDetected(TSStreamInfo &streamInfo,
BaseAVContext *pContext, PIDType type, bool &ignore);
virtual void SignalUnknownPIDDetected(TSStreamInfo &streamInfo);
virtual bool FeedData(BaseAVContext *pContext, uint8_t *pData,
uint32_t dataLength, double pts, double dts, bool isAudio);
private:
bool DetermineChunkSize(IOBuffer &buffer);
};
#endif /* _INBOUNDTSPROTOCOL_H */
#endif /* defined HAS_PROTOCOL_TS && defined HAS_MEDIA_TS */
| 2,779
|
C++
|
.h
| 68
| 38.970588
| 77
| 0.802519
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,396
|
basetsappprotocolhandler.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/ts/basetsappprotocolhandler.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined HAS_PROTOCOL_TS && defined HAS_MEDIA_TS
#ifndef _BASETSAPPPROTOCOLHANDLER_H
#define _BASETSAPPPROTOCOLHANDLER_H
#include "application/baseappprotocolhandler.h"
class BaseClientApplication;
class InboundTSProtocol;
class InNetTSStream;
class DLLEXP BaseTSAppProtocolHandler
: public BaseAppProtocolHandler {
public:
BaseTSAppProtocolHandler(Variant &configuration);
virtual ~BaseTSAppProtocolHandler();
virtual void RegisterProtocol(BaseProtocol *pProtocol);
virtual void UnRegisterProtocol(BaseProtocol *pProtocol);
};
#endif /* _BASETSAPPPROTOCOLHANDLER_H */
#endif /* defined HAS_PROTOCOL_TS && defined HAS_MEDIA_TS */
| 1,420
|
C++
|
.h
| 35
| 38.685714
| 72
| 0.789091
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,397
|
innettsstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/ts/innettsstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined HAS_PROTOCOL_TS && defined HAS_MEDIA_TS
#ifndef _INNETTSSTREAM_H
#define _INNETTSSTREAM_H
#include "streaming/baseinnetstream.h"
#include "streaming/streamcapabilities.h"
class DLLEXP InNetTSStream
: public BaseInNetStream {
private:
//audio section
bool _hasAudio;
//video section
bool _hasVideo;
StreamCapabilities _streamCapabilities;
bool _enabled;
public:
InNetTSStream(BaseProtocol *pProtocol, string name, uint32_t bandwidthHint);
virtual ~InNetTSStream();
virtual StreamCapabilities * GetCapabilities();
bool HasAudio();
void HasAudio(bool value);
bool HasVideo();
void HasVideo(bool value);
void Enable(bool value);
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual void ReadyForSend();
virtual bool IsCompatibleWithType(uint64_t type);
virtual void SignalOutStreamAttached(BaseOutStream *pOutStream);
virtual void SignalOutStreamDetached(BaseOutStream *pOutStream);
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
};
#endif /* _INNETTSSTREAM_H */
#endif /* defined HAS_PROTOCOL_TS && defined HAS_MEDIA_TS */
| 2,076
|
C++
|
.h
| 56
| 35.035714
| 77
| 0.778995
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,398
|
basertspappprotocolhandler.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/basertspappprotocolhandler.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _BASERTSPAPPPROTOCOLHANDLER_H
#define _BASERTSPAPPPROTOCOLHANDLER_H
#include "application/baseappprotocolhandler.h"
#include "streaming/streamcapabilities.h"
class RTSPProtocol;
class BaseInNetStream;
class OutboundConnectivity;
class DLLEXP BaseRTSPAppProtocolHandler
: public BaseAppProtocolHandler {
protected:
Variant _realms;
string _usersFile;
bool _authenticatePlay;
double _lastUsersFileUpdate;
map<string, uint32_t> _httpSessions;
public:
BaseRTSPAppProtocolHandler(Variant &configuration);
virtual ~BaseRTSPAppProtocolHandler();
virtual bool ParseAuthenticationNode(Variant &node, Variant &result);
virtual void RegisterProtocol(BaseProtocol *pProtocol);
virtual void UnRegisterProtocol(BaseProtocol *pProtocol);
virtual bool PullExternalStream(URI uri, Variant streamConfig);
virtual bool PushLocalStream(Variant streamConfig);
static bool SignalProtocolCreated(BaseProtocol *pProtocol,
Variant ¶meters);
virtual bool HandleHTTPRequest(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent);
virtual bool HandleRTSPRequest(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent);
virtual bool HandleRTSPResponse(RTSPProtocol *pFrom, Variant &responseHeaders,
string &responseContent);
virtual bool HandleHTTPResponse(RTSPProtocol *pFrom, Variant &responseHeaders,
string &responseContent);
protected:
//handle requests routines
virtual bool HandleRTSPRequestOptions(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestDescribe(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestSetup(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestSetupOutbound(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestSetupInbound(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestTearDown(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestAnnounce(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestPause(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestPlayOrRecord(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestPlay(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestRecord(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestSetParameter(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual bool HandleRTSPRequestGetParameter(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
//handle response routines
virtual bool HandleHTTPResponse(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleHTTPResponse200(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleHTTPResponse401(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleHTTPResponse200Get(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleHTTPResponse401Get(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse200(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse401(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse404(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse200Options(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse200Describe(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse200Setup(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse200Play(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse200Announce(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse200Record(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse404Play(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
virtual bool HandleRTSPResponse404Describe(RTSPProtocol *pFrom, Variant &requestHeaders,
string &requestContent, Variant &responseHeaders,
string &responseContent);
//operations
virtual bool TriggerPlayOrAnnounce(RTSPProtocol *pFrom);
protected:
virtual bool NeedAuthentication(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
virtual string GetAuthenticationRealm(RTSPProtocol *pFrom,
Variant &requestHeaders, string &requestContent);
private:
void ComputeRTPInfoHeader(RTSPProtocol *pFrom,
OutboundConnectivity *pOutboundConnectivity, double start);
void ParseRange(string raw, double &start, double &end);
double ParseNPT(string raw);
bool AnalyzeUri(RTSPProtocol *pFrom, string rawUri);
string GetStreamName(RTSPProtocol *pFrom);
OutboundConnectivity *GetOutboundConnectivity(RTSPProtocol *pFrom, bool forceTcp);
BaseInStream *GetInboundStream(string streamName, RTSPProtocol *pFrom);
StreamCapabilities *GetInboundStreamCapabilities(string streamName, RTSPProtocol *pFrom);
string GetAudioTrack(RTSPProtocol *pFrom,
StreamCapabilities *pCapabilities);
string GetVideoTrack(RTSPProtocol *pFrom,
StreamCapabilities *pCapabilities);
bool SendSetupTrackMessages(RTSPProtocol *pFrom);
bool ParseUsersFile();
bool SendAuthenticationChallenge(RTSPProtocol *pFrom, Variant &realm);
string ComputeSDP(RTSPProtocol *pFrom, string localStreamName,
string targetStreamName, bool isAnnounce);
void EnableDisableOutput(RTSPProtocol *pFrom, bool value);
};
#endif /* _BASERTSPAPPPROTOCOLHANDLER_H */
#endif /* HAS_PROTOCOL_RTP */
| 7,993
|
C++
|
.h
| 162
| 46.660494
| 90
| 0.82681
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,399
|
inboundrtpprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/inboundrtpprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _INBOUNDRTPPROTOCOL_H
#define _INBOUNDRTPPROTOCOL_H
#include "protocols/baseprotocol.h"
#include "protocols/rtp/rtpheader.h"
class InNetRTPStream;
class InboundConnectivity;
//#define RTP_DETECT_ROLLOVER
class DLLEXP InboundRTPProtocol
: public BaseProtocol {
private:
RTPHeader _rtpHeader;
uint8_t _spsPpsPeriod;
InNetRTPStream *_pInStream;
InboundConnectivity *_pConnectivity;
uint16_t _lastSeq;
uint16_t _seqRollOver;
bool _isAudio;
uint32_t _packetsCount;
bool _unsolicited;
#ifdef RTP_DETECT_ROLLOVER
uint64_t _lastTimestamp;
uint64_t _timestampRollover;
#endif
public:
InboundRTPProtocol();
virtual ~InboundRTPProtocol();
virtual bool Initialize(Variant ¶meters);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer);
virtual bool SignalInputData(IOBuffer &buffer, sockaddr_in *pPeerAddress);
uint32_t GetSSRC();
uint32_t GetExtendedSeq();
void SetStream(InNetRTPStream *pInStream, bool isAudio, bool unsolicited);
void SetInbboundConnectivity(InboundConnectivity *pConnectivity);
};
#endif /* _INBOUNDRTPPROTOCOL_H */
#endif /* HAS_PROTOCOL_RTP */
| 2,034
|
C++
|
.h
| 58
| 33.206897
| 75
| 0.791455
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,400
|
sdp.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/sdp.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _SDP_H
#define _SDP_H
#include "common.h"
#define SDP_SESSION "session"
#define SDP_MEDIATRACKS "mediaTracks"
#define SDP_A "attributes"
#define SDP_B "bandwidth"
#define SDP_C "connection"
#define SDP_E "email"
#define SDP_I "sessionInfo"
#define SDP_K "encryptionKey"
#define SDP_M "media"
#define SDP_O "owner"
#define SDP_P "phone"
#define SDP_R "repeat"
#define SDP_S "sessionName"
#define SDP_T "startStopTime"
#define SDP_U "descriptionUri"
#define SDP_V "version"
#define SDP_Z "timeZone"
#define SDP_TRACK_GLOBAL_INDEX(x) ((x)["globalTrackIndex"])
#define SDP_TRACK_IS_AUDIO(x) ((x)["isAudio"])
#define SDP_TRACK_BANDWIDTH(x) ((x)["bandwidth"])
#define SDP_TRACK_CLOCKRATE(x) ((x)["clockRate"])
#define SDP_VIDEO_SERVER_IP(x) ((x)["ip"])
#define SDP_VIDEO_CONTROL_URI(x) ((x)["controlUri"])
#define SDP_VIDEO_CODEC(x) ((x)["codec"])
#define SDP_VIDEO_CODEC_H264_SPS(x) ((x)["h264SPS"])
#define SDP_VIDEO_CODEC_H264_PPS(x) ((x)["h264PPS"])
#define SDP_AUDIO_SERVER_IP(x) ((x)["ip"])
#define SDP_AUDIO_CONTROL_URI(x) ((x)["controlUri"])
#define SDP_AUDIO_CODEC(x) ((x)["codec"])
#define SDP_AUDIO_CODEC_SETUP(x) ((x)["codecSetup"])
#define SDP_AUDIO_TRANSPORT(x) ((x)["encodingNameString"])
class DLLEXP SDP
: public Variant {
public:
SDP();
virtual ~SDP();
static bool ParseSDP(SDP &sdp, string &raw);
Variant GetVideoTrack(uint32_t index, string contentBase);
Variant GetAudioTrack(uint32_t index, string contentBase);
string GetStreamName();
uint32_t GetTotalBandwidth();
static bool ParseTransportLine(string raw, Variant &result);
static bool ParseTransportLinePart(string raw, Variant &result);
private:
static bool ParseSection(Variant &result, vector<string> &lines,
uint32_t start, uint32_t length);
static bool ParseSDPLine(Variant &result, string &line);
static bool ParseSDPLineA(string &attributeName, Variant &value, string line);
static bool ParseSDPLineB(Variant &result, string line);
static bool ParseSDPLineC(Variant &result, string line);
static bool ParseSDPLineE(Variant &result, string line);
static bool ParseSDPLineI(Variant &result, string line);
static bool ParseSDPLineK(Variant &result, string line);
static bool ParseSDPLineM(Variant &result, string line);
static bool ParseSDPLineO(Variant &result, string line);
static bool ParseSDPLineP(Variant &result, string line);
static bool ParseSDPLineR(Variant &result, string line);
static bool ParseSDPLineS(Variant &result, string line);
static bool ParseSDPLineT(Variant &result, string line);
static bool ParseSDPLineU(Variant &result, string line);
static bool ParseSDPLineV(Variant &result, string line);
static bool ParseSDPLineZ(Variant &result, string line);
Variant GetTrack(uint32_t index, string type);
private:
Variant ParseVideoTrack(Variant &track);
Variant ParseAudioTrack(Variant &track);
};
#endif /* _SDP_H */
#endif /* HAS_PROTOCOL_RTP */
| 3,730
|
C++
|
.h
| 91
| 39.32967
| 79
| 0.749449
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,401
|
nattraversalprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/nattraversalprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _NATTRAVERSALPROTOCOL_H
#define _NATTRAVERSALPROTOCOL_H
#include "protocols/baseprotocol.h"
class OutboundConnectivity;
class NATTraversalProtocol
: public BaseProtocol {
sockaddr_in *_pOutboundAddress;
public:
NATTraversalProtocol();
virtual ~NATTraversalProtocol();
virtual bool Initialize(Variant ¶meters);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer);
virtual bool SignalInputData(IOBuffer &buffer, sockaddr_in *pPeerAddress);
void SetOutboundAddress(sockaddr_in *pOutboundAddress);
};
#endif /* _NATTRAVERSALPROTOCOL_H */
#endif /* HAS_PROTOCOL_RTP */
| 1,528
|
C++
|
.h
| 39
| 37.307692
| 75
| 0.785425
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,402
|
rtspprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/rtspprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _RTSPPROTOCOL_H
#define _RTSPPROTOCOL_H
#include "protocols/baseprotocol.h"
#include "protocols/timer/basetimerprotocol.h"
#include "protocols/rtp/sdp.h"
#include "streaming/baseoutnetrtpudpstream.h"
class BaseRTSPAppProtocolHandler;
class BaseInNetStream;
class BaseOutNetRTPUDPStream;
class InboundRTPProtocol;
class InNetRTPStream;
class OutboundConnectivity;
class InboundConnectivity;
class BaseOutStream;
class PassThroughProtocol;
struct RTPClient;
//#define RTSP_DUMP_TRAFFIC
class DLLEXP RTSPProtocol
: public BaseProtocol {
private:
class RTSPKeepAliveTimer
: public BaseTimerProtocol {
private:
uint32_t _protocolId;
public:
RTSPKeepAliveTimer(uint32_t protocolId);
virtual ~RTSPKeepAliveTimer();
virtual bool TimePeriodElapsed();
};
#ifdef RTSP_DUMP_TRAFFIC
string _debugInputData;
#endif /* RTSP_DUMP_TRAFFIC */
protected:
uint32_t _state;
bool _rtpData;
uint32_t _rtpDataLength;
uint32_t _rtpDataChanel;
Variant _inboundHeaders;
string _inboundContent;
uint32_t _contentLength;
SDP _inboundSDP;
BaseRTSPAppProtocolHandler *_pProtocolHandler;
IOBuffer _outputBuffer;
Variant _responseHeaders;
string _responseContent;
Variant _requestHeaders;
string _requestContent;
uint32_t _requestSequence;
map<uint32_t, Variant> _pendingRequestHeaders;
map<uint32_t, string> _pendingRequestContent;
OutboundConnectivity *_pOutboundConnectivity;
InboundConnectivity *_pInboundConnectivity;
Variant _authentication;
uint32_t _keepAliveTimerId;
BaseOutStream *_pOutStream;
string _keepAliveURI;
string _keepAliveMethod;
string _sessionId;
bool _enableTearDown;
IOBuffer _internalBuffer;
uint32_t _maxBufferSize;
uint32_t _clientSideBuffer;
bool _isHTTPTunneled;
string _xSessionCookie;
string _httpTunnelUri;
string _httpTunnelHostPort;
uint32_t _passThroughProtocolId;
public:
RTSPProtocol();
virtual ~RTSPProtocol();
virtual IOBuffer * GetOutputBuffer();
virtual bool Initialize(Variant ¶meters);
virtual void SetApplication(BaseClientApplication *pApplication);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
bool FeedRTSPRequest(string &data);
virtual bool SignalInputData(IOBuffer &buffer);
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
virtual void EnqueueForDelete();
void IsHTTPTunneled(bool value);
bool IsHTTPTunneled();
bool OpenHTTPTunnel();
string GetSessionId();
string GenerateSessionId();
bool SetSessionId(string sessionId);
bool SetAuthentication(string authenticateHeader, string userName,
string password, bool isRtsp);
void EnableSendRenewStream();
bool EnableKeepAlive(uint32_t period, string keepAliveURI);
void EnableTearDown();
void SetKeepAliveMethod(string keepAliveMethod);
bool SendKeepAlive();
bool HasConnectivity();
SDP &GetInboundSDP();
//void ClearRequestMessage();
void PushRequestFirstLine(string method, string url, string version);
void PushRequestHeader(string name, string value);
void PushRequestContent(string outboundContent, bool append);
bool SendRequestMessage();
uint32_t LastRequestSequence();
bool GetRequest(uint32_t seqId, Variant &result, string &content);
void ClearResponseMessage();
void PushResponseFirstLine(string version, uint32_t code, string reason);
void PushResponseHeader(string name, string value);
void PushResponseContent(string outboundContent, bool append);
bool SendResponseMessage();
OutboundConnectivity * GetOutboundConnectivity(BaseInNetStream *pInNetStream,
bool forceTcp);
void CloseOutboundConnectivity();
InboundConnectivity *GetInboundConnectivity(string sdpStreamName,
uint32_t bandwidthHint, uint8_t rtcpDetectionInterval);
InboundConnectivity *GetInboundConnectivity();
// InboundConnectivity *GetInboundConnectivity1(Variant &videoTrack,
// Variant &audioTrack, string sdpStreamName, uint32_t bandwidthHint);
void CloseInboundConnectivity();
bool SendRaw(uint8_t *pBuffer, uint32_t length, bool allowDrop);
bool SendRaw(MSGHDR *pMessage, uint16_t length, RTPClient *pClient,
bool isAudio, bool isData, bool allowDrop);
void SetOutStream(BaseOutStream *pOutStream);
static bool SignalProtocolCreated(BaseProtocol *pProtocol,
Variant ¶meters);
private:
bool SignalPassThroughProtocolCreated(PassThroughProtocol *pProtocol,
Variant ¶meters);
bool SendMessage(string &firstLine, Variant &headers, string &content);
bool ParseHeaders(IOBuffer &buffer);
bool ParseInterleavedHeaders(IOBuffer &buffer);
bool ParseNormalHeaders(IOBuffer &buffer);
bool ParseFirstLine(string &line);
bool HandleRTSPMessage(IOBuffer &buffer);
};
#endif /* _RTSPPROTOCOL_H */
#endif /* HAS_PROTOCOL_RTP */
| 5,541
|
C++
|
.h
| 153
| 34.130719
| 78
| 0.814214
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,403
|
inboundconnectivity.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/connectivity/inboundconnectivity.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _INBOUNDCONNECTIVITY_H
#define _INBOUNDCONNECTIVITY_H
#include "protocols/rtp/connectivity/baseconnectivity.h"
class InboundRTPProtocol;
class RTCPProtocol;
class InNetRTPStream;
class RTSPProtocol;
class BaseProtocol;
class DLLEXP InboundConnectivity
: public BaseConnectivity {
private:
RTSPProtocol *_pRTSP;
uint32_t _rtpVideoId;
uint32_t _rtcpVideoId;
uint8_t _videoRR[60];
Variant _videoTrack;
uint32_t _rtpAudioId;
uint32_t _rtcpAudioId;
uint8_t _audioRR[60];
Variant _audioTrack;
InNetRTPStream *_pInStream;
BaseProtocol *_pProtocols[256];
IOBuffer _inputBuffer;
sockaddr_in _dummyAddress;
bool _forceTcp;
string _streamName;
uint32_t _bandwidthHint;
uint8_t _rtcpDetectionInterval;
public:
InboundConnectivity(RTSPProtocol *pRTSP, string streamName,
uint32_t bandwidthHint, uint8_t rtcpDetectionInterval);
virtual ~InboundConnectivity();
void EnqueueForDelete();
bool AddTrack(Variant &track, bool isAudio);
bool Initialize();
string GetTransportHeaderLine(bool isAudio, bool isClient);
bool FeedData(uint32_t channelId, uint8_t *pBuffer, uint32_t bufferLength);
string GetClientPorts(bool isAudio);
string GetAudioClientPorts();
string GetVideoClientPorts();
bool SendRR(bool isAudio);
void ReportSR(uint64_t ntpMicroseconds, uint32_t rtpTimestamp, bool isAudio);
private:
void Cleanup();
bool CreateCarriers(InboundRTPProtocol *pRTP, RTCPProtocol *pRTCP);
};
#endif /* _INBOUNDCONNECTIVITY_H */
#endif /* HAS_PROTOCOL_RTP */
| 2,291
|
C++
|
.h
| 67
| 32.179104
| 78
| 0.790666
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,404
|
outboundconnectivity.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/connectivity/outboundconnectivity.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _OUTBOUNDCONNECTIVITY_H
#define _OUTBOUNDCONNECTIVITY_H
#include "protocols/rtp/connectivity/baseconnectivity.h"
class BaseOutNetRTPUDPStream;
class RTSPProtocol;
struct RTPClient {
uint32_t protocolId;
bool isUdp;
bool hasAudio;
sockaddr_in audioDataAddress;
sockaddr_in audioRtcpAddress;
uint32_t audioPacketsCount;
uint32_t audioBytesCount;
uint8_t audioDataChannel;
uint8_t audioRtcpChannel;
bool hasVideo;
sockaddr_in videoDataAddress;
sockaddr_in videoRtcpAddress;
uint32_t videoPacketsCount;
uint32_t videoBytesCount;
uint8_t videoDataChannel;
uint8_t videoRtcpChannel;
RTPClient() {
protocolId = 0;
isUdp = false;
hasAudio = false;
memset(&audioDataAddress, 0, sizeof (audioDataAddress));
memset(&audioRtcpAddress, 0, sizeof (audioRtcpAddress));
audioPacketsCount = 0;
audioBytesCount = 0;
audioDataChannel = 0xff;
audioRtcpChannel = 0xff;
hasVideo = false;
memset(&videoDataAddress, 0, sizeof (videoDataAddress));
memset(&videoRtcpAddress, 0, sizeof (videoRtcpAddress));
videoPacketsCount = 0;
videoBytesCount = 0;
videoDataChannel = 0xff;
videoRtcpChannel = 0xff;
}
};
class DLLEXP OutboundConnectivity
: public BaseConnectivity {
private:
bool _forceTcp;
RTSPProtocol *_pRTSPProtocol;
BaseOutNetRTPUDPStream *_pOutStream;
MSGHDR _dataMessage;
MSGHDR _rtcpMessage;
uint8_t *_pRTCPNTP;
uint8_t *_pRTCPRTP;
uint8_t *_pRTCPSPC;
uint8_t *_pRTCPSOC;
uint64_t _startupTime;
RTPClient _rtpClient;
bool _hasVideo;
SOCKET _videoDataFd;
uint16_t _videoDataPort;
SOCKET _videoRTCPFd;
uint16_t _videoRTCPPort;
uint32_t _videoNATDataId;
uint32_t _videoNATRTCPId;
double _videoSampleRate;
bool _hasAudio;
SOCKET _audioDataFd;
uint16_t _audioDataPort;
SOCKET _audioRTCPFd;
uint16_t _audioRTCPPort;
uint32_t _audioNATDataId;
uint32_t _audioNATRTCPId;
double _audioSampleRate;
int32_t _amountSent;
uint32_t _dummyValue;
public:
OutboundConnectivity(bool forceTcp, RTSPProtocol *pRTSPProtocol);
virtual ~OutboundConnectivity();
bool Initialize();
void Enable(bool value);
void SetOutStream(BaseOutNetRTPUDPStream *pOutStream);
string GetVideoPorts();
string GetAudioPorts();
string GetVideoChannels();
string GetAudioChannels();
uint32_t GetAudioSSRC();
uint32_t GetVideoSSRC();
uint16_t GetLastVideoSequence();
uint16_t GetLastAudioSequence();
void HasAudio(bool value);
void HasVideo(bool value);
bool RegisterUDPVideoClient(uint32_t rtspProtocolId, sockaddr_in &data,
sockaddr_in &rtcp);
bool RegisterUDPAudioClient(uint32_t rtspProtocolId, sockaddr_in &data,
sockaddr_in &rtcp);
bool RegisterTCPVideoClient(uint32_t rtspProtocolId, uint8_t data, uint8_t rtcp);
bool RegisterTCPAudioClient(uint32_t rtspProtocolId, uint8_t data, uint8_t rtcp);
void SignalDetachedFromInStream();
bool FeedVideoData(MSGHDR &message, double pts, double dts);
bool FeedAudioData(MSGHDR &message, double pts, double dts);
void ReadyForSend();
private:
bool InitializePorts(SOCKET &dataFd, uint16_t &dataPort,
uint32_t &natDataId, SOCKET &RTCPFd, uint16_t &RTCPPort,
uint32_t &natRTCPId);
bool FeedData(MSGHDR &message, double pts, double dts, bool isAudio);
};
#endif /* _OUTBOUNDCONNECTIVITY_H */
#endif /* HAS_PROTOCOL_RTP */
| 4,039
|
C++
|
.h
| 126
| 29.873016
| 82
| 0.788042
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,405
|
innetrtpstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/streaming/innetrtpstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _INNETRTPSTREAM_H
#define _INNETRTPSTREAM_H
#include "streaming/baseinnetstream.h"
#include "protocols/rtp/rtpheader.h"
#define RTCP_PRESENCE_UNKNOWN 0
#define RTCP_PRESENCE_AVAILABLE 1
#define RTCP_PRESENCE_ABSENT 2
class DLLEXP InNetRTPStream
: public BaseInNetStream {
private:
StreamCapabilities _capabilities;
bool _hasAudio;
bool _isLatm;
uint16_t _audioSequence;
double _audioNTP;
double _audioRTP;
double _audioLastDts;
uint32_t _audioLastRTP;
uint32_t _audioRTPRollCount;
double _audioFirstTimestamp;
uint32_t _lastAudioRTCPRTP;
uint32_t _audioRTCPRTPRollCount;
double _audioSampleRate;
bool _hasVideo;
IOBuffer _currentNalu;
uint16_t _videoSequence;
double _videoNTP;
double _videoRTP;
double _videoLastPts;
double _videoLastDts;
uint32_t _videoLastRTP;
uint32_t _videoRTPRollCount;
double _videoFirstTimestamp;
uint32_t _lastVideoRTCPRTP;
uint32_t _videoRTCPRTPRollCount;
double _videoSampleRate;
uint8_t _rtcpPresence;
uint8_t _rtcpDetectionInterval;
time_t _rtcpDetectionStart;
size_t _dtsCacheSize;
map<double, double> _dtsCache;
IOBuffer _sps;
IOBuffer _pps;
//double _maxDts;
public:
InNetRTPStream(BaseProtocol *pProtocol, string name, Variant &videoTrack,
Variant &audioTrack, uint32_t bandwidthHint,
uint8_t rtcpDetectionInterval);
virtual ~InNetRTPStream();
virtual StreamCapabilities * GetCapabilities();
virtual void ReadyForSend();
virtual bool IsCompatibleWithType(uint64_t type);
virtual void SignalOutStreamAttached(BaseOutStream *pOutStream);
virtual void SignalOutStreamDetached(BaseOutStream *pOutStream);
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
bool FeedVideoData(uint8_t *pData, uint32_t dataLength,
RTPHeader &rtpHeader);
bool FeedAudioData(uint8_t *pData, uint32_t dataLength,
RTPHeader &rtpHeader);
void ReportSR(uint64_t ntpMicroseconds, uint32_t rtpTimestamp, bool isAudio);
private:
bool FeedAudioDataAU(uint8_t *pData, uint32_t dataLength,
RTPHeader &rtpHeader);
bool FeedAudioDataLATM(uint8_t *pData, uint32_t dataLength,
RTPHeader &rtpHeader);
virtual bool InternalFeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double dts, bool isAudio);
uint64_t ComputeRTP(uint32_t ¤tRtp, uint32_t &lastRtp,
uint32_t &rtpRollCount);
};
#endif /* _INNETRTPSTREAM_H */
#endif /* HAS_PROTOCOL_RTP */
| 3,462
|
C++
|
.h
| 99
| 32.79798
| 78
| 0.790212
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,406
|
outnetrtpudph264stream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/streaming/outnetrtpudph264stream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _OUTNETRTPUDPH264STREAM_H
#define _OUTNETRTPUDPH264STREAM_H
#include "protocols/rtp/streaming/baseoutnetrtpudpstream.h"
class DLLEXP OutNetRTPUDPH264Stream
: public BaseOutNetRTPUDPStream {
private:
bool _forceTcp;
MSGHDR _videoData;
double _videoSampleRate;
VideoCodecInfo *_pVideoInfo;
bool _firstVideoFrame;
double _lastVideoPts;
MSGHDR _audioData;
double _audioSampleRate;
AudioCodecInfo *_pAudioInfo;
IOBuffer _auBuffer;
double _auPts;
uint32_t _auCount;
uint32_t _maxRTPPacketSize;
public:
OutNetRTPUDPH264Stream(BaseProtocol *pProtocol, string name, bool forceTcp);
virtual ~OutNetRTPUDPH264Stream();
protected:
virtual bool FinishInitialization(
GenericProcessDataSetup *pGenericProcessDataSetup);
virtual bool PushVideoData(IOBuffer &buffer, double pts, double dts,
bool isKeyFrame);
virtual bool PushAudioData(IOBuffer &buffer, double pts, double dts);
virtual bool IsCodecSupported(uint64_t codec);
virtual void SignalAudioStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, AudioCodecInfo *pOld,
AudioCodecInfo *pNew);
virtual void SignalVideoStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, VideoCodecInfo *pOld,
VideoCodecInfo *pNew);
private:
virtual void SignalAttachedToInStream();
};
#endif /* _OUTNETRTPUDPH264STREAM_H */
#endif /* HAS_PROTOCOL_RTP */
| 2,147
|
C++
|
.h
| 59
| 34.288136
| 77
| 0.798558
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,407
|
baseoutnetrtpudpstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/rtp/streaming/baseoutnetrtpudpstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_RTP
#ifndef _BASEOUTNETRTPUDPSTREAM_H
#define _BASEOUTNETRTPUDPSTREAM_H
#include "streaming/baseoutnetstream.h"
class OutboundConnectivity;
class DLLEXP BaseOutNetRTPUDPStream
: public BaseOutNetStream {
protected:
uint32_t _audioSsrc;
uint32_t _videoSsrc;
OutboundConnectivity *_pConnectivity;
uint16_t _videoCounter;
uint16_t _audioCounter;
bool _hasAudio;
bool _hasVideo;
bool _enabled;
public:
BaseOutNetRTPUDPStream(BaseProtocol *pProtocol, string name);
virtual ~BaseOutNetRTPUDPStream();
void Enable(bool value);
OutboundConnectivity *GetConnectivity();
void SetConnectivity(OutboundConnectivity *pConnectivity);
void HasAudioVideo(bool hasAudio, bool hasVideo);
uint32_t AudioSSRC();
uint32_t VideoSSRC();
uint16_t VideoCounter();
uint16_t AudioCounter();
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
virtual bool IsCompatibleWithType(uint64_t type);
virtual void SignalDetachedFromInStream();
virtual void SignalStreamCompleted();
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
protected:
virtual bool FinishInitialization(
GenericProcessDataSetup *pGenericProcessDataSetup);
};
#endif /* _BASEOUTNETRTPUDPSTREAM_H */
#endif /* HAS_PROTOCOL_RTP */
| 2,231
|
C++
|
.h
| 62
| 33.887097
| 72
| 0.790719
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,408
|
inboundliveflvprotocol.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/liveflv/inboundliveflvprotocol.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_LIVEFLV
#ifndef _INBOUNDLIVEFLVPROTOCOL_H
#define _INBOUNDLIVEFLVPROTOCOL_H
#include "protocols/baseprotocol.h"
class InNetLiveFLVStream;
class DLLEXP InboundLiveFLVProtocol
: public BaseProtocol {
private:
InNetLiveFLVStream *_pStream;
bool _headerParsed;
bool _waitForMetadata;
public:
InboundLiveFLVProtocol();
virtual ~InboundLiveFLVProtocol();
virtual bool Initialize(Variant ¶meters);
virtual bool AllowFarProtocol(uint64_t type);
virtual bool AllowNearProtocol(uint64_t type);
virtual bool SignalInputData(int32_t recvAmount);
virtual bool SignalInputData(IOBuffer &buffer);
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
private:
bool InitializeStream(string streamName);
string ComputeStreamName(string suggestion);
};
#endif /* _INBOUNDLIVEFLVPROTOCOL_H */
#endif /* HAS_PROTOCOL_LIVEFLV */
| 1,636
|
C++
|
.h
| 44
| 35.318182
| 72
| 0.789141
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,409
|
innetliveflvstream.h
|
shiretu_crtmpserver/sources/thelib/include/protocols/liveflv/innetliveflvstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_LIVEFLV
#ifndef _INNETLIVEFLVSTREAM_H
#define _INNETLIVEFLVSTREAM_H
#include "streaming/baseinnetstream.h"
class DLLEXP InNetLiveFLVStream
: public BaseInNetStream {
private:
double _lastVideoPts;
double _lastVideoDts;
double _lastAudioTime;
Variant _lastStreamMessage;
StreamCapabilities _streamCapabilities;
bool _audioCapabilitiesInitialized;
bool _videoCapabilitiesInitialized;
public:
InNetLiveFLVStream(BaseProtocol *pProtocol, string name);
virtual ~InNetLiveFLVStream();
virtual StreamCapabilities * GetCapabilities();
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual void ReadyForSend();
virtual bool IsCompatibleWithType(uint64_t type);
virtual void SignalOutStreamAttached(BaseOutStream *pOutStream);
virtual void SignalOutStreamDetached(BaseOutStream *pOutStream);
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
bool SendStreamMessage(Variant &completeMessage, bool persistent);
bool SendStreamMessage(string functionName, Variant ¶meters,
bool persistent);
};
#endif /* _INNETLIVEFLVSTREAM_H */
#endif /* HAS_PROTOCOL_LIVEFLV */
| 2,115
|
C++
|
.h
| 54
| 37.074074
| 72
| 0.79561
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,410
|
baseappprotocolhandler.h
|
shiretu_crtmpserver/sources/thelib/include/application/baseappprotocolhandler.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEAPPPROTOCOLHANDLER_H
#define _BASEAPPPROTOCOLHANDLER_H
#include "common.h"
class BaseClientApplication;
class StreamMetadataResolver;
class BaseProtocol;
class BaseInStream;
/*!
@class BaseAppProtocolHandler
@brief
*/
class DLLEXP BaseAppProtocolHandler {
private:
BaseClientApplication *_pApplication;
protected:
Variant _configuration;
public:
BaseAppProtocolHandler(Variant &configuration);
virtual ~BaseAppProtocolHandler();
virtual bool ParseAuthenticationNode(Variant &node, Variant &result);
/*!
@brief Sets the application.
@param pApplication
*/
virtual void SetApplication(BaseClientApplication *pApplication);
/*!
@brief Sets the pointer to the application.
*/
BaseClientApplication *GetApplication();
/*!
@brief Gets the porotocol handler of the application.
@param protocolType - Type of portocol
*/
BaseAppProtocolHandler * GetProtocolHandler(uint64_t protocolType);
/*!
@brief
*/
virtual bool PullExternalStream(URI uri, Variant streamConfig);
/*!
@brief
*/
virtual bool PushLocalStream(Variant streamConfig);
/*!
@brief
*/
virtual void RegisterProtocol(BaseProtocol *pProtocol) = 0;
/*!
@brief
*/
virtual void UnRegisterProtocol(BaseProtocol *pProtocol) = 0;
/*!
* @brief returns the stream metadata resolver associated with this application
*/
StreamMetadataResolver *GetStreamMetadataResolver();
};
#endif /* _BASEAPPPROTOCOLHANDLER_H */
| 2,219
|
C++
|
.h
| 74
| 27.716216
| 80
| 0.776786
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,411
|
baseclientapplication.h
|
shiretu_crtmpserver/sources/thelib/include/application/baseclientapplication.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASECLIENTAPPLICATION_H
#define _BASECLIENTAPPLICATION_H
#include "common.h"
#include "streaming/streamsmanager.h"
#include "netio/netio.h"
class BaseProtocol;
class BaseAppProtocolHandler;
class BaseStream;
class IOHandler;
class StreamMetadataResolver;
enum OperationType {
OPERATION_TYPE_STANDARD = 0,
OPERATION_TYPE_PULL,
OPERATION_TYPE_PUSH
};
/*!
@brief
*/
class DLLEXP BaseClientApplication {
private:
static uint32_t _idGenerator;
uint32_t _id;
string _name;
vector<string> _aliases;
map<uint64_t, BaseAppProtocolHandler *> _protocolsHandlers;
StreamsManager _streamsManager;
map<string, string> _streamAliases;
bool _hasStreamAliases;
StreamMetadataResolver *_pStreamMetadataResolver;
Variant _dummy;
protected:
Variant _configuration;
bool _isDefault;
Variant _authSettings;
public:
BaseClientApplication(Variant &configuration);
virtual ~BaseClientApplication();
/*!
@brief Returns the application's id. The id is auto-generated in the constructor
*/
uint32_t GetId();
/*!
@brief Returns the name of the application, taken from the configuration file.
*/
string GetName();
/*!
@brief Returns the variant that contains the configuration information about the application.
*/
Variant &GetConfiguration();
/*!
@brief Returns the alias of the application from the configuration file
*/
vector<string> GetAliases();
/*!
@brief Returns the boolean that tells if the application is the default application.
*/
bool IsDefault();
StreamsManager *GetStreamsManager();
StreamMetadataResolver *GetStreamMetadataResolver();
virtual bool Initialize();
virtual bool ActivateAcceptors(vector<IOHandler *> &acceptors);
virtual bool ActivateAcceptor(IOHandler *pIOHandler);
string GetServicesInfo();
virtual bool AcceptTCPConnection(TCPAcceptor *pTCPAcceptor);
/*!
@brief Registers this application to the BaseAppProtocolHandler.
@protocolType - Type of protocol
@pAppProtocolHandler
*/
void RegisterAppProtocolHandler(uint64_t protocolType,
BaseAppProtocolHandler *pAppProtocolHandler);
/*!
@brief Erases this application to the BaseAppProtocolHandler by setting it to NULL.
@param protocolType - Type of protocol
*/
void UnRegisterAppProtocolHandler(uint64_t protocolType);
/*!
@brief Checks and see if the duplicate inbound network streams are available. Always returns true if allowDuplicateNetworkStreams is set to true inside the config file
@param streamName - The stream name we want to see is free or not
@param pProtocol - The protocol associated with this request (can be NULL)
*/
virtual bool StreamNameAvailable(string streamName, BaseProtocol *pProtocol);
template<class T>
T *GetProtocolHandler(BaseProtocol *pProtocol) {
if (pProtocol == NULL)
return NULL;
return (T *) GetProtocolHandler(pProtocol);
}
BaseAppProtocolHandler *GetProtocolHandler(BaseProtocol *pProtocol);
BaseAppProtocolHandler *GetProtocolHandler(uint64_t protocolType);
bool HasProtocolHandler(uint64_t protocolType);
template<class T>
T *GetProtocolHandler(string &scheme) {
return (T *) GetProtocolHandler(scheme);
}
virtual BaseAppProtocolHandler *GetProtocolHandler(string &scheme);
/*!
@brief This is called bt the framework when an outbound connection failed to connect
@param customParameters
*/
virtual bool OutboundConnectionFailed(Variant &customParameters);
/*!
@brief Registers the protocol to the client application
@param pProtocol
*/
virtual void RegisterProtocol(BaseProtocol *pProtocol);
/*!
@brief Erases the protocol to the client application
@param pProtocol
*/
virtual void UnRegisterProtocol(BaseProtocol *pProtocol);
/*!
@brief Displays the registered stream's ID, type, and name in the logs
@param pStream
*/
virtual void SignalStreamRegistered(BaseStream *pStream);
/*!
@brief Displays the unregistered stream's ID, type, and name in the logs
@param pStream
*/
virtual void SignalStreamUnRegistered(BaseStream *pStream);
virtual bool PullExternalStreams();
virtual bool PullExternalStream(Variant &streamConfig);
virtual bool PushLocalStream(Variant &streamConfig);
bool ParseAuthentication();
virtual void SignalUnLinkingStreams(BaseInStream *pInStream, BaseOutStream *pOutStream);
/*!
@brief Deletes all active protocols and IOHandlers bound to the application.
@param pApplication
*/
static void Shutdown(BaseClientApplication *pApplication);
/*!
* Stream aliasing for playback
*/
virtual string GetStreamNameByAlias(string &streamName, bool remove = true);
bool SetStreamAlias(string &streamName, string &streamAlias);
bool RemoveStreamAlias(string &streamAlias);
map<string, string> & GetAllStreamAliases();
OperationType GetOperationType(BaseProtocol *pProtocol, Variant &streamConfig);
OperationType GetOperationType(Variant &allParameters, Variant &streamConfig);
void StoreConnectionType(Variant &dest, BaseProtocol *pProtocol);
Variant &GetStreamSettings(Variant &src);
private:
string GetServiceInfo(IOHandler *pIOHander);
};
#endif /* _BASECLIENTAPPLICATION_H */
| 5,865
|
C++
|
.h
| 164
| 33.408537
| 169
| 0.795238
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,412
|
configfile.h
|
shiretu_crtmpserver/sources/thelib/include/configuration/configfile.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CONFIGFILE_H
#define _CONFIGFILE_H
#include "common.h"
#include "configuration/module.h"
class DLLEXP ConfigFile {
private:
Variant _configuration;
Variant _logAppenders;
string _rootAppFolder;
Variant _applications;
map<string, string> _uniqueNames;
GetApplicationFunction_t _staticGetApplicationFunction;
GetFactoryFunction_t _staticGetFactoryFunction;
map<string, Module> _modules;
bool _isOrigin;
public:
ConfigFile(GetApplicationFunction_t staticGetApplicationFunction,
GetFactoryFunction_t staticGetFactoryFunction);
virtual ~ConfigFile();
bool IsDaemon();
bool IsOrigin();
string GetServicesInfo();
Variant &GetApplicationsConfigurations();
bool LoadLuaFile(string path, bool forceDaemon);
bool LoadXmlFile(string path, bool forceDaemon);
bool ConfigLogAppenders();
bool ConfigModules();
bool ConfigFactories();
bool ConfigAcceptors();
bool ConfigInstances();
bool ConfigApplications();
private:
bool ConfigLogAppender(Variant &node);
bool ConfigModule(Variant &node);
bool Normalize();
bool NormalizeLogAppenders();
bool NormalizeLogAppender(Variant &node);
bool NormalizeApplications();
bool NormalizeApplication(Variant &node);
bool NormalizeApplicationAcceptor(Variant &node, string baseFolder);
bool NormalizeApplicationAliases(Variant &node);
};
#endif /* _CONFIGFILE_H */
| 2,113
|
C++
|
.h
| 61
| 32.622951
| 72
| 0.79285
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,413
|
baseinstream.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/baseinstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEINSTREAM_H
#define _BASEINSTREAM_H
#include "streaming/basestream.h"
class BaseOutStream;
/*!
@class BaseInStream
*/
class DLLEXP BaseInStream
: public BaseStream {
private:
bool _canCallOutStreamDetached;
protected:
map<uint32_t, BaseOutStream *> _linkedStreams;
LinkedListNode<BaseOutStream *> *_pOutStreams;
public:
BaseInStream(BaseProtocol *pProtocol, uint64_t type, string name);
virtual ~BaseInStream();
vector<BaseOutStream *> GetOutStreams();
/*!
@brief Returns information about the stream
@param info
*/
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
/*!
@brief Links an out-stream to this stream
@param pOutStream - the out-stream to be linked to this in stream.
@param reverseLink - if true, pOutStream::Link will be called internally this is used to break the infinite calls.
*/
virtual bool Link(BaseOutStream *pOutStream, bool reverseLink = true);
/*!
@brief Unlinks an out-stream tot his stream
@param pOutStream - the out-stream to be unlinked from this in stream.
@param reverseUnLink - if true, pOutStream::UnLink will be called internally this is used to break the infinite calls
*/
virtual bool UnLink(BaseOutStream *pOutStream, bool reverseUnLink = true);
/*!
@brief This will start the feeding process
@param dts - the timestamp where we want to seek before start the feeding process
*/
virtual bool Play(double dts, double length);
/*!
@brief This will pause the feeding process
*/
virtual bool Pause();
/*!
@brief This will resume the feeding process
*/
virtual bool Resume();
/*!
@brief This will seek to the specified point in time.
@param dts
*/
virtual bool Seek(double dts);
/*!
@brief This will stop the feeding process
*/
virtual bool Stop();
/*!
* @brief trigger SignalStreamCapabilitiesChanged on all subscribed streams
*/
virtual void AudioStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, AudioCodecInfo *pOld,
AudioCodecInfo *pNew);
virtual void VideoStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, VideoCodecInfo *pOld,
VideoCodecInfo *pNew);
/*!
@brief Called after the link is complete
@param pOutStream - the newly added stream
*/
virtual void SignalOutStreamAttached(BaseOutStream *pOutStream) = 0;
/*!
@brief Called after the link is broken
@param pOutStream - the removed stream
*/
virtual void SignalOutStreamDetached(BaseOutStream *pOutStream) = 0;
StreamCapabilities * GetCapabilities();
/*!
*
*/
virtual uint32_t GetInputVideoTimescale();
virtual uint32_t GetInputAudioTimescale();
};
#endif /* _BASEINSTREAM_H */
| 3,426
|
C++
|
.h
| 102
| 31.107843
| 119
| 0.761732
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,414
|
baseinnetstream.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/baseinnetstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEINNETSTREAM_H
#define _BASEINNETSTREAM_H
#include "streaming/baseinstream.h"
class DLLEXP BaseInNetStream
: public BaseInStream {
public:
BaseInNetStream(BaseProtocol *pProtocol, uint64_t type, string name);
virtual ~BaseInNetStream();
};
#endif /* _BASEINNETSTREAM_H */
| 1,065
|
C++
|
.h
| 28
| 36.142857
| 72
| 0.762367
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,415
|
streamcapabilities.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/streamcapabilities.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CODECINFO_H
#define _CODECINFO_H
#include "common.h"
class BaseInStream;
struct CodecInfo {
uint64_t _type;
uint32_t _samplingRate;
double _transferRate;
CodecInfo();
virtual ~CodecInfo();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(IOBuffer & buffer);
virtual void GetRTMPMetadata(Variant & destination);
virtual operator string();
};
struct VideoCodecInfo : CodecInfo {
uint32_t _width;
uint32_t _height;
uint32_t _frameRateNominator;
uint32_t _frameRateDenominator;
VideoCodecInfo();
virtual ~VideoCodecInfo();
double GetFPS();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(IOBuffer & buffer);
virtual void GetRTMPMetadata(Variant & destination);
virtual operator string();
};
struct VideoCodecInfoPassThrough : VideoCodecInfo {
VideoCodecInfoPassThrough();
virtual ~VideoCodecInfoPassThrough();
bool Init();
virtual void GetRTMPMetadata(Variant & destination);
};
struct VideoCodecInfoH264 : VideoCodecInfo {
uint8_t _level;
uint8_t _profile;
uint8_t *_pSPS;
uint32_t _spsLength;
uint8_t *_pPPS;
uint32_t _ppsLength;
IOBuffer _rtmpRepresentation;
IOBuffer _sps;
IOBuffer _pps;
VideoCodecInfoH264();
virtual ~VideoCodecInfoH264();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(IOBuffer & buffer);
virtual operator string();
bool Init(uint8_t *pSPS, uint32_t spsLength, uint8_t *pPPS, uint32_t ppsLength,
uint32_t samplingRate);
virtual void GetRTMPMetadata(Variant & destination);
IOBuffer & GetRTMPRepresentation();
IOBuffer & GetSPSBuffer();
IOBuffer & GetPPSBuffer();
bool Compare(uint8_t *pSPS, uint32_t spsLength, uint8_t *pPPS,
uint32_t ppsLength);
};
struct VideoCodecInfoSorensonH263 : VideoCodecInfo {
uint8_t *_pHeaders;
uint32_t _length;
VideoCodecInfoSorensonH263();
virtual ~VideoCodecInfoSorensonH263();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(IOBuffer & buffer);
virtual operator string();
bool Init(uint8_t *pHeaders, uint32_t length);
virtual void GetRTMPMetadata(Variant & destination);
};
struct VideoCodecInfoVP6 : VideoCodecInfo {
uint8_t *_pHeaders;
uint32_t _length;
VideoCodecInfoVP6();
virtual ~VideoCodecInfoVP6();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(IOBuffer & buffer);
virtual operator string();
bool Init(uint8_t *pHeaders, uint32_t length);
virtual void GetRTMPMetadata(Variant & destination);
};
struct AudioCodecInfo : CodecInfo {
uint8_t _channelsCount;
uint8_t _bitsPerSample;
int32_t _samplesPerPacket;
AudioCodecInfo();
virtual ~AudioCodecInfo();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(IOBuffer & buffer);
virtual void GetRTMPMetadata(Variant & destination);
virtual operator string();
};
struct AudioCodecInfoPassThrough : AudioCodecInfo {
AudioCodecInfoPassThrough();
virtual ~AudioCodecInfoPassThrough();
bool Init();
virtual void GetRTMPMetadata(Variant & destination);
};
struct AudioCodecInfoAAC : AudioCodecInfo {
uint8_t _audioObjectType;
uint8_t _sampleRateIndex;
uint8_t *_pCodecBytes;
uint8_t _codecBytesLength;
IOBuffer _rtmpRepresentation;
AudioCodecInfoAAC();
virtual ~AudioCodecInfoAAC();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(IOBuffer & buffer);
virtual operator string();
bool Init(uint8_t *pCodecBytes, uint8_t codecBytesLength, bool simple);
IOBuffer & GetRTMPRepresentation();
virtual void GetRTMPMetadata(Variant & destination);
void GetADTSRepresentation(uint8_t *pDest, uint32_t length);
static void UpdateADTSRepresentation(uint8_t *pDest, uint32_t length);
bool Compare(uint8_t *pCodecBytes, uint8_t codecBytesLength, bool simple);
};
struct AudioCodecInfoNellymoser : AudioCodecInfo {
AudioCodecInfoNellymoser();
virtual ~AudioCodecInfoNellymoser();
bool Init(uint32_t samplingRate, uint8_t channelsCount, uint8_t bitsPerSample);
virtual void GetRTMPMetadata(Variant & destination);
};
struct AudioCodecInfoMP3 : AudioCodecInfo {
AudioCodecInfoMP3();
virtual ~AudioCodecInfoMP3();
bool Init(uint32_t samplingRate, uint8_t channelsCount, uint8_t bitsPerSample);
virtual void GetRTMPMetadata(Variant & destination);
};
class StreamCapabilities {
private:
VideoCodecInfo *_pVideoTrack;
AudioCodecInfo *_pAudioTrack;
double _transferRate;
Variant _baseMetadata;
public:
StreamCapabilities();
virtual ~StreamCapabilities();
void Clear();
void ClearVideo();
void ClearAudio();
virtual bool Serialize(IOBuffer & buffer);
virtual bool Deserialize(string & filePath, BaseInStream *pInStream);
virtual bool Deserialize(const char *pFilePath, BaseInStream *pInStream);
virtual bool Deserialize(IOBuffer & buffer, BaseInStream *pInStream);
virtual operator string();
/*!
* @brief Returns the detected transfer rate in bits/s. If the returned value is
* less than 0, that menas the transfer rate is not available
*/
double GetTransferRate();
/*!
* @brief Sets the transfer rate in bits per second. This will override
* bitrate detection from the audio and video tracks
*
* @param value - the value expressed in bits/second
*/
void SetTransferRate(double value);
/*!
* @brief Returns the video codec type or CODEC_VIDEO_UNKNOWN if video
* not available
*/
uint64_t GetVideoCodecType();
/*!
* @brief Returns the audio codec type or CODEC_AUDIO_UNKNOWN if audio
* not available
*/
uint64_t GetAudioCodecType();
/*!
* @brief Returns the video codec as a pointer to the specified class
*/
template<typename T> T * GetVideoCodec() {
if (_pVideoTrack != NULL)
return (T *) _pVideoTrack;
return NULL;
}
/*!
* @brief Returns the generic video codec
*/
VideoCodecInfo *GetVideoCodec();
/*!
* @brief Returns the audio codec as a pointer to the specified class
*/
template<typename T> T * GetAudioCodec() {
if (_pAudioTrack != NULL)
return (T *) _pAudioTrack;
return NULL;
}
/*!
* @brief Returns the generic audio codec
*/
AudioCodecInfo *GetAudioCodec();
/*!
* @brief Pupulates RTMP info metadata
*
* @param destination where the information will be stored
*/
void GetRTMPMetadata(Variant &destination);
void SetRTMPMetadata(Variant &baseMetadata);
VideoCodecInfoPassThrough * AddTrackVideoPassThrough(
BaseInStream *pInStream);
VideoCodecInfoH264 * AddTrackVideoH264(uint8_t *pSPS, uint32_t spsLength,
uint8_t *pPPS, uint32_t ppsLength, uint32_t samplingRate,
BaseInStream *pInStream);
VideoCodecInfoSorensonH263 * AddTrackVideoSorensonH263(uint8_t *pData,
uint32_t length, BaseInStream *pInStream);
VideoCodecInfoVP6 * AddTrackVideoVP6(uint8_t *pData, uint32_t length,
BaseInStream *pInStream);
AudioCodecInfoPassThrough * AddTrackAudioPassThrough(BaseInStream *pInStream);
AudioCodecInfoAAC * AddTrackAudioAAC(uint8_t *pCodecBytes,
uint8_t codecBytesLength, bool simple, BaseInStream *pInStream);
AudioCodecInfoNellymoser * AddTrackAudioNellymoser(uint32_t samplingRate,
uint8_t channelsCount, uint8_t bitsPerSample, BaseInStream *pInStream);
AudioCodecInfoMP3 * AddTrackAudioMP3(uint32_t samplingRate,
uint8_t channelsCount, uint8_t bitsPerSample, BaseInStream *pInStream);
};
#endif /* _CODECINFO_H */
| 7,982
|
C++
|
.h
| 233
| 32.04721
| 81
| 0.781663
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,416
|
baseoutfilestream.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/baseoutfilestream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEOUTFILESTREAM_H
#define _BASEOUTFILESTREAM_H
#include "streaming/baseoutstream.h"
class DLLEXP BaseOutFileStream
: public BaseOutStream {
public:
BaseOutFileStream(BaseProtocol *pProtocol, uint64_t type, string name);
virtual ~BaseOutFileStream();
};
#endif /* _BASEOUTFILESTREAM_H */
| 1,079
|
C++
|
.h
| 28
| 36.642857
| 72
| 0.76555
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,417
|
baseoutnetstream.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/baseoutnetstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEOUTNETSTREAM_H
#define _BASEOUTNETSTREAM_H
#include "streaming/baseoutstream.h"
class DLLEXP BaseOutNetStream
: public BaseOutStream {
public:
BaseOutNetStream(BaseProtocol *pProtocol, uint64_t type, string name);
virtual ~BaseOutNetStream();
};
#endif /* _BASEOUTNETSTREAM_H */
| 1,073
|
C++
|
.h
| 28
| 36.428571
| 72
| 0.764196
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,418
|
streamstypes.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/streamstypes.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _STREAMSTYPES_H
#define _STREAMSTYPES_H
#define ST_NEUTRAL_RTMP MAKE_TAG2('N','R')
#define ST_IN MAKE_TAG1('I')
#define ST_IN_NET MAKE_TAG2('I','N')
#define ST_IN_NET_RTMP MAKE_TAG3('I','N','R')
#define ST_IN_NET_LIVEFLV MAKE_TAG6('I','N','L','F','L','V')
#define ST_IN_NET_TS MAKE_TAG4('I','N','T','S')
#define ST_IN_NET_RTP MAKE_TAG3('I','N','P')
#define ST_IN_FILE MAKE_TAG2('I','F')
#define ST_IN_FILE_RTMP MAKE_TAG3('I','F','R')
#define ST_OUT MAKE_TAG1('O')
#define ST_OUT_NET MAKE_TAG2('O','N')
#define ST_OUT_NET_RTMP MAKE_TAG3('O','N','R')
#define ST_OUT_NET_RTMP_4_TS MAKE_TAG6('O','N','R','4','T','S')
#define ST_OUT_NET_RTMP_4_RTMP MAKE_TAG5('O','N','R','4','R')
#define ST_OUT_NET_RTP MAKE_TAG3('O','N','P')
#define ST_OUT_FILE MAKE_TAG2('O','F')
#define ST_OUT_FILE_RTMP MAKE_TAG3('O','F','R')
#define ST_OUT_FILE_RTMP_FLV MAKE_TAG6('O','F','R','F','L','V')
#endif /* _STREAMSTYPES_H */
| 1,723
|
C++
|
.h
| 39
| 42.615385
| 72
| 0.668255
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,419
|
baseoutstream.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/baseoutstream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEOUTSTREAM_H
#define _BASEOUTSTREAM_H
#include "streaming/basestream.h"
class BaseInStream;
enum NALUMarkerType {
NALU_MARKER_TYPE_NONE = 0,
NALU_MARKER_TYPE_0001,
NALU_MARKER_TYPE_SIZE
};
struct GenericProcessDataSetup {
/*!
* @brief video setup
*/
union {
/*!
* @brief AVC setup
*/
struct {
/*!
* @brief It will insert a NALU marker like this:<br>
* NALU_MARKER_TYPE_NONE - no marker is inserted<br>
* NALU_MARKER_TYPE_0001 - the marker has the value of 0x00000001<br>
* NALU_MARKER_TYPE_SIZE - the marker has the value equal with the
* size of the NALU as a 4 bytes unsigned integer in network order<br>
*/
NALUMarkerType _naluMarkerType;
/*!
* @brief If true, a PD NALU will be inserted in front of each and every
* frame. Useful when TS output is needed. It should be false (no PD) when
* RTMP/RTSP output is required
*/
bool _insertPDNALU;
/*!
* @brief If true, the standard h264 RTMP header will be inserted in the frame
*/
bool _insertRTMPPayloadHeader;
/*!
* @brief If true, SPS/PPS will be inserted before IDR
*/
bool _insertSPSPPSBeforeIDR;
/*!
* @brief If true, it will aggregate all the NALS with the same timestamp
* on the same packet
*/
bool _aggregateNALU;
/*!
* @brief bulk initialization of flags rather than setting them one
* by one. Preferred method. Easier to track changes
*/
void Init(NALUMarkerType naluMarkerType, bool insertPDNALU,
bool insertRTMPPayloadHeader, bool insertSPSPPSBeforeIDR,
bool aggregateNALU) {
_naluMarkerType = naluMarkerType;
_insertPDNALU = insertPDNALU;
_insertRTMPPayloadHeader = insertRTMPPayloadHeader;
_insertSPSPPSBeforeIDR = insertSPSPPSBeforeIDR;
_aggregateNALU = aggregateNALU;
}
} avc;
} video;
/*!
* @brief audio setup
*/
union {
/*!
* @brief AAC setup
*/
struct {
/*!
* @brief If true, the standard ADTS header will be inserted in the frame
*/
bool _insertADTSHeader;
/*!
* @brief If true, the standard AAC RTMP header will be inserted in the frame
*/
bool _insertRTMPPayloadHeader;
} aac;
} audio;
/*!
* @brief The time base which is going to be used for all pts/dts. If the
* value is less than 0, no time base is going to be applied. Otherwise,
* the specified time base is going to be applied. Expressed in milliseconds
*/
double _timeBase;
/*!
* @brief the maximum value of the frame size. if 0, the maximum value is
* considered infinite
*/
uint32_t _maxFrameSize;
/*!
* @brief This value is first computed from the audio track detection and also
* from the supported audio codecs. When FinishInitialization, the inheritor
* has a chance to put it on false (manually disabling the track).
*/
bool _hasAudio;
/*!
* @brief This value is first computed from the video track detection and also
* from the supported video codecs. When FinishInitialization, the inheritor
* has a chance to put it on false (manually disabling the track).
*/
bool _hasVideo;
/*!
* @brief This value is the video codec id detected from the input stream
* This is a read-only value.
*/
uint64_t _videoCodec;
/*!
* @brief This value is the audio codec id detected from the input stream
* This is a read-only value.
*/
uint64_t _audioCodec;
/*!
* @brief The input stream capabilities
*/
StreamCapabilities *_pStreamCapabilities;
};
class DLLEXP BaseOutStream
: public BaseStream {
private:
bool _canCallDetachedFromInStream;
string _aliasName;
uint64_t _inStreamType;
//member variables used by GenericProcessData member function
//audio
IOBuffer _audioBucket;
IOBuffer _audioFrame;
uint8_t _adtsHeader[7];
uint8_t _adtsHeaderCache[7];
double _lastAudioTimestamp;
//video
IOBuffer _videoBucket;
IOBuffer _videoFrame;
bool _isKeyFrame;
double _lastVideoPts;
double _lastVideoDts;
double _zeroTimeBase;
GenericProcessDataSetup _genericProcessDataSetup;
double _maxWaitDts;
protected:
BaseInStream *_pInStream;
public:
BaseOutStream(BaseProtocol *pProtocol, uint64_t type, string name);
virtual ~BaseOutStream();
void SetAliasName(string &aliasName);
/*!
@brief Returns the stream capabilities. Specifically, codec and codec related info
*/
virtual StreamCapabilities * GetCapabilities();
/*!
@brief The networking layer signaled the availability for sending data
*/
virtual void ReadyForSend();
/*!
@brief Links an in-stream to this stream
@param pInStream - the in-stream where we want to attach
@param reverseLink - if true, pInStream::Link will be called internally this is used to break the infinite calls.
*/
virtual bool Link(BaseInStream *pInStream, bool reverseLink = true);
/*!
@brief Unlinks an in-stream to this stream
@param reverseUnLink - if true, pInStream::UnLink will be called internally this is used to break the infinite calls
*/
virtual bool UnLink(bool reverseUnLink = true);
/*!
@brief Returns true if this stream is linked to an inbound stream. Otherwise, returns false
*/
bool IsLinked();
/*!
@brief Returns the feeder of this stream
*/
BaseInStream *GetInStream();
/*!
@brief This will return information about the stream
@param info
*/
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
/*!
@brief This will start the feeding process
@param dts - the timestamp where we want to seek before start the feeding process\
@param length
*/
virtual bool Play(double dts, double length);
/*!
@brief This will pause the feeding process
*/
virtual bool Pause();
/*!
@brief This will resume the feeding process
*/
virtual bool Resume();
/*!
@brief This will seek to the specified point in time.
@param dts
*/
virtual bool Seek(double dts);
/*!
@brief This will stop the feeding process
*/
virtual bool Stop();
/*!
@brief Called after the link is complete
*/
virtual void SignalAttachedToInStream() = 0;
/*!
@brief Called after the link is broken
*/
virtual void SignalDetachedFromInStream() = 0;
/*!
@brief Called when the feeder finished the work
*/
virtual void SignalStreamCompleted() = 0;
virtual void SignalAudioStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, AudioCodecInfo *pOld,
AudioCodecInfo *pNew) = 0;
virtual void SignalVideoStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, VideoCodecInfo *pOld,
VideoCodecInfo *pNew) = 0;
protected:
/*!
* @brief This function can be used to split the audio and video data
* into meaningful parts. Only works with H264 and AAC content
*
* @param pData - the pointer to the chunk of data
*
* @param dataLength - the size of pData in bytes
*
* @param processedLength - how many bytes of the entire frame were
* processed so far
*
* @param totalLength - the size in bytes of the entire frame
*
* @param pts - presentation timestamp
*
* @param dts - decoding timestamp
*
* @param isAudio - if true, the packet contains audio data. Otherwise it
* contains video data
*
* @return should return true for success or false for errors
*
* @discussion dataLength+processedLength==totalLength at all times
*/
bool GenericProcessData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual void GenericSignalAudioStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, AudioCodecInfo *pOld,
AudioCodecInfo *pNew);
virtual void GenericSignalVideoStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, VideoCodecInfo *pOld,
VideoCodecInfo *pNew);
/*!
* @brief This function is called when generic parsing is used. It offers
* the inheritors the opportunity to do other initializations.
*/
virtual bool FinishInitialization(
GenericProcessDataSetup *pGenericProcessDataSetup);
/*!
* @brief This function will be called by the GenericProcessData function
* when a complete video frame is available
*
* @param buffer - contains the frame formatted according to
* _genericProcessDataSetup structure
*
* @param pts - presentation timestamp
*
* @param dts - decoding timestamp
*
* @param isKeyFrame - if true, the frame is an I frame. Otherwise is a P frame
*
* @return should return true for success or false for errors
*
* @discussion The receiver of this call should do what is appropriate with
* the buffer and return true or false. buffer will always contain a
* complete video frame. The video frame contains all the necessary NAL
* units to properly decode the frame on the target. It is formatted
* according to _genericProcessDataSetup structure
*/
virtual bool PushVideoData(IOBuffer &buffer, double pts, double dts, bool isKeyFrame) = 0;
/*!
* @brief This function will be called by the GenericProcessData function
* when a complete audio frame is available
*
* @param buffer - contains the frame formatted according to
* _genericProcessDataSetup structure
*
* @param pts - presentation timestamp
*
* @param dts - decoding timestamp
*
* @return should return true for success or false for errors
*
* @discussion The receiver of this call should do what is appropriate with
* the buffer and return true or false. buffer will always contain a
* complete audio frame. It is formatted according to
* _genericProcessDataSetup structure
*/
virtual bool PushAudioData(IOBuffer &buffer, double pts, double dts) = 0;
/*!
* @brief This function will be called by the framework to see if the output
* stream supports the target codec.
*
* @return should return true if the codec is supported, otherwise it should
* return false. When false is returned, the track is deactivated on output
*/
virtual bool IsCodecSupported(uint64_t codec) = 0;
private:
void GenericStreamCapabilitiesChanged();
/*!
* @brief This function is used internally to reset the state of the stream.
* Called from UnLink(), constructor and destructor
*/
void Reset();
/*!
* @brief Used internally by GenericProcessData to validate the stream capabilities
* and check if it contains H264/AAC
*
* @param dts - current frame dts timestamp
*
* @discussion When the input stream is of type RTMP (file, network or liveflv)
* than the framework will wait for the codecs no longer than _maxWaitDts
*/
bool ValidateCodecs(double dts);
/*
* Used internally to insert various regions of the payload. They use
* _genericProcessDataSetup structure to determine how the parts are put in
*/
void InsertVideoNALUMarker(uint32_t naluSize);
void InsertVideoRTMPPayloadHeader(uint32_t cts);
void MarkVideoRTMPPayloadHeaderKeyFrame();
void InsertVideoPDNALU();
void InsertVideoSPSPPSBeforeIDR();
void InsertAudioADTSHeader(uint32_t length);
void InsertAudioRTMPPayloadHeader();
/*
* Will process H264 content coming from an RTMP source and call PushVideoData
*/
bool ProcessH264FromRTMP(uint8_t *pBuffer, uint32_t length, double pts, double dts);
/*
* Will process H264 content coming from a TS or RTP source and call PushVideoData
*/
bool ProcessH264FromTS(uint8_t *pBuffer, uint32_t length, double pts, double dts);
/*
* Will process AAC content coming from an RTMP source and call PushAudioData
*/
bool ProcessAACFromRTMP(uint8_t *pBuffer, uint32_t length, double pts, double dts);
/*
* Will process MP3 content coming from an RTMP source and call PushAudioData
*/
bool ProcessMP3FromRTMP(uint8_t *pBuffer, uint32_t length, double pts, double dts);
/*
* Will process AAC content coming from a TS or RTP source and call PushAudioData
*/
bool ProcessAACFromTS(uint8_t *pBuffer, uint32_t length, double pts, double dts);
/*
* Will process MP3 content coming from a TS or RTP source and call PushAudioData
*/
bool ProcessMP3FromTS(uint8_t *pBuffer, uint32_t length, double pts, double dts);
};
#endif /* _BASEOUTBOUNDSTREAM_H */
| 12,801
|
C++
|
.h
| 378
| 30.896825
| 118
| 0.747715
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,420
|
basestream.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/basestream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASESTREAM_H
#define _BASESTREAM_H
#include "common.h"
#include "streaming/streamcapabilities.h"
class StreamsManager;
class BaseProtocol;
/*!
@class BaseStream
*/
class DLLEXP BaseStream {
private:
static uint32_t _uniqueIdGenerator;
Variant _connectionType;
protected:
string _nearIp;
uint16_t _nearPort;
string _farIp;
uint16_t _farPort;
StreamsManager *_pStreamsManager;
uint64_t _type;
uint32_t _uniqueId;
BaseProtocol *_pProtocol;
string _name;
double _creationTimestamp;
struct {
struct {
uint64_t bytesCount;
uint64_t droppedBytesCount;
uint64_t packetsCount;
uint64_t droppedPacketsCount;
} audio, video;
} _stats;
public:
BaseStream(BaseProtocol *pProtocol, uint64_t type, string name);
virtual ~BaseStream();
virtual bool SetStreamsManager(StreamsManager *pStreamsManager);
/*!
@brief Returns the stream manager. This is read-only
*/
StreamsManager * GetStreamsManager();
/*!
@brief Returns the stream capabilities. Specifically, codec and codec related info
*/
virtual StreamCapabilities * GetCapabilities() = 0;
/*!
@brief Returns the type of this stream. This is read-only
*/
uint64_t GetType();
/*!
@brief Returns the unique id of this stream. This is read-only
*/
uint32_t GetUniqueId();
/*!
@brief returns the creation timestamp expressed in milliseconds for 1970 epoch
*/
double GetSpawnTimestamp();
/*!
@brief Returns the name of this stream. This is setup-once
*/
string GetName();
/*!
@brief Sets the name of the stream
@param name - Name of stream in string format
*/
void SetName(string name);
/*!
@brief This will return information about the stream
@param info
*/
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
/*!
@brief Returns the protocol that owns this stream.
*/
BaseProtocol * GetProtocol();
/*!
@brief Tells if this stream is enqueued for delete or not based on the pProtocol
*/
virtual bool IsEnqueueForDelete();
/*!
@brief Will enqueue this stream for delete along with his protocol
*/
virtual void EnqueueForDelete();
/*!
@brief This will start the feeding process
@param dts - the timestamp where we want to see before start the feeding process
@param length - time limit
*/
virtual bool Play(double dts, double length) = 0;
/*!
@brief This will pause the feeding process
*/
virtual bool Pause() = 0;
/*!
@brief This will resume the feeding process
*/
virtual bool Resume() = 0;
/*!
@brief will seek to the specified point in time.
@param dts
*/
virtual bool Seek(double dts) = 0;
/*!
@brief This will stop the feeding process
*/
virtual bool Stop() = 0;
/*!
@brief Called when a play command was issued
@param dts - the timestamp where we want to seek before start the feeding process
@param length
*/
virtual bool SignalPlay(double &dts, double &length) = 0;
/*!
@brief Called when a pasue command was issued
*/
virtual bool SignalPause() = 0;
/*!
@brief Called when a resume command was issued
*/
virtual bool SignalResume() = 0;
/*!
@brief Called when a seek command was issued
@param dts
*/
virtual bool SignalSeek(double &dts) = 0;
/*!
@brief Called when a stop command was issued
*/
virtual bool SignalStop() = 0;
/*!
@param pData - the buffer containing the data
@param dataLength - the size of pData in bytes
@param processedLength - if pData is only partial data, this shows the numbers of bytes processed so far, excluding pData
@param totalLength - if pData is only partial data, this shows the total number of bytes inside the current packet
@param isAudio - true if pData is audio data, false if pData is video data
@discussion Rules:
dataLength+processedLength<=totalLength
dataLength<=totalLength
processedLength<=totalLength
dataLength!=0
*/
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio) = 0;
/*!
@brief The networking layer signaled the availability for sending data
*/
virtual void ReadyForSend() = 0;
/*!
@brief This is called to ensure that the linking process can be done
@param type - the target type to which this strem must be linked against
*/
virtual bool IsCompatibleWithType(uint64_t type) = 0;
operator string();
private:
void StoreConnectionType();
void GetIpPortInfo();
};
#endif /* _BASESTREAM_H */
| 5,232
|
C++
|
.h
| 176
| 27.130682
| 123
| 0.742482
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,421
|
baseinfilestream.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/baseinfilestream.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEINFILESTREAM_H
#define _BASEINFILESTREAM_H
#include "streaming/baseinstream.h"
#include "mediaformats/readers/mediaframe.h"
#include "mediaformats/readers/mediafile.h"
#include "mediaformats/readers/streammetadataresolver.h"
#include "protocols/timer/basetimerprotocol.h"
enum TimerType {
TIMER_TYPE_HIGH_GRANULARITY = 0,
TIMER_TYPE_LOW_GRANULARITY,
TIMER_TYPE_NONE
};
/*!
@class BaseInFileStream
@brief
*/
class TSFrameReader;
class DLLEXP BaseInFileStream
: public BaseInStream {
private:
class InFileStreamTimer
: public BaseTimerProtocol {
private:
BaseInFileStream *_pInFileStream;
public:
InFileStreamTimer(BaseInFileStream *pInFileStream);
virtual ~InFileStreamTimer();
void ResetStream();
virtual bool TimePeriodElapsed();
};
friend class InFileStreamTimer;
InFileStreamTimer *_pTimer;
MediaFile *_pSeekFile;
MediaFile *_pFile;
//frame info
uint32_t _totalFrames;
uint32_t _currentFrameIndex;
MediaFrame _currentFrame;
//timing info
double _totalSentTime;
double _totalSentTimeBase;
double _startFeedingTime;
//buffering info
uint32_t _clientSideBufferLength;
IOBuffer _videoBuffer;
IOBuffer _audioBuffer;
//current state info
uint8_t _streamingState;
bool _audioVideoCodecsSent;
//seek offsets
uint64_t _seekBaseOffset;
uint64_t _framesBaseOffset;
uint64_t _timeToIndexOffset;
//stream capabilities
StreamCapabilities _streamCapabilities;
//when to stop playback
double _playLimit;
//high granularity timers
bool _highGranularityTimers;
bool _keepClientBufferFull;
//Used to compute temporary data where needed. Is not stack safe
IOBuffer _tempBuffer;
uint64_t _tsChunkStart;
uint64_t _tsChunkSize;
double _tsPts;
double _tsDts;
Metadata _metadata;
uint64_t _servedBytesCount;
public:
BaseInFileStream(BaseProtocol *pProtocol, uint64_t type, string name);
virtual ~BaseInFileStream();
void SetClientSideBuffer(uint32_t value);
uint32_t GetClientSideBuffer();
void KeepClientBufferFull(bool value);
bool KeepClientBufferFull();
bool StreamCompleted();
/*!
@brief Returns the stream capabilities. Specifically, codec and codec related info
*/
virtual StreamCapabilities * GetCapabilities();
/*!
@brief This will initialize the stream internally.
@param clientSideBufferLength - the client side buffer length expressed in seconds
*/
virtual bool Initialize(Metadata &metadata, TimerType timerType,
uint32_t granularity);
virtual bool InitializeTimer(int32_t clientSideBufferLength, TimerType timerType,
uint32_t granularity);
double GetPosition();
/*!
@brief Called when a play command was issued
@param dts - the timestamp where we want to seek before start the feeding process
*/
virtual bool SignalPlay(double &dts, double &length);
/*!
@brief Called when a pasue command was issued
*/
virtual bool SignalPause();
/*!
@brief Called when a resume command was issued
*/
virtual bool SignalResume();
/*!
@brief Called when a seek command was issued
@param dts
*/
virtual bool SignalSeek(double &dts);
/*!
@brief Called when a stop command was issued
*/
virtual bool SignalStop();
/*!
@brief This is called by the framework. The networking layer signaled the availability for sending data
*/
virtual void ReadyForSend();
protected:
virtual bool BuildFrame(MediaFile *pFile, MediaFrame &mediaFrame,
IOBuffer &buffer) = 0;
virtual bool FeedMetaData(MediaFile *pFile, MediaFrame &mediaFrame) = 0;
private:
/*!
@brief This will seek to the specified point in time.
@param dts - the timestamp where we want to seek before start the feeding process
*/
bool InternalSeek(double &dts);
public:
/*!
@brief This is the function that will actually do the feeding.
@discussion It is called by the framework and it must deliver one frame at a time to all subscribers
*/
virtual bool Feed(bool &dataSent);
private:
/*!
@brief This function will ensure that the codec packets are sent. Also it preserves the current timings and frame index
*/
bool SendCodecs();
bool SendCodecsRTMP();
bool SendCodecsTS();
virtual bool FeedRTMP(bool &dataSent);
virtual bool FeedTS(bool &dataSent);
};
#endif /* _BASEINFILESTREAM_H */
| 4,993
|
C++
|
.h
| 160
| 28.85625
| 121
| 0.781185
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,422
|
codectypes.h
|
shiretu_crtmpserver/sources/thelib/include/streaming/codectypes.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CODECTYPES_H
#define _CODECTYPES_H
#include "common.h"
#define CODEC_UNKNOWN MAKE_TAG3('U','N','K')
#define CODEC_VIDEO MAKE_TAG1('V')
#define CODEC_VIDEO_UNKNOWN MAKE_TAG4('V','U','N','K')
#define CODEC_VIDEO_PASS_THROUGH MAKE_TAG3('V','P','T')
#define CODEC_VIDEO_JPEG MAKE_TAG5('V','J','P','E','G')
#define CODEC_VIDEO_SORENSONH263 MAKE_TAG5('V','S','2','6','3')
#define CODEC_VIDEO_SCREENVIDEO MAKE_TAG3('V','S','V')
#define CODEC_VIDEO_SCREENVIDEO2 MAKE_TAG4('V','S','V','2')
#define CODEC_VIDEO_VP6 MAKE_TAG4('V','V','P','6')
#define CODEC_VIDEO_VP6ALPHA MAKE_TAG5('V','V','P','6','A')
#define CODEC_VIDEO_H264 MAKE_TAG5('V','H','2','6','4')
#define CODEC_AUDIO MAKE_TAG1('A')
#define CODEC_AUDIO_UNKNOWN MAKE_TAG4('A','U','N','K')
#define CODEC_AUDIO_PASS_THROUGH MAKE_TAG3('A','P','T')
#define CODEC_AUDIO_PCMLE MAKE_TAG6('A','P','C','M','L','E')
#define CODEC_AUDIO_PCMBE MAKE_TAG6('A','P','C','M','B','E')
#define CODEC_AUDIO_NELLYMOSER MAKE_TAG3('A','N','M')
#define CODEC_AUDIO_MP3 MAKE_TAG4('A','M','P','3')
#define CODEC_AUDIO_AAC MAKE_TAG4('A','A','A','C')
#define CODEC_AUDIO_G711A MAKE_TAG6('A','G','7','1','1','A')
#define CODEC_AUDIO_G711U MAKE_TAG6('A','G','7','1','1','U')
#define CODEC_AUDIO_SPEEX MAKE_TAG6('A','S','P','E','E','X')
#define CODEC_SUBTITLE MAKE_TAG1('S')
#define CODEC_SUBTITLE_UNKNOWN MAKE_TAG4('S','U','N','K')
#define CODEC_SUBTITLE_SRT MAKE_TAG4('S','S','R','T')
#define CODEC_SUBTITLE_SUB MAKE_TAG4('S','S','U','B')
#endif /* _CODECTYPES_H */
| 2,326
|
C++
|
.h
| 48
| 46.916667
| 72
| 0.666814
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,423
|
baseoutrecording.h
|
shiretu_crtmpserver/sources/thelib/include/recording/baseoutrecording.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _BASEOUTRECORDING_H
#define _BASEOUTRECORDING_H
#include "streaming/baseoutfilestream.h"
class BaseClientApplication;
class DLLEXP BaseOutRecording
: public BaseOutFileStream {
protected:
Variant _settings;
public:
BaseOutRecording(BaseProtocol *pProtocol, uint64_t type, string name,
Variant &settings);
virtual ~BaseOutRecording();
virtual void GetStats(Variant &info, uint32_t namespaceId = 0);
virtual bool IsCompatibleWithType(uint64_t type);
virtual bool SignalPlay(double &dts, double &length);
virtual bool SignalPause();
virtual bool SignalResume();
virtual bool SignalSeek(double &dts);
virtual bool SignalStop();
virtual void SignalAttachedToInStream();
virtual void SignalDetachedFromInStream();
virtual void SignalStreamCompleted();
virtual bool FeedData(uint8_t *pData, uint32_t dataLength,
uint32_t processedLength, uint32_t totalLength,
double pts, double dts, bool isAudio);
virtual void SignalAudioStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, AudioCodecInfo *pOld,
AudioCodecInfo *pNew);
virtual void SignalVideoStreamCapabilitiesChanged(
StreamCapabilities *pCapabilities, VideoCodecInfo *pOld,
VideoCodecInfo *pNew);
};
#endif /* _BASEOUTRECORDING_H */
| 2,015
|
C++
|
.h
| 51
| 37.313725
| 72
| 0.788963
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,424
|
outfileflv.h
|
shiretu_crtmpserver/sources/thelib/include/recording/flv/outfileflv.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _OUTFILEFLV_H
#define _OUTFILEFLV_H
#include "recording/baseoutrecording.h"
class BaseOutRecording;
class DLLEXP OutFileFLV
: public BaseOutRecording {
private:
File *_pFile;
uint32_t _prevTagSize;
uint8_t _tagHeader[11];
double _chunkLength;
bool _waitForIDR;
double _lastVideoDts;
double _lastAudioDts;
uint32_t _chunkCount;
Variant _metadata;
IOBuffer _buff;
public:
OutFileFLV(BaseProtocol *pProtocol, string name, Variant &settings);
static OutFileFLV* GetInstance(BaseClientApplication *pApplication,
string name, Variant &settings);
virtual ~OutFileFLV();
protected:
virtual bool FinishInitialization(
GenericProcessDataSetup *pGenericProcessDataSetup);
virtual bool PushVideoData(IOBuffer &buffer, double pts, double dts, bool isKeyFrame);
virtual bool PushAudioData(IOBuffer &buffer, double pts, double dts);
virtual bool IsCodecSupported(uint64_t codec);
private:
bool WriteFLVHeader(bool hasAudio, bool hasVideo);
bool WriteFLVMetaData();
bool WriteFLVCodecAudio(AudioCodecInfoAAC *pInfoAudio);
bool WriteFLVCodecVideo(VideoCodecInfoH264 *pInfoVideo);
bool InitializeFLVFile(GenericProcessDataSetup *pGenericProcessDataSetup);
bool WriteMetaData(GenericProcessDataSetup *pGenericProcessDataSetup);
bool WriteCodecSetupBytes(GenericProcessDataSetup *pGenericProcessDataSetup);
void UpdateDuration();
bool SplitFile();
};
#endif /* _OUTFILEFLV_H */
| 2,176
|
C++
|
.h
| 58
| 35.586207
| 87
| 0.799811
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.