├── README.md ├── src ├── testMain.cpp ├── silenceException.cpp ├── RMSMeasurement.cpp ├── silenceDetector.cpp ├── main.cpp ├── detectorTypes.cpp └── streamDumper.cpp ├── inc ├── silenceException.hpp ├── RMSMeasurement.hpp ├── detectorTypes.hpp ├── silenceDetector.hpp └── streamDumper.hpp ├── Makefile ├── test.xml ├── LICENSE.txt └── lib └── rapidxml-1.13 ├── license.txt ├── rapidxml_utils.hpp ├── rapidxml_iterators.hpp ├── rapidxml_print.hpp └── manual.html /README.md: -------------------------------------------------------------------------------- 1 | Silence-Detector 2 | ================ 3 | 4 | Detects and logs when a LiveWire stream has no audio. 5 | -------------------------------------------------------------------------------- /src/testMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //192.168.0.200 239.192.39.123, 5004 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | silenceDetector sd; 8 | sd.setIPAddress("239.192.39.123"); 9 | sd.setBindingAddress("192.168.0.200"); 10 | sd.setPort("5004"); 11 | 12 | sd.signalProcessingLoop(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/silenceException.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | silenceException::silenceException(std::string in) 4 | { 5 | msg = in; 6 | } 7 | 8 | silenceException::~silenceException() throw() 9 | { 10 | //empty 11 | } 12 | 13 | const char * silenceException::what() const throw() 14 | { 15 | return (char *)msg.c_str(); 16 | } 17 | -------------------------------------------------------------------------------- /inc/silenceException.hpp: -------------------------------------------------------------------------------- 1 | #ifndef SILENCEEXCEPTION_H 2 | #define SILENCEEXCEPTION_H 3 | 4 | #include 5 | #include 6 | 7 | class silenceException : public std::exception 8 | { 9 | public: 10 | silenceException(std::string); 11 | ~silenceException() throw(); 12 | virtual const char *what() const throw(); 13 | 14 | private: 15 | std::string msg; 16 | }; 17 | 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /inc/RMSMeasurement.hpp: -------------------------------------------------------------------------------- 1 | #ifndef RMSMEASUREMENT_H 2 | #define RMSMEASUREMENT_H 3 | 4 | class RMSMeasurement 5 | { 6 | public: 7 | RMSMeasurement(); 8 | ~RMSMeasurement(); 9 | RMSMeasurement(const unsigned char*, unsigned long); 10 | void setData(const unsigned char*, unsigned long); 11 | double getMeasurementValue() const; 12 | 13 | private: 14 | double measurementValue; 15 | 16 | }; 17 | 18 | #endif 19 | 20 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | IFLAGS=-I./inc -Ilib/rapidxml-1.13 2 | LIBS =-lcurl 3 | OBJDIR=bin 4 | SRCDIR=src 5 | OBJS=bin/silenceException.o bin/detectorTypes.o bin/silenceDetector.o bin/RMSMeasurement.o bin/streamDumper.o 6 | 7 | default: silenceDetector 8 | 9 | $(OBJDIR) : 10 | mkdir $(OBJDIR) 11 | 12 | $(OBJDIR)/%.o : $(SRCDIR)/%.cpp $(OBJDIR) 13 | g++ -c $(IFLAGS) $< -o $@ 14 | 15 | test : $(OBJS) bin/testMain.o 16 | g++ -o $(OBJDIR)/test $^ $(LIBS) 17 | 18 | clean: 19 | rm $(OBJDIR)/* 20 | 21 | silenceDetector: bin/silenceException.o bin/detectorTypes.o bin/silenceDetector.o bin/RMSMeasurement.o bin/streamDumper.o bin/main.o 22 | g++ -o $(OBJDIR)/silenceDetector $^ $(LIBS) 23 | 24 | -------------------------------------------------------------------------------- /inc/detectorTypes.hpp: -------------------------------------------------------------------------------- 1 | #ifndef DETECTORTYPES_H 2 | #define DETECTORTYPES_H 3 | 4 | #include 5 | 6 | class detectorEmail : public detectorAction 7 | { 8 | public: 9 | detectorEmail(const std::string&, const std::string&, const std::string&); 10 | detectorEmail(); 11 | ~detectorEmail(); 12 | 13 | private: 14 | std::string emailTo; 15 | std::string emailServer; 16 | std::string emailMessage; 17 | void doAction(); 18 | void sendEmail(const std::string&, const std::string&, const std::string&); 19 | 20 | }; 21 | 22 | class detectorLog : public detectorAction 23 | { 24 | public: 25 | detectorLog(const std::string&, const std::string&); 26 | detectorLog(); 27 | ~detectorLog(); 28 | 29 | private: 30 | std::string logFn; 31 | std::string logMessage; 32 | void doAction(); 33 | void writeLog(); 34 | }; 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /test.xml: -------------------------------------------------------------------------------- 1 | 192.168.0.200 2 | 239.192.39.123 3 | 5004 4 | 5 | log 6 | Silence for 1 hour. 7 | /tmp/silence_log 8 | 25000 9 | 3600 10 | 11 | 12 | log 13 | Silence for 30 minutes. 14 | /tmp/silence_log 15 | 25000 16 | 1800 17 | 18 | 19 | log 20 | Silence for 10 seconds. 21 | /tmp/silence_log 22 | 25000 23 | 10 24 | 25 | 26 | log 27 | Silence for 30 seconds. 28 | /tmp/silence_log 29 | 25000 30 | 30 31 | 32 | 33 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Benjamin Yu, WMFO Tufts Freeform Radio 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /inc/silenceDetector.hpp: -------------------------------------------------------------------------------- 1 | #ifndef SILENCEDETECTOR_H 2 | #define SILENCEDETECTOR_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | class silenceDetector; 9 | class detectorAction; 10 | 11 | class silenceDetector 12 | { 13 | public: 14 | 15 | silenceDetector(); 16 | ~silenceDetector(); 17 | void setIPAddress(const std::string&); 18 | void setBindingAddress(const std::string&); 19 | void setPort(const std::string&); 20 | void signalProcessingLoop(); 21 | void addDetectorAction(detectorAction*); 22 | 23 | private: 24 | //Members 25 | streamDumper *sDump; 26 | std::string IPAddr; 27 | std::string bindAddr; 28 | unsigned int port; 29 | std::list actionList; 30 | 31 | }; 32 | 33 | 34 | //base class 35 | class detectorAction 36 | { 37 | public: 38 | detectorAction(); 39 | ~detectorAction(); 40 | double getSilenceThreshold(); 41 | unsigned long getSilenceCount(); 42 | void setSilenceCount(const unsigned long); 43 | void setSilenceThreshold(const double); 44 | void sendMeasurement(const double); 45 | 46 | private: 47 | virtual void doAction(); 48 | unsigned long counts; 49 | unsigned long countsThreshold; 50 | double silenceThreshold; 51 | }; 52 | 53 | #endif 54 | 55 | -------------------------------------------------------------------------------- /src/RMSMeasurement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TWO_TO_23RD 8388608 5 | 6 | RMSMeasurement::RMSMeasurement() 7 | { 8 | measurementValue = 0.0; 9 | } 10 | 11 | RMSMeasurement::~RMSMeasurement() 12 | { 13 | 14 | } 15 | 16 | RMSMeasurement::RMSMeasurement(const unsigned char *in, unsigned long len) 17 | { 18 | setData(in, len); 19 | } 20 | 21 | void RMSMeasurement::setData(const unsigned char *in, unsigned long len) 22 | { 23 | //Create RMS sound level measurement off of two channel data 24 | long right; 25 | long left; 26 | measurementValue = 0.0; 27 | unsigned long num_samples = len/6; //6 is the 2*(size of one sample in one channel = 3) 28 | 29 | for (unsigned long i = 0; i < len; i += 6) //6 is the 2*(size of one sample = 3) 30 | { 31 | //Remember, 24 bit big endian samples, and they are signed (bleh) 32 | left = ((in[i] & 127) << 16) | (in[i+1] << 8) | (in[i+2]); 33 | if (in[i] & 128) 34 | { 35 | //Must apply the two's complement since the MSB is set 36 | left += -TWO_TO_23RD; 37 | } 38 | 39 | right = ((in[i+3] & 127) << 16) | (in[i+4] << 8) | (in[i+5]); 40 | if (in[i+3] & 128) 41 | { 42 | //Must apply the two's complemennt since the MSB is set 43 | right += -TWO_TO_23RD; 44 | } 45 | 46 | //Right now using measurementValue to hold the mean of the squares 47 | measurementValue += std::pow(((left + right)/2.0), 2.0)/num_samples; 48 | } 49 | 50 | //Take square root to finish calculation 51 | measurementValue = std::sqrt(measurementValue); 52 | 53 | } 54 | 55 | double RMSMeasurement::getMeasurementValue() const 56 | { 57 | return measurementValue; 58 | } 59 | 60 | -------------------------------------------------------------------------------- /src/silenceDetector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | silenceDetector::silenceDetector() 7 | { 8 | sDump = NULL; 9 | actionList.empty(); 10 | } 11 | 12 | silenceDetector::~silenceDetector() 13 | { 14 | if (sDump != NULL) 15 | delete sDump; 16 | 17 | std::list::iterator it; 18 | 19 | for (it = actionList.begin(); it != actionList.end(); ++it) 20 | { 21 | delete (*it); 22 | } 23 | } 24 | 25 | void silenceDetector::setIPAddress(const std::string &in) 26 | { 27 | IPAddr = in; 28 | } 29 | 30 | void silenceDetector::setBindingAddress(const std::string &in) 31 | { 32 | bindAddr = in; 33 | } 34 | 35 | void silenceDetector::setPort(const std::string &in) 36 | { 37 | port = atoi(in.c_str()); 38 | } 39 | 40 | void silenceDetector::addDetectorAction(detectorAction *in) 41 | { 42 | if (in == NULL) 43 | throw silenceException("Attempted to add null detectorAction to queue."); 44 | 45 | actionList.push_back(in); 46 | } 47 | 48 | void silenceDetector::signalProcessingLoop() 49 | { 50 | unsigned char buf[3*2*48000]; //Believe this is one second 51 | double measurementValue; 52 | try 53 | { 54 | sDump = new streamDumper(bindAddr, IPAddr, port); 55 | } 56 | catch (std::exception e) 57 | { 58 | std::cerr << "Unable to begin streamDumping..." << std::endl; 59 | std::cerr << e.what() << std::endl; 60 | return; 61 | } 62 | 63 | while(1) 64 | { 65 | try 66 | { 67 | sDump->getSocketData(buf, 3*2*48000); 68 | measurementValue = RMSMeasurement(buf, 3*2*48000).getMeasurementValue(); 69 | //std::cout << "RMS Value: " << measurementValue << std::endl; 70 | 71 | std::list::iterator it; 72 | for (it = actionList.begin(); it != actionList.end(); ++it) 73 | { 74 | (*it)->sendMeasurement(measurementValue); 75 | } 76 | } 77 | catch (std::exception e) 78 | { 79 | std::cerr << "Error while monitoring stream..." << std::endl; 80 | std::cerr << e.what() << std::endl; 81 | } 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /lib/rapidxml-1.13/license.txt: -------------------------------------------------------------------------------- 1 | Use of this software is granted under one of the following two licenses, 2 | to be chosen freely by the user. 3 | 4 | 1. Boost Software License - Version 1.0 - August 17th, 2003 5 | =============================================================================== 6 | 7 | Copyright (c) 2006, 2007 Marcin Kalicinski 8 | 9 | Permission is hereby granted, free of charge, to any person or organization 10 | obtaining a copy of the software and accompanying documentation covered by 11 | this license (the "Software") to use, reproduce, display, distribute, 12 | execute, and transmit the Software, and to prepare derivative works of the 13 | Software, and to permit third-parties to whom the Software is furnished to 14 | do so, all subject to the following: 15 | 16 | The copyright notices in the Software and this entire statement, including 17 | the above license grant, this restriction and the following disclaimer, 18 | must be included in all copies of the Software, in whole or in part, and 19 | all derivative works of the Software, unless such copies or derivative 20 | works are solely in the form of machine-executable object code generated by 21 | a source language processor. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT 26 | SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE 27 | FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, 28 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 29 | DEALINGS IN THE SOFTWARE. 30 | 31 | 2. The MIT License 32 | =============================================================================== 33 | 34 | Copyright (c) 2006, 2007 Marcin Kalicinski 35 | 36 | Permission is hereby granted, free of charge, to any person obtaining a copy 37 | of this software and associated documentation files (the "Software"), to deal 38 | in the Software without restriction, including without limitation the rights 39 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 40 | of the Software, and to permit persons to whom the Software is furnished to do so, 41 | subject to the following conditions: 42 | 43 | The above copyright notice and this permission notice shall be included in all 44 | copies or substantial portions of the Software. 45 | 46 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 47 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 48 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 49 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 50 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 51 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 52 | IN THE SOFTWARE. 53 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | void processDetectorAction(rapidxml::xml_node<> *, silenceDetector &); 13 | 14 | int main(int argc, char *argv[]) 15 | { 16 | if (argc < 2) 17 | { 18 | std::cout << "Usage: silenceDetector " << std::endl; 19 | return 1; 20 | } 21 | 22 | //Daemonize 23 | if (fork() != 0) 24 | return 0; 25 | 26 | setsid(); 27 | 28 | if (fork() != 0) 29 | return 0; 30 | 31 | std::fstream f; 32 | f.open(argv[1], std::ios_base::in); 33 | if (f.fail()) 34 | { 35 | std::cerr << "Unable to open config file." << std::endl; 36 | return 1; 37 | } 38 | 39 | std::string config_xml; 40 | while (!f.eof()) 41 | { 42 | char c = f.get(); 43 | if (!f.eof()) 44 | config_xml += c; 45 | } 46 | 47 | char *buf = new char[config_xml.length()+1]; 48 | strncpy(buf, config_xml.c_str(), config_xml.length()); 49 | buf[config_xml.length()] = 0; 50 | rapidxml::xml_document<> xml; 51 | try 52 | { 53 | xml.parse<0>(buf); 54 | } 55 | catch (std::exception e) 56 | { 57 | std::cerr << "Unable to parse xml configuration file." << std::endl; 58 | std::cerr << e.what() << std::endl; 59 | return 1; 60 | } 61 | 62 | silenceDetector sd; 63 | rapidxml::xml_node<> *node = xml.first_node(); 64 | if (node == 0) 65 | { 66 | std::cerr << "Empty document." << std::endl; 67 | return 1; 68 | } 69 | 70 | while (node != 0) 71 | { 72 | if (!strcmp(node->name(), "BindingAddress")) 73 | { 74 | sd.setBindingAddress(node->first_node()->value()); 75 | } 76 | else if ( !strcmp(node->name(), "IPAddress") ) 77 | { 78 | sd.setIPAddress(node->first_node()->value()); 79 | } 80 | else if ( !strcmp(node->name(), "Port") ) 81 | { 82 | sd.setPort(node->first_node()->value()); 83 | } 84 | else if ( !strcmp(node->name(), "Action") ) 85 | { 86 | processDetectorAction(node, sd); 87 | } 88 | 89 | node = node->next_sibling(); 90 | } 91 | 92 | sd.signalProcessingLoop(); 93 | return 0; 94 | } 95 | 96 | void processDetectorAction(rapidxml::xml_node<> *node, silenceDetector &sd) 97 | { 98 | std::string actionType; 99 | std::map params; 100 | detectorAction *newAction; 101 | bool makeAction = true; 102 | for (rapidxml::xml_node<> *n = node->first_node(); n != 0; n = n->next_sibling()) 103 | { 104 | detectorAction *act; 105 | if ( !strcmp(n->name(), "Type") ) 106 | { 107 | actionType = n->first_node()->value(); 108 | } 109 | else 110 | { 111 | params[n->name()] = n->first_node()->value(); 112 | } 113 | } 114 | 115 | if (actionType == "email") 116 | { 117 | newAction = new detectorEmail(params["to"], params["server"], params["message"]); 118 | } 119 | else if (actionType == "log") 120 | { 121 | newAction = new detectorLog(params["message"], params["file"]); 122 | } 123 | else 124 | { 125 | makeAction = false; 126 | } 127 | 128 | if (makeAction) 129 | { 130 | newAction->setSilenceThreshold(atoi(params["threshold"].c_str())); 131 | newAction->setSilenceCount(atoi(params["counts"].c_str())); 132 | std::cout << newAction->getSilenceCount() << " " << newAction->getSilenceThreshold() << std::endl; 133 | sd.addDetectorAction(newAction); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /inc/streamDumper.hpp: -------------------------------------------------------------------------------- 1 | #ifndef STREAMDUMPER_H 2 | #define STREAMDUMPER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | class streamDumper 10 | { 11 | public: 12 | streamDumper(); 13 | streamDumper(const std::string &bindAddr, const std::string &ipaddr, int portNumber); 14 | void openMulticastStream(const std::string &bindAddr, const std::string &ipaddr, int portNumber); 15 | ~streamDumper(); 16 | void getSocketData(unsigned char* buf, unsigned long bufLen); 17 | 18 | private: 19 | std::string multicastAddr; 20 | int port; 21 | bool socketActive; 22 | bool subscriptionActive; 23 | int socketDescriptor; 24 | unsigned char *remainderData; 25 | unsigned long remainderDataLength; 26 | void openSocket(); 27 | void closeSocket(); 28 | void readSocket(); 29 | 30 | class RTPHeader 31 | { 32 | public: 33 | RTPHeader(); 34 | RTPHeader(unsigned char*); 35 | ~RTPHeader(); 36 | void readData(unsigned char*); 37 | int getVersion() const; 38 | bool hasPadding() const; 39 | bool hasExtension() const; 40 | unsigned int getCSRCCount() const; 41 | unsigned int getPayloadType() const; 42 | unsigned long getSequenceNumber() const; 43 | unsigned long getTimestamp() const; 44 | unsigned long getSSRCIdentifier() const; 45 | unsigned long getHeaderLength() const; 46 | 47 | private: 48 | int version; 49 | bool padding; 50 | bool extensions; 51 | unsigned int CSRCCount; 52 | unsigned int payloadType; 53 | unsigned long sequenceNumber; 54 | unsigned long timeStamp; 55 | unsigned long SSRCIdentifier; 56 | unsigned long extensionLength; 57 | 58 | }; 59 | 60 | class RTPPacket 61 | { 62 | public: 63 | RTPHeader header; 64 | RTPPacket(); 65 | RTPPacket(unsigned char*, unsigned long); 66 | ~RTPPacket(); 67 | void readData(unsigned char*, unsigned long); 68 | unsigned long getContentLength() const; 69 | unsigned char *getContent() const; 70 | bool operator<(const RTPPacket &b) const; 71 | RTPPacket(const RTPPacket &b); 72 | RTPPacket &operator=(const RTPPacket &b); 73 | 74 | private: 75 | unsigned char *content; 76 | unsigned long contentLength; 77 | 78 | }; 79 | 80 | void setRemainderData(const unsigned char *, unsigned long, const std::list&); 81 | 82 | }; 83 | 84 | //Exceptions 85 | class streamDumperException : public std::exception 86 | { 87 | public: 88 | streamDumperException(const std::string &reason) throw() 89 | { 90 | exceptionWhat = reason; 91 | } 92 | 93 | virtual const char *what() const throw() 94 | { 95 | return exceptionWhat.c_str(); 96 | } 97 | 98 | virtual ~streamDumperException() throw() {}; 99 | 100 | private: 101 | std::string exceptionWhat; 102 | 103 | }; 104 | 105 | #endif 106 | 107 | -------------------------------------------------------------------------------- /lib/rapidxml-1.13/rapidxml_utils.hpp: -------------------------------------------------------------------------------- 1 | #ifndef RAPIDXML_UTILS_HPP_INCLUDED 2 | #define RAPIDXML_UTILS_HPP_INCLUDED 3 | 4 | // Copyright (C) 2006, 2009 Marcin Kalicinski 5 | // Version 1.13 6 | // Revision $DateTime: 2009/05/13 01:46:17 $ 7 | //! \file rapidxml_utils.hpp This file contains high-level rapidxml utilities that can be useful 8 | //! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective. 9 | 10 | #include "rapidxml.hpp" 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | namespace rapidxml 17 | { 18 | 19 | //! Represents data loaded from a file 20 | template 21 | class file 22 | { 23 | 24 | public: 25 | 26 | //! Loads file into the memory. Data will be automatically destroyed by the destructor. 27 | //! \param filename Filename to load. 28 | file(const char *filename) 29 | { 30 | using namespace std; 31 | 32 | // Open stream 33 | basic_ifstream stream(filename, ios::binary); 34 | if (!stream) 35 | throw runtime_error(string("cannot open file ") + filename); 36 | stream.unsetf(ios::skipws); 37 | 38 | // Determine stream size 39 | stream.seekg(0, ios::end); 40 | size_t size = stream.tellg(); 41 | stream.seekg(0); 42 | 43 | // Load data and add terminating 0 44 | m_data.resize(size + 1); 45 | stream.read(&m_data.front(), static_cast(size)); 46 | m_data[size] = 0; 47 | } 48 | 49 | //! Loads file into the memory. Data will be automatically destroyed by the destructor 50 | //! \param stream Stream to load from 51 | file(std::basic_istream &stream) 52 | { 53 | using namespace std; 54 | 55 | // Load data and add terminating 0 56 | stream.unsetf(ios::skipws); 57 | m_data.assign(istreambuf_iterator(stream), istreambuf_iterator()); 58 | if (stream.fail() || stream.bad()) 59 | throw runtime_error("error reading stream"); 60 | m_data.push_back(0); 61 | } 62 | 63 | //! Gets file data. 64 | //! \return Pointer to data of file. 65 | Ch *data() 66 | { 67 | return &m_data.front(); 68 | } 69 | 70 | //! Gets file data. 71 | //! \return Pointer to data of file. 72 | const Ch *data() const 73 | { 74 | return &m_data.front(); 75 | } 76 | 77 | //! Gets file data size. 78 | //! \return Size of file data, in characters. 79 | std::size_t size() const 80 | { 81 | return m_data.size(); 82 | } 83 | 84 | private: 85 | 86 | std::vector m_data; // File data 87 | 88 | }; 89 | 90 | //! Counts children of node. Time complexity is O(n). 91 | //! \return Number of children of node 92 | template 93 | inline std::size_t count_children(xml_node *node) 94 | { 95 | xml_node *child = node->first_node(); 96 | std::size_t count = 0; 97 | while (child) 98 | { 99 | ++count; 100 | child = child->next_sibling(); 101 | } 102 | return count; 103 | } 104 | 105 | //! Counts attributes of node. Time complexity is O(n). 106 | //! \return Number of attributes of node 107 | template 108 | inline std::size_t count_attributes(xml_node *node) 109 | { 110 | xml_attribute *attr = node->first_attribute(); 111 | std::size_t count = 0; 112 | while (attr) 113 | { 114 | ++count; 115 | attr = attr->next_attribute(); 116 | } 117 | return count; 118 | } 119 | 120 | } 121 | 122 | #endif 123 | -------------------------------------------------------------------------------- /src/detectorTypes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | detectorAction::detectorAction() 9 | { 10 | counts = 0; 11 | countsThreshold = 0; 12 | silenceThreshold = 0.0; 13 | } 14 | 15 | detectorAction::~detectorAction() 16 | { 17 | //empty 18 | } 19 | 20 | double detectorAction::getSilenceThreshold() 21 | { 22 | return silenceThreshold; 23 | } 24 | 25 | void detectorAction::setSilenceThreshold(const double in) 26 | { 27 | if (in > 0.0) 28 | { 29 | silenceThreshold = in; 30 | } 31 | else 32 | { 33 | throw silenceException("silenceThreshold must be greater than 0."); 34 | } 35 | } 36 | 37 | unsigned long detectorAction::getSilenceCount() 38 | { 39 | return countsThreshold; 40 | } 41 | 42 | void detectorAction::setSilenceCount(const unsigned long in) 43 | { 44 | countsThreshold = in; 45 | } 46 | 47 | void detectorAction::sendMeasurement(const double in) 48 | { 49 | if (in > silenceThreshold) 50 | { 51 | counts = 0; 52 | return; 53 | } 54 | 55 | if (++counts == countsThreshold) 56 | { 57 | doAction(); 58 | return; 59 | } 60 | } 61 | 62 | void detectorAction::doAction() 63 | { 64 | //empty 65 | } 66 | 67 | //detectorEmail class 68 | 69 | detectorEmail::detectorEmail() 70 | { 71 | //empty 72 | } 73 | 74 | detectorEmail::~detectorEmail() 75 | { 76 | //empty 77 | } 78 | 79 | extern "C" size_t emailCallback(void *, size_t, size_t, void *); 80 | 81 | detectorEmail::detectorEmail(const std::string &to, const std::string &Server, const std::string &msg) 82 | { 83 | emailTo = to; 84 | emailServer = Server; 85 | emailMessage = msg; 86 | } 87 | 88 | void detectorEmail::doAction() 89 | { 90 | sendEmail(emailTo, emailServer, emailMessage); 91 | } 92 | 93 | void detectorEmail::sendEmail(const std::string &to, const std::string &server, const std::string &message) 94 | { 95 | CURL *curl; 96 | CURLcode res; 97 | curl_slist *recipients = NULL; 98 | 99 | curl = curl_easy_init(); 100 | if (!curl) 101 | { 102 | throw silenceException("Unable to initialize curl while sending alert email."); 103 | } 104 | 105 | curl_easy_setopt(curl, CURLOPT_URL, ("smtp://" + server).c_str()); 106 | curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "silenceDetector@wmfo.org"); 107 | recipients = curl_slist_append(recipients, to.c_str()); 108 | curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); 109 | 110 | //Add the headers 111 | std::string message2 = "To: " + to + "\nFrom: silenceDetector@wmfo.org\nSubject: Silence Alert\n\n" 112 | + message; 113 | 114 | curl_easy_setopt(curl, CURLOPT_READFUNCTION, emailCallback); 115 | curl_easy_setopt(curl, CURLOPT_READDATA, &message2); 116 | 117 | res = curl_easy_perform(curl); 118 | if (res != CURLE_OK) 119 | { 120 | curl_slist_free_all(recipients); 121 | curl_easy_cleanup(curl); 122 | throw silenceException("Curl initialized, but sending of emails failed."); 123 | return; 124 | } 125 | 126 | curl_slist_free_all(recipients); 127 | curl_easy_cleanup(curl); 128 | 129 | } 130 | 131 | //Internal Function, use to access C Code 132 | //Will erase the std::string pointed to by messageString 133 | extern "C" size_t emailCallback(void *buf, size_t size, size_t numbmemb, void *messageString) 134 | { 135 | std::string *message = (std::string *)messageString; 136 | size_t numBytes; 137 | std::cout << message->c_str() << std::endl; 138 | 139 | if (message->length() == 0) 140 | return 0; 141 | 142 | if (size*numbmemb <= message->length()) 143 | { 144 | numBytes = size * numbmemb; 145 | } 146 | else 147 | { 148 | numBytes = message->length(); 149 | } 150 | 151 | size_t actualBytesSent = message->copy((char *)buf, numBytes, 0); 152 | message->erase(0, actualBytesSent); 153 | 154 | return actualBytesSent; 155 | } 156 | 157 | //log class 158 | 159 | detectorLog::detectorLog() 160 | { 161 | //empty 162 | } 163 | 164 | detectorLog::~detectorLog() 165 | { 166 | //empty 167 | } 168 | 169 | 170 | detectorLog::detectorLog(const std::string &msg, const std::string &_logFn) 171 | { 172 | logMessage = msg; 173 | logFn = _logFn; 174 | } 175 | 176 | void detectorLog::doAction() 177 | { 178 | writeLog(); 179 | } 180 | 181 | void detectorLog::writeLog() 182 | { 183 | std::fstream file; 184 | file.open(logFn.c_str(), std::ios_base::out | std::ios_base::app); 185 | 186 | if (file.fail()) 187 | throw silenceException("Unable to open log file."); 188 | 189 | time_t timer; 190 | time(&timer); 191 | std::string logTime = ctime(&timer); 192 | logTime[logTime.length() - 1] = ':'; //remove the new line 193 | file << logTime << " " << logMessage << std::endl; 194 | 195 | file.close(); 196 | } 197 | 198 | -------------------------------------------------------------------------------- /lib/rapidxml-1.13/rapidxml_iterators.hpp: -------------------------------------------------------------------------------- 1 | #ifndef RAPIDXML_ITERATORS_HPP_INCLUDED 2 | #define RAPIDXML_ITERATORS_HPP_INCLUDED 3 | 4 | // Copyright (C) 2006, 2009 Marcin Kalicinski 5 | // Version 1.13 6 | // Revision $DateTime: 2009/05/13 01:46:17 $ 7 | //! \file rapidxml_iterators.hpp This file contains rapidxml iterators 8 | 9 | #include "rapidxml.hpp" 10 | 11 | namespace rapidxml 12 | { 13 | 14 | //! Iterator of child nodes of xml_node 15 | template 16 | class node_iterator 17 | { 18 | 19 | public: 20 | 21 | typedef typename xml_node value_type; 22 | typedef typename xml_node &reference; 23 | typedef typename xml_node *pointer; 24 | typedef std::ptrdiff_t difference_type; 25 | typedef std::bidirectional_iterator_tag iterator_category; 26 | 27 | node_iterator() 28 | : m_node(0) 29 | { 30 | } 31 | 32 | node_iterator(xml_node *node) 33 | : m_node(node->first_node()) 34 | { 35 | } 36 | 37 | reference operator *() const 38 | { 39 | assert(m_node); 40 | return *m_node; 41 | } 42 | 43 | pointer operator->() const 44 | { 45 | assert(m_node); 46 | return m_node; 47 | } 48 | 49 | node_iterator& operator++() 50 | { 51 | assert(m_node); 52 | m_node = m_node->next_sibling(); 53 | return *this; 54 | } 55 | 56 | node_iterator operator++(int) 57 | { 58 | node_iterator tmp = *this; 59 | ++this; 60 | return tmp; 61 | } 62 | 63 | node_iterator& operator--() 64 | { 65 | assert(m_node && m_node->previous_sibling()); 66 | m_node = m_node->previous_sibling(); 67 | return *this; 68 | } 69 | 70 | node_iterator operator--(int) 71 | { 72 | node_iterator tmp = *this; 73 | ++this; 74 | return tmp; 75 | } 76 | 77 | bool operator ==(const node_iterator &rhs) 78 | { 79 | return m_node == rhs.m_node; 80 | } 81 | 82 | bool operator !=(const node_iterator &rhs) 83 | { 84 | return m_node != rhs.m_node; 85 | } 86 | 87 | private: 88 | 89 | xml_node *m_node; 90 | 91 | }; 92 | 93 | //! Iterator of child attributes of xml_node 94 | template 95 | class attribute_iterator 96 | { 97 | 98 | public: 99 | 100 | typedef typename xml_attribute value_type; 101 | typedef typename xml_attribute &reference; 102 | typedef typename xml_attribute *pointer; 103 | typedef std::ptrdiff_t difference_type; 104 | typedef std::bidirectional_iterator_tag iterator_category; 105 | 106 | attribute_iterator() 107 | : m_attribute(0) 108 | { 109 | } 110 | 111 | attribute_iterator(xml_node *node) 112 | : m_attribute(node->first_attribute()) 113 | { 114 | } 115 | 116 | reference operator *() const 117 | { 118 | assert(m_attribute); 119 | return *m_attribute; 120 | } 121 | 122 | pointer operator->() const 123 | { 124 | assert(m_attribute); 125 | return m_attribute; 126 | } 127 | 128 | attribute_iterator& operator++() 129 | { 130 | assert(m_attribute); 131 | m_attribute = m_attribute->next_attribute(); 132 | return *this; 133 | } 134 | 135 | attribute_iterator operator++(int) 136 | { 137 | attribute_iterator tmp = *this; 138 | ++this; 139 | return tmp; 140 | } 141 | 142 | attribute_iterator& operator--() 143 | { 144 | assert(m_attribute && m_attribute->previous_attribute()); 145 | m_attribute = m_attribute->previous_attribute(); 146 | return *this; 147 | } 148 | 149 | attribute_iterator operator--(int) 150 | { 151 | attribute_iterator tmp = *this; 152 | ++this; 153 | return tmp; 154 | } 155 | 156 | bool operator ==(const attribute_iterator &rhs) 157 | { 158 | return m_attribute == rhs.m_attribute; 159 | } 160 | 161 | bool operator !=(const attribute_iterator &rhs) 162 | { 163 | return m_attribute != rhs.m_attribute; 164 | } 165 | 166 | private: 167 | 168 | xml_attribute *m_attribute; 169 | 170 | }; 171 | 172 | } 173 | 174 | #endif 175 | -------------------------------------------------------------------------------- /src/streamDumper.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | streamDumper::streamDumper() 10 | { 11 | socketActive = false; 12 | socketDescriptor = -1; 13 | subscriptionActive = false; 14 | remainderData = NULL; 15 | remainderDataLength = 0; 16 | } 17 | 18 | streamDumper::streamDumper(const std::string &bindAddr, const std::string &ipaddr, int portNumber) 19 | { 20 | socketActive = false; 21 | socketDescriptor = -1; 22 | subscriptionActive = false; 23 | remainderData = NULL; 24 | remainderDataLength = 0; 25 | openMulticastStream(bindAddr, ipaddr, portNumber); 26 | } 27 | 28 | streamDumper::~streamDumper() 29 | { 30 | if (socketActive == true) 31 | { 32 | //Need to close the socket. 33 | closeSocket(); 34 | } 35 | } 36 | 37 | void streamDumper::closeSocket() 38 | { 39 | if (!socketActive) 40 | throw streamDumperException("Cannot close socket (never active)."); 41 | 42 | close(socketDescriptor); 43 | } 44 | 45 | void streamDumper::openSocket() 46 | { 47 | socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0); 48 | 49 | //Check for errors 50 | if (socketDescriptor < 0) 51 | { 52 | //Throw an exception 53 | throw streamDumperException("Unable to create a socket."); 54 | } 55 | 56 | socketActive = true; 57 | } 58 | 59 | void streamDumper::openMulticastStream(const std::string &bindAddr, const std::string &ipaddr, int portnum) 60 | { 61 | //Check 62 | if (socketActive) 63 | throw streamDumperException("Socket is already active."); 64 | if (subscriptionActive) 65 | throw streamDumperException("Already subscribed to a multicast stream."); 66 | 67 | //Setup the ip structure 68 | ip_mreq multicastSubscriptionReq; 69 | if (!inet_aton(ipaddr.c_str(), &multicastSubscriptionReq.imr_multiaddr)) 70 | throw streamDumperException("Invalid IP address specified."); 71 | if (!inet_aton(bindAddr.c_str(), &multicastSubscriptionReq.imr_interface)) 72 | throw streamDumperException("Invalid bind address specified."); 73 | //multicastSubscriptionReq.imr_interface.s_addr = htonl(INADDR_ANY); 74 | 75 | //Open the socket 76 | openSocket(); 77 | 78 | //Bind the socket 79 | sockaddr_in bindStruct; 80 | memset(&bindStruct, 0, sizeof(bindStruct)); 81 | bindStruct.sin_family = AF_INET; 82 | bindStruct.sin_addr.s_addr = htonl(INADDR_ANY); 83 | bindStruct.sin_port = htons(portnum); 84 | if (bind(socketDescriptor, (sockaddr *) &bindStruct, sizeof(bindStruct)) != 0) 85 | throw streamDumperException("Unable to bind socket to address."); 86 | 87 | //Attempt to join the multicast group 88 | if (setsockopt(socketDescriptor, IPPROTO_IP, IP_ADD_MEMBERSHIP, &multicastSubscriptionReq, sizeof(multicastSubscriptionReq)) != 0) 89 | throw streamDumperException("Unable to join multicast group."); 90 | 91 | subscriptionActive = true; 92 | } 93 | 94 | void streamDumper::getSocketData(unsigned char *buf, unsigned long buflen) 95 | { 96 | if (!socketActive) 97 | throw streamDumperException("Cannot receive data. Socket not active."); 98 | if (!subscriptionActive) 99 | throw streamDumperException("Cannot receive data. Not subscribed to multicast group."); 100 | if (buflen < 1) 101 | return; 102 | 103 | unsigned char packetBuf[2048]; 104 | unsigned long curCache = remainderDataLength; 105 | unsigned char *pos = buf; 106 | std::list packets; 107 | 108 | while (curCache < buflen) 109 | { 110 | ssize_t num_bytes = recvfrom(socketDescriptor, packetBuf, 2048, 0, NULL, NULL); 111 | RTPPacket rtpPacket(packetBuf, num_bytes); 112 | curCache += rtpPacket.getContentLength(); 113 | packets.push_back(rtpPacket); 114 | } 115 | 116 | packets.sort(); 117 | 118 | //Add the remainder data to the buffer 119 | if (remainderDataLength > 0) 120 | { 121 | if (remainderDataLength < buflen) 122 | { 123 | memcpy(pos, remainderData, remainderDataLength); 124 | pos += remainderDataLength; 125 | remainderDataLength = 0; 126 | delete[] remainderData; 127 | remainderData = NULL; 128 | } 129 | else 130 | { 131 | //Buffer is not big enough to hold entirety of remainder data 132 | memcpy(pos, remainderData, buflen); 133 | unsigned char *leftOverBytes = new unsigned char[remainderDataLength-buflen]; 134 | memcpy(leftOverBytes, remainderData+buflen, remainderDataLength-buflen); 135 | setRemainderData(leftOverBytes, remainderDataLength-buflen, packets); 136 | delete[] leftOverBytes; 137 | return; 138 | } 139 | } 140 | 141 | //Add the packet data 142 | std::list::iterator it = packets.begin(); 143 | while (pos < (buf + buflen)) 144 | { 145 | if ((*it).getContentLength() < ((buf + buflen) - pos)) 146 | { 147 | //Copy the whole packet in 148 | memcpy(pos, (*it).getContent(), (*it).getContentLength()); 149 | pos += (*it).getContentLength(); 150 | it++; 151 | packets.pop_front(); 152 | } 153 | else 154 | { 155 | //Need to copy only some of the packet in 156 | unsigned char *endbuf = buf + buflen; 157 | unsigned long numLeftOverBytes = (*it).getContentLength() - (endbuf - pos); 158 | unsigned long numBytesToWrite = endbuf - pos; 159 | memcpy(pos, (*it).getContent(), numBytesToWrite); 160 | unsigned char *leftOverBytes = new unsigned char[numLeftOverBytes]; 161 | memcpy(leftOverBytes, (*it).getContent() + numBytesToWrite, numLeftOverBytes); 162 | it++; 163 | packets.pop_front(); 164 | setRemainderData(leftOverBytes, numLeftOverBytes, packets); 165 | delete[] leftOverBytes; 166 | return; 167 | } 168 | } 169 | 170 | 171 | // std::cout << "Recv'd " << num_bytes << " from the socket." << std::endl; 172 | // std::cout << "Version: " << rtpHead.getVersion() << std::endl; 173 | // std::cout << "Padding: " << rtpHead.hasPadding() << std::endl; 174 | // std::cout << "Extensions: " << rtpHead.hasExtension() << std::endl; 175 | // std::cout << "CSRCCount: " << rtpHead.getCSRCCount() << std::endl; 176 | // std::cout << "PayloadType: " << rtpHead.getPayloadType() << std::endl; 177 | // std::cout << "Sequence #: " << rtpPacket.header.getSequenceNumber() << std::endl; 178 | // std::cout << "Timestamp: " << rtpHead.getTimestamp() << std::endl; 179 | // std::cout << "SSRC: " << rtpHead.getSSRCIdentifier() << std::endl << std::endl; 180 | // std::cout << "Header Length: " << rtpPacket.header.getHeaderLength() << std::endl; 181 | // std::cout << "Content Length: " << rtpPacket.getContentLength() << std::endl; 182 | } 183 | 184 | void streamDumper::setRemainderData(const unsigned char *data, unsigned long data_len, const std::list& l) 185 | { 186 | //Determine how much data we have here 187 | unsigned long newRemainderDataLength = data_len; 188 | for (std::list::const_iterator i = l.begin(); i != l.end(); i++) 189 | { 190 | newRemainderDataLength += (*i).getContentLength(); 191 | } 192 | 193 | unsigned char *newRemainderData = new unsigned char[newRemainderDataLength]; 194 | unsigned char *pos = newRemainderData; 195 | 196 | //Copy the raw data 197 | memcpy(pos, data, data_len); 198 | pos += data_len; 199 | 200 | //Copy the data from full packets 201 | for (std::list::const_iterator i = l.begin(); i != l.end(); i++) 202 | { 203 | memcpy(pos, (*i).getContent(), (*i).getContentLength()); 204 | pos += (*i).getContentLength(); 205 | } 206 | 207 | //Clear the old remainder data and set new data 208 | delete[] remainderData; 209 | remainderData = newRemainderData; 210 | remainderDataLength = newRemainderDataLength; 211 | } 212 | 213 | streamDumper::RTPHeader::RTPHeader() 214 | { 215 | version = 0; 216 | padding = false; 217 | extensions = false; 218 | CSRCCount = 0; 219 | payloadType = 0; 220 | sequenceNumber = 0; 221 | timeStamp = 0; 222 | SSRCIdentifier = 0; 223 | extensionLength = 0; 224 | } 225 | 226 | streamDumper::RTPHeader::~RTPHeader() { }; 227 | 228 | streamDumper::RTPHeader::RTPHeader(unsigned char *in) 229 | { 230 | version = 0; 231 | padding = false; 232 | extensions = false; 233 | CSRCCount = 0; 234 | payloadType = 0; 235 | sequenceNumber = 0; 236 | timeStamp = 0; 237 | SSRCIdentifier = 0; 238 | extensionLength = 0; 239 | readData(in); 240 | } 241 | 242 | void streamDumper::RTPHeader::readData(unsigned char *in) 243 | { 244 | version = (in[0] & 192) >> 6; 245 | padding = in[0] & (1 << 5); 246 | extensions = in[0] & (1 << 4); 247 | CSRCCount = ((1 << 3) | (1 << 2) | (1 << 1) | 1) & in[0]; 248 | payloadType = in[1] & ~128; 249 | sequenceNumber = (in[2] << 8) | (in[3]); 250 | timeStamp = (in[4] << 24) | (in[5] << 16) | (in[6] << 8) | in[7]; 251 | SSRCIdentifier = (in[8] << 24) | (in[9] << 16) | (in[10] << 8) | in[11]; 252 | 253 | //Extenstion length code 254 | if (extensions) 255 | { 256 | unsigned long ind = 16 + 4*CSRCCount + 2; 257 | extensionLength = (in[ind] << 8) | in[ind+1]; 258 | extensionLength = (extensionLength+1)*4; 259 | } 260 | else 261 | { 262 | extensionLength = 0; 263 | } 264 | } 265 | 266 | unsigned long streamDumper::RTPHeader::getHeaderLength() const 267 | { 268 | return 12 + 4*CSRCCount + extensionLength; 269 | } 270 | 271 | int streamDumper::RTPHeader::getVersion() const 272 | { 273 | return version; 274 | } 275 | 276 | bool streamDumper::RTPHeader::hasPadding() const 277 | { 278 | return padding; 279 | } 280 | 281 | bool streamDumper::RTPHeader::hasExtension() const 282 | { 283 | return extensions; 284 | } 285 | 286 | unsigned int streamDumper::RTPHeader::getCSRCCount() const 287 | { 288 | return CSRCCount; 289 | } 290 | 291 | unsigned int streamDumper::RTPHeader::getPayloadType() const 292 | { 293 | return payloadType; 294 | } 295 | 296 | unsigned long streamDumper::RTPHeader::getSequenceNumber() const 297 | { 298 | return sequenceNumber; 299 | } 300 | 301 | unsigned long streamDumper::RTPHeader::getTimestamp() const 302 | { 303 | return timeStamp; 304 | } 305 | 306 | unsigned long streamDumper::RTPHeader::getSSRCIdentifier() const 307 | { 308 | return SSRCIdentifier; 309 | } 310 | 311 | streamDumper::RTPPacket::RTPPacket() 312 | { 313 | content = NULL; 314 | contentLength = 0; 315 | } 316 | 317 | streamDumper::RTPPacket::~RTPPacket() 318 | { 319 | if (content != NULL) 320 | delete[] content; 321 | } 322 | 323 | streamDumper::RTPPacket::RTPPacket(unsigned char *in, unsigned long in_len) 324 | { 325 | content = NULL; 326 | contentLength = 0; 327 | readData(in, in_len); 328 | } 329 | 330 | void streamDumper::RTPPacket::readData(unsigned char *in, unsigned long in_len) 331 | { 332 | if (in_len < 12) 333 | throw streamDumperException("RTP Packet must be at least 12 bytes long."); 334 | 335 | header.readData(in); 336 | contentLength = in_len - header.getHeaderLength(); 337 | if (contentLength > 0) 338 | { 339 | content = new unsigned char[contentLength]; 340 | memcpy(content, in+header.getHeaderLength(), contentLength); 341 | } 342 | } 343 | 344 | unsigned long streamDumper::RTPPacket::getContentLength() const 345 | { 346 | return contentLength; 347 | } 348 | 349 | unsigned char *streamDumper::RTPPacket::getContent() const 350 | { 351 | return content; 352 | } 353 | 354 | streamDumper::RTPPacket::RTPPacket(const RTPPacket &b) 355 | { 356 | //Copy constructor 357 | if (b.contentLength > 0) 358 | { 359 | contentLength = b.contentLength; 360 | header = b.header; 361 | content = new unsigned char[contentLength]; 362 | memcpy(content, b.content, contentLength); 363 | } 364 | else 365 | { 366 | contentLength = 0; 367 | content = NULL; 368 | }; 369 | 370 | } 371 | 372 | streamDumper::RTPPacket& streamDumper::RTPPacket::operator=(const streamDumper::RTPPacket &b) 373 | { 374 | //Assignment operator 375 | if (contentLength > 0) 376 | { 377 | //Clear old memory 378 | delete[] content; 379 | } 380 | 381 | if (b.contentLength > 0) 382 | { 383 | header = b.header; 384 | contentLength = b.contentLength; 385 | content = new unsigned char[contentLength]; 386 | memcpy(content, b.content, contentLength); 387 | } 388 | else 389 | { 390 | header = b.header; 391 | contentLength = 0; 392 | content = NULL; 393 | } 394 | 395 | return *this; 396 | } 397 | 398 | bool streamDumper::RTPPacket::operator<(const RTPPacket &b) const 399 | { 400 | unsigned long seq_a, seq_b; 401 | seq_a = header.getSequenceNumber(); 402 | seq_b = b.header.getSequenceNumber(); 403 | 404 | if (seq_a < seq_b) 405 | { 406 | if ((seq_b - seq_a) < 32768) 407 | { 408 | //No wrap around 409 | return true; 410 | } 411 | else 412 | { 413 | //Wrap around 414 | return false; 415 | } 416 | } 417 | else 418 | { 419 | // b < a 420 | if ((seq_a - seq_b) < 32768) 421 | { 422 | //No wrap around 423 | return false; 424 | } 425 | else 426 | { 427 | //Wrap around 428 | return true; 429 | } 430 | } 431 | 432 | } 433 | -------------------------------------------------------------------------------- /lib/rapidxml-1.13/rapidxml_print.hpp: -------------------------------------------------------------------------------- 1 | #ifndef RAPIDXML_PRINT_HPP_INCLUDED 2 | #define RAPIDXML_PRINT_HPP_INCLUDED 3 | 4 | // Copyright (C) 2006, 2009 Marcin Kalicinski 5 | // Version 1.13 6 | // Revision $DateTime: 2009/05/13 01:46:17 $ 7 | //! \file rapidxml_print.hpp This file contains rapidxml printer implementation 8 | 9 | #include "rapidxml.hpp" 10 | 11 | // Only include streams if not disabled 12 | #ifndef RAPIDXML_NO_STREAMS 13 | #include 14 | #include 15 | #endif 16 | 17 | namespace rapidxml 18 | { 19 | 20 | /////////////////////////////////////////////////////////////////////// 21 | // Printing flags 22 | 23 | const int print_no_indenting = 0x1; //!< Printer flag instructing the printer to suppress indenting of XML. See print() function. 24 | 25 | /////////////////////////////////////////////////////////////////////// 26 | // Internal 27 | 28 | //! \cond internal 29 | namespace internal 30 | { 31 | 32 | /////////////////////////////////////////////////////////////////////////// 33 | // Internal character operations 34 | 35 | // Copy characters from given range to given output iterator 36 | template 37 | inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out) 38 | { 39 | while (begin != end) 40 | *out++ = *begin++; 41 | return out; 42 | } 43 | 44 | // Copy characters from given range to given output iterator and expand 45 | // characters into references (< > ' " &) 46 | template 47 | inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out) 48 | { 49 | while (begin != end) 50 | { 51 | if (*begin == noexpand) 52 | { 53 | *out++ = *begin; // No expansion, copy character 54 | } 55 | else 56 | { 57 | switch (*begin) 58 | { 59 | case Ch('<'): 60 | *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';'); 61 | break; 62 | case Ch('>'): 63 | *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';'); 64 | break; 65 | case Ch('\''): 66 | *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';'); 67 | break; 68 | case Ch('"'): 69 | *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';'); 70 | break; 71 | case Ch('&'): 72 | *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); 73 | break; 74 | default: 75 | *out++ = *begin; // No expansion, copy character 76 | } 77 | } 78 | ++begin; // Step to next character 79 | } 80 | return out; 81 | } 82 | 83 | // Fill given output iterator with repetitions of the same character 84 | template 85 | inline OutIt fill_chars(OutIt out, int n, Ch ch) 86 | { 87 | for (int i = 0; i < n; ++i) 88 | *out++ = ch; 89 | return out; 90 | } 91 | 92 | // Find character 93 | template 94 | inline bool find_char(const Ch *begin, const Ch *end) 95 | { 96 | while (begin != end) 97 | if (*begin++ == ch) 98 | return true; 99 | return false; 100 | } 101 | 102 | /////////////////////////////////////////////////////////////////////////// 103 | // Internal printing operations 104 | 105 | // Print node 106 | template 107 | inline OutIt print_node(OutIt out, const xml_node *node, int flags, int indent) 108 | { 109 | // Print proper node type 110 | switch (node->type()) 111 | { 112 | 113 | // Document 114 | case node_document: 115 | out = print_children(out, node, flags, indent); 116 | break; 117 | 118 | // Element 119 | case node_element: 120 | out = print_element_node(out, node, flags, indent); 121 | break; 122 | 123 | // Data 124 | case node_data: 125 | out = print_data_node(out, node, flags, indent); 126 | break; 127 | 128 | // CDATA 129 | case node_cdata: 130 | out = print_cdata_node(out, node, flags, indent); 131 | break; 132 | 133 | // Declaration 134 | case node_declaration: 135 | out = print_declaration_node(out, node, flags, indent); 136 | break; 137 | 138 | // Comment 139 | case node_comment: 140 | out = print_comment_node(out, node, flags, indent); 141 | break; 142 | 143 | // Doctype 144 | case node_doctype: 145 | out = print_doctype_node(out, node, flags, indent); 146 | break; 147 | 148 | // Pi 149 | case node_pi: 150 | out = print_pi_node(out, node, flags, indent); 151 | break; 152 | 153 | // Unknown 154 | default: 155 | assert(0); 156 | break; 157 | } 158 | 159 | // If indenting not disabled, add line break after node 160 | if (!(flags & print_no_indenting)) 161 | *out = Ch('\n'), ++out; 162 | 163 | // Return modified iterator 164 | return out; 165 | } 166 | 167 | // Print children of the node 168 | template 169 | inline OutIt print_children(OutIt out, const xml_node *node, int flags, int indent) 170 | { 171 | for (xml_node *child = node->first_node(); child; child = child->next_sibling()) 172 | out = print_node(out, child, flags, indent); 173 | return out; 174 | } 175 | 176 | // Print attributes of the node 177 | template 178 | inline OutIt print_attributes(OutIt out, const xml_node *node, int flags) 179 | { 180 | for (xml_attribute *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute()) 181 | { 182 | if (attribute->name() && attribute->value()) 183 | { 184 | // Print attribute name 185 | *out = Ch(' '), ++out; 186 | out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out); 187 | *out = Ch('='), ++out; 188 | // Print attribute value using appropriate quote type 189 | if (find_char(attribute->value(), attribute->value() + attribute->value_size())) 190 | { 191 | *out = Ch('\''), ++out; 192 | out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out); 193 | *out = Ch('\''), ++out; 194 | } 195 | else 196 | { 197 | *out = Ch('"'), ++out; 198 | out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out); 199 | *out = Ch('"'), ++out; 200 | } 201 | } 202 | } 203 | return out; 204 | } 205 | 206 | // Print data node 207 | template 208 | inline OutIt print_data_node(OutIt out, const xml_node *node, int flags, int indent) 209 | { 210 | assert(node->type() == node_data); 211 | if (!(flags & print_no_indenting)) 212 | out = fill_chars(out, indent, Ch('\t')); 213 | out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); 214 | return out; 215 | } 216 | 217 | // Print data node 218 | template 219 | inline OutIt print_cdata_node(OutIt out, const xml_node *node, int flags, int indent) 220 | { 221 | assert(node->type() == node_cdata); 222 | if (!(flags & print_no_indenting)) 223 | out = fill_chars(out, indent, Ch('\t')); 224 | *out = Ch('<'); ++out; 225 | *out = Ch('!'); ++out; 226 | *out = Ch('['); ++out; 227 | *out = Ch('C'); ++out; 228 | *out = Ch('D'); ++out; 229 | *out = Ch('A'); ++out; 230 | *out = Ch('T'); ++out; 231 | *out = Ch('A'); ++out; 232 | *out = Ch('['); ++out; 233 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 234 | *out = Ch(']'); ++out; 235 | *out = Ch(']'); ++out; 236 | *out = Ch('>'); ++out; 237 | return out; 238 | } 239 | 240 | // Print element node 241 | template 242 | inline OutIt print_element_node(OutIt out, const xml_node *node, int flags, int indent) 243 | { 244 | assert(node->type() == node_element); 245 | 246 | // Print element name and attributes, if any 247 | if (!(flags & print_no_indenting)) 248 | out = fill_chars(out, indent, Ch('\t')); 249 | *out = Ch('<'), ++out; 250 | out = copy_chars(node->name(), node->name() + node->name_size(), out); 251 | out = print_attributes(out, node, flags); 252 | 253 | // If node is childless 254 | if (node->value_size() == 0 && !node->first_node()) 255 | { 256 | // Print childless node tag ending 257 | *out = Ch('/'), ++out; 258 | *out = Ch('>'), ++out; 259 | } 260 | else 261 | { 262 | // Print normal node tag ending 263 | *out = Ch('>'), ++out; 264 | 265 | // Test if node contains a single data node only (and no other nodes) 266 | xml_node *child = node->first_node(); 267 | if (!child) 268 | { 269 | // If node has no children, only print its value without indenting 270 | out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); 271 | } 272 | else if (child->next_sibling() == 0 && child->type() == node_data) 273 | { 274 | // If node has a sole data child, only print its value without indenting 275 | out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out); 276 | } 277 | else 278 | { 279 | // Print all children with full indenting 280 | if (!(flags & print_no_indenting)) 281 | *out = Ch('\n'), ++out; 282 | out = print_children(out, node, flags, indent + 1); 283 | if (!(flags & print_no_indenting)) 284 | out = fill_chars(out, indent, Ch('\t')); 285 | } 286 | 287 | // Print node end 288 | *out = Ch('<'), ++out; 289 | *out = Ch('/'), ++out; 290 | out = copy_chars(node->name(), node->name() + node->name_size(), out); 291 | *out = Ch('>'), ++out; 292 | } 293 | return out; 294 | } 295 | 296 | // Print declaration node 297 | template 298 | inline OutIt print_declaration_node(OutIt out, const xml_node *node, int flags, int indent) 299 | { 300 | // Print declaration start 301 | if (!(flags & print_no_indenting)) 302 | out = fill_chars(out, indent, Ch('\t')); 303 | *out = Ch('<'), ++out; 304 | *out = Ch('?'), ++out; 305 | *out = Ch('x'), ++out; 306 | *out = Ch('m'), ++out; 307 | *out = Ch('l'), ++out; 308 | 309 | // Print attributes 310 | out = print_attributes(out, node, flags); 311 | 312 | // Print declaration end 313 | *out = Ch('?'), ++out; 314 | *out = Ch('>'), ++out; 315 | 316 | return out; 317 | } 318 | 319 | // Print comment node 320 | template 321 | inline OutIt print_comment_node(OutIt out, const xml_node *node, int flags, int indent) 322 | { 323 | assert(node->type() == node_comment); 324 | if (!(flags & print_no_indenting)) 325 | out = fill_chars(out, indent, Ch('\t')); 326 | *out = Ch('<'), ++out; 327 | *out = Ch('!'), ++out; 328 | *out = Ch('-'), ++out; 329 | *out = Ch('-'), ++out; 330 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 331 | *out = Ch('-'), ++out; 332 | *out = Ch('-'), ++out; 333 | *out = Ch('>'), ++out; 334 | return out; 335 | } 336 | 337 | // Print doctype node 338 | template 339 | inline OutIt print_doctype_node(OutIt out, const xml_node *node, int flags, int indent) 340 | { 341 | assert(node->type() == node_doctype); 342 | if (!(flags & print_no_indenting)) 343 | out = fill_chars(out, indent, Ch('\t')); 344 | *out = Ch('<'), ++out; 345 | *out = Ch('!'), ++out; 346 | *out = Ch('D'), ++out; 347 | *out = Ch('O'), ++out; 348 | *out = Ch('C'), ++out; 349 | *out = Ch('T'), ++out; 350 | *out = Ch('Y'), ++out; 351 | *out = Ch('P'), ++out; 352 | *out = Ch('E'), ++out; 353 | *out = Ch(' '), ++out; 354 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 355 | *out = Ch('>'), ++out; 356 | return out; 357 | } 358 | 359 | // Print pi node 360 | template 361 | inline OutIt print_pi_node(OutIt out, const xml_node *node, int flags, int indent) 362 | { 363 | assert(node->type() == node_pi); 364 | if (!(flags & print_no_indenting)) 365 | out = fill_chars(out, indent, Ch('\t')); 366 | *out = Ch('<'), ++out; 367 | *out = Ch('?'), ++out; 368 | out = copy_chars(node->name(), node->name() + node->name_size(), out); 369 | *out = Ch(' '), ++out; 370 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 371 | *out = Ch('?'), ++out; 372 | *out = Ch('>'), ++out; 373 | return out; 374 | } 375 | 376 | } 377 | //! \endcond 378 | 379 | /////////////////////////////////////////////////////////////////////////// 380 | // Printing 381 | 382 | //! Prints XML to given output iterator. 383 | //! \param out Output iterator to print to. 384 | //! \param node Node to be printed. Pass xml_document to print entire document. 385 | //! \param flags Flags controlling how XML is printed. 386 | //! \return Output iterator pointing to position immediately after last character of printed text. 387 | template 388 | inline OutIt print(OutIt out, const xml_node &node, int flags = 0) 389 | { 390 | return internal::print_node(out, &node, flags, 0); 391 | } 392 | 393 | #ifndef RAPIDXML_NO_STREAMS 394 | 395 | //! Prints XML to given output stream. 396 | //! \param out Output stream to print to. 397 | //! \param node Node to be printed. Pass xml_document to print entire document. 398 | //! \param flags Flags controlling how XML is printed. 399 | //! \return Output stream. 400 | template 401 | inline std::basic_ostream &print(std::basic_ostream &out, const xml_node &node, int flags = 0) 402 | { 403 | print(std::ostream_iterator(out), node, flags); 404 | return out; 405 | } 406 | 407 | //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process. 408 | //! \param out Output stream to print to. 409 | //! \param node Node to be printed. 410 | //! \return Output stream. 411 | template 412 | inline std::basic_ostream &operator <<(std::basic_ostream &out, const xml_node &node) 413 | { 414 | return print(out, node); 415 | } 416 | 417 | #endif 418 | 419 | } 420 | 421 | #endif 422 | -------------------------------------------------------------------------------- /lib/rapidxml-1.13/manual.html: -------------------------------------------------------------------------------- 1 |

RAPIDXML Manual

Version 1.13

Copyright (C) 2006, 2009 Marcin Kalicinski
See accompanying file license.txt for license information.

Table of Contents

1. What is RapidXml?
1.1 Dependencies And Compatibility
1.2 Character Types And Encodings
1.3 Error Handling
1.4 Memory Allocation
1.5 W3C Compliance
1.6 API Design
1.7 Reliability
1.8 Acknowledgements
2. Two Minute Tutorial
2.1 Parsing
2.2 Accessing The DOM Tree
2.3 Modifying The DOM Tree
2.4 Printing XML
3. Differences From Regular XML Parsers
3.1 Lifetime Of Source Text
3.2 Ownership Of Strings
3.3 Destructive Vs Non-Destructive Mode
4. Performance
4.1 Comparison With Other Parsers
5. Reference

1. What is RapidXml?

RapidXml is an attempt to create the fastest XML DOM parser possible, while retaining useability, portability and reasonable W3C compatibility. It is an in-situ parser written in C++, with parsing speed approaching that of strlen() function executed on the same data.

89 | Entire parser is contained in a single header file, so no building or linking is neccesary. To use it you just need to copy rapidxml.hpp file to a convenient place (such as your project directory), and include it where needed. You may also want to use printing functions contained in header rapidxml_print.hpp.

1.1 Dependencies And Compatibility

RapidXml has no dependencies other than a very small subset of standard C++ library (<cassert>, <cstdlib>, <new> and <exception>, unless exceptions are disabled). It should compile on any reasonably conformant compiler, and was tested on Visual C++ 2003, Visual C++ 2005, Visual C++ 2008, gcc 3, gcc 4, and Comeau 4.3.3. Care was taken that no warnings are produced on these compilers, even with highest warning levels enabled.

1.2 Character Types And Encodings

RapidXml is character type agnostic, and can work both with narrow and wide characters. Current version does not fully support UTF-16 or UTF-32, so use of wide characters is somewhat incapacitated. However, it should succesfully parse wchar_t strings containing UTF-16 or UTF-32 if endianness of the data matches that of the machine. UTF-8 is fully supported, including all numeric character references, which are expanded into appropriate UTF-8 byte sequences (unless you enable parse_no_utf8 flag).

90 | Note that RapidXml performs no decoding - strings returned by name() and value() functions will contain text encoded using the same encoding as source file. Rapidxml understands and expands the following character references: &apos; &amp; &quot; &lt; &gt; &#...; Other character references are not expanded.

1.3 Error Handling

By default, RapidXml uses C++ exceptions to report errors. If this behaviour is undesirable, RAPIDXML_NO_EXCEPTIONS can be defined to suppress exception code. See parse_error class and parse_error_handler() function for more information.

1.4 Memory Allocation

RapidXml uses a special memory pool object to allocate nodes and attributes, because direct allocation using new operator would be far too slow. Underlying memory allocations performed by the pool can be customized by use of memory_pool::set_allocator() function. See class memory_pool for more information.

1.5 W3C Compliance

RapidXml is not a W3C compliant parser, primarily because it ignores DOCTYPE declarations. There is a number of other, minor incompatibilities as well. Still, it can successfully parse and produce complete trees of all valid XML files in W3C conformance suite (over 1000 files specially designed to find flaws in XML processors). In destructive mode it performs whitespace normalization and character entity substitution for a small set of built-in entities.

1.6 API Design

RapidXml API is minimalistic, to reduce code size as much as possible, and facilitate use in embedded environments. Additional convenience functions are provided in separate headers: rapidxml_utils.hpp and rapidxml_print.hpp. Contents of these headers is not an essential part of the library, and is currently not documented (otherwise than with comments in code).

1.7 Reliability

RapidXml is very robust and comes with a large harness of unit tests. Special care has been taken to ensure stability of the parser no matter what source text is thrown at it. One of the unit tests produces 100,000 randomly corrupted variants of XML document, which (when uncorrupted) contains all constructs recognized by RapidXml. RapidXml passes this test when it correctly recognizes that errors have been introduced, and does not crash or loop indefinitely.

91 | Another unit test puts RapidXml head-to-head with another, well estabilished XML parser, and verifies that their outputs match across a wide variety of small and large documents.

92 | Yet another test feeds RapidXml with over 1000 test files from W3C compliance suite, and verifies that correct results are obtained. There are also additional tests that verify each API function separately, and test that various parsing modes work as expected.

1.8 Acknowledgements

I would like to thank Arseny Kapoulkine for his work on pugixml, which was an inspiration for this project. Additional thanks go to Kristen Wegner for creating pugxml, from which pugixml was derived. Janusz Wohlfeil kindly ran RapidXml speed tests on hardware that I did not have access to, allowing me to expand performance comparison table.

2. Two Minute Tutorial

2.1 Parsing

The following code causes RapidXml to parse a zero-terminated string named text:
using namespace rapidxml;
 93 | xml_document<> doc;    // character type defaults to char
 94 | doc.parse<0>(text);    // 0 means default parse flags
 95 | 
doc object is now a root of DOM tree containing representation of the parsed XML. Because all RapidXml interface is contained inside namespace rapidxml, users must either bring contents of this namespace into scope, or fully qualify all the names. Class xml_document represents a root of the DOM hierarchy. By means of public inheritance, it is also an xml_node and a memory_pool. Template parameter of xml_document::parse() function is used to specify parsing flags, with which you can fine-tune behaviour of the parser. Note that flags must be a compile-time constant.

2.2 Accessing The DOM Tree

To access the DOM tree, use methods of xml_node and xml_attribute classes:
cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
 96 | xml_node<> *node = doc.first_node("foobar");
 97 | cout << "Node foobar has value " << node->value() << "\n";
 98 | for (xml_attribute<> *attr = node->first_attribute();
 99 |      attr; attr = attr->next_attribute())
100 | {
101 |     cout << "Node foobar has attribute " << attr->name() << " ";
102 |     cout << "with value " << attr->value() << "\n";
103 | }
104 | 

2.3 Modifying The DOM Tree

DOM tree produced by the parser is fully modifiable. Nodes and attributes can be added/removed, and their contents changed. The below example creates a HTML document, whose sole contents is a link to google.com website:
xml_document<> doc;
105 | xml_node<> *node = doc.allocate_node(node_element, "a", "Google");
106 | doc.append_node(node);
107 | xml_attribute<> *attr = doc.allocate_attribute("href", "google.com");
108 | node->append_attribute(attr);
109 | 
One quirk is that nodes and attributes do not own the text of their names and values. This is because normally they only store pointers to the source text. So, when assigning a new name or value to the node, care must be taken to ensure proper lifetime of the string. The easiest way to achieve it is to allocate the string from the xml_document memory pool. In the above example this is not necessary, because we are only assigning character constants. But the code below uses memory_pool::allocate_string() function to allocate node name (which will have the same lifetime as the document), and assigns it to a new node:
xml_document<> doc;
110 | char *node_name = doc.allocate_string(name);        // Allocate string and copy name into it
111 | xml_node<> *node = doc.allocate_node(node_element, node_name);  // Set node name to node_name
112 | 
Check Reference section for description of the entire interface.

2.4 Printing XML

You can print xml_document and xml_node objects into an XML string. Use print() function or operator <<, which are defined in rapidxml_print.hpp header.
using namespace rapidxml;
113 | xml_document<> doc;    // character type defaults to char
114 | // ... some code to fill the document
115 | 
116 | // Print to stream using operator <<
117 | std::cout << doc;   
118 | 
119 | // Print to stream using print function, specifying printing flags
120 | print(std::cout, doc, 0);   // 0 means default printing flags
121 | 
122 | // Print to string using output iterator
123 | std::string s;
124 | print(std::back_inserter(s), doc, 0);
125 | 
126 | // Print to memory buffer using output iterator
127 | char buffer[4096];                      // You are responsible for making the buffer large enough!
128 | char *end = print(buffer, doc, 0);      // end contains pointer to character after last printed character
129 | *end = 0;                               // Add string terminator after XML
130 | 

3. Differences From Regular XML Parsers

RapidXml is an in-situ parser, which allows it to achieve very high parsing speed. In-situ means that parser does not make copies of strings. Instead, it places pointers to the source text in the DOM hierarchy.

3.1 Lifetime Of Source Text

In-situ parsing requires that source text lives at least as long as the document object. If source text is destroyed, names and values of nodes in DOM tree will become destroyed as well. Additionally, whitespace processing, character entity translation, and zero-termination of strings require that source text be modified during parsing (but see non-destructive mode). This makes the text useless for further processing once it was parsed by RapidXml.

131 | In many cases however, these are not serious issues.

3.2 Ownership Of Strings

Nodes and attributes produced by RapidXml do not own their name and value strings. They merely hold the pointers to them. This means you have to be careful when setting these values manually, by using xml_base::name(const Ch *) or xml_base::value(const Ch *) functions. Care must be taken to ensure that lifetime of the string passed is at least as long as lifetime of the node/attribute. The easiest way to achieve it is to allocate the string from memory_pool owned by the document. Use memory_pool::allocate_string() function for this purpose.

3.3 Destructive Vs Non-Destructive Mode

By default, the parser modifies source text during the parsing process. This is required to achieve character entity translation, whitespace normalization, and zero-termination of strings.

132 | In some cases this behaviour may be undesirable, for example if source text resides in read only memory, or is mapped to memory directly from file. By using appropriate parser flags (parse_non_destructive), source text modifications can be disabled. However, because RapidXml does in-situ parsing, it obviously has the following side-effects:

4. Performance

RapidXml achieves its speed through use of several techniques:
  • In-situ parsing. When building DOM tree, RapidXml does not make copies of string data, such as node names and values. Instead, it stores pointers to interior of the source text.
  • Use of template metaprogramming techniques. This allows it to move much of the work to compile time. Through magic of the templates, C++ compiler generates a separate copy of parsing code for any combination of parser flags you use. In each copy, all possible decisions are made at compile time and all unused code is omitted.
  • Extensive use of lookup tables for parsing.
  • Hand-tuned C++ with profiling done on several most popular CPUs.
This results in a very small and fast code: a parser which is custom tailored to exact needs with each invocation.

4.1 Comparison With Other Parsers

The table below compares speed of RapidXml to some other parsers, and to strlen() function executed on the same data. On a modern CPU (as of 2007), you can expect parsing throughput to be close to 1 GB/s. As a rule of thumb, parsing speed is about 50-100x faster than Xerces DOM, 30-60x faster than TinyXml, 3-12x faster than pugxml, and about 5% - 30% faster than pugixml, the fastest XML parser I know of.
  • The test file is a real-world, 50kB large, moderately dense XML file.
  • All timing is done by using RDTSC instruction present in Pentium-compatible CPUs.
  • No profile-guided optimizations are used.
  • All parsers are running in their fastest modes.
  • The results are given in CPU cycles per character, so frequency of CPUs is irrelevant.
  • The results are minimum values from a large number of runs, to minimize effects of operating system activity, task switching, interrupt handling etc.
  • A single parse of the test file takes about 1/10th of a millisecond, so with large number of runs there is a good chance of hitting at least one no-interrupt streak, and obtaining undisturbed results.
Platform
Compiler
strlen() RapidXml pugixml 0.3 pugxml TinyXml
Pentium 4
MSVC 8.0
2.5
5.4
7.0
61.7
298.8
Pentium 4
gcc 4.1.1
0.8
6.1
9.5
67.0
413.2
Core 2
MSVC 8.0
1.0
4.5
5.0
24.6
154.8
Core 2
gcc 4.1.1
0.6
4.6
5.4
28.3
229.3
Athlon XP
MSVC 8.0
3.1
7.7
8.0
25.5
182.6
Athlon XP
gcc 4.1.1
0.9
8.2
9.2
33.7
265.2
Pentium 3
MSVC 8.0
2.0
6.3
7.0
30.9
211.9
Pentium 3
gcc 4.1.1
1.0
6.7
8.9
35.3
316.0
(*) All results are in CPU cycles per character of source text

5. Reference

This section lists all classes, functions, constants etc. and describes them in detail.
class 133 | template 134 | rapidxml::memory_pool
135 | constructor 136 | memory_pool()
137 | destructor 138 | ~memory_pool()
function allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)
function allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)
function allocate_string(const Ch *source=0, std::size_t size=0)
function clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0)
function clear()
function set_allocator(alloc_func *af, free_func *ff)

class rapidxml::parse_error
139 | constructor 140 | parse_error(const char *what, void *where)
function what() const
function where() const

class 141 | template 142 | rapidxml::xml_attribute
143 | constructor 144 | xml_attribute()
function document() const
function previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const

class 145 | template 146 | rapidxml::xml_base
147 | constructor 148 | xml_base()
function name() const
function name_size() const
function value() const
function value_size() const
function name(const Ch *name, std::size_t size)
function name(const Ch *name)
function value(const Ch *value, std::size_t size)
function value(const Ch *value)
function parent() const

class 149 | template 150 | rapidxml::xml_document
151 | constructor 152 | xml_document()
function parse(Ch *text)
function clear()

class 153 | template 154 | rapidxml::xml_node
155 | constructor 156 | xml_node(node_type type)
function type() const
function document() const
function first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function type(node_type type)
function prepend_node(xml_node< Ch > *child)
function append_node(xml_node< Ch > *child)
function insert_node(xml_node< Ch > *where, xml_node< Ch > *child)
function remove_first_node()
function remove_last_node()
function remove_node(xml_node< Ch > *where)
function remove_all_nodes()
function prepend_attribute(xml_attribute< Ch > *attribute)
function append_attribute(xml_attribute< Ch > *attribute)
function insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute)
function remove_first_attribute()
function remove_last_attribute()
function remove_attribute(xml_attribute< Ch > *where)
function remove_all_attributes()

namespace rapidxml
enum node_type
function parse_error_handler(const char *what, void *where)
function print(OutIt out, const xml_node< Ch > &node, int flags=0)
function print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0)
function operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node)
157 | constant 158 | parse_no_data_nodes
159 | constant 160 | parse_no_element_values
161 | constant 162 | parse_no_string_terminators
163 | constant 164 | parse_no_entity_translation
165 | constant 166 | parse_no_utf8
167 | constant 168 | parse_declaration_node
169 | constant 170 | parse_comment_nodes
171 | constant 172 | parse_doctype_node
173 | constant 174 | parse_pi_nodes
175 | constant 176 | parse_validate_closing_tags
177 | constant 178 | parse_trim_whitespace
179 | constant 180 | parse_normalize_whitespace
181 | constant 182 | parse_default
183 | constant 184 | parse_non_destructive
185 | constant 186 | parse_fastest
187 | constant 188 | parse_full
189 | constant 190 | print_no_indenting


class 191 | template 192 | rapidxml::memory_pool

193 | 194 | Defined in rapidxml.hpp
195 | Base class for 196 | xml_document

Description

This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. In most cases, you will not need to use this class directly. However, if you need to create nodes manually or modify names/values of nodes, you are encouraged to use memory_pool of relevant xml_document to allocate the memory. Not only is this faster than allocating them by using new operator, but also their lifetime will be tied to the lifetime of document, possibly simplyfing memory management.

197 | Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. You can also call allocate_string() function to allocate strings. Such strings can then be used as names or values of nodes without worrying about their lifetime. Note that there is no free() function -- all allocations are freed at once when clear() function is called, or when the pool is destroyed.

198 | It is also possible to create a standalone memory_pool, and use it to allocate nodes, whose lifetime will not be tied to any document.

199 | Pool maintains RAPIDXML_STATIC_POOL_SIZE bytes of statically allocated memory. Until static memory is exhausted, no dynamic memory allocations are done. When static memory is exhausted, pool allocates additional blocks of memory of size RAPIDXML_DYNAMIC_POOL_SIZE each, by using global new[] and delete[] operators. This behaviour can be changed by setting custom allocation routines. Use set_allocator() function to set them.

200 | Allocations for nodes, attributes and strings are aligned at RAPIDXML_ALIGNMENT bytes. This value defaults to the size of pointer on target architecture.

201 | To obtain absolutely top performance from the parser, it is important that all nodes are allocated from a single, contiguous block of memory. Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. If required, you can tweak RAPIDXML_STATIC_POOL_SIZE, RAPIDXML_DYNAMIC_POOL_SIZE and RAPIDXML_ALIGNMENT to obtain best wasted memory to performance compromise. To do it, define their values before rapidxml.hpp file is included.

Parameters

Ch
Character type of created nodes.

202 | constructor 203 | memory_pool::memory_pool

Synopsis

memory_pool(); 204 |

Description

Constructs empty pool with default allocator functions.

205 | destructor 206 | memory_pool::~memory_pool

Synopsis

~memory_pool(); 207 |

Description

Destroys pool and frees all the memory. This causes memory occupied by nodes allocated by the pool to be freed. Nodes allocated from the pool are no longer valid.

function memory_pool::allocate_node

Synopsis

xml_node<Ch>* allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0); 208 |

Description

Allocates a new node from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

type
Type of node to create.
name
Name to assign to the node, or 0 to assign no name.
value
Value to assign to the node, or 0 to assign no value.
name_size
Size of name to assign, or 0 to automatically calculate size from name string.
value_size
Size of value to assign, or 0 to automatically calculate size from value string.

Returns

Pointer to allocated node. This pointer will never be NULL.

function memory_pool::allocate_attribute

Synopsis

xml_attribute<Ch>* allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0); 209 |

Description

Allocates a new attribute from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

name
Name to assign to the attribute, or 0 to assign no name.
value
Value to assign to the attribute, or 0 to assign no value.
name_size
Size of name to assign, or 0 to automatically calculate size from name string.
value_size
Size of value to assign, or 0 to automatically calculate size from value string.

Returns

Pointer to allocated attribute. This pointer will never be NULL.

function memory_pool::allocate_string

Synopsis

Ch* allocate_string(const Ch *source=0, std::size_t size=0); 210 |

Description

Allocates a char array of given size from the pool, and optionally copies a given string to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

source
String to initialize the allocated memory with, or 0 to not initialize it.
size
Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated.

Returns

Pointer to allocated char array. This pointer will never be NULL.

function memory_pool::clone_node

Synopsis

xml_node<Ch>* clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0); 211 |

Description

Clones an xml_node and its hierarchy of child nodes and attributes. Nodes and attributes are allocated from this memory pool. Names and values are not cloned, they are shared between the clone and the source. Result node can be optionally specified as a second parameter, in which case its contents will be replaced with cloned source node. This is useful when you want to clone entire document.

Parameters

source
Node to clone.
result
Node to put results in, or 0 to automatically allocate result node

Returns

Pointer to cloned node. This pointer will never be NULL.

function memory_pool::clear

Synopsis

void clear(); 212 |

Description

Clears the pool. This causes memory occupied by nodes allocated by the pool to be freed. Any nodes or strings allocated from the pool will no longer be valid.

function memory_pool::set_allocator

Synopsis

void set_allocator(alloc_func *af, free_func *ff); 213 |

Description

Sets or resets the user-defined memory allocation functions for the pool. This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. Allocation function must not return invalid pointer on failure. It should either throw, stop the program, or use longjmp() function to pass control to other place of program. If it returns invalid pointer, results are undefined.

214 | User defined allocation functions must have the following forms:

215 | void *allocate(std::size_t size);
216 | void free(void *pointer);

Parameters

af
Allocation function, or 0 to restore default function
ff
Free function, or 0 to restore default function

class rapidxml::parse_error

217 | 218 | Defined in rapidxml.hpp

Description

Parse error exception. This exception is thrown by the parser when an error occurs. Use what() function to get human-readable error message. Use where() function to get a pointer to position within source text where error was detected.

219 | If throwing exceptions by the parser is undesirable, it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included. This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception. This function must be defined by the user.

220 | This class derives from std::exception class.

221 | constructor 222 | parse_error::parse_error

Synopsis

parse_error(const char *what, void *where); 223 |

Description

Constructs parse error.

function parse_error::what

Synopsis

virtual const char* what() const; 224 |

Description

Gets human readable description of error.

Returns

Pointer to null terminated description of the error.

function parse_error::where

Synopsis

Ch* where() const; 225 |

Description

Gets pointer to character data where error happened. Ch should be the same as char type of xml_document that produced the error.

Returns

Pointer to location within the parsed string where error occured.

class 226 | template 227 | rapidxml::xml_attribute

228 | 229 | Defined in rapidxml.hpp
230 | Inherits from 231 | xml_base

Description

Class representing attribute node of XML document. Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). Note that after parse, both name and value of attribute will point to interior of source text used for parsing. Thus, this text must persist in memory for the lifetime of attribute.

Parameters

Ch
Character type to use.

232 | constructor 233 | xml_attribute::xml_attribute

Synopsis

xml_attribute(); 234 |

Description

Constructs an empty attribute with the specified type. Consider using memory_pool of appropriate xml_document if allocating attributes manually.

function xml_attribute::document

Synopsis

xml_document<Ch>* document() const; 235 |

Description

Gets document of which attribute is a child.

Returns

Pointer to document that contains this attribute, or 0 if there is no parent document.

function xml_attribute::previous_attribute

Synopsis

xml_attribute<Ch>* previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 236 |

Description

Gets previous attribute, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_attribute::next_attribute

Synopsis

xml_attribute<Ch>* next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 237 |

Description

Gets next attribute, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

class 238 | template 239 | rapidxml::xml_base

240 | 241 | Defined in rapidxml.hpp
242 | Base class for 243 | xml_attribute xml_node

Description

Base class for xml_node and xml_attribute implementing common functions: name(), name_size(), value(), value_size() and parent().

Parameters

Ch
Character type to use

244 | constructor 245 | xml_base::xml_base

Synopsis

xml_base(); 246 |

function xml_base::name

Synopsis

Ch* name() const; 247 |

Description

Gets name of the node. Interpretation of name depends on type of node. Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.

248 | Use name_size() function to determine length of the name.

Returns

Name of node, or empty string if node has no name.

function xml_base::name_size

Synopsis

std::size_t name_size() const; 249 |

Description

Gets size of node name, not including terminator character. This function works correctly irrespective of whether name is or is not zero terminated.

Returns

Size of node name, in characters.

function xml_base::value

Synopsis

Ch* value() const; 250 |

Description

Gets value of node. Interpretation of value depends on type of node. Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.

251 | Use value_size() function to determine length of the value.

Returns

Value of node, or empty string if node has no value.

function xml_base::value_size

Synopsis

std::size_t value_size() const; 252 |

Description

Gets size of node value, not including terminator character. This function works correctly irrespective of whether value is or is not zero terminated.

Returns

Size of node value, in characters.

function xml_base::name

Synopsis

void name(const Ch *name, std::size_t size); 253 |

Description

Sets name of node to a non zero-terminated string. See Ownership Of Strings .

254 | Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use memory_pool of the document to allocate the string - on destruction of the document the string will be automatically freed.

255 | Size of name must be specified separately, because name does not have to be zero terminated. Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated).

Parameters

name
Name of node to set. Does not have to be zero terminated.
size
Size of name, in characters. This does not include zero terminator, if one is present.

function xml_base::name

Synopsis

void name(const Ch *name); 256 |

Description

Sets name of node to a zero-terminated string. See also Ownership Of Strings and xml_node::name(const Ch *, std::size_t).

Parameters

name
Name of node to set. Must be zero terminated.

function xml_base::value

Synopsis

void value(const Ch *value, std::size_t size); 257 |

Description

Sets value of node to a non zero-terminated string. See Ownership Of Strings .

258 | Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use memory_pool of the document to allocate the string - on destruction of the document the string will be automatically freed.

259 | Size of value must be specified separately, because it does not have to be zero terminated. Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated).

260 | If an element has a child node of type node_data, it will take precedence over element value when printing. If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser.

Parameters

value
value of node to set. Does not have to be zero terminated.
size
Size of value, in characters. This does not include zero terminator, if one is present.

function xml_base::value

Synopsis

void value(const Ch *value); 261 |

Description

Sets value of node to a zero-terminated string. See also Ownership Of Strings and xml_node::value(const Ch *, std::size_t).

Parameters

value
Vame of node to set. Must be zero terminated.

function xml_base::parent

Synopsis

xml_node<Ch>* parent() const; 262 |

Description

Gets node parent.

Returns

Pointer to parent node, or 0 if there is no parent.

class 263 | template 264 | rapidxml::xml_document

265 | 266 | Defined in rapidxml.hpp
267 | Inherits from 268 | xml_node memory_pool

Description

This class represents root of the DOM hierarchy. It is also an xml_node and a memory_pool through public inheritance. Use parse() function to build a DOM tree from a zero-terminated XML text string. parse() function allocates memory for nodes and attributes by using functions of xml_document, which are inherited from memory_pool. To access root node of the document, use the document itself, as if it was an xml_node.

Parameters

Ch
Character type to use.

269 | constructor 270 | xml_document::xml_document

Synopsis

xml_document(); 271 |

Description

Constructs empty XML document.

function xml_document::parse

Synopsis

void parse(Ch *text); 272 |

Description

Parses zero-terminated XML string according to given flags. Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used. The string must persist for the lifetime of the document. In case of error, rapidxml::parse_error exception will be thrown.

273 | If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. Make sure that data is zero-terminated.

274 | Document can be parsed into multiple times. Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool.

Parameters

text
XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser.

function xml_document::clear

Synopsis

void clear(); 275 |

Description

Clears the document by deleting all nodes and clearing the memory pool. All nodes owned by document pool are destroyed.

class 276 | template 277 | rapidxml::xml_node

278 | 279 | Defined in rapidxml.hpp
280 | Inherits from 281 | xml_base
282 | Base class for 283 | xml_document

Description

Class representing a node of XML document. Each node may have associated name and value strings, which are available through name() and value() functions. Interpretation of name and value depends on type of the node. Type of node can be determined by using type() function.

284 | Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. Thus, this text must persist in the memory for the lifetime of node.

Parameters

Ch
Character type to use.

285 | constructor 286 | xml_node::xml_node

Synopsis

xml_node(node_type type); 287 |

Description

Constructs an empty node with the specified type. Consider using memory_pool of appropriate document to allocate nodes manually.

Parameters

type
Type of node to construct.

function xml_node::type

Synopsis

node_type type() const; 288 |

Description

Gets type of node.

Returns

Type of node.

function xml_node::document

Synopsis

xml_document<Ch>* document() const; 289 |

Description

Gets document of which node is a child.

Returns

Pointer to document that contains this node, or 0 if there is no parent document.

function xml_node::first_node

Synopsis

xml_node<Ch>* first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 290 |

Description

Gets first child node, optionally matching node name.

Parameters

name
Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found child, or 0 if not found.

function xml_node::last_node

Synopsis

xml_node<Ch>* last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 291 |

Description

Gets last child node, optionally matching node name. Behaviour is undefined if node has no children. Use first_node() to test if node has children.

Parameters

name
Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found child, or 0 if not found.

function xml_node::previous_sibling

Synopsis

xml_node<Ch>* previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 292 |

Description

Gets previous sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use parent() to test if node has a parent.

Parameters

name
Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found sibling, or 0 if not found.

function xml_node::next_sibling

Synopsis

xml_node<Ch>* next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 293 |

Description

Gets next sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use parent() to test if node has a parent.

Parameters

name
Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found sibling, or 0 if not found.

function xml_node::first_attribute

Synopsis

xml_attribute<Ch>* first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 294 |

Description

Gets first attribute of node, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_node::last_attribute

Synopsis

xml_attribute<Ch>* last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 295 |

Description

Gets last attribute of node, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_node::type

Synopsis

void type(node_type type); 296 |

Description

Sets type of node.

Parameters

type
Type of node to set.

function xml_node::prepend_node

Synopsis

void prepend_node(xml_node< Ch > *child); 297 |

Description

Prepends a new child node. The prepended child becomes the first child, and all existing children are moved one position back.

Parameters

child
Node to prepend.

function xml_node::append_node

Synopsis

void append_node(xml_node< Ch > *child); 298 |

Description

Appends a new child node. The appended child becomes the last child.

Parameters

child
Node to append.

function xml_node::insert_node

Synopsis

void insert_node(xml_node< Ch > *where, xml_node< Ch > *child); 299 |

Description

Inserts a new child node at specified place inside the node. All children after and including the specified node are moved one position back.

Parameters

where
Place where to insert the child, or 0 to insert at the back.
child
Node to insert.

function xml_node::remove_first_node

Synopsis

void remove_first_node(); 300 |

Description

Removes first child node. If node has no children, behaviour is undefined. Use first_node() to test if node has children.

function xml_node::remove_last_node

Synopsis

void remove_last_node(); 301 |

Description

Removes last child of the node. If node has no children, behaviour is undefined. Use first_node() to test if node has children.

function xml_node::remove_node

Synopsis

void remove_node(xml_node< Ch > *where); 302 |

Description

Removes specified child from the node.

function xml_node::remove_all_nodes

Synopsis

void remove_all_nodes(); 303 |

Description

Removes all child nodes (but not attributes).

function xml_node::prepend_attribute

Synopsis

void prepend_attribute(xml_attribute< Ch > *attribute); 304 |

Description

Prepends a new attribute to the node.

Parameters

attribute
Attribute to prepend.

function xml_node::append_attribute

Synopsis

void append_attribute(xml_attribute< Ch > *attribute); 305 |

Description

Appends a new attribute to the node.

Parameters

attribute
Attribute to append.

function xml_node::insert_attribute

Synopsis

void insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute); 306 |

Description

Inserts a new attribute at specified place inside the node. All attributes after and including the specified attribute are moved one position back.

Parameters

where
Place where to insert the attribute, or 0 to insert at the back.
attribute
Attribute to insert.

function xml_node::remove_first_attribute

Synopsis

void remove_first_attribute(); 307 |

Description

Removes first attribute of the node. If node has no attributes, behaviour is undefined. Use first_attribute() to test if node has attributes.

function xml_node::remove_last_attribute

Synopsis

void remove_last_attribute(); 308 |

Description

Removes last attribute of the node. If node has no attributes, behaviour is undefined. Use first_attribute() to test if node has attributes.

function xml_node::remove_attribute

Synopsis

void remove_attribute(xml_attribute< Ch > *where); 309 |

Description

Removes specified attribute from node.

Parameters

where
Pointer to attribute to be removed.

function xml_node::remove_all_attributes

Synopsis

void remove_all_attributes(); 310 |

Description

Removes all attributes of node.

enum node_type

Description

Enumeration listing all node types produced by the parser. Use xml_node::type() function to query node type.

Values

node_document
A document node. Name and value are empty.
node_element
An element node. Name contains element name. Value contains text of first data node.
node_data
A data node. Name is empty. Value contains data text.
node_cdata
A CDATA node. Name is empty. Value contains data text.
node_comment
A comment node. Name is empty. Value contains comment text.
node_declaration
A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.
node_doctype
A DOCTYPE node. Name is empty. Value contains DOCTYPE text.
node_pi
A PI node. Name contains target. Value contains instructions.

function parse_error_handler

Synopsis

void rapidxml::parse_error_handler(const char *what, void *where); 311 |

Description

When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function is called to notify user about the error. It must be defined by the user.

312 | This function cannot return. If it does, the results are undefined.

313 | A very simple definition might look like that: 314 | void rapidxml::parse_error_handler(const char *what, void *where) 315 | { 316 | std::cout << "Parse error: " << what << "\n"; 317 | std::abort(); 318 | } 319 |

Parameters

what
Human readable description of the error.
where
Pointer to character data where error was detected.

function print

Synopsis

OutIt rapidxml::print(OutIt out, const xml_node< Ch > &node, int flags=0); 320 |

Description

Prints XML to given output iterator.

Parameters

out
Output iterator to print to.
node
Node to be printed. Pass xml_document to print entire document.
flags
Flags controlling how XML is printed.

Returns

Output iterator pointing to position immediately after last character of printed text.

function print

Synopsis

std::basic_ostream<Ch>& rapidxml::print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0); 321 |

Description

Prints XML to given output stream.

Parameters

out
Output stream to print to.
node
Node to be printed. Pass xml_document to print entire document.
flags
Flags controlling how XML is printed.

Returns

Output stream.

function operator<<

Synopsis

std::basic_ostream<Ch>& rapidxml::operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node); 322 |

Description

Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.

Parameters

out
Output stream to print to.
node
Node to be printed.

Returns

Output stream.

323 | constant 324 | parse_no_data_nodes

Synopsis

const int parse_no_data_nodes 325 | = 0x1; 326 |

Description

Parse flag instructing the parser to not create data nodes. Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified. Can be combined with other flags by use of | operator.

327 | See xml_document::parse() function.

328 | constant 329 | parse_no_element_values

Synopsis

const int parse_no_element_values 330 | = 0x2; 331 |

Description

Parse flag instructing the parser to not use text of first data node as a value of parent element. Can be combined with other flags by use of | operator. Note that child data nodes of element node take precendence over its value when printing. That is, if element has one or more child data nodes and a value, the value will be ignored. Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements.

332 | See xml_document::parse() function.

333 | constant 334 | parse_no_string_terminators

Synopsis

const int parse_no_string_terminators 335 | = 0x4; 336 |

Description

Parse flag instructing the parser to not place zero terminators after strings in the source text. By default zero terminators are placed, modifying source text. Can be combined with other flags by use of | operator.

337 | See xml_document::parse() function.

338 | constant 339 | parse_no_entity_translation

Synopsis

const int parse_no_entity_translation 340 | = 0x8; 341 |

Description

Parse flag instructing the parser to not translate entities in the source text. By default entities are translated, modifying source text. Can be combined with other flags by use of | operator.

342 | See xml_document::parse() function.

343 | constant 344 | parse_no_utf8

Synopsis

const int parse_no_utf8 345 | = 0x10; 346 |

Description

Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. By default, UTF-8 handling is enabled. Can be combined with other flags by use of | operator.

347 | See xml_document::parse() function.

348 | constant 349 | parse_declaration_node

Synopsis

const int parse_declaration_node 350 | = 0x20; 351 |

Description

Parse flag instructing the parser to create XML declaration node. By default, declaration node is not created. Can be combined with other flags by use of | operator.

352 | See xml_document::parse() function.

353 | constant 354 | parse_comment_nodes

Synopsis

const int parse_comment_nodes 355 | = 0x40; 356 |

Description

Parse flag instructing the parser to create comments nodes. By default, comment nodes are not created. Can be combined with other flags by use of | operator.

357 | See xml_document::parse() function.

358 | constant 359 | parse_doctype_node

Synopsis

const int parse_doctype_node 360 | = 0x80; 361 |

Description

Parse flag instructing the parser to create DOCTYPE node. By default, doctype node is not created. Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. Can be combined with other flags by use of | operator.

362 | See xml_document::parse() function.

363 | constant 364 | parse_pi_nodes

Synopsis

const int parse_pi_nodes 365 | = 0x100; 366 |

Description

Parse flag instructing the parser to create PI nodes. By default, PI nodes are not created. Can be combined with other flags by use of | operator.

367 | See xml_document::parse() function.

368 | constant 369 | parse_validate_closing_tags

Synopsis

const int parse_validate_closing_tags 370 | = 0x200; 371 |

Description

Parse flag instructing the parser to validate closing tag names. If not set, name inside closing tag is irrelevant to the parser. By default, closing tags are not validated. Can be combined with other flags by use of | operator.

372 | See xml_document::parse() function.

373 | constant 374 | parse_trim_whitespace

Synopsis

const int parse_trim_whitespace 375 | = 0x400; 376 |

Description

Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. By default, whitespace is not trimmed. This flag does not cause the parser to modify source text. Can be combined with other flags by use of | operator.

377 | See xml_document::parse() function.

378 | constant 379 | parse_normalize_whitespace

Synopsis

const int parse_normalize_whitespace 380 | = 0x800; 381 |

Description

Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag. By default, whitespace is not normalized. If this flag is specified, source text will be modified. Can be combined with other flags by use of | operator.

382 | See xml_document::parse() function.

383 | constant 384 | parse_default

Synopsis

const int parse_default 385 | = 0; 386 |

Description

Parse flags which represent default behaviour of the parser. This is always equal to 0, so that all other flags can be simply ored together. Normally there is no need to inconveniently disable flags by anding with their negated (~) values. This also means that meaning of each flag is a negation of the default setting. For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is enabled by default, and using the flag will disable it.

387 | See xml_document::parse() function.

388 | constant 389 | parse_non_destructive

Synopsis

const int parse_non_destructive 390 | = parse_no_string_terminators | parse_no_entity_translation; 391 |

Description

A combination of parse flags that forbids any modifications of the source text. This also results in faster parsing. However, note that the following will occur:
  • names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends
  • entities will not be translated
  • whitespace will not be normalized
392 | See xml_document::parse() function.

393 | constant 394 | parse_fastest

Synopsis

const int parse_fastest 395 | = parse_non_destructive | parse_no_data_nodes; 396 |

Description

A combination of parse flags resulting in fastest possible parsing, without sacrificing important data.

397 | See xml_document::parse() function.

398 | constant 399 | parse_full

Synopsis

const int parse_full 400 | = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags; 401 |

Description

A combination of parse flags resulting in largest amount of data being extracted. This usually results in slowest parsing.

402 | See xml_document::parse() function.

403 | constant 404 | print_no_indenting

Synopsis

const int print_no_indenting 405 | = 0x1; 406 |

Description

Printer flag instructing the printer to suppress indenting of XML. See print() function.

--------------------------------------------------------------------------------