From f8eb63de66199d4401a8fa2665b45caebff9cd16 Mon Sep 17 00:00:00 2001 From: Rick de Jager Date: Sat, 9 Jan 2021 18:15:19 +0100 Subject: [PATCH] Clang-format the project to a more "common" style --- .clang-format | 3 + clang-format.sh | 1 + src/AUtils.h | 231 ++- src/Arg.cc | 18 +- src/Arg.h | 65 +- src/Arguments.cc | 1371 +++++++-------- src/Arguments.h | 251 +-- src/AssertionFailed.cc | 38 +- src/AssertionFailed.h | 16 +- src/AuData.h | 38 +- src/AuFile.cc | 358 ++-- src/AuFile.h | 93 +- src/AuSampleValues.cc | 16 +- src/AuSampleValues.h | 8 +- src/AudioData.h | 213 ++- src/AudioSampleValue.h | 170 +- src/BFSAPHeuristic.cc | 206 +-- src/BFSAPHeuristic.h | 55 +- src/BinaryIO.cc | 454 +++-- src/BinaryIO.h | 327 ++-- src/BitString.cc | 795 ++++----- src/BitString.h | 463 +++-- src/BmpFile.cc | 1554 +++++++++-------- src/BmpFile.h | 240 +-- src/BmpPaletteSampleValue.cc | 65 +- src/BmpPaletteSampleValue.h | 31 +- src/BmpRGBSampleValue.cc | 209 ++- src/BmpRGBSampleValue.h | 80 +- src/BmpSampleValue.cc | 19 +- src/BmpSampleValue.h | 39 +- src/ColorPalette.h | 31 +- src/Cracker.cc | 339 ++-- src/Cracker.h | 63 +- src/CvrStgFile.cc | 289 ++- src/CvrStgFile.h | 282 ++- src/CvrStgObject.h | 53 +- src/DFSAPHeuristic.cc | 372 ++-- src/DFSAPHeuristic.h | 126 +- src/DMDConstructionHeuristic.cc | 69 +- src/DMDConstructionHeuristic.h | 23 +- src/Edge.cc | 242 ++- src/Edge.h | 133 +- src/EdgeIterator.cc | 305 ++-- src/EdgeIterator.h | 217 +-- src/EmbData.cc | 516 +++--- src/EmbData.h | 198 ++- src/Embedder.cc | 441 +++-- src/Embedder.h | 52 +- src/EncryptionAlgorithm.cc | 147 +- src/EncryptionAlgorithm.h | 129 +- src/EncryptionMode.cc | 111 +- src/EncryptionMode.h | 74 +- src/Extractor.cc | 141 +- src/Extractor.h | 24 +- src/Globals.h | 37 +- src/Graph.cc | 1134 ++++++------ src/Graph.h | 325 ++-- src/JpegFile.cc | 368 ++-- src/JpegFile.h | 74 +- src/JpegSampleValue.cc | 114 +- src/JpegSampleValue.h | 22 +- src/MCryptPP.cc | 493 +++--- src/MCryptPP.h | 167 +- src/MHashKeyGen.cc | 130 +- src/MHashKeyGen.h | 42 +- src/MHashPP.cc | 165 +- src/MHashPP.h | 123 +- src/Matching.cc | 593 ++++--- src/Matching.h | 376 ++-- src/MatchingAlgorithm.cc | 19 +- src/MatchingAlgorithm.h | 29 +- src/PasswordCracker.cc | 380 ++-- src/PasswordCracker.h | 35 +- src/ProgressOutput.cc | 76 +- src/ProgressOutput.h | 67 +- src/PseudoRandomSource.cc | 11 +- src/PseudoRandomSource.h | 40 +- src/RGBTriple.cc | 21 +- src/RGBTriple.h | 52 +- src/RandomSource.cc | 132 +- src/RandomSource.h | 82 +- src/SMDConstructionHeuristic.cc | 46 +- src/SMDConstructionHeuristic.h | 28 +- src/SampleOccurence.h | 30 +- src/SampleValue.cc | 56 +- src/SampleValue.h | 212 ++- src/SampleValueAdjacencyList.cc | 141 +- src/SampleValueAdjacencyList.h | 63 +- src/SeedCracker.cc | 308 ++-- src/SeedCracker.h | 35 +- src/Selector.cc | 220 ++- src/Selector.h | 141 +- src/Session.cc | 657 +++---- src/Session.h | 37 +- src/SteghideError.cc | 30 +- src/SteghideError.h | 12 +- src/Terminal.cc | 64 +- src/Terminal.h | 18 +- src/Utils.cc | 55 +- src/Utils.h | 14 +- src/Vertex.cc | 295 ++-- src/Vertex.h | 197 ++- src/WKSConstructionHeuristic.cc | 342 ++-- src/WKSConstructionHeuristic.h | 100 +- src/WavChunk.cc | 14 +- src/WavChunk.h | 23 +- src/WavChunkHeader.cc | 40 +- src/WavChunkHeader.h | 26 +- src/WavChunkUnused.cc | 24 +- src/WavChunkUnused.h | 27 +- src/WavFile.cc | 655 ++++--- src/WavFile.h | 115 +- src/WavFormatChunk.cc | 105 +- src/WavFormatChunk.h | 55 +- src/WavPCMSampleValue.cc | 152 +- src/WavPCMSampleValue.h | 38 +- src/common.h | 66 +- src/error.cc | 168 +- src/error.h | 68 +- src/main.cc | 27 +- src/msg.cc | 230 ++- src/msg.h | 135 +- tests/steghide/AUtilsTest.cc | 30 +- tests/steghide/AUtilsTest.h | 14 +- tests/steghide/AuFileTest.cc | 187 +- tests/steghide/AuFileTest.h | 36 +- tests/steghide/AudioSampleValueTest.cc | 90 +- tests/steghide/AudioSampleValueTest.h | 25 +- tests/steghide/BFSAPHeuristicTest.cc | 213 +-- tests/steghide/BFSAPHeuristicTest.h | 46 +- tests/steghide/BitStringTest.cc | 751 ++++---- tests/steghide/BitStringTest.h | 39 +- tests/steghide/BmpFileTest.cc | 64 +- tests/steghide/BmpFileTest.h | 24 +- tests/steghide/BmpOS2FileTest.cc | 180 +- tests/steghide/BmpOS2FileTest.h | 36 +- tests/steghide/BmpPaletteSampleValueTest.cc | 112 +- tests/steghide/BmpPaletteSampleValueTest.h | 33 +- tests/steghide/BmpRGBSampleValueTest.cc | 98 +- tests/steghide/BmpRGBSampleValueTest.h | 25 +- tests/steghide/BmpWinFileTest.cc | 205 ++- tests/steghide/BmpWinFileTest.h | 30 +- tests/steghide/CvrStgFileTest.cc | 298 ++-- tests/steghide/CvrStgFileTest.h | 65 +- tests/steghide/DFSAPHeuristicTest.cc | 365 ++-- tests/steghide/DFSAPHeuristicTest.h | 46 +- tests/steghide/DummyFile.cc | 108 +- tests/steghide/DummyFile.h | 83 +- tests/steghide/DummySampleValue.cc | 61 +- tests/steghide/DummySampleValue.h | 38 +- tests/steghide/EdgeIteratorTest.cc | 409 ++--- tests/steghide/EdgeIteratorTest.h | 58 +- tests/steghide/EmbDataTest.cc | 148 +- tests/steghide/EmbDataTest.h | 28 +- tests/steghide/GraphTest.cc | 513 +++--- tests/steghide/GraphTest.h | 48 +- tests/steghide/JpegFileTest.cc | 74 +- tests/steghide/JpegFileTest.h | 34 +- tests/steghide/JpegSampleValueTest.cc | 56 +- tests/steghide/JpegSampleValueTest.h | 26 +- tests/steghide/MCryptPPTest.cc | 25 +- tests/steghide/MCryptPPTest.h | 18 +- tests/steghide/MHashKeyGenTest.cc | 5 +- tests/steghide/MHashKeyGenTest.h | 10 +- tests/steghide/MHashPPTest.cc | 133 +- tests/steghide/MHashPPTest.h | 42 +- tests/steghide/MatchingTest.cc | 361 ++-- tests/steghide/MatchingTest.h | 42 +- .../steghide/SampleValueAdjacencyListTest.cc | 132 +- tests/steghide/SampleValueAdjacencyListTest.h | 20 +- tests/steghide/SampleValueTest.cc | 50 +- tests/steghide/SampleValueTest.h | 62 +- tests/steghide/SelectorTest.cc | 96 +- tests/steghide/SelectorTest.h | 28 +- tests/steghide/Test.h | 28 +- tests/steghide/TestCategory.h | 6 +- tests/steghide/TestCategoryCaller.h | 23 +- tests/steghide/TestSuite.cc | 176 +- tests/steghide/TestSuite.h | 60 +- tests/steghide/UnitTest.cc | 68 +- tests/steghide/UnitTest.h | 66 +- .../steghide/WKSConstructionHeuristicTest.cc | 159 +- tests/steghide/WKSConstructionHeuristicTest.h | 48 +- tests/steghide/WavFileTest.cc | 137 +- tests/steghide/WavFileTest.h | 42 +- tests/steghide/WavPCMSampleValueTest.cc | 93 +- tests/steghide/WavPCMSampleValueTest.h | 25 +- tests/steghide/main.cc | 171 +- tests/steghide/utcommon.h | 6 +- 189 files changed, 14303 insertions(+), 14505 deletions(-) create mode 100644 .clang-format create mode 100755 clang-format.sh diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..6233a4e --- /dev/null +++ b/.clang-format @@ -0,0 +1,3 @@ +BasedOnStyle: llvm +IndentWidth: 4 +ColumnLimit: 100 \ No newline at end of file diff --git a/clang-format.sh b/clang-format.sh new file mode 100755 index 0000000..a1ddbf5 --- /dev/null +++ b/clang-format.sh @@ -0,0 +1 @@ +find . -regex '.*\.\(cc\|cpp\|hh\|h\)' -exec clang-format -i {} \; diff --git a/src/AUtils.h b/src/AUtils.h index 76abe91..be584d9 100644 --- a/src/AUtils.h +++ b/src/AUtils.h @@ -23,8 +23,8 @@ #include #ifndef log2 - // this is in an #ifndef because some cmath implementations #define log2 and some not -# define log2(x) (log(x) / log(2.0)) +// this is in an #ifndef because some cmath implementations #define log2 and some not +#define log2(x) (log(x) / log(2.0)) #endif /** @@ -32,146 +32,125 @@ * \brief provides some generic functions for non-standard arithmetic operations **/ class AUtils { - public: - /** - * return the maximum of a and b (needs >) - **/ - template static T max (T a, T b) ; - - /** - * return the minimum of a and b (needs <) - **/ - template static T min (T a, T b) ; - - /** - * returns a divided through b rounded up to nearest "integer" (needs =, --, +, /) - **/ - template static T div_roundup (T a, T b) ; - - /** - * substraction with the modification to return 0 (T()) for negative difference (needs >, -, T()) - **/ - template static T bminus (T a, T b) ; - - /** - * addition with the modification to return top for sums that are larger than top - **/ - template static T bplus (T a, T b) ; - template static T bplus (T a, T b, T top) ; - - /** - * calculate the sum s[0]+...s[n-1] modulo m (needs =, +, % for T and =, CTYPE(), <, ++ for CTYPE) - **/ - template static T modsum (T* s, CTYPE n, T m) ; - - /** - * round up x to nearest integer - **/ - template static IT roundup (FT x) ; - - /** - * compute 2-logarithm of n (rounded up to nearest int), i.e. number of bits needed to store values from {0,...,n-1} - **/ - template static T log2_ceil (T n) ; -} ; - -template -T AUtils::max (T a, T b) -{ - if (a > b) { - return a ; - } - else { - return b ; - } + public: + /** + * return the maximum of a and b (needs >) + **/ + template static T max(T a, T b); + + /** + * return the minimum of a and b (needs <) + **/ + template static T min(T a, T b); + + /** + * returns a divided through b rounded up to nearest "integer" (needs =, --, +, /) + **/ + template static T div_roundup(T a, T b); + + /** + * substraction with the modification to return 0 (T()) for negative difference (needs >, -, + *T()) + **/ + template static T bminus(T a, T b); + + /** + * addition with the modification to return top for sums that are larger than top + **/ + template static T bplus(T a, T b); + template static T bplus(T a, T b, T top); + + /** + * calculate the sum s[0]+...s[n-1] modulo m (needs =, +, % for T and =, CTYPE(), <, ++ for + *CTYPE) + **/ + template static T modsum(T *s, CTYPE n, T m); + + /** + * round up x to nearest integer + **/ + template static IT roundup(FT x); + + /** + * compute 2-logarithm of n (rounded up to nearest int), i.e. number of bits needed to store + *values from {0,...,n-1} + **/ + template static T log2_ceil(T n); +}; + +template T AUtils::max(T a, T b) { + if (a > b) { + return a; + } else { + return b; + } } -template -T AUtils::min (T a, T b) -{ - if (a < b) { - return a ; - } - else { - return b ; - } +template T AUtils::min(T a, T b) { + if (a < b) { + return a; + } else { + return b; + } } -template -T AUtils::div_roundup (T a, T b) -{ - T c = b-- ; - return ((a + b) / c) ; +template T AUtils::div_roundup(T a, T b) { + T c = b--; + return ((a + b) / c); } -template -T AUtils::bminus (T a, T b) -{ - if (a > b) { - return (a - b) ; - } - else { - return T() ; - } +template T AUtils::bminus(T a, T b) { + if (a > b) { + return (a - b); + } else { + return T(); + } } -template -T AUtils::bplus (T a, T b) -{ - a += b ; - if (a > top) { - return top ; - } - else { - return a ; - } +template T AUtils::bplus(T a, T b) { + a += b; + if (a > top) { + return top; + } else { + return a; + } } -template -T AUtils::bplus (T a, T b, T top) -{ - a += b ; - if (a > top) { - return top ; - } - else { - return a ; - } +template T AUtils::bplus(T a, T b, T top) { + a += b; + if (a > top) { + return top; + } else { + return a; + } } -template -T AUtils::modsum (T* s, CTYPE n, T m) -{ - T retval = 0 ; - for (CTYPE i = CTYPE() ; i < n ; ++i) { - retval = (retval + s[i]) % m ; - } - return retval ; +template T AUtils::modsum(T *s, CTYPE n, T m) { + T retval = 0; + for (CTYPE i = CTYPE(); i < n; ++i) { + retval = (retval + s[i]) % m; + } + return retval; } -template -IT AUtils::roundup (FT x) -{ - IT retval = 0 ; - FT intpart = (FT) ((IT) x) ; - if (x - intpart == (FT) 0.0) { - retval = (IT) x ; - } - else { - retval = ((IT) x) + 1 ; - } - return retval ; +template IT AUtils::roundup(FT x) { + IT retval = 0; + FT intpart = (FT)((IT)x); + if (x - intpart == (FT)0.0) { + retval = (IT)x; + } else { + retval = ((IT)x) + 1; + } + return retval; } -template -T AUtils::log2_ceil (T n) -{ - T retval = 0 ; - while (n > 1) { - n = div_roundup (n, 2) ; - ++retval ; - } - return retval ; +template T AUtils::log2_ceil(T n) { + T retval = 0; + while (n > 1) { + n = div_roundup(n, 2); + ++retval; + } + return retval; } #endif // ndef SH_AUTILS_H diff --git a/src/Arg.cc b/src/Arg.cc index c19c31b..f8b7098 100644 --- a/src/Arg.cc +++ b/src/Arg.cc @@ -20,16 +20,14 @@ #include "Arg.h" -template Arg::Arg (T v, bool setbyuser) -{ - set = false ; - setValue (v, setbyuser) ; +template Arg::Arg(T v, bool setbyuser) { + set = false; + setValue(v, setbyuser); } -template void Arg::setValue (T v, bool setbyuser) -{ - Value = v ; - if (setbyuser) { - set = true ; - } +template void Arg::setValue(T v, bool setbyuser) { + Value = v; + if (setbyuser) { + set = true; + } } diff --git a/src/Arg.h b/src/Arg.h index 9a09a94..c9c1910 100644 --- a/src/Arg.h +++ b/src/Arg.h @@ -32,39 +32,48 @@ #include #endif -template class Arg { - public: - Arg (void) : set(false) {} ; - Arg (T v, bool setbyuser = true) ; +template class Arg { + public: + Arg(void) : set(false){}; + Arg(T v, bool setbyuser = true); - T getValue (void) const - { return Value ; } ; + T getValue(void) const { return Value; }; - void setValue (T v, bool setbyuser = true) ; + void setValue(T v, bool setbyuser = true); - bool is_set (void) const - { return set ; } ; + bool is_set(void) const { return set; }; - private: - T Value ; - bool set ; -} ; + private: + T Value; + bool set; +}; -enum COMMAND { EMBED, EXTRACT, CRACK, SEED_CRACK, INFO, ENCINFO, SHOWVERSION, SHOWLICENSE, SHOWHELP, PRINTFREQS } ; -enum VERBOSITY { QUIET, NORMAL, VERBOSE, STATS } ; -enum DEBUGCOMMAND { NONE, PRINTGRAPH, PRINTGMLGRAPH, PRINTGMLVERTEX } ; +enum COMMAND { + EMBED, + EXTRACT, + CRACK, + SEED_CRACK, + INFO, + ENCINFO, + SHOWVERSION, + SHOWLICENSE, + SHOWHELP, + PRINTFREQS +}; +enum VERBOSITY { QUIET, NORMAL, VERBOSE, STATS }; +enum DEBUGCOMMAND { NONE, PRINTGRAPH, PRINTGMLGRAPH, PRINTGMLVERTEX }; -typedef Arg ArgCommand ; -typedef Arg ArgVerbosity ; -typedef Arg ArgBool ; -typedef Arg ArgString ; -typedef Arg ArgULong ; -typedef Arg ArgInt ; -typedef Arg ArgFloat ; -typedef Arg ArgEncAlgo ; -typedef Arg ArgEncMode ; -typedef Arg ArgUInt ; -typedef Arg > ArgStringList ; -typedef Arg ArgDebugCommand ; +typedef Arg ArgCommand; +typedef Arg ArgVerbosity; +typedef Arg ArgBool; +typedef Arg ArgString; +typedef Arg ArgULong; +typedef Arg ArgInt; +typedef Arg ArgFloat; +typedef Arg ArgEncAlgo; +typedef Arg ArgEncMode; +typedef Arg ArgUInt; +typedef Arg> ArgStringList; +typedef Arg ArgDebugCommand; #endif // ndef SH_ARG_H diff --git a/src/Arguments.cc b/src/Arguments.cc index 91ed0e4..1b4dc69 100644 --- a/src/Arguments.cc +++ b/src/Arguments.cc @@ -33,746 +33,747 @@ #include "msg.h" // the global Arguments object -Arguments Args ; - -Arguments::Arguments (int argc, char* argv[]) -{ - bool delete_next = false ; - for (int i = 1 ; i < argc ; ++i) { - TheArguments.push_back (std::string(argv[i])) ; - - if (delete_next) { - // overwrite passphrase in argv in order to avoid that it can be read with the ps command - unsigned int len = strlen(argv[i]) ; - for (unsigned int j = 0 ; j < len ; j++) { - argv[i][j] = ' ' ; - } - delete_next = false ; - } - - if (std::string(argv[i]) == "-p" || std::string(argv[i]) == "--passphrase") { - delete_next = true ; - } - } +Arguments Args; + +Arguments::Arguments(int argc, char *argv[]) { + bool delete_next = false; + for (int i = 1; i < argc; ++i) { + TheArguments.push_back(std::string(argv[i])); + + if (delete_next) { + // overwrite passphrase in argv in order to avoid that it can be read with + // the ps command + unsigned int len = strlen(argv[i]); + for (unsigned int j = 0; j < len; j++) { + argv[i][j] = ' '; + } + delete_next = false; + } + + if (std::string(argv[i]) == "-p" || std::string(argv[i]) == "--passphrase") { + delete_next = true; + } + } } -void Arguments::parse () -{ - // if there are no arguments -> show help - if (TheArguments.empty()) { - Command.setValue (SHOWHELP) ; - return ; - } - - // Otherwise, we start by looking for a command. - // A command must start with two dashes. - - ArgIt curarg = TheArguments.begin() ; - - parse_Command (curarg) ; - setDefaults (); - - // Next, parse all keyword arguments. This returns all unmatched arguments - std::vector leftOvers = parse_Arguments (curarg) ; - // Parse the leftover arguments as positional arguments - parse_Positional (leftOvers) ; - - // (command-specific) argument post-processing - if (Command.getValue() == EMBED) { - if ((CvrFn.getValue() == "") && (EmbFn.getValue() == "")) { - throw ArgError (_("standard input cannot be used for cover data AND data to be embedded.")) ; - } - if (!StgFn.is_set() && CvrFn.is_set()) { - StgFn.setValue (CvrFn.getValue()) ; - Force.setValue (true) ; - } - } - - if (Command.getValue() == EMBED || Command.getValue() == EXTRACT) { - if (!Passphrase.is_set()) { - // prompt for passphrase - if (Command.getValue() == EMBED) { - if ((CvrFn.getValue() == "") || (EmbFn.getValue() == "")) { - throw ArgError (_("if standard input is used, the passphrase must be specified on the command line.")) ; - } - Passphrase.setValue (getPassphrase (true)) ; - } - else if (Command.getValue() == EXTRACT) { - if (StgFn.getValue() == "") { - throw ArgError (_("if standard input is used, the passphrase must be specified on the command line.")) ; - } - Passphrase.setValue (getPassphrase()) ; - } - } - } -} +void Arguments::parse() { + // if there are no arguments -> show help + if (TheArguments.empty()) { + Command.setValue(SHOWHELP); + return; + } -void Arguments::parse_Command (ArgIt& curarg) -{ - std::string CommandString = *curarg ; - - if (CommandString == "--crack") { - Command.setValue (CRACK) ; - } - else if (CommandString == "--embed") { - Command.setValue (EMBED) ; - } - else if (CommandString == "--extract") { - Command.setValue (EXTRACT) ; - } - else if (CommandString == "--seed") { - Command.setValue (SEED_CRACK) ; - } - else if (CommandString == "--info") { - Command.setValue (INFO) ; - } - else if (CommandString == "--encinfo") { - Command.setValue (ENCINFO) ; - } - else if (CommandString == "--version") { - Command.setValue (SHOWVERSION) ; - } - else if (CommandString == "--license") { - Command.setValue (SHOWLICENSE) ; - } - else if (CommandString == "--help") { - Command.setValue (SHOWHELP) ; - } else { - // If none of these matched, assume cracking mode - Command.setValue (CRACK) ; - // Return without pushing curarg forwards (since we didn't - // match anything) - return ; - } - curarg++ ; -} + // Otherwise, we start by looking for a command. + // A command must start with two dashes. + + ArgIt curarg = TheArguments.begin(); + + parse_Command(curarg); + setDefaults(); + + // Next, parse all keyword arguments. This returns all unmatched arguments + std::vector leftOvers = parse_Arguments(curarg); + // Parse the leftover arguments as positional arguments + parse_Positional(leftOvers); + + // (command-specific) argument post-processing + if (Command.getValue() == EMBED) { + if ((CvrFn.getValue() == "") && (EmbFn.getValue() == "")) { + throw ArgError(_("standard input cannot be used for cover data AND data " + "to be embedded.")); + } + if (!StgFn.is_set() && CvrFn.is_set()) { + StgFn.setValue(CvrFn.getValue()); + Force.setValue(true); + } + } -void Arguments::parse_Positional (std::vector positionalArgs) -{ - // Decide what to do with the arguments, based on the command - switch (Command.getValue()) - { - case CRACK: - { - ArgString* posPtr[]{&StgFn, &WordlistFn, &ExtFn} ; - for (int i = 0; i < 3 && i < positionalArgs.size(); i++) { - if (! posPtr[i]->is_set()) - posPtr[i]->setValue(positionalArgs[i]) ; - } - } - break; - case SEED_CRACK: - { - // Extract this file into that file - ArgString* posPtr[]{&StgFn, &ExtFn} ; - for (int i = 0; i < 2 && i < positionalArgs.size(); i++) { - if (! posPtr[i]->is_set()) - posPtr[i]->setValue(positionalArgs[i]) ; - } - } - break; - case EMBED: - { - // Embed this in that and output there - ArgString* posPtr[]{&EmbFn, &CvrFn, &StgFn} ; - for (int i = 0; i < 3 && i < positionalArgs.size(); i++) { - if (! posPtr[i]->is_set()) - posPtr[i]->setValue(positionalArgs[i]) ; - } - } - break; - case EXTRACT: - { - // Extract this file into that file - ArgString* posPtr[]{&StgFn, &ExtFn} ; - for (int i = 0; i < 2 && i < positionalArgs.size(); i++) { - if (! posPtr[i]->is_set()) - posPtr[i]->setValue(positionalArgs[i]) ; - } - } - break; - case INFO: - if (positionalArgs.size() > 0 && ! CvrFn.is_set()) { - CvrFn.setValue(positionalArgs[0]) ; - } - - default: - break; - } + if (Command.getValue() == EMBED || Command.getValue() == EXTRACT) { + if (!Passphrase.is_set()) { + // prompt for passphrase + if (Command.getValue() == EMBED) { + if ((CvrFn.getValue() == "") || (EmbFn.getValue() == "")) { + throw ArgError(_("if standard input is used, the passphrase must be " + "specified on the command line.")); + } + Passphrase.setValue(getPassphrase(true)); + } else if (Command.getValue() == EXTRACT) { + if (StgFn.getValue() == "") { + throw ArgError(_("if standard input is used, the passphrase must be " + "specified on the command line.")); + } + Passphrase.setValue(getPassphrase()); + } + } + } } -std::vector Arguments::parse_Arguments (ArgIt& curarg) -{ - // Anything that isn't a dashed argument (-v, -wl bla.txt, etc..) - // is added to this vector - std::vector leftOvers ; - while (curarg != TheArguments.end()) { - // Match any arguments that aren't of the shape -.* - if (curarg->c_str()[0] != '-' || *curarg == "-") { - // If the argument is a single '-', translate it to "" - if (*curarg == "-") { - leftOvers.push_back("") ; - } else { - leftOvers.push_back(*curarg) ; - } - curarg++ ; - continue ; - } - - // Anything starting with "-" is a flag, and should be parsed. - if (*curarg == "-ef" || *curarg == "--embedfile") { - std::vector compatible{EMBED} ; - parse_Generic_String(curarg, compatible, &EmbFn) ; - } else if (*curarg == "-xf" || *curarg == "--extractfile") { - std::vector compatible{EXTRACT, CRACK, SEED_CRACK} ; - parse_Generic_String(curarg, compatible, &ExtFn) ; - } else if (*curarg == "-cf" || *curarg == "--coverfile") { - std::vector compatible{EMBED} ; - parse_Generic_String(curarg, compatible, &CvrFn) ; - } else if (*curarg == "-sf" || *curarg == "--stegofile") { - std::vector compatible{EMBED, EXTRACT, CRACK, SEED_CRACK} ; - parse_Generic_String(curarg, compatible, &StgFn) ; - } else if (*curarg == "-wl" || *curarg == "--wordlist") { - std::vector compatible{CRACK} ; - parse_Generic_String(curarg, compatible, &WordlistFn) ; - } else if (*curarg == "-p" || *curarg == "--passphrase") { - std::vector compatible{} ; - parse_Generic_String(curarg, compatible, &Passphrase) ; - }else if (*curarg == "-K" || *curarg == "--nochecksum") { - std::vector compatible{} ; - parse_Generic_Bool(curarg, compatible, &Checksum, false) ; - } else if (*curarg == "-N" || *curarg == "--dontembedname") { - std::vector compatible{EMBED} ; - parse_Generic_Bool(curarg, compatible, &EmbedEmbFn, false) ; - } else if (*curarg == "-f" || *curarg == "--force") { - std::vector compatible{EMBED, EXTRACT, CRACK, SEED_CRACK} ; - parse_Generic_Bool(curarg, compatible, &Force, true) ; - } else if (*curarg == "-s" || *curarg == "--skipdefault") { - std::vector compatible{CRACK} ; - parse_Generic_Bool(curarg, compatible, &SkipDefaultGuesses, true) ; - } - // If there is no generic parser available, use a specific parser - else { - if (parse_Compression(curarg)) continue ; - if (parse_Encryption(curarg)) continue ; - if (parse_Radius(curarg)) continue ; - if (parse_Goal(curarg)) continue ; - if (parse_Threading(curarg)) continue ; - if (parse_Verbosity(curarg)) continue ; - if (parse_Debug(curarg)) continue ; // TODO - rename Debug -> Undocumented - - throw ArgError (_("unknown argument \"%s\"."), curarg->c_str()) ; - } - } - return leftOvers ; +void Arguments::parse_Command(ArgIt &curarg) { + std::string CommandString = *curarg; + + if (CommandString == "--crack") { + Command.setValue(CRACK); + } else if (CommandString == "--embed") { + Command.setValue(EMBED); + } else if (CommandString == "--extract") { + Command.setValue(EXTRACT); + } else if (CommandString == "--seed") { + Command.setValue(SEED_CRACK); + } else if (CommandString == "--info") { + Command.setValue(INFO); + } else if (CommandString == "--encinfo") { + Command.setValue(ENCINFO); + } else if (CommandString == "--version") { + Command.setValue(SHOWVERSION); + } else if (CommandString == "--license") { + Command.setValue(SHOWLICENSE); + } else if (CommandString == "--help") { + Command.setValue(SHOWHELP); + } else { + // If none of these matched, assume cracking mode + Command.setValue(CRACK); + // Return without pushing curarg forwards (since we didn't + // match anything) + return; + } + curarg++; } -bool Arguments::parse_Generic_String (ArgIt& curarg, std::vector compatibleCommands, ArgString* destArg) -{ - std::string argflag = *curarg ; - - // A generic string argument requires two values, -someflag, somevalue - if (++curarg == TheArguments.end()) { - throw ArgError (_("the argument \"%s\" requires a value"), argflag.c_str()) ; - } - bool compatible = false ; - // If the compatibleCommands is empty, this argument doesn't have conflicts. - if (compatibleCommands.empty()) { - compatible = true ; - } - // Otherwise, we check whether the current command is specified as compatible - else { - for (COMMAND c : compatibleCommands) { - if (Command.getValue() == c) { - compatible = true ; - } - } - } - if (! compatible) { - throw ArgError (_("the argument \"%s\" is not compatible with the current command"), argflag.c_str()) ; - } - if (destArg->is_set()) { - throw ArgError (_("the \"%s\" argument can be used only once."), argflag.c_str()) ; - } - - // Translate - to the empty string, to indicate stdin/stdout - if (*curarg == "-") { - destArg->setValue ("") ; - } else { - destArg->setValue (curarg->c_str()) ; - } - curarg++ ; - return true ; +void Arguments::parse_Positional(std::vector positionalArgs) { + // Decide what to do with the arguments, based on the command + switch (Command.getValue()) { + case CRACK: { + ArgString *posPtr[]{&StgFn, &WordlistFn, &ExtFn}; + for (int i = 0; i < 3 && i < positionalArgs.size(); i++) { + if (!posPtr[i]->is_set()) + posPtr[i]->setValue(positionalArgs[i]); + } + } break; + case SEED_CRACK: { + // Extract this file into that file + ArgString *posPtr[]{&StgFn, &ExtFn}; + for (int i = 0; i < 2 && i < positionalArgs.size(); i++) { + if (!posPtr[i]->is_set()) + posPtr[i]->setValue(positionalArgs[i]); + } + } break; + case EMBED: { + // Embed this in that and output there + ArgString *posPtr[]{&EmbFn, &CvrFn, &StgFn}; + for (int i = 0; i < 3 && i < positionalArgs.size(); i++) { + if (!posPtr[i]->is_set()) + posPtr[i]->setValue(positionalArgs[i]); + } + } break; + case EXTRACT: { + // Extract this file into that file + ArgString *posPtr[]{&StgFn, &ExtFn}; + for (int i = 0; i < 2 && i < positionalArgs.size(); i++) { + if (!posPtr[i]->is_set()) + posPtr[i]->setValue(positionalArgs[i]); + } + } break; + case INFO: + if (positionalArgs.size() > 0 && !CvrFn.is_set()) { + CvrFn.setValue(positionalArgs[0]); + } + + default: + break; + } } -bool Arguments::parse_Generic_Bool (ArgIt& curarg, std::vector compatibleCommands, ArgBool* destArg, bool ifMatch) -{ - bool compatible = false ; - // If the compatibleCommands is empty, this argument doesn't have conflicts. - if (compatibleCommands.empty()) { - compatible = true ; - } - // Otherwise, we check whether the current command is specified as compatible - else { - for (COMMAND c : compatibleCommands) { - if (Command.getValue() == c) { - compatible = true ; - } - } - } - if (! compatible) { - throw ArgError (_("the argument \"%s\" is not compatible with the current command"), curarg->c_str()) ; - } - if (destArg->is_set()) { - throw ArgError (_("the \"%s\" argument can be used only once."), curarg->c_str()) ; - } - else { - destArg->setValue (ifMatch) ; - } - curarg++ ; - return true ; +std::vector Arguments::parse_Arguments(ArgIt &curarg) { + // Anything that isn't a dashed argument (-v, -wl bla.txt, etc..) + // is added to this vector + std::vector leftOvers; + while (curarg != TheArguments.end()) { + // Match any arguments that aren't of the shape -.* + if (curarg->c_str()[0] != '-' || *curarg == "-") { + // If the argument is a single '-', translate it to "" + if (*curarg == "-") { + leftOvers.push_back(""); + } else { + leftOvers.push_back(*curarg); + } + curarg++; + continue; + } + + // Anything starting with "-" is a flag, and should be parsed. + if (*curarg == "-ef" || *curarg == "--embedfile") { + std::vector compatible{EMBED}; + parse_Generic_String(curarg, compatible, &EmbFn); + } else if (*curarg == "-xf" || *curarg == "--extractfile") { + std::vector compatible{EXTRACT, CRACK, SEED_CRACK}; + parse_Generic_String(curarg, compatible, &ExtFn); + } else if (*curarg == "-cf" || *curarg == "--coverfile") { + std::vector compatible{EMBED}; + parse_Generic_String(curarg, compatible, &CvrFn); + } else if (*curarg == "-sf" || *curarg == "--stegofile") { + std::vector compatible{EMBED, EXTRACT, CRACK, SEED_CRACK}; + parse_Generic_String(curarg, compatible, &StgFn); + } else if (*curarg == "-wl" || *curarg == "--wordlist") { + std::vector compatible{CRACK}; + parse_Generic_String(curarg, compatible, &WordlistFn); + } else if (*curarg == "-p" || *curarg == "--passphrase") { + std::vector compatible{}; + parse_Generic_String(curarg, compatible, &Passphrase); + } else if (*curarg == "-K" || *curarg == "--nochecksum") { + std::vector compatible{}; + parse_Generic_Bool(curarg, compatible, &Checksum, false); + } else if (*curarg == "-N" || *curarg == "--dontembedname") { + std::vector compatible{EMBED}; + parse_Generic_Bool(curarg, compatible, &EmbedEmbFn, false); + } else if (*curarg == "-f" || *curarg == "--force") { + std::vector compatible{EMBED, EXTRACT, CRACK, SEED_CRACK}; + parse_Generic_Bool(curarg, compatible, &Force, true); + } else if (*curarg == "-s" || *curarg == "--skipdefault") { + std::vector compatible{CRACK}; + parse_Generic_Bool(curarg, compatible, &SkipDefaultGuesses, true); + } + // If there is no generic parser available, use a specific parser + else { + if (parse_Compression(curarg)) + continue; + if (parse_Encryption(curarg)) + continue; + if (parse_Radius(curarg)) + continue; + if (parse_Goal(curarg)) + continue; + if (parse_Threading(curarg)) + continue; + if (parse_Verbosity(curarg)) + continue; + if (parse_Debug(curarg)) + continue; // TODO - rename Debug -> Undocumented + + throw ArgError(_("unknown argument \"%s\"."), curarg->c_str()); + } + } + return leftOvers; } +bool Arguments::parse_Generic_String(ArgIt &curarg, std::vector compatibleCommands, + ArgString *destArg) { + std::string argflag = *curarg; + // A generic string argument requires two values, -someflag, somevalue + if (++curarg == TheArguments.end()) { + throw ArgError(_("the argument \"%s\" requires a value"), argflag.c_str()); + } + bool compatible = false; + // If the compatibleCommands is empty, this argument doesn't have conflicts. + if (compatibleCommands.empty()) { + compatible = true; + } + // Otherwise, we check whether the current command is specified as compatible + else { + for (COMMAND c : compatibleCommands) { + if (Command.getValue() == c) { + compatible = true; + } + } + } + if (!compatible) { + throw ArgError(_("the argument \"%s\" is not compatible with the current command"), + argflag.c_str()); + } + if (destArg->is_set()) { + throw ArgError(_("the \"%s\" argument can be used only once."), argflag.c_str()); + } -bool Arguments::parse_Threading (ArgIt& curarg) -{ - bool found = false ; - - if (*curarg == "-t" || *curarg == "--threads") { - if (Command.getValue() != CRACK && Command.getValue() != SEED_CRACK) { - throw ArgError (_("the argument \"%s\" can only be used with the \"%s\" and \"%s\" commands."), curarg->c_str(), "crack", "seed") ; - } - - if (Threads.is_set()) { - throw ArgError (_("the \"%s\" argument can be used only once."), curarg->c_str()) ; - } - if (++curarg == TheArguments.end()) { - throw ArgError (_("the \"%s\" argument must be followed by the number of threads."), (curarg - 1)->c_str()) ; - } - else { - int tmp; - if (sscanf(curarg->c_str(), "%d", &tmp) == 1) { - if (tmp > 0) { - Threads.setValue (tmp) ; - found = true ; - curarg++ ; - } else { - throw ArgError (_("The number of threads must be greater than 0.")) ; - } - } else { - throw ArgError (_("The number of threads must be an integer")) ; - } - } - } - return found ; + // Translate - to the empty string, to indicate stdin/stdout + if (*curarg == "-") { + destArg->setValue(""); + } else { + destArg->setValue(curarg->c_str()); + } + curarg++; + return true; } -bool Arguments::parse_Compression (ArgIt& curarg) -{ - bool found = false ; - - if (*curarg == "-z" || *curarg == "--compress") { - if (Command.getValue() != EMBED) { - throw ArgError (_("the argument \"%s\" can only be used with the \"embed\" command."), curarg->c_str()) ; - } - - if (Compression.is_set()) { - throw ArgError (_("the compression argument can be used only once.")) ; - } - - if (++curarg == TheArguments.end()) { - throw ArgError (_("the \"%s\" argument must be followed by the compression level."), (curarg - 1)->c_str()) ; - } - - int tmp = 0 ; - sscanf (curarg->c_str(), "%d", &tmp) ; - if (tmp < 1 || tmp > 9) { - throw ArgError (_("\"%s\" is not a valid compression level."), curarg->c_str()) ; - } - Compression.setValue (tmp) ; - - found = true ; - curarg++ ; - } - else if (*curarg == "-Z" || *curarg == "--dontcompress") { - if (Command.getValue() != EMBED) { - throw ArgError (_("the argument \"%s\" can only be used with the \"%s\" command."), curarg->c_str(), "embed") ; - } - - if (Compression.is_set()) { - throw ArgError (_("the compression argument can be used only once.")) ; - } - - Compression.setValue (NoCompression) ; - - found = true ; - curarg++ ; - } - - return found ; +bool Arguments::parse_Generic_Bool(ArgIt &curarg, std::vector compatibleCommands, + ArgBool *destArg, bool ifMatch) { + bool compatible = false; + // If the compatibleCommands is empty, this argument doesn't have conflicts. + if (compatibleCommands.empty()) { + compatible = true; + } + // Otherwise, we check whether the current command is specified as compatible + else { + for (COMMAND c : compatibleCommands) { + if (Command.getValue() == c) { + compatible = true; + } + } + } + if (!compatible) { + throw ArgError(_("the argument \"%s\" is not compatible with the current command"), + curarg->c_str()); + } + if (destArg->is_set()) { + throw ArgError(_("the \"%s\" argument can be used only once."), curarg->c_str()); + } else { + destArg->setValue(ifMatch); + } + curarg++; + return true; } -bool Arguments::parse_Encryption (ArgIt& curarg) -{ - bool found = false ; - - if (*curarg == "-e" || *curarg == "--encryption") { - if (Command.getValue() != EMBED) { - throw ArgError (_("the argument \"%s\" can only be used with the \"%s\" command."), curarg->c_str(), "embed") ; - } - - if (EncAlgo.is_set() || EncMode.is_set()) { - throw ArgError (_("the encryption argument can be used only once.")) ; - } - - if (++curarg == TheArguments.end()) { - throw ArgError (_("the \"%s\" argument must be followed by encryption parameters."), (curarg - 1)->c_str()) ; - } - - std::string s1, s2 ; - if ((*curarg)[0] == '-') { - throw ArgError (_("the \"%s\" argument must be followed by encryption parameters."), (curarg - 1)->c_str()) ; - } - else { - s1 = *curarg ; - if (curarg + 1 == TheArguments.end()) { - s2 = "" ; - } - else { - if ((*(curarg + 1))[0] == '-') { - s2 = "" ; - } - else { - ++curarg ; // set to second encryption specifier - s2 = *curarg ; - } - } - } - - if (s1 == "none" && s2 == "") { - EncAlgo.setValue (s1) ; - } - else { - bool s1_isalgo = false, s1_ismode = false ; - bool s2_isalgo = false, s2_ismode = false ; - - if (s1 != "") { - s1_isalgo = EncryptionAlgorithm::isValidStringRep (s1) ; - s1_ismode = EncryptionMode::isValidStringRep (s1) ; - - myassert (!(s1_isalgo && s1_ismode)) ; - if (!(s1_isalgo || s1_ismode)) { - throw SteghideError (_("\"%s\" is neither an algorithm nor a mode supported by libmcrypt."), s1.c_str()) ; - } - } - if (s2 != "") { - s2_isalgo = EncryptionAlgorithm::isValidStringRep (s2) ; - s2_ismode = EncryptionMode::isValidStringRep (s2) ; - - myassert (!(s2_isalgo && s2_ismode)) ; - if (!(s2_isalgo || s2_ismode)) { - throw SteghideError (_("\"%s\" is neither an algorithm nor a mode supported by libmcrypt."), s2.c_str()) ; - } - } - - if (s1_isalgo && s2_isalgo) { - throw SteghideError (_("\"%s\" and \"%s\" are both libmcrypt algorithms. please specify only one."), s1.c_str(), s2.c_str()) ; - } - if (s1_ismode && s2_ismode) { - throw SteghideError (_("\"%s\" and \"%s\" are both libmcrypt modes. please specify only one."), s1.c_str(), s2.c_str()) ; - } - - if (s1_isalgo) { - EncAlgo.setValue (s1) ; - } - if (s1_ismode) { - EncMode.setValue (s1) ; - } - if (s2_isalgo) { - EncAlgo.setValue (s2) ; - } - if (s2_ismode) { - EncMode.setValue (s2) ; - } - - if (!MCryptPP::AlgoSupportsMode (EncAlgo.getValue(), EncMode.getValue())) { - throw SteghideError (_("the encryption algorithm \"%s\" can not be used with the mode \"%s\"."), - EncAlgo.getValue().getStringRep().c_str(), EncMode.getValue().getStringRep().c_str()) ; - } - } - found = true ; - curarg++ ; - } - - return found ; +bool Arguments::parse_Threading(ArgIt &curarg) { + bool found = false; + + if (*curarg == "-t" || *curarg == "--threads") { + if (Command.getValue() != CRACK && Command.getValue() != SEED_CRACK) { + throw ArgError(_("the argument \"%s\" can only be used with the \"%s\" " + "and \"%s\" commands."), + curarg->c_str(), "crack", "seed"); + } + + if (Threads.is_set()) { + throw ArgError(_("the \"%s\" argument can be used only once."), curarg->c_str()); + } + if (++curarg == TheArguments.end()) { + throw ArgError(_("the \"%s\" argument must be followed by the number of threads."), + (curarg - 1)->c_str()); + } else { + int tmp; + if (sscanf(curarg->c_str(), "%d", &tmp) == 1) { + if (tmp > 0) { + Threads.setValue(tmp); + found = true; + curarg++; + } else { + throw ArgError(_("The number of threads must be greater than 0.")); + } + } else { + throw ArgError(_("The number of threads must be an integer")); + } + } + } + return found; } -bool Arguments::parse_Radius (ArgIt& curarg) -{ - bool found = false ; - - if (*curarg == "-r" || *curarg == "--radius") { - if (Command.getValue() != EMBED) { - throw ArgError (_("the argument \"%s\" can only be used with the \"%s\" command."), curarg->c_str(), "embed") ; - } - - if (Radius.is_set()) { - throw ArgError (_("the radius argument can be used only once.")) ; - } - - if (++curarg == TheArguments.end()) { - throw ArgError (_("the \"%s\" argument must be followed by the neighbourhood radius."), (curarg - 1)->c_str()) ; - } +bool Arguments::parse_Compression(ArgIt &curarg) { + bool found = false; + + if (*curarg == "-z" || *curarg == "--compress") { + if (Command.getValue() != EMBED) { + throw ArgError(_("the argument \"%s\" can only be used with the \"embed\" command."), + curarg->c_str()); + } + + if (Compression.is_set()) { + throw ArgError(_("the compression argument can be used only once.")); + } + + if (++curarg == TheArguments.end()) { + throw ArgError(_("the \"%s\" argument must be followed by the compression level."), + (curarg - 1)->c_str()); + } + + int tmp = 0; + sscanf(curarg->c_str(), "%d", &tmp); + if (tmp < 1 || tmp > 9) { + throw ArgError(_("\"%s\" is not a valid compression level."), curarg->c_str()); + } + Compression.setValue(tmp); + + found = true; + curarg++; + } else if (*curarg == "-Z" || *curarg == "--dontcompress") { + if (Command.getValue() != EMBED) { + throw ArgError(_("the argument \"%s\" can only be used with the \"%s\" command."), + curarg->c_str(), "embed"); + } + + if (Compression.is_set()) { + throw ArgError(_("the compression argument can be used only once.")); + } + + Compression.setValue(NoCompression); + + found = true; + curarg++; + } - unsigned long tmp = 0 ; - sscanf (curarg->c_str(), "%lu", &tmp) ; - Radius.setValue (tmp) ; + return found; +} - found = true ; - curarg++ ; - } +bool Arguments::parse_Encryption(ArgIt &curarg) { + bool found = false; + + if (*curarg == "-e" || *curarg == "--encryption") { + if (Command.getValue() != EMBED) { + throw ArgError(_("the argument \"%s\" can only be used with the \"%s\" command."), + curarg->c_str(), "embed"); + } + + if (EncAlgo.is_set() || EncMode.is_set()) { + throw ArgError(_("the encryption argument can be used only once.")); + } + + if (++curarg == TheArguments.end()) { + throw ArgError(_("the \"%s\" argument must be followed by encryption parameters."), + (curarg - 1)->c_str()); + } + + std::string s1, s2; + if ((*curarg)[0] == '-') { + throw ArgError(_("the \"%s\" argument must be followed by encryption parameters."), + (curarg - 1)->c_str()); + } else { + s1 = *curarg; + if (curarg + 1 == TheArguments.end()) { + s2 = ""; + } else { + if ((*(curarg + 1))[0] == '-') { + s2 = ""; + } else { + ++curarg; // set to second encryption specifier + s2 = *curarg; + } + } + } + + if (s1 == "none" && s2 == "") { + EncAlgo.setValue(s1); + } else { + bool s1_isalgo = false, s1_ismode = false; + bool s2_isalgo = false, s2_ismode = false; + + if (s1 != "") { + s1_isalgo = EncryptionAlgorithm::isValidStringRep(s1); + s1_ismode = EncryptionMode::isValidStringRep(s1); + + myassert(!(s1_isalgo && s1_ismode)); + if (!(s1_isalgo || s1_ismode)) { + throw SteghideError(_("\"%s\" is neither an algorithm nor a mode " + "supported by libmcrypt."), + s1.c_str()); + } + } + if (s2 != "") { + s2_isalgo = EncryptionAlgorithm::isValidStringRep(s2); + s2_ismode = EncryptionMode::isValidStringRep(s2); + + myassert(!(s2_isalgo && s2_ismode)); + if (!(s2_isalgo || s2_ismode)) { + throw SteghideError(_("\"%s\" is neither an algorithm nor a mode " + "supported by libmcrypt."), + s2.c_str()); + } + } + + if (s1_isalgo && s2_isalgo) { + throw SteghideError(_("\"%s\" and \"%s\" are both libmcrypt " + "algorithms. please specify only one."), + s1.c_str(), s2.c_str()); + } + if (s1_ismode && s2_ismode) { + throw SteghideError(_("\"%s\" and \"%s\" are both libmcrypt modes. " + "please specify only one."), + s1.c_str(), s2.c_str()); + } + + if (s1_isalgo) { + EncAlgo.setValue(s1); + } + if (s1_ismode) { + EncMode.setValue(s1); + } + if (s2_isalgo) { + EncAlgo.setValue(s2); + } + if (s2_ismode) { + EncMode.setValue(s2); + } + + if (!MCryptPP::AlgoSupportsMode(EncAlgo.getValue(), EncMode.getValue())) { + throw SteghideError(_("the encryption algorithm \"%s\" can not be used " + "with the mode \"%s\"."), + EncAlgo.getValue().getStringRep().c_str(), + EncMode.getValue().getStringRep().c_str()); + } + } + found = true; + curarg++; + } - return found ; + return found; } -bool Arguments::parse_Goal (ArgIt& curarg) -{ - bool found = false ; +bool Arguments::parse_Radius(ArgIt &curarg) { + bool found = false; - if (*curarg == "-g" || *curarg == "--goal") { - if (Command.getValue() != EMBED) { - throw ArgError (_("the argument \"%s\" can only be used with the \"%s\" command."), curarg->c_str(), "embed") ; - } + if (*curarg == "-r" || *curarg == "--radius") { + if (Command.getValue() != EMBED) { + throw ArgError(_("the argument \"%s\" can only be used with the \"%s\" command."), + curarg->c_str(), "embed"); + } - if (Goal.is_set()) { - throw ArgError (_("the goal argument can be used only once.")) ; - } + if (Radius.is_set()) { + throw ArgError(_("the radius argument can be used only once.")); + } - if (++curarg == TheArguments.end()) { - throw ArgError (_("the \"%s\" argument must be followed by a number between 0 and 100."), (curarg - 1)->c_str()) ; - } + if (++curarg == TheArguments.end()) { + throw ArgError(_("the \"%s\" argument must be followed by the " + "neighbourhood radius."), + (curarg - 1)->c_str()); + } - float tmp = 0 ; - sscanf (curarg->c_str(), "%f", &tmp) ; - if (tmp < 0 || tmp > 100) { - throw ArgError (_("the \"%s\" argument must be followed by a number between 0 and 100."), (curarg - 1)->c_str()) ; - } - Goal.setValue (tmp) ; + unsigned long tmp = 0; + sscanf(curarg->c_str(), "%lu", &tmp); + Radius.setValue(tmp); - found = true ; - curarg++ ; - } + found = true; + curarg++; + } - return found ; + return found; } -bool Arguments::parse_Verbosity (ArgIt& curarg) -{ - bool found = false ; - - if (*curarg == "-q" || *curarg == "--quiet") { - found = true ; - - if (Command.getValue() != EMBED && Command.getValue() != EXTRACT - && Command.getValue() != CRACK && Command.getValue() != SEED_CRACK) { - throw ArgError (_("the argument \"%s\" can only be used with the \"%s\", \"%s\", \"%s\", and \"%s\" commands."), - curarg->c_str(), "embed", "extract", "crack", "seed") ; - } - - if (Verbosity.is_set()) { - throw ArgError (_("the \"%s\" argument cannot be used here because the verbosity has already been set."), curarg->c_str()) ; - } - - Verbosity.setValue (QUIET) ; - curarg++ ; - } - else if (*curarg == "-v" || *curarg == "--verbose") { - found = true ; - - if (Command.getValue() != EMBED && Command.getValue() != EXTRACT && Command.getValue() != CRACK - && Command.getValue() != SEED_CRACK && Command.getValue() != SHOWHELP && Command.getValue() != SHOWVERSION) { - throw ArgError (_("the argument \"%s\" can only be used with the \"%s\", \"%s\", \"%s\", \"%s\", \"%s\" and \"%s\" commands."), - curarg->c_str(), "embed", "extract", "crack", "seed", "version", "help") ; - } +bool Arguments::parse_Goal(ArgIt &curarg) { + bool found = false; + + if (*curarg == "-g" || *curarg == "--goal") { + if (Command.getValue() != EMBED) { + throw ArgError(_("the argument \"%s\" can only be used with the \"%s\" command."), + curarg->c_str(), "embed"); + } + + if (Goal.is_set()) { + throw ArgError(_("the goal argument can be used only once.")); + } + + if (++curarg == TheArguments.end()) { + throw ArgError(_("the \"%s\" argument must be followed by a number " + "between 0 and 100."), + (curarg - 1)->c_str()); + } + + float tmp = 0; + sscanf(curarg->c_str(), "%f", &tmp); + if (tmp < 0 || tmp > 100) { + throw ArgError(_("the \"%s\" argument must be followed by a number " + "between 0 and 100."), + (curarg - 1)->c_str()); + } + Goal.setValue(tmp); + + found = true; + curarg++; + } - if (Verbosity.is_set()) { - throw ArgError (_("the \"%s\" argument cannot be used here because the verbosity has already been set."), curarg->c_str()) ; - } + return found; +} - Verbosity.setValue (VERBOSE) ; - curarg++ ; - } +bool Arguments::parse_Verbosity(ArgIt &curarg) { + bool found = false; + + if (*curarg == "-q" || *curarg == "--quiet") { + found = true; + + if (Command.getValue() != EMBED && Command.getValue() != EXTRACT && + Command.getValue() != CRACK && Command.getValue() != SEED_CRACK) { + throw ArgError(_("the argument \"%s\" can only be used with the \"%s\", " + "\"%s\", \"%s\", and \"%s\" commands."), + curarg->c_str(), "embed", "extract", "crack", "seed"); + } + + if (Verbosity.is_set()) { + throw ArgError(_("the \"%s\" argument cannot be used here because the " + "verbosity has already been set."), + curarg->c_str()); + } + + Verbosity.setValue(QUIET); + curarg++; + } else if (*curarg == "-v" || *curarg == "--verbose") { + found = true; + + if (Command.getValue() != EMBED && Command.getValue() != EXTRACT && + Command.getValue() != CRACK && Command.getValue() != SEED_CRACK && + Command.getValue() != SHOWHELP && Command.getValue() != SHOWVERSION) { + throw ArgError(_("the argument \"%s\" can only be used with the \"%s\", " + "\"%s\", \"%s\", \"%s\", \"%s\" and \"%s\" commands."), + curarg->c_str(), "embed", "extract", "crack", "seed", "version", "help"); + } + + if (Verbosity.is_set()) { + throw ArgError(_("the \"%s\" argument cannot be used here because the " + "verbosity has already been set."), + curarg->c_str()); + } + + Verbosity.setValue(VERBOSE); + curarg++; + } - return found ; + return found; } -bool Arguments::parse_Debug (ArgIt& curarg) -{ - bool found = false ; - - if (*curarg == "--printgraph") { - if (DebugCommand.is_set()) { - throw SteghideError (_("you cannot use more than one debug command at a time.")) ; - } - - DebugCommand.setValue (PRINTGRAPH) ; - - found = true ; - curarg++ ; - } - else if (*curarg == "--printgmlgraph") { - if (DebugCommand.is_set()) { - throw SteghideError (_("you cannot use more than one debug command at a time.")) ; - } - - DebugCommand.setValue (PRINTGMLGRAPH) ; - - found = true ; - curarg++ ; - } - else if (*curarg == "--printgmlvertex") { - if (DebugCommand.is_set()) { - throw SteghideError (_("you cannot use more than one debug command at a time.")) ; - } - - DebugCommand.setValue (PRINTGMLVERTEX) ; - curarg++ ; - - int tmp = 0 ; - sscanf (curarg->c_str(), "%d", &tmp) ; - GmlGraphRecDepth.setValue (tmp) ; - curarg++ ; - sscanf (curarg->c_str(), "%d", &tmp) ; - GmlStartVertex.setValue (tmp) ; - - found = true ; - curarg++ ; - } - else if (*curarg == "--printstats") { - if (DebugCommand.is_set()) { - throw SteghideError (_("you cannot use more than one debug command at a time.")) ; - } - - if (Verbosity.is_set()) { - throw ArgError (_("the \"%s\" argument cannot be used here because the verbosity has already been set."), curarg->c_str()) ; - } - - Verbosity.setValue (STATS) ; - - found = true ; - ++curarg ; - } - else if (*curarg == "--debuglevel") { - if (DebugLevel.is_set()) { - throw ArgError (_("the debug level argument can be used only once.")) ; - } - - if (++curarg == TheArguments.end()) { - throw ArgError (_("the \"%s\" argument must be followed by the debug level."), (curarg - 1)->c_str()) ; - } - - unsigned int tmp = 0 ; - sscanf (curarg->c_str(), "%u", &tmp) ; - DebugLevel.setValue (tmp) ; - - found = true ; - ++curarg ; - } - else if (*curarg == "--check") { - // TODO usual error checking (omitted due to message freeze) - Check.setValue (true) ; - - found = true ; - ++curarg ; - } - - return found ; +bool Arguments::parse_Debug(ArgIt &curarg) { + bool found = false; + + if (*curarg == "--printgraph") { + if (DebugCommand.is_set()) { + throw SteghideError(_("you cannot use more than one debug command at a time.")); + } + + DebugCommand.setValue(PRINTGRAPH); + + found = true; + curarg++; + } else if (*curarg == "--printgmlgraph") { + if (DebugCommand.is_set()) { + throw SteghideError(_("you cannot use more than one debug command at a time.")); + } + + DebugCommand.setValue(PRINTGMLGRAPH); + + found = true; + curarg++; + } else if (*curarg == "--printgmlvertex") { + if (DebugCommand.is_set()) { + throw SteghideError(_("you cannot use more than one debug command at a time.")); + } + + DebugCommand.setValue(PRINTGMLVERTEX); + curarg++; + + int tmp = 0; + sscanf(curarg->c_str(), "%d", &tmp); + GmlGraphRecDepth.setValue(tmp); + curarg++; + sscanf(curarg->c_str(), "%d", &tmp); + GmlStartVertex.setValue(tmp); + + found = true; + curarg++; + } else if (*curarg == "--printstats") { + if (DebugCommand.is_set()) { + throw SteghideError(_("you cannot use more than one debug command at a time.")); + } + + if (Verbosity.is_set()) { + throw ArgError(_("the \"%s\" argument cannot be used here because the " + "verbosity has already been set."), + curarg->c_str()); + } + + Verbosity.setValue(STATS); + + found = true; + ++curarg; + } else if (*curarg == "--debuglevel") { + if (DebugLevel.is_set()) { + throw ArgError(_("the debug level argument can be used only once.")); + } + + if (++curarg == TheArguments.end()) { + throw ArgError(_("the \"%s\" argument must be followed by the debug level."), + (curarg - 1)->c_str()); + } + + unsigned int tmp = 0; + sscanf(curarg->c_str(), "%u", &tmp); + DebugLevel.setValue(tmp); + + found = true; + ++curarg; + } else if (*curarg == "--check") { + // TODO usual error checking (omitted due to message freeze) + Check.setValue(true); + + found = true; + ++curarg; + } + + return found; } -std::string Arguments::getPassphrase (bool doublecheck) -{ - int c = EOF ; +std::string Arguments::getPassphrase(bool doublecheck) { + int c = EOF; #ifndef HAVE_TERMIOS_H - Warning w (_("unknown terminal. the passphrase you type now will be visible.")) ; - w.printMessage() ; + Warning w(_("unknown terminal. the passphrase you type now will be visible.")); + w.printMessage(); #endif - std::cerr << _("Enter passphrase: ") ; - Terminal term ; - term.EchoOff() ; - - std::string s1 = "" ; + std::cerr << _("Enter passphrase: "); + Terminal term; + term.EchoOff(); + + std::string s1 = ""; while ((c = std::cin.get()) != '\n') { - s1 += c ; + s1 += c; } - term.reset() ; - std::cerr << std::endl ; + term.reset(); + std::cerr << std::endl; - if (doublecheck) { - std::cerr << _("Re-Enter passphrase: ") ; - term.EchoOff() ; + if (doublecheck) { + std::cerr << _("Re-Enter passphrase: "); + term.EchoOff(); - std::string s2 = "" ; - while ((c = std::cin.get()) != '\n') { - s2 += c ; - } + std::string s2 = ""; + while ((c = std::cin.get()) != '\n') { + s2 += c; + } - term.reset() ; - std::cerr << std::endl ; + term.reset(); + std::cerr << std::endl; - if (s1 != s2) { - throw SteghideError (_("the passphrases do not match.")) ; - } - } + if (s1 != s2) { + throw SteghideError(_("the passphrases do not match.")); + } + } - return s1 ; + return s1; } -bool Arguments::stdin_isused () const -{ - bool retval = false ; - if (Command.getValue() == EMBED && (EmbFn.getValue() == "" || CvrFn.getValue() == "")) { - retval = true ; - } - else if (Command.getValue() == EXTRACT && StgFn.getValue() == "") { - retval = true ; - } - else if (Command.getValue() == INFO && CvrFn.getValue() == "") { - retval = true ; - } - return retval ; +bool Arguments::stdin_isused() const { + bool retval = false; + if (Command.getValue() == EMBED && (EmbFn.getValue() == "" || CvrFn.getValue() == "")) { + retval = true; + } else if (Command.getValue() == EXTRACT && StgFn.getValue() == "") { + retval = true; + } else if (Command.getValue() == INFO && CvrFn.getValue() == "") { + retval = true; + } + return retval; } -void Arguments::setDefaults (void) -{ - myassert (Command.is_set()) ; - - EmbFn.setValue ("", false) ; - CvrFn.setValue ("", false) ; - EncAlgo.setValue (Default_EncAlgo, false) ; - EncMode.setValue (Default_EncMode, false) ; - Checksum.setValue (Default_Checksum, false) ; - Compression.setValue (Default_Compression, false) ; - EmbedEmbFn.setValue (Default_EmbedEmbFn, false) ; - ExtFn.setValue ("", false) ; - Passphrase.setValue ("", false) ; - StgFn.setValue ("", false) ; - WordlistFn.setValue ("/usr/share/wordlists/rockyou.txt", false) ; - Threads.setValue (std::thread::hardware_concurrency(), false) ; - Force.setValue (Default_Force, false) ; - SkipDefaultGuesses.setValue (Default_SkipDefaultGuesses, false) ; - Verbosity.setValue (Default_Verbosity, false) ; - Radius.setValue (Default_Radius, false) ; - Goal.setValue (Default_Goal, false) ; - Check.setValue (Default_Check, false) ; - DebugCommand.setValue (Default_DebugCommand, false) ; - DebugLevel.setValue (Default_DebugLevel, false) ; - GmlGraphRecDepth.setValue (Default_GmlGraphRecDepth, false) ; - GmlStartVertex.setValue (Default_GmlStartVertex, false) ; +void Arguments::setDefaults(void) { + myassert(Command.is_set()); + + EmbFn.setValue("", false); + CvrFn.setValue("", false); + EncAlgo.setValue(Default_EncAlgo, false); + EncMode.setValue(Default_EncMode, false); + Checksum.setValue(Default_Checksum, false); + Compression.setValue(Default_Compression, false); + EmbedEmbFn.setValue(Default_EmbedEmbFn, false); + ExtFn.setValue("", false); + Passphrase.setValue("", false); + StgFn.setValue("", false); + WordlistFn.setValue("/usr/share/wordlists/rockyou.txt", false); + Threads.setValue(std::thread::hardware_concurrency(), false); + Force.setValue(Default_Force, false); + SkipDefaultGuesses.setValue(Default_SkipDefaultGuesses, false); + Verbosity.setValue(Default_Verbosity, false); + Radius.setValue(Default_Radius, false); + Goal.setValue(Default_Goal, false); + Check.setValue(Default_Check, false); + DebugCommand.setValue(Default_DebugCommand, false); + DebugLevel.setValue(Default_DebugLevel, false); + GmlGraphRecDepth.setValue(Default_GmlGraphRecDepth, false); + GmlStartVertex.setValue(Default_GmlStartVertex, false); } -const EncryptionAlgorithm Arguments::Default_EncAlgo = EncryptionAlgorithm (EncryptionAlgorithm::RIJNDAEL128) ; -const EncryptionMode Arguments::Default_EncMode = EncryptionMode (EncryptionMode::CBC) ; +const EncryptionAlgorithm Arguments::Default_EncAlgo = + EncryptionAlgorithm(EncryptionAlgorithm::RIJNDAEL128); +const EncryptionMode Arguments::Default_EncMode = EncryptionMode(EncryptionMode::CBC); diff --git a/src/Arguments.h b/src/Arguments.h index e0c1832..1e0062e 100644 --- a/src/Arguments.h +++ b/src/Arguments.h @@ -36,130 +36,133 @@ * \brief parsing and data representation of command-line arguments **/ class Arguments { - public: - Arguments (void) {} ; - - /** - * initialize this Arguments object with argc and argv - **/ - Arguments (int argc, char *argv[]) ; - - /** - * parse Argc and Argv filling the Arg* member variable for later access - **/ - void parse (void) ; - - /** - * is standard input used ? - according to the given arguments - **/ - bool stdin_isused (void) const ; - - /// the command to be executed in this session - ArgCommand Command ; - /// the name of the command to be executed in this session (as supplied by the user) - std::string CommandString ; - - /// the embed file name, "" if stdin - ArgString EmbFn ; - /// the extract file name, "" if stdout - ArgString ExtFn ; - /// the cover file name, "" if stdin - ArgString CvrFn ; - /// the stego file name, "" if stdout/stdin - ArgString StgFn ; - /// the wordlist file name, "" if stdout/stdin - ArgString WordlistFn ; - ArgString Passphrase ; - ArgBool Checksum ; - ArgInt Compression ; - ArgInt Threads ; - ArgBool EmbedEmbFn ; - ArgEncAlgo EncAlgo ; - ArgEncMode EncMode ; - ArgULong Radius ; - ArgFloat Goal ; - ArgBool Force ; - ArgBool SkipDefaultGuesses ; - ArgVerbosity Verbosity ; - ArgDebugCommand DebugCommand ; - ArgBool Check ; - ArgStringList FileList ; - ArgUInt DebugLevel ; - ArgUInt GmlGraphRecDepth ; - ArgUInt GmlStartVertex ; - - std::string getPassphrase (bool doublecheck = false) ; - - private: - typedef std::vector::const_iterator ArgIt ; - - static const int NoCompression = 0 ; - - static const EncryptionAlgorithm Default_EncAlgo ; - static const EncryptionMode Default_EncMode ; - static const bool Default_Checksum = true ; - static const int Default_Compression = 9 ; // slowest, but smallest - static const bool Default_EmbedEmbFn = true ; - static const bool Default_Force = false ; - static const bool Default_SkipDefaultGuesses = false ; - static const VERBOSITY Default_Verbosity = NORMAL ; - static const unsigned long Default_Radius = 0 ; // there is no default radius for all file formats - static const unsigned int Max_Algorithm = 3 ; - static constexpr float Default_Goal = 100.0 ; - static const DEBUGCOMMAND Default_DebugCommand = NONE ; - static const bool Default_Check = false ; - static const unsigned int Default_DebugLevel = 0 ; - static const unsigned int Default_GmlGraphRecDepth = 0 ; - static const unsigned int Default_GmlStartVertex = 0 ; - - /** - * parse the command - * - * Note: parse_Command is the only parse_* function that requires curarg to be a command. - * (because the command is the only argument with a fixed position). - **/ - void parse_Command (ArgIt& curarg) ; - - /** - * Parse arguments based on their positions. - * Will fully ignore any argument starting with - - **/ - void parse_Positional (std::vector) ; - - /** - * Parse arguments starting with a - - **/ - std::vector parse_Arguments (ArgIt& curarg) ; - - /** - * test if curarg points to an emb filename argument and if yes: parse it - * \return true iff one or more arguments have been parsed - **/ - bool parse_EmbFn (ArgIt& curarg) ; - - bool parse_Generic_String (ArgIt& curarg, std::vector compatibleCommands, ArgString* destArg) ; - bool parse_Generic_Bool (ArgIt& curarg, std::vector compatibleCommands, ArgBool* destArg, bool ifMatch) ; - - bool parse_ExtFn (ArgIt& curarg) ; - bool parse_CvrFn (ArgIt& curarg) ; - bool parse_StgFn (ArgIt& curarg) ; - bool parse_WordlistFn (ArgIt& curarg) ; - bool parse_Passphrase (ArgIt& curarg) ; - bool parse_Checksum (ArgIt& curarg) ; - bool parse_Compression (ArgIt& curarg) ; - bool parse_EmbedEmbFn (ArgIt& curarg) ; - bool parse_Encryption (ArgIt& curarg) ; - bool parse_Radius (ArgIt& curarg) ; - bool parse_Goal (ArgIt& curarg) ; - bool parse_Force (ArgIt& curarg) ; - bool parse_Threading (ArgIt& curarg) ; - bool parse_Verbosity (ArgIt& curarg) ; - bool parse_Debug (ArgIt& curarg) ; - - void setDefaults (void) ; - - std::vector TheArguments ; -} ; + public: + Arguments(void){}; + + /** + * initialize this Arguments object with argc and argv + **/ + Arguments(int argc, char *argv[]); + + /** + * parse Argc and Argv filling the Arg* member variable for later access + **/ + void parse(void); + + /** + * is standard input used ? - according to the given arguments + **/ + bool stdin_isused(void) const; + + /// the command to be executed in this session + ArgCommand Command; + /// the name of the command to be executed in this session (as supplied by the user) + std::string CommandString; + + /// the embed file name, "" if stdin + ArgString EmbFn; + /// the extract file name, "" if stdout + ArgString ExtFn; + /// the cover file name, "" if stdin + ArgString CvrFn; + /// the stego file name, "" if stdout/stdin + ArgString StgFn; + /// the wordlist file name, "" if stdout/stdin + ArgString WordlistFn; + ArgString Passphrase; + ArgBool Checksum; + ArgInt Compression; + ArgInt Threads; + ArgBool EmbedEmbFn; + ArgEncAlgo EncAlgo; + ArgEncMode EncMode; + ArgULong Radius; + ArgFloat Goal; + ArgBool Force; + ArgBool SkipDefaultGuesses; + ArgVerbosity Verbosity; + ArgDebugCommand DebugCommand; + ArgBool Check; + ArgStringList FileList; + ArgUInt DebugLevel; + ArgUInt GmlGraphRecDepth; + ArgUInt GmlStartVertex; + + std::string getPassphrase(bool doublecheck = false); + + private: + typedef std::vector::const_iterator ArgIt; + + static const int NoCompression = 0; + + static const EncryptionAlgorithm Default_EncAlgo; + static const EncryptionMode Default_EncMode; + static const bool Default_Checksum = true; + static const int Default_Compression = 9; // slowest, but smallest + static const bool Default_EmbedEmbFn = true; + static const bool Default_Force = false; + static const bool Default_SkipDefaultGuesses = false; + static const VERBOSITY Default_Verbosity = NORMAL; + static const unsigned long Default_Radius = + 0; // there is no default radius for all file formats + static const unsigned int Max_Algorithm = 3; + static constexpr float Default_Goal = 100.0; + static const DEBUGCOMMAND Default_DebugCommand = NONE; + static const bool Default_Check = false; + static const unsigned int Default_DebugLevel = 0; + static const unsigned int Default_GmlGraphRecDepth = 0; + static const unsigned int Default_GmlStartVertex = 0; + + /** + * parse the command + * + * Note: parse_Command is the only parse_* function that requires curarg to be a command. + * (because the command is the only argument with a fixed position). + **/ + void parse_Command(ArgIt &curarg); + + /** + * Parse arguments based on their positions. + * Will fully ignore any argument starting with - + **/ + void parse_Positional(std::vector); + + /** + * Parse arguments starting with a - + **/ + std::vector parse_Arguments(ArgIt &curarg); + + /** + * test if curarg points to an emb filename argument and if yes: parse it + * \return true iff one or more arguments have been parsed + **/ + bool parse_EmbFn(ArgIt &curarg); + + bool parse_Generic_String(ArgIt &curarg, std::vector compatibleCommands, + ArgString *destArg); + bool parse_Generic_Bool(ArgIt &curarg, std::vector compatibleCommands, + ArgBool *destArg, bool ifMatch); + + bool parse_ExtFn(ArgIt &curarg); + bool parse_CvrFn(ArgIt &curarg); + bool parse_StgFn(ArgIt &curarg); + bool parse_WordlistFn(ArgIt &curarg); + bool parse_Passphrase(ArgIt &curarg); + bool parse_Checksum(ArgIt &curarg); + bool parse_Compression(ArgIt &curarg); + bool parse_EmbedEmbFn(ArgIt &curarg); + bool parse_Encryption(ArgIt &curarg); + bool parse_Radius(ArgIt &curarg); + bool parse_Goal(ArgIt &curarg); + bool parse_Force(ArgIt &curarg); + bool parse_Threading(ArgIt &curarg); + bool parse_Verbosity(ArgIt &curarg); + bool parse_Debug(ArgIt &curarg); + + void setDefaults(void); + + std::vector TheArguments; +}; // gcc does not support the export keyword #include "Arg.cc" diff --git a/src/AssertionFailed.cc b/src/AssertionFailed.cc index 9f6d217..b508a9d 100644 --- a/src/AssertionFailed.cc +++ b/src/AssertionFailed.cc @@ -21,35 +21,33 @@ * a significant amount of changes and bugs in stegseek might not be his fault. */ -#include #include "AssertionFailed.h" +#include -void AssertionFailed::printMessage () const -{ - printf ("\n") ; - SteghideError::printMessage() ; - printf (_("This means that you have found a bug. Please open an issue on Github\n" - "if you have a way to reproduce the error.\n" - "Stegseek has to exit now. Sorry.\n")) ; +void AssertionFailed::printMessage() const { + printf("\n"); + SteghideError::printMessage(); + printf(_("This means that you have found a bug. Please open an issue on Github\n" + "if you have a way to reproduce the error.\n" + "Stegseek has to exit now. Sorry.\n")); } -char* AssertionFailed::stripDir (const char *fn) -{ - int i = 0, j = 0, start = 0, end = 0 ; +char *AssertionFailed::stripDir(const char *fn) { + int i = 0, j = 0, start = 0, end = 0; - end = i = strlen (fn) - 1 ; + end = i = strlen(fn) - 1; while ((i >= 0) && (fn[i] != '\\') && (fn[i] != '/')) { - i-- ; + i--; } - start = i + 1 ; + start = i + 1; - char* retval = (char *) malloc (end - start + 2) ; + char *retval = (char *)malloc(end - start + 2); - j = 0 ; - for (i = start ; i <= end ; i++, j++) { - retval[j] = fn [i] ; + j = 0; + for (i = start; i <= end; i++, j++) { + retval[j] = fn[i]; } - retval[j] = '\0' ; + retval[j] = '\0'; - return retval ; + return retval; } diff --git a/src/AssertionFailed.h b/src/AssertionFailed.h index 7c28a3c..342a9f1 100644 --- a/src/AssertionFailed.h +++ b/src/AssertionFailed.h @@ -21,18 +21,18 @@ #ifndef SH_ASSERTIONFAILED_H #define SH_ASSERTIONFAILED_H -#include "common.h" #include "SteghideError.h" +#include "common.h" class AssertionFailed : public SteghideError { - public: - AssertionFailed (const char* fn, unsigned int l) - : SteghideError(_("assertion failed in %s at line number %d."), stripDir(fn), l) {} ; + public: + AssertionFailed(const char *fn, unsigned int l) + : SteghideError(_("assertion failed in %s at line number %d."), stripDir(fn), l){}; - void printMessage (void) const ; + void printMessage(void) const; - private: - char* stripDir (const char* fn) ; -} ; + private: + char *stripDir(const char *fn); +}; #endif // ndef SH_ASSERTION_FAILED diff --git a/src/AuData.h b/src/AuData.h index d287c5a..efe6270 100644 --- a/src/AuData.h +++ b/src/AuData.h @@ -21,27 +21,39 @@ #ifndef SH_AUDATA_H #define SH_AUDATA_H -#include "BinaryIO.h" #include "AudioData.h" +#include "BinaryIO.h" // AuMuLawAudioData -typedef AudioDataImpl AuMuLawAudioData ; -template<> inline BYTE AuMuLawAudioData::readValue (BinaryIO* io) const { return (io->read8()) ; } -template<> inline void AuMuLawAudioData::writeValue (BinaryIO* io, BYTE v) const { io->write8(v) ; } +typedef AudioDataImpl AuMuLawAudioData; +template <> inline BYTE AuMuLawAudioData::readValue(BinaryIO *io) const { return (io->read8()); } +template <> inline void AuMuLawAudioData::writeValue(BinaryIO *io, BYTE v) const { io->write8(v); } // AuPCM8AudioData -typedef AudioDataImpl AuPCM8AudioData ; -template<> inline SBYTE AuPCM8AudioData::readValue (BinaryIO* io) const { return ((SBYTE) io->read8()) ; } -template<> inline void AuPCM8AudioData::writeValue (BinaryIO* io, SBYTE v) const { io->write8((BYTE) v) ; } +typedef AudioDataImpl AuPCM8AudioData; +template <> inline SBYTE AuPCM8AudioData::readValue(BinaryIO *io) const { + return ((SBYTE)io->read8()); +} +template <> inline void AuPCM8AudioData::writeValue(BinaryIO *io, SBYTE v) const { + io->write8((BYTE)v); +} // AuPCM16AudioData -typedef AudioDataImpl AuPCM16AudioData ; -template<> inline SWORD16 AuPCM16AudioData::readValue (BinaryIO* io) const { return ((SWORD16) io->read16_be()) ; } -template<> inline void AuPCM16AudioData::writeValue (BinaryIO* io, SWORD16 v) const { io->write16_be((UWORD16) v) ; } +typedef AudioDataImpl AuPCM16AudioData; +template <> inline SWORD16 AuPCM16AudioData::readValue(BinaryIO *io) const { + return ((SWORD16)io->read16_be()); +} +template <> inline void AuPCM16AudioData::writeValue(BinaryIO *io, SWORD16 v) const { + io->write16_be((UWORD16)v); +} // AuPCM32AudioData -typedef AudioDataImpl AuPCM32AudioData ; -template<> inline SWORD32 AuPCM32AudioData::readValue (BinaryIO* io) const { return ((SWORD32) io->read32_be()) ; } -template<> inline void AuPCM32AudioData::writeValue (BinaryIO* io, SWORD32 v) const { io->write32_be((UWORD32) v) ; } +typedef AudioDataImpl AuPCM32AudioData; +template <> inline SWORD32 AuPCM32AudioData::readValue(BinaryIO *io) const { + return ((SWORD32)io->read32_be()); +} +template <> inline void AuPCM32AudioData::writeValue(BinaryIO *io, SWORD32 v) const { + io->write32_be((UWORD32)v); +} #endif // ndef SH_AUDATA_H diff --git a/src/AuFile.cc b/src/AuFile.cc index 48e0f3a..d412d4d 100644 --- a/src/AuFile.cc +++ b/src/AuFile.cc @@ -21,6 +21,7 @@ #include #include #include +#include #include #include "AuData.h" @@ -33,198 +34,189 @@ #include "common.h" #include "error.h" -AuFile::AuFile (BinaryIO *io) - : CvrStgFile() -{ - setSamplesPerVertex (SamplesPerVertex) ; - setEmbValueModulus (EmbValueModulus) ; - read (io) ; +AuFile::AuFile(BinaryIO *io) : CvrStgFile() { + setSamplesPerVertex(SamplesPerVertex); + setEmbValueModulus(EmbValueModulus); + read(io); } -AuFile::~AuFile (void) -{ - delete Data ; +AuFile::~AuFile(void) { delete Data; } + +void AuFile::read(BinaryIO *io) { + CvrStgFile::read(io); + + try { + Header.id[0] = '.'; + Header.id[1] = 's'; + Header.id[2] = 'n'; + Header.id[3] = 'd'; + + // read header + Header.offset = getBinIO()->read32_be(); + Header.size = getBinIO()->read32_be(); + UWORD32 encoding = getBinIO()->read32_be(); + Header.samplerate = getBinIO()->read32_be(); + Header.channels = getBinIO()->read32_be(); + + // read infofield + unsigned long leninfofield = Header.offset - AuHeader::HeaderSize; + if (leninfofield > 0) { + Infofield.resize(leninfofield); + for (unsigned long i = 0; i < leninfofield; i++) { + Infofield[i] = getBinIO()->read8(); + } + } + + // read data + switch (encoding) { + case MULAW8: + setRadius(Radius_MuLaw8); + Data = new AuMuLawAudioData(this); + break; + + case PCM8: + setRadius(Radius_PCM8); + Data = new AuPCM8AudioData(this); + break; + + case PCM16: + setRadius(Radius_PCM16); + Data = new AuPCM16AudioData(this); + break; + + default: + if (getBinIO()->is_std()) { + throw NotImplementedError( + _("the au file on standard input uses the unknown encoding %d."), encoding); + } else { + throw NotImplementedError(_("the au file \"%s\" uses the unknown encoding %d."), + getBinIO()->getName().c_str(), encoding); + } + break; + }; + Header.encoding = (ENCODING)encoding; + } catch (BinaryInputError e) { + switch (e.getType()) { + case BinaryInputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while reading the au headers from the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::FILE_EOF: { + throw SteghideError(_("premature end of file \"%s\" while reading au headers."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::STDIN_ERR: { + throw SteghideError( + _("an error occurred while reading the au headers from standard input.")); + break; + } + + case BinaryInputError::STDIN_EOF: { + throw SteghideError( + _("premature end of data from standard input while reading au headers.")); + break; + } + } + } + + // if available, use size of audio data, else read until eof + unsigned long n = AudioData::NoLimit; + if (Header.size != AuHeader::SizeUnknown) { + myassert(Header.size % Header.getBytesPerSample() == 0); + n = Header.size / Header.getBytesPerSample(); + } + Data->read(getBinIO(), n); } -void AuFile::read (BinaryIO *io) -{ - CvrStgFile::read (io) ; - - try { - Header.id[0] = '.' ; - Header.id[1] = 's' ; - Header.id[2] = 'n' ; - Header.id[3] = 'd' ; - - // read header - Header.offset = getBinIO()->read32_be() ; - Header.size = getBinIO()->read32_be() ; - UWORD32 encoding = getBinIO()->read32_be() ; - Header.samplerate = getBinIO()->read32_be() ; - Header.channels = getBinIO()->read32_be() ; - - // read infofield - unsigned long leninfofield = Header.offset - AuHeader::HeaderSize ; - if (leninfofield > 0) { - Infofield.resize (leninfofield) ; - for (unsigned long i = 0 ; i < leninfofield ; i++) { - Infofield[i] = getBinIO()->read8() ; - } - } - - // read data - switch (encoding) { - case MULAW8: - setRadius (Radius_MuLaw8) ; - Data = new AuMuLawAudioData (this) ; - break ; - - case PCM8: - setRadius (Radius_PCM8) ; - Data = new AuPCM8AudioData (this) ; - break ; - - case PCM16: - setRadius (Radius_PCM16) ; - Data = new AuPCM16AudioData (this) ; - break ; - - default: - if (getBinIO()->is_std()) { - throw NotImplementedError (_("the au file on standard input uses the unknown encoding %d."), encoding) ; - } - else { - throw NotImplementedError (_("the au file \"%s\" uses the unknown encoding %d."), getBinIO()->getName().c_str(), encoding) ; - } - break ; - } ; - Header.encoding = (ENCODING) encoding ; - } - catch (BinaryInputError e) { - switch (e.getType()) { - case BinaryInputError::FILE_ERR: - { - throw SteghideError (_("an error occurred while reading the au headers from the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; - } - - case BinaryInputError::FILE_EOF: - { - throw SteghideError (_("premature end of file \"%s\" while reading au headers."), getBinIO()->getName().c_str()) ; - break ; - } - - case BinaryInputError::STDIN_ERR: - { - throw SteghideError (_("an error occurred while reading the au headers from standard input.")) ; - break ; - } - - case BinaryInputError::STDIN_EOF: - { - throw SteghideError (_("premature end of data from standard input while reading au headers.")) ; - break ; - } - } - } - - // if available, use size of audio data, else read until eof - unsigned long n = AudioData::NoLimit ; - if (Header.size != AuHeader::SizeUnknown) { - myassert (Header.size % Header.getBytesPerSample() == 0) ; - n = Header.size / Header.getBytesPerSample() ; - } - Data->read (getBinIO(), n) ; +void AuFile::write() { + CvrStgFile::write(); + + try { + // write header + getBinIO()->write8(Header.id[0]); + getBinIO()->write8(Header.id[1]); + getBinIO()->write8(Header.id[2]); + getBinIO()->write8(Header.id[3]); + getBinIO()->write32_be(Header.offset); + getBinIO()->write32_be(Header.size); + getBinIO()->write32_be((UWORD32)Header.encoding); + getBinIO()->write32_be(Header.samplerate); + getBinIO()->write32_be(Header.channels); + + // write infofield + for (unsigned long i = 0; i < Infofield.size(); i++) { + getBinIO()->write8(Infofield[i]); + } + } catch (BinaryOutputError e) { + switch (e.getType()) { + case BinaryOutputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while writing the au headers to the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryOutputError::STDOUT_ERR: { + throw SteghideError( + _("an error occurred while writing the au headers to standard output.")); + break; + } + } + } + + Data->write(getBinIO(), AudioData::NoLimit); } -void AuFile::write () -{ - CvrStgFile::write() ; - - try { - // write header - getBinIO()->write8 (Header.id[0]) ; - getBinIO()->write8 (Header.id[1]) ; - getBinIO()->write8 (Header.id[2]) ; - getBinIO()->write8 (Header.id[3]) ; - getBinIO()->write32_be (Header.offset) ; - getBinIO()->write32_be (Header.size) ; - getBinIO()->write32_be ((UWORD32) Header.encoding) ; - getBinIO()->write32_be (Header.samplerate) ; - getBinIO()->write32_be (Header.channels) ; - - // write infofield - for (unsigned long i = 0 ; i < Infofield.size() ; i++) { - getBinIO()->write8 (Infofield[i]) ; - } - } - catch (BinaryOutputError e) { - switch (e.getType()) { - case BinaryOutputError::FILE_ERR: - { - throw SteghideError (_("an error occurred while writing the au headers to the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; - } - - case BinaryOutputError::STDOUT_ERR: - { - throw SteghideError (_("an error occurred while writing the au headers to standard output.")) ; - break ; - } - } - } - - Data->write (getBinIO(), AudioData::NoLimit) ; -} +std::list AuFile::getProperties() const { + std::list retval; + + // format + std::string formatstring = "au audio"; + switch (Header.encoding) { + case MULAW8: + formatstring += _(", mu-law encoding"); + break; + + case PCM8: + case PCM16: + formatstring += _(", PCM encoding"); + break; + } + retval.push_back(CvrStgFile::Property(_("format"), formatstring)); -std::list AuFile::getProperties () const -{ - std::list retval ; - - // format - std::string formatstring = "au audio" ; - switch (Header.encoding) { - case MULAW8: - formatstring += _(", mu-law encoding") ; - break ; - - case PCM8: - case PCM16: - formatstring += _(", PCM encoding") ; - break ; - } - retval.push_back (CvrStgFile::Property (_("format"), formatstring)) ; - - return retval ; + return retval; } -unsigned short AuFile::AuHeader::getBytesPerSample () const -{ - unsigned short retval = 0 ; - switch (encoding) { - case MULAW8: - retval = 1 ; - break ; - - case PCM8: - retval = 1 ; - break ; - - case PCM16: - retval = 2 ; - break ; - - default: - myassert(0) ; - break ; - } - return retval ; +unsigned short AuFile::AuHeader::getBytesPerSample() const { + unsigned short retval = 0; + switch (encoding) { + case MULAW8: + retval = 1; + break; + + case PCM8: + retval = 1; + break; + + case PCM16: + retval = 2; + break; + + default: + myassert(0); + break; + } + return retval; } -std::vector AuFile::getMatchingAlgorithms (Graph* g, Matching* m) const -{ - std::vector retval ; - retval.push_back (new SMDConstructionHeuristic (g, m)) ; - retval.push_back (new DFSAPHeuristic (g, m)) ; - return retval ; +std::vector AuFile::getMatchingAlgorithms(Graph *g, Matching *m) const { + std::vector retval; + retval.push_back(new SMDConstructionHeuristic(g, m)); + retval.push_back(new DFSAPHeuristic(g, m)); + return retval; } diff --git a/src/AuFile.h b/src/AuFile.h index 92eca92..6d519f1 100644 --- a/src/AuFile.h +++ b/src/AuFile.h @@ -26,58 +26,57 @@ #include "AudioData.h" #include "CvrStgFile.h" -class BinaryIO ; +class BinaryIO; /** * \class AuFile * \brief a CvrStgFile in Sun .au format **/ class AuFile : public CvrStgFile { - public: - AuFile (BinaryIO *io) ; - ~AuFile (void) ; - - void read (BinaryIO *io) ; - void write (void) ; - - std::list getProperties (void) const ; - std::vector getMatchingAlgorithms (Graph* g, Matching* m) const ; - - unsigned long getNumSamples (void) const - { return Data->getNumSamples() ; } ; - - void replaceSample (const SamplePos pos, const SampleValue* s) - { return Data->replaceSample(pos, s) ; } ; - - SampleValue* getSampleValue (SamplePos pos) const - { return Data->getSampleValue(pos) ; } ; - - private: - enum ENCODING { MULAW8 = 1, PCM8 = 2, PCM16 = 3 } ; - class AuHeader { - public: - char id[4] ; - UWORD32 offset ; - UWORD32 size ; - ENCODING encoding ; - UWORD32 samplerate ; - UWORD32 channels ; - - static const UWORD32 SizeUnknown = 0xFFFFFFFF ; - static const unsigned short HeaderSize = 24 ; - - unsigned short getBytesPerSample (void) const ; - } ; - - static const UWORD32 Radius_MuLaw8 = 1 ; - static const UWORD32 Radius_PCM8 = 1 ; - static const UWORD32 Radius_PCM16 = 20 ; - static const unsigned short SamplesPerVertex = 2 ; - static const EmbValue EmbValueModulus = 2 ; - - AuHeader Header ; - std::vector Infofield ; - AudioData* Data ; -} ; + public: + AuFile(BinaryIO *io); + ~AuFile(void); + + void read(BinaryIO *io); + void write(void); + + std::list getProperties(void) const; + std::vector getMatchingAlgorithms(Graph *g, Matching *m) const; + + unsigned long getNumSamples(void) const { return Data->getNumSamples(); }; + + void replaceSample(const SamplePos pos, const SampleValue *s) { + return Data->replaceSample(pos, s); + }; + + SampleValue *getSampleValue(SamplePos pos) const { return Data->getSampleValue(pos); }; + + private: + enum ENCODING { MULAW8 = 1, PCM8 = 2, PCM16 = 3 }; + class AuHeader { + public: + char id[4]; + UWORD32 offset; + UWORD32 size; + ENCODING encoding; + UWORD32 samplerate; + UWORD32 channels; + + static const UWORD32 SizeUnknown = 0xFFFFFFFF; + static const unsigned short HeaderSize = 24; + + unsigned short getBytesPerSample(void) const; + }; + + static const UWORD32 Radius_MuLaw8 = 1; + static const UWORD32 Radius_PCM8 = 1; + static const UWORD32 Radius_PCM16 = 20; + static const unsigned short SamplesPerVertex = 2; + static const EmbValue EmbValueModulus = 2; + + AuHeader Header; + std::vector Infofield; + AudioData *Data; +}; #endif /* ndef SH_AUFILE_H */ diff --git a/src/AuSampleValues.cc b/src/AuSampleValues.cc index f5b4ff5..55e9f83 100644 --- a/src/AuSampleValues.cc +++ b/src/AuSampleValues.cc @@ -21,17 +21,17 @@ #include "AuSampleValues.h" // AuMuLawSampleValue -template<> const BYTE AuMuLawSampleValue::MinValue = 0 ; -template<> const BYTE AuMuLawSampleValue::MaxValue = BYTE_MAX ; +template <> const BYTE AuMuLawSampleValue::MinValue = 0; +template <> const BYTE AuMuLawSampleValue::MaxValue = BYTE_MAX; // AuPCM8SampleValue -template<> const SBYTE AuPCM8SampleValue::MinValue = SBYTE_MIN ; -template<> const SBYTE AuPCM8SampleValue::MaxValue = SBYTE_MAX ; +template <> const SBYTE AuPCM8SampleValue::MinValue = SBYTE_MIN; +template <> const SBYTE AuPCM8SampleValue::MaxValue = SBYTE_MAX; // AuPCM16SampleValue -template<> const SWORD16 AuPCM16SampleValue::MinValue = SWORD16_MIN ; -template<> const SWORD16 AuPCM16SampleValue::MaxValue = SWORD16_MAX ; +template <> const SWORD16 AuPCM16SampleValue::MinValue = SWORD16_MIN; +template <> const SWORD16 AuPCM16SampleValue::MaxValue = SWORD16_MAX; // AuPCM32SampleValue -template<> const SWORD32 AuPCM32SampleValue::MinValue = SWORD32_MIN ; -template<> const SWORD32 AuPCM32SampleValue::MaxValue = SWORD32_MAX ; +template <> const SWORD32 AuPCM32SampleValue::MinValue = SWORD32_MIN; +template <> const SWORD32 AuPCM32SampleValue::MaxValue = SWORD32_MAX; diff --git a/src/AuSampleValues.h b/src/AuSampleValues.h index 4fbc804..a099fec 100644 --- a/src/AuSampleValues.h +++ b/src/AuSampleValues.h @@ -23,9 +23,9 @@ #include "AudioSampleValue.h" -typedef AudioSampleValue AuMuLawSampleValue ; -typedef AudioSampleValue AuPCM8SampleValue ; -typedef AudioSampleValue AuPCM16SampleValue ; -typedef AudioSampleValue AuPCM32SampleValue ; +typedef AudioSampleValue AuMuLawSampleValue; +typedef AudioSampleValue AuPCM8SampleValue; +typedef AudioSampleValue AuPCM16SampleValue; +typedef AudioSampleValue AuPCM32SampleValue; #endif // ndef SH_AUSAMPLEVALUES_H diff --git a/src/AudioData.h b/src/AudioData.h index 79c5443..e9b84e1 100644 --- a/src/AudioData.h +++ b/src/AudioData.h @@ -24,7 +24,7 @@ #include #include "AudioSampleValue.h" -class BinaryIO ; +class BinaryIO; #include "CvrStgObject.h" /** @@ -35,135 +35,132 @@ class BinaryIO ; * of audio data, i.e. all different instances of AudioDataImpl. **/ class AudioData : public CvrStgObject { - public: - /// constant that can be used as parameter to read and write to indicate that there is no limit - static const UWORD32 NoLimit = 0 ; + public: + /// constant that can be used as parameter to read and write to indicate that there is no limit + static const UWORD32 NoLimit = 0; - virtual void read (BinaryIO* io, UWORD32 n = NoLimit) = 0 ; - virtual void write (BinaryIO* io, UWORD32 n = NoLimit) = 0 ; -} ; + virtual void read(BinaryIO *io, UWORD32 n = NoLimit) = 0; + virtual void write(BinaryIO *io, UWORD32 n = NoLimit) = 0; +}; /** * \class AudioDataImpl * \brief implementation of the AudioData-Interface **/ -template > +template > class AudioDataImpl : public AudioData { - public: - AudioDataImpl (CvrStgFile* f) : TheCvrStgFile(f) {} ; - virtual ~AudioDataImpl (void) {} ; + public: + AudioDataImpl(CvrStgFile *f) : TheCvrStgFile(f){}; + virtual ~AudioDataImpl(void){}; - void read (BinaryIO* io, UWORD32 n = AudioData::NoLimit) ; - void write (BinaryIO* io, UWORD32 n = AudioData::NoLimit) ; + void read(BinaryIO *io, UWORD32 n = AudioData::NoLimit); + void write(BinaryIO *io, UWORD32 n = AudioData::NoLimit); - unsigned long getNumSamples (void) const ; - SampleValue* getSampleValue (const SamplePos pos) const ; - void replaceSample (const SamplePos pos, const SampleValue* s) ; + unsigned long getNumSamples(void) const; + SampleValue *getSampleValue(const SamplePos pos) const; + void replaceSample(const SamplePos pos, const SampleValue *s); - private: - std::vector Data ; - CvrStgFile* TheCvrStgFile ; + private: + std::vector Data; + CvrStgFile *TheCvrStgFile; - ValueType readValue (BinaryIO* io) const ; - void writeValue (BinaryIO* io, ValueType v) const ; -} ; + ValueType readValue(BinaryIO *io) const; + void writeValue(BinaryIO *io, ValueType v) const; +}; #include "error.h" -template -void AudioDataImpl::read (BinaryIO* io, UWORD32 n) -{ - try { - if (n == NoLimit) { - Data.clear() ; - while (!io->eof()) { - Data.push_back (readValue(io)) ; - } - } - else { - Data.resize (n) ; - for (UWORD32 i = 0 ; i < n ; i++) { - Data[i] = readValue(io) ; - } - } - } - catch (BinaryInputError e) { - switch (e.getType()) { - case BinaryInputError::FILE_ERR: - { - throw SteghideError (_("an error occurred while reading the audio data from the file \"%s\"."), io->getName().c_str()) ; - break ; - } - - case BinaryInputError::FILE_EOF: - { - throw SteghideError (_("premature end of file \"%s\" while reading audio data."), io->getName().c_str()) ; - break ; - } - - case BinaryInputError::STDIN_ERR: - { - throw SteghideError (_("an error occurred while reading the audio data from standard input.")) ; - break ; - } - - case BinaryInputError::STDIN_EOF: - { - throw SteghideError (_("premature end of data from standard input while reading audio data.")) ; - break ; - } - } - } +template +void AudioDataImpl::read(BinaryIO *io, UWORD32 n) { + try { + if (n == NoLimit) { + Data.clear(); + while (!io->eof()) { + Data.push_back(readValue(io)); + } + } else { + Data.resize(n); + for (UWORD32 i = 0; i < n; i++) { + Data[i] = readValue(io); + } + } + } catch (BinaryInputError e) { + switch (e.getType()) { + case BinaryInputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while reading the audio data from the file \"%s\"."), + io->getName().c_str()); + break; + } + + case BinaryInputError::FILE_EOF: { + throw SteghideError(_("premature end of file \"%s\" while reading audio data."), + io->getName().c_str()); + break; + } + + case BinaryInputError::STDIN_ERR: { + throw SteghideError( + _("an error occurred while reading the audio data from standard input.")); + break; + } + + case BinaryInputError::STDIN_EOF: { + throw SteghideError( + _("premature end of data from standard input while reading audio data.")); + break; + } + } + } } -template -void AudioDataImpl::write (BinaryIO* io, UWORD32 n) -{ - try { - if (n == NoLimit) { - n = Data.size() ; - } - for (UWORD32 i = 0 ; i < n ; i++) { - writeValue (io, Data[i]) ; - } - } - catch (BinaryOutputError e) { - switch (e.getType()) { - case BinaryOutputError::FILE_ERR: - { - throw SteghideError (_("an error occurred while writing the audio data to the file \"%s\"."), io->getName().c_str()) ; - break ; - } - - case BinaryOutputError::STDOUT_ERR: - { - throw SteghideError (_("an error occurred while writing the audio data to standard output.")) ; - break ; - } - } - } +template +void AudioDataImpl::write(BinaryIO *io, UWORD32 n) { + try { + if (n == NoLimit) { + n = Data.size(); + } + for (UWORD32 i = 0; i < n; i++) { + writeValue(io, Data[i]); + } + } catch (BinaryOutputError e) { + switch (e.getType()) { + case BinaryOutputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while writing the audio data to the file \"%s\"."), + io->getName().c_str()); + break; + } + + case BinaryOutputError::STDOUT_ERR: { + throw SteghideError( + _("an error occurred while writing the audio data to standard output.")); + break; + } + } + } } -template -unsigned long AudioDataImpl::getNumSamples (void) const -{ - return Data.size() ; +template +unsigned long AudioDataImpl::getNumSamples(void) const { + return Data.size(); } -template -SampleValue* AudioDataImpl::getSampleValue (const SamplePos pos) const -{ - myassert (pos < Data.size()) ; - return ((SampleValue*) new SampleValueType (Data[pos])) ; +template +SampleValue * +AudioDataImpl::getSampleValue(const SamplePos pos) const { + myassert(pos < Data.size()); + return ((SampleValue *)new SampleValueType(Data[pos])); } -template -void AudioDataImpl::replaceSample (const SamplePos pos, const SampleValue* s) -{ - const SampleValueType* sample = dynamic_cast (s) ; - myassert (sample) ; - myassert (pos < Data.size()) ; - Data[pos] = sample->getValue() ; +template +void AudioDataImpl::replaceSample(const SamplePos pos, + const SampleValue *s) { + const SampleValueType *sample = dynamic_cast(s); + myassert(sample); + myassert(pos < Data.size()); + Data[pos] = sample->getValue(); } #endif // ndef SH_AUDIODATA_H diff --git a/src/AudioSampleValue.h b/src/AudioSampleValue.h index 2414e11..62d707b 100644 --- a/src/AudioSampleValue.h +++ b/src/AudioSampleValue.h @@ -31,106 +31,98 @@ * identify the correct implementation for a given audio format. **/ enum AUDIOSAMPLETYPE { - /// au 8 Bit mu-law - AuMuLaw, - /// au 8 Bit linear pcm - AuPCM8, - /// au 16 Bit linear pcm - AuPCM16, - /// au 32 Bit linear pcm - AuPCM32 -} ; + /// au 8 Bit mu-law + AuMuLaw, + /// au 8 Bit linear pcm + AuPCM8, + /// au 16 Bit linear pcm + AuPCM16, + /// au 32 Bit linear pcm + AuPCM32 +}; /** * \class AudioSampleValue * \brief a class representing an audio sample **/ -template -class AudioSampleValue : public SampleValue { - public: - AudioSampleValue (ValueType v) ; - - ValueType getValue (void) const { return Value ; } ; - - SampleValue* getNearestTargetSampleValue (EmbValue t) const ; - UWORD32 calcDistance (const SampleValue* s) const ; - std::string getName (void) const ; - - private: - ValueType Value ; - static const ValueType MinValue ; - static const ValueType MaxValue ; - - UWORD32 calcKey (ValueType v) const { return (v - MinValue) ; } ; - EmbValue calcEValue (ValueType v) const { return ((EmbValue) ((v - MinValue) % Globs.TheCvrStgFile->getEmbValueModulus())) ; } ; -} ; - -template -AudioSampleValue::AudioSampleValue (ValueType v) - : SampleValue(), Value(v) -{ - Key = calcKey(v) ; - EValue = calcEValue(v) ; +template class AudioSampleValue : public SampleValue { + public: + AudioSampleValue(ValueType v); + + ValueType getValue(void) const { return Value; }; + + SampleValue *getNearestTargetSampleValue(EmbValue t) const; + UWORD32 calcDistance(const SampleValue *s) const; + std::string getName(void) const; + + private: + ValueType Value; + static const ValueType MinValue; + static const ValueType MaxValue; + + UWORD32 calcKey(ValueType v) const { return (v - MinValue); }; + EmbValue calcEValue(ValueType v) const { + return ((EmbValue)((v - MinValue) % Globs.TheCvrStgFile->getEmbValueModulus())); + }; +}; + +template +AudioSampleValue::AudioSampleValue(ValueType v) : SampleValue(), Value(v) { + Key = calcKey(v); + EValue = calcEValue(v); } -template -UWORD32 AudioSampleValue::calcDistance (const SampleValue* s) const -{ - const AudioSampleValue* sample = (const AudioSampleValue*) s ; - /* If s is not a correct AudioSampleValue then we get into real trouble here. - But calcDistance is called very often, a dynamic_cast costs a lot of time and - it does not make sense to pass anything but a correct AudioSampleValue as s anyway. */ - - if (sample->Value > Value) { - return sample->Value - Value ; - } - else { - return Value - sample->Value ; - } +template +UWORD32 AudioSampleValue::calcDistance(const SampleValue *s) const { + const AudioSampleValue *sample = (const AudioSampleValue *)s; + /* If s is not a correct AudioSampleValue then we get into real trouble here. + But calcDistance is called very often, a dynamic_cast costs a lot of time and + it does not make sense to pass anything but a correct AudioSampleValue as s anyway. */ + + if (sample->Value > Value) { + return sample->Value - Value; + } else { + return Value - sample->Value; + } } -template -SampleValue* AudioSampleValue::getNearestTargetSampleValue (EmbValue t) const -{ - ValueType val_up = Value, val_down = Value, newval = 0 ; - bool found = false ; - - do { - if (val_up < MaxValue) { - val_up++ ; - } - if (val_down > MinValue) { - val_down-- ; - } - - if (calcEValue(val_up) == t && calcEValue(val_down) == t) { - if (RndSrc.getBool()) { - newval = val_up ; - } - else { - newval = val_down ; - } - found = true ; - } - else if (calcEValue(val_up) == t) { - newval = val_up ; - found = true ; - } - else if (calcEValue(val_down) == t) { - newval = val_down ; - found = true ; - } - } while (!found) ; - - return ((SampleValue *) new AudioSampleValue (newval)) ; +template +SampleValue *AudioSampleValue::getNearestTargetSampleValue(EmbValue t) const { + ValueType val_up = Value, val_down = Value, newval = 0; + bool found = false; + + do { + if (val_up < MaxValue) { + val_up++; + } + if (val_down > MinValue) { + val_down--; + } + + if (calcEValue(val_up) == t && calcEValue(val_down) == t) { + if (RndSrc.getBool()) { + newval = val_up; + } else { + newval = val_down; + } + found = true; + } else if (calcEValue(val_up) == t) { + newval = val_up; + found = true; + } else if (calcEValue(val_down) == t) { + newval = val_down; + found = true; + } + } while (!found); + + return ((SampleValue *)new AudioSampleValue(newval)); } -template -std::string AudioSampleValue::getName (void) const -{ - char buf[128] ; - sprintf (buf, "%ld", (long) Value) ; - return std::string (buf) ; +template +std::string AudioSampleValue::getName(void) const { + char buf[128]; + sprintf(buf, "%ld", (long)Value); + return std::string(buf); } #endif // ndef SH_AUDIOSAMPLEVALUE_H diff --git a/src/BFSAPHeuristic.cc b/src/BFSAPHeuristic.cc index 05dc3a7..e8dcc4f 100644 --- a/src/BFSAPHeuristic.cc +++ b/src/BFSAPHeuristic.cc @@ -25,130 +25,132 @@ #include "Matching.h" #include "common.h" -BFSAPHeuristic::BFSAPHeuristic (Graph* g, Matching* m) - : MatchingAlgorithm (g, m, 100.0) -{ - unsigned long numvertices = g->getNumVertices() ; - - VertexVisited = new bool[numvertices] ; - BackEdge = new Edge[numvertices] ; - for (VertexLabel l = 0 ; l < numvertices ; l++) { - VertexVisited[l] = false ; - } +BFSAPHeuristic::BFSAPHeuristic(Graph *g, Matching *m) : MatchingAlgorithm(g, m, 100.0) { + unsigned long numvertices = g->getNumVertices(); + + VertexVisited = new bool[numvertices]; + BackEdge = new Edge[numvertices]; + for (VertexLabel l = 0; l < numvertices; l++) { + VertexVisited[l] = false; + } } -BFSAPHeuristic::~BFSAPHeuristic () -{ - delete[] VertexVisited ; - delete[] BackEdge ; +BFSAPHeuristic::~BFSAPHeuristic() { + delete[] VertexVisited; + delete[] BackEdge; } -void BFSAPHeuristic::run () -{ - const Edge** path = new const Edge*[TheGraph->getNumVertices()] ; +void BFSAPHeuristic::run() { + const Edge **path = new const Edge *[TheGraph->getNumVertices()]; - const std::list ExposedVertices = TheMatching->getExposedVertices() ; - for (std::list::const_iterator expv = ExposedVertices.begin() ; - (expv != ExposedVertices.end()) && (TheMatching->getCardinality() < CardinalityGoal) ; expv++) { - if (TheMatching->isExposed (*expv)) { - unsigned long pathlength = searchAugmentingPath (*expv, path) ; + const std::list ExposedVertices = TheMatching->getExposedVertices(); + for (std::list::const_iterator expv = ExposedVertices.begin(); + (expv != ExposedVertices.end()) && (TheMatching->getCardinality() < CardinalityGoal); + expv++) { + if (TheMatching->isExposed(*expv)) { + unsigned long pathlength = searchAugmentingPath(*expv, path); #ifdef DEBUG - if (pathlength == 0) { - printDebug (5, "BFSAPHeuristic: could not find augmenting path for vertex %lu", (*expv)->getLabel()) ; - } - else { - if (RUNDEBUGLEVEL(5)) { - std::cerr << "BFSAPHeuristic: found augmenting path for vertex " << (*expv)->getLabel() << ": " ; - for (unsigned long i = 0 ; i < pathlength ; i++) { - std::cerr << path[i]->getVertex1()->getLabel() << "-" << path[i]->getVertex2()->getLabel() ; - if (i != pathlength - 1) { - std::cerr << ", " ; - } - } - std::cerr << std::endl ; - } - } + if (pathlength == 0) { + printDebug(5, "BFSAPHeuristic: could not find augmenting path for vertex %lu", + (*expv)->getLabel()); + } else { + if (RUNDEBUGLEVEL(5)) { + std::cerr << "BFSAPHeuristic: found augmenting path for vertex " + << (*expv)->getLabel() << ": "; + for (unsigned long i = 0; i < pathlength; i++) { + std::cerr << path[i]->getVertex1()->getLabel() << "-" + << path[i]->getVertex2()->getLabel(); + if (i != pathlength - 1) { + std::cerr << ", "; + } + } + std::cerr << std::endl; + } + } #endif - if (pathlength > 0) { - TheMatching->augment ((const Edge**) path, pathlength) ; - } - } - } + if (pathlength > 0) { + TheMatching->augment((const Edge **)path, pathlength); + } + } + } - delete[] path ; + delete[] path; } -unsigned long BFSAPHeuristic::searchAugmentingPath (Vertex *v0, const Edge** path) -{ +unsigned long BFSAPHeuristic::searchAugmentingPath(Vertex *v0, const Edge **path) { #ifdef DEBUG - printDebug (5, "BFSAPHeuristic: starting search for augmenting path from vertex %lu", v0->getLabel()) ; + printDebug(5, "BFSAPHeuristic: starting search for augmenting path from vertex %lu", + v0->getLabel()); #endif - unsigned long pathlen = 0 ; - bool foundap = false ; + unsigned long pathlen = 0; + bool foundap = false; - std::list srclist ; - std::list destlist ; - srclist.push_back (v0) ; - VertexVisited[v0->getLabel()] = true ; + std::list srclist; + std::list destlist; + srclist.push_back(v0); + VertexVisited[v0->getLabel()] = true; - for (unsigned int depth = 0 ; !foundap && !srclist.empty() ; depth++) { - myassert (destlist.empty()) ; + for (unsigned int depth = 0; !foundap && !srclist.empty(); depth++) { + myassert(destlist.empty()); - // for all vertices v1 in srclist... - for (std::list::const_iterator vit = srclist.begin() ; vit != srclist.end() && !foundap ; vit++) { - Vertex* v1 = *vit ; + // for all vertices v1 in srclist... + for (std::list::const_iterator vit = srclist.begin(); + vit != srclist.end() && !foundap; vit++) { + Vertex *v1 = *vit; #ifdef DEBUG - printDebug (6, "BFSAPHeuristic: starting search iteration from vertex %lu", v1->getLabel()) ; + printDebug(6, "BFSAPHeuristic: starting search iteration from vertex %lu", + v1->getLabel()); #endif - // ...iterate through all... - EdgeIterator edgeit (v1) ; - while (!edgeit.isFinished() && !foundap) { - Edge e = **edgeit ; + // ...iterate through all... + EdgeIterator edgeit(v1); + while (!edgeit.isFinished() && !foundap) { + Edge e = **edgeit; - // ...unmatched edges of v1 - if (!TheMatching->includesEdge(e)) { - Vertex* v2 = e.getOtherVertex(v1) ; + // ...unmatched edges of v1 + if (!TheMatching->includesEdge(e)) { + Vertex *v2 = e.getOtherVertex(v1); #ifdef DEBUG - printDebug (7, "BFSAPHeuristic: examining unmatched edge %lu - %lu", v1->getLabel(), v2->getLabel()) ; + printDebug(7, "BFSAPHeuristic: examining unmatched edge %lu - %lu", + v1->getLabel(), v2->getLabel()); #endif - if (!VertexVisited[v2->getLabel()]) { // v2 is not yet visited -> visit it! - VertexVisited[v2->getLabel()] = true ; - BackEdge[v2->getLabel()] = e ; - - if (TheMatching->isExposed(v2)) { // an augmenting path has been found! - foundap = true ; - pathlen = 2 * depth + 1 ; - // build path backwards - Vertex *v = v2 ; - for (int j = pathlen - 1 ; j >= 0 ; j--) { - path[j] = &BackEdge[v->getLabel()] ; - v = BackEdge[v->getLabel()].getOtherVertex(v) ; - } - } - else { // continue searching - Edge me = *(TheMatching->getMatchingEdge(v2)) ; - Vertex* v3 = me.getOtherVertex(v2) ; - BackEdge[v3->getLabel()] = me ; - destlist.push_back (v3) ; // use v3 as a v1 in next iteration - VertexVisited[v3->getLabel()] = true ; - } - } - } - - ++edgeit ; - } - } - - if (!foundap) { - // prepare for next iteration - srclist.clear() ; - srclist.splice (srclist.begin(), destlist) ; - } - } - - return pathlen ; + if (!VertexVisited[v2->getLabel()]) { // v2 is not yet visited -> + // visit it! + VertexVisited[v2->getLabel()] = true; + BackEdge[v2->getLabel()] = e; + + if (TheMatching->isExposed(v2)) { // an augmenting path has been found! + foundap = true; + pathlen = 2 * depth + 1; + // build path backwards + Vertex *v = v2; + for (int j = pathlen - 1; j >= 0; j--) { + path[j] = &BackEdge[v->getLabel()]; + v = BackEdge[v->getLabel()].getOtherVertex(v); + } + } else { // continue searching + Edge me = *(TheMatching->getMatchingEdge(v2)); + Vertex *v3 = me.getOtherVertex(v2); + BackEdge[v3->getLabel()] = me; + destlist.push_back(v3); // use v3 as a v1 in next iteration + VertexVisited[v3->getLabel()] = true; + } + } + } + + ++edgeit; + } + } + + if (!foundap) { + // prepare for next iteration + srclist.clear(); + srclist.splice(srclist.begin(), destlist); + } + } + + return pathlen; } diff --git a/src/BFSAPHeuristic.h b/src/BFSAPHeuristic.h index 43dbb82..fa563da 100644 --- a/src/BFSAPHeuristic.h +++ b/src/BFSAPHeuristic.h @@ -25,40 +25,39 @@ #include "MatchingAlgorithm.h" #include "Vertex.h" -class Edge ; +class Edge; #include "Graph.h" -class Matching ; +class Matching; /** * \class BFSAPHeuristic * \brief a matching algorithm implementing a heuristic breadth-first-search for augmenting paths **/ class BFSAPHeuristic : public MatchingAlgorithm { - public: - /** - * construct an BFSAPHeuristic object - * \param g the graph on which this heuristic should run - * \param m the matching to start with - **/ - BFSAPHeuristic (Graph* g, Matching* m) ; - - virtual ~BFSAPHeuristic (void) ; - - const char* getName (void) const - { return "BFS Augmenting Path Heuristic" ; } ; - - void run (void) ; - - private: - /** - * \param v0 an exposed vertex - * \param path an array of Edge pointers where the path will be put - * \return the length of the path (the number of valid edges in path) - **/ - unsigned long searchAugmentingPath (Vertex* v0, const Edge** path) ; - - bool* VertexVisited ; - Edge* BackEdge ; -} ; + public: + /** + * construct an BFSAPHeuristic object + * \param g the graph on which this heuristic should run + * \param m the matching to start with + **/ + BFSAPHeuristic(Graph *g, Matching *m); + + virtual ~BFSAPHeuristic(void); + + const char *getName(void) const { return "BFS Augmenting Path Heuristic"; }; + + void run(void); + + private: + /** + * \param v0 an exposed vertex + * \param path an array of Edge pointers where the path will be put + * \return the length of the path (the number of valid edges in path) + **/ + unsigned long searchAugmentingPath(Vertex *v0, const Edge **path); + + bool *VertexVisited; + Edge *BackEdge; +}; #endif // ndef SH_BFSAPHeuristic diff --git a/src/BinaryIO.cc b/src/BinaryIO.cc index a953ef4..df10b87 100644 --- a/src/BinaryIO.cc +++ b/src/BinaryIO.cc @@ -24,300 +24,280 @@ #include "common.h" #include "error.h" -void BinaryIO::init () -{ - setName ("") ; - setStream (NULL) ; - set_open (false) ; +void BinaryIO::init() { + setName(""); + setStream(NULL); + set_open(false); } -BinaryIO::BinaryIO (void) -{ - init() ; -} +BinaryIO::BinaryIO(void) { init(); } -BinaryIO::BinaryIO (const std::string& fn, MODE m) -{ - init() ; - open (fn, m) ; +BinaryIO::BinaryIO(const std::string &fn, MODE m) { + init(); + open(fn, m); } -BinaryIO::~BinaryIO (void) -{ - if (is_open()) { - close () ; - } +BinaryIO::~BinaryIO(void) { + if (is_open()) { + close(); + } } -bool BinaryIO::Fileexists (const std::string& fn) const -{ - bool retval = false ; - FILE *fd = fopen (fn.c_str(), "r") ; - if (fd != NULL) { - retval = true ; - fclose (fd) ; - } - return retval ; +bool BinaryIO::Fileexists(const std::string &fn) const { + bool retval = false; + FILE *fd = fopen(fn.c_str(), "r"); + if (fd != NULL) { + retval = true; + fclose(fd); + } + return retval; } -void BinaryIO::checkForce (const std::string& fn) const -{ - if (!Args.Force.getValue()) { - if (Fileexists (fn)) { - Question q (_("the file \"%s\" does already exist. overwrite ?"), fn.c_str()) ; - q.printMessage() ; - if (!q.getAnswer()) { - throw SteghideError (_("did not write to file \"%s\"."), fn.c_str()) ; - } - } - } +void BinaryIO::checkForce(const std::string &fn) const { + if (!Args.Force.getValue()) { + if (Fileexists(fn)) { + Question q(_("the file \"%s\" does already exist. overwrite ?"), fn.c_str()); + q.printMessage(); + if (!q.getAnswer()) { + throw SteghideError(_("did not write to file \"%s\"."), fn.c_str()); + } + } + } } -void BinaryIO::open (const std::string& fn, MODE m) -{ - if (fn == "") { - switch (m) { - case READ: { - setStream (stdin) ; - break ; } - - case WRITE: { - setStream (stdout) ; - break ; } - - default: { - myassert (0) ; - break ; } - } - } - else { - FILE *s = NULL ; - const char *cmode ; - - switch (m) { - case READ: { - cmode = "rb" ; - break ; } - - case WRITE: { - checkForce (fn) ; - cmode = "wb" ; - break ; } - - default: { - myassert(0) ; - break ; } - } - - if ((s = fopen (fn.c_str(), cmode)) == NULL) { - throw SteghideError (_("could not open the file \"%s\"."), fn.c_str()) ; - } - - setStream (s) ; - } - setName (fn) ; - setMode (m) ; - set_open (true) ; +void BinaryIO::open(const std::string &fn, MODE m) { + if (fn == "") { + switch (m) { + case READ: { + setStream(stdin); + break; + } + + case WRITE: { + setStream(stdout); + break; + } + + default: { + myassert(0); + break; + } + } + } else { + FILE *s = NULL; + const char *cmode; + + switch (m) { + case READ: { + cmode = "rb"; + break; + } + + case WRITE: { + checkForce(fn); + cmode = "wb"; + break; + } + + default: { + myassert(0); + break; + } + } + + if ((s = fopen(fn.c_str(), cmode)) == NULL) { + throw SteghideError(_("could not open the file \"%s\"."), fn.c_str()); + } + + setStream(s); + } + setName(fn); + setMode(m); + set_open(true); } -bool BinaryIO::eof (void) const -{ - int c = fgetc (getStream()) ; - bool retval = feof (getStream()) ; - ungetc (c, getStream()) ; - return retval ; +bool BinaryIO::eof(void) const { + int c = fgetc(getStream()); + bool retval = feof(getStream()); + ungetc(c, getStream()); + return retval; } -void BinaryIO::close (void) -{ - myassert (is_open()) ; +void BinaryIO::close(void) { + myassert(is_open()); - if (getName() != "") { - if (fclose (getStream()) == EOF) { - throw SteghideError (_("could not close the file \"%s\"."), getName().c_str()) ; - } - } + if (getName() != "") { + if (fclose(getStream()) == EOF) { + throw SteghideError(_("could not close the file \"%s\"."), getName().c_str()); + } + } - setName ("") ; - setStream (NULL) ; - set_open (false) ; + setName(""); + setStream(NULL); + set_open(false); } -BYTE BinaryIO::read8 (void) -{ - myassert (getMode() == READ) ; - myassert (is_open()) ; +BYTE BinaryIO::read8(void) { + myassert(getMode() == READ); + myassert(is_open()); - int c = EOF ; - if ((c = fgetc (getStream())) == EOF) { - throw BinaryInputError (getName(), getStream()) ; - } + int c = EOF; + if ((c = fgetc(getStream())) == EOF) { + throw BinaryInputError(getName(), getStream()); + } - return (BYTE) c ; + return (BYTE)c; } -UWORD16 BinaryIO::read16_le (void) -{ - myassert (getMode() == READ) ; - myassert (is_open()) ; +UWORD16 BinaryIO::read16_le(void) { + myassert(getMode() == READ); + myassert(is_open()); - int bytes[2] ; - for (int i = 0 ; i < 2 ; i++) { - if ((bytes[i] = fgetc (getStream())) == EOF) { - throw BinaryInputError (getName(), getStream()) ; - } - } + int bytes[2]; + for (int i = 0; i < 2; i++) { + if ((bytes[i] = fgetc(getStream())) == EOF) { + throw BinaryInputError(getName(), getStream()); + } + } - return ((bytes[1] << 8) | bytes[0]) ; + return ((bytes[1] << 8) | bytes[0]); } -UWORD16 BinaryIO::read16_be (void) -{ - myassert (getMode() == READ) ; - myassert (is_open()) ; +UWORD16 BinaryIO::read16_be(void) { + myassert(getMode() == READ); + myassert(is_open()); - int bytes[2] ; - for (int i = 0 ; i < 2 ; i++) { - if ((bytes[i] = fgetc (getStream())) == EOF) { - throw BinaryInputError (getName(), getStream()) ; - } - } + int bytes[2]; + for (int i = 0; i < 2; i++) { + if ((bytes[i] = fgetc(getStream())) == EOF) { + throw BinaryInputError(getName(), getStream()); + } + } - return ((bytes[0] << 8) | bytes[1]) ; + return ((bytes[0] << 8) | bytes[1]); } -UWORD32 BinaryIO::read32_le (void) -{ - myassert (getMode() == READ) ; - myassert (is_open()) ; +UWORD32 BinaryIO::read32_le(void) { + myassert(getMode() == READ); + myassert(is_open()); - int bytes[4] ; - for (int i = 0 ; i < 4 ; i++) { - if ((bytes[i] = fgetc (getStream())) == EOF) { - throw BinaryInputError (getName(), getStream()) ; - } - } + int bytes[4]; + for (int i = 0; i < 4; i++) { + if ((bytes[i] = fgetc(getStream())) == EOF) { + throw BinaryInputError(getName(), getStream()); + } + } - return ((bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0]) ; + return ((bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0]); } -UWORD32 BinaryIO::read32_be (void) -{ - myassert (getMode() == READ) ; - myassert (is_open()) ; +UWORD32 BinaryIO::read32_be(void) { + myassert(getMode() == READ); + myassert(is_open()); - int bytes[4] ; - for (int i = 0 ; i < 4 ; i++) { - if ((bytes[i] = fgetc (getStream())) == EOF) { - throw BinaryInputError (getName(), getStream()) ; - } - } + int bytes[4]; + for (int i = 0; i < 4; i++) { + if ((bytes[i] = fgetc(getStream())) == EOF) { + throw BinaryInputError(getName(), getStream()); + } + } - return ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) ; + return ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]); } -UWORD32 BinaryIO::read_le (unsigned short n) -{ - myassert (getMode() == READ) ; - myassert (is_open()) ; - myassert (n <= 4) ; - - UWORD32 retval = 0 ; - for (unsigned short i = 0 ; i < n ; i++) { - int byte = EOF ; - if ((byte = fgetc (getStream())) == EOF) { - throw BinaryInputError (getName(), getStream()) ; - } - retval |= (((BYTE) byte) << (8 * i)) ; - } - - return retval ; +UWORD32 BinaryIO::read_le(unsigned short n) { + myassert(getMode() == READ); + myassert(is_open()); + myassert(n <= 4); + + UWORD32 retval = 0; + for (unsigned short i = 0; i < n; i++) { + int byte = EOF; + if ((byte = fgetc(getStream())) == EOF) { + throw BinaryInputError(getName(), getStream()); + } + retval |= (((BYTE)byte) << (8 * i)); + } + + return retval; } -std::string BinaryIO::readstring (unsigned int len) -{ - char retval[len + 1] ; - for (unsigned int i = 0 ; i < len ; i++) { - retval[i] = (char) read8() ; - } - retval[len] = '\0' ; - return std::string (retval) ; +std::string BinaryIO::readstring(unsigned int len) { + char retval[len + 1]; + for (unsigned int i = 0; i < len; i++) { + retval[i] = (char)read8(); + } + retval[len] = '\0'; + return std::string(retval); } -void BinaryIO::write8 (BYTE val) -{ - myassert (getMode() == WRITE) ; - myassert (is_open()) ; +void BinaryIO::write8(BYTE val) { + myassert(getMode() == WRITE); + myassert(is_open()); - if (fputc ((int) val, getStream()) == EOF) { - throw BinaryOutputError (getName()) ; - } + if (fputc((int)val, getStream()) == EOF) { + throw BinaryOutputError(getName()); + } } -void BinaryIO::write16_le (UWORD16 val) -{ - myassert (getMode() == WRITE) ; - myassert (is_open()) ; - - for (int i = 0 ; i <= 1 ; i++) { - if (fputc ((val >> (8 * i)) & 0xFF, getStream()) == EOF) { - throw BinaryOutputError (getName()) ; - } - } +void BinaryIO::write16_le(UWORD16 val) { + myassert(getMode() == WRITE); + myassert(is_open()); + + for (int i = 0; i <= 1; i++) { + if (fputc((val >> (8 * i)) & 0xFF, getStream()) == EOF) { + throw BinaryOutputError(getName()); + } + } } -void BinaryIO::write16_be (UWORD16 val) -{ - myassert (getMode() == WRITE) ; - myassert (is_open()) ; +void BinaryIO::write16_be(UWORD16 val) { + myassert(getMode() == WRITE); + myassert(is_open()); - for (int i = 1 ; i >= 0 ; i--) { - if (fputc ((val >> (8 * i)) & 0xFF, getStream()) == EOF) { - throw BinaryOutputError (getName()) ; - } - } + for (int i = 1; i >= 0; i--) { + if (fputc((val >> (8 * i)) & 0xFF, getStream()) == EOF) { + throw BinaryOutputError(getName()); + } + } } -void BinaryIO::write32_le (UWORD32 val) -{ - myassert (getMode() == WRITE) ; - myassert (is_open()) ; +void BinaryIO::write32_le(UWORD32 val) { + myassert(getMode() == WRITE); + myassert(is_open()); - for (int i = 0 ; i <= 3 ; i++) { - if (fputc ((val >> (8 * i)) & 0xFF, getStream()) == EOF) { - throw BinaryOutputError (getName()) ; - } - } + for (int i = 0; i <= 3; i++) { + if (fputc((val >> (8 * i)) & 0xFF, getStream()) == EOF) { + throw BinaryOutputError(getName()); + } + } } -void BinaryIO::write32_be (UWORD32 val) -{ - myassert (getMode() == WRITE) ; - myassert (is_open()) ; +void BinaryIO::write32_be(UWORD32 val) { + myassert(getMode() == WRITE); + myassert(is_open()); - for (int i = 3 ; i >= 0 ; i--) { - if (fputc ((val >> (8 * i)) & 0xFF, getStream()) == EOF) { - throw BinaryOutputError (getName()) ; - } - } + for (int i = 3; i >= 0; i--) { + if (fputc((val >> (8 * i)) & 0xFF, getStream()) == EOF) { + throw BinaryOutputError(getName()); + } + } } -void BinaryIO::write_le (UWORD32 val, unsigned short n) -{ - myassert (getMode() == WRITE) ; - myassert (is_open()) ; - myassert (n <= 4) ; - - for (short i = 0 ; i < n ; i++) { - if (fputc ((val >> (8 * i)) & 0xFF, getStream()) == EOF) { - throw BinaryOutputError (getName()) ; - } - } +void BinaryIO::write_le(UWORD32 val, unsigned short n) { + myassert(getMode() == WRITE); + myassert(is_open()); + myassert(n <= 4); + + for (short i = 0; i < n; i++) { + if (fputc((val >> (8 * i)) & 0xFF, getStream()) == EOF) { + throw BinaryOutputError(getName()); + } + } } -void BinaryIO::writestring (const std::string& s) -{ - if (fputs (s.c_str(), getStream()) == EOF) { - throw BinaryOutputError (getName()) ; - } +void BinaryIO::writestring(const std::string &s) { + if (fputs(s.c_str(), getStream()) == EOF) { + throw BinaryOutputError(getName()); + } } diff --git a/src/BinaryIO.h b/src/BinaryIO.h index 3c33506..1bd3a9f 100644 --- a/src/BinaryIO.h +++ b/src/BinaryIO.h @@ -31,173 +31,164 @@ * \brief provides methods for file i/o as needed by the rest of steghide **/ class BinaryIO { - public: - enum MODE { READ, WRITE } ; - - BinaryIO (void) ; - - /** - * construct a BinaryIO object - * \param fn the filename ("" to indicate stdin/stdout) - * \param m the mode (BinaryIO::READ or BinaryIO::WRITE) - * - * The file described by fn is opened in the given mode. - **/ - BinaryIO (const std::string& fn, MODE m) ; - - ~BinaryIO (void) ; - - /** - * get the name (with path) of this file - **/ - const std::string& getName (void) const - { return Name ; } ; - - /** - * is this file currently opened ? - **/ - bool is_open (void) const - { return FileOpen ; } ; - - /** - * is this file a standard stream (stdin or stdout) ? - **/ - bool is_std (void) const - { return (getStream() != NULL && getName() == "") ; } ; - - /** - * get the current position in the current file - **/ - unsigned long getPos (void) const - { return ftell(getStream()) ; } ; - - /** - * is the current state of this file at the end of the file - **/ - bool eof (void) const ; - - /** - * open the file given by fn in the mode m - * \param fn a filename ("" to indicate stdin/stdout) - * \param m the mode (BinaryIO::READ or BinaryIO::WRITE) - **/ - void open (const std::string& fn, MODE m) ; - - /** - * close the currently open file - it is save to call close() even if is_std() is true - **/ - void close (void) ; - - /** - * read one byte from the file - **/ - BYTE read8 (void) ; - - /** - * read two bytes from the file using little-endian byte ordering - **/ - UWORD16 read16_le (void) ; - - /** - * read two bytes from the file using big-endian byte ordering - **/ - UWORD16 read16_be (void) ; - - /** - * read four bytes from the file using little-endian byte ordering - **/ - UWORD32 read32_le (void) ; - - /** - * read four bytes from the file using big-endian byte ordering - **/ - UWORD32 read32_be (void) ; - - /** - * read n bytes (little endian byte ordering) - * \param n the number of bytes to read (must be <= 4) - **/ - UWORD32 read_le (unsigned short n) ; - - /** - * read a string with length len from the file - **/ - std::string readstring (unsigned int len) ; - - /** - * write one byte to the file - **/ - void write8 (BYTE val) ; - - /** - * write two bytes to the file using little-endian byte ordering - **/ - void write16_le (UWORD16 val) ; - - /** - * write two bytes to the file using big-endian byte ordering - **/ - void write16_be (UWORD16 val) ; - - /** - * write four bytes to the file using little-endian byte ordering - **/ - void write32_le (UWORD32 val) ; - - /** - * write four bytes to the file using big-endian byte ordering - **/ - void write32_be (UWORD32 val) ; - - /** - * write n bytes of val (little endian byte ordering) - * \param n the number of bytes to write (must be <= 4) - * \param val the value - **/ - void write_le (UWORD32 val, unsigned short n) ; - - void writestring (const std::string& s) ; - - /** - * get the underlying cstdio FILE* pointer - **/ - FILE* getStream (void) const - { return Stream ; } ; - - protected: - void setStream (FILE* s) - { Stream = s ; } ; - - void setName (const std::string& fn) - { Name = fn ; } ; - - MODE getMode (void) const - { return Mode ; } ; - - void setMode (MODE m) - { Mode = m ; } ; - - private: - std::string Name ; - FILE *Stream ; - bool FileOpen ; - MODE Mode ; - - void init (void) ; - - void set_open (bool o) - { FileOpen = o ; } ; - - /** - * when opening a file in write mode perform various checks depending on the value of the force argument - **/ - void checkForce (const std::string& fn) const ; - - /** - * check if the file described by fn exists - * \return true iff a fopen call with fn as file name succeeded - **/ - bool Fileexists (const std::string& fn) const ; -} ; + public: + enum MODE { READ, WRITE }; + + BinaryIO(void); + + /** + * construct a BinaryIO object + * \param fn the filename ("" to indicate stdin/stdout) + * \param m the mode (BinaryIO::READ or BinaryIO::WRITE) + * + * The file described by fn is opened in the given mode. + **/ + BinaryIO(const std::string &fn, MODE m); + + ~BinaryIO(void); + + /** + * get the name (with path) of this file + **/ + const std::string &getName(void) const { return Name; }; + + /** + * is this file currently opened ? + **/ + bool is_open(void) const { return FileOpen; }; + + /** + * is this file a standard stream (stdin or stdout) ? + **/ + bool is_std(void) const { return (getStream() != NULL && getName() == ""); }; + + /** + * get the current position in the current file + **/ + unsigned long getPos(void) const { return ftell(getStream()); }; + + /** + * is the current state of this file at the end of the file + **/ + bool eof(void) const; + + /** + * open the file given by fn in the mode m + * \param fn a filename ("" to indicate stdin/stdout) + * \param m the mode (BinaryIO::READ or BinaryIO::WRITE) + **/ + void open(const std::string &fn, MODE m); + + /** + * close the currently open file - it is save to call close() even if is_std() is true + **/ + void close(void); + + /** + * read one byte from the file + **/ + BYTE read8(void); + + /** + * read two bytes from the file using little-endian byte ordering + **/ + UWORD16 read16_le(void); + + /** + * read two bytes from the file using big-endian byte ordering + **/ + UWORD16 read16_be(void); + + /** + * read four bytes from the file using little-endian byte ordering + **/ + UWORD32 read32_le(void); + + /** + * read four bytes from the file using big-endian byte ordering + **/ + UWORD32 read32_be(void); + + /** + * read n bytes (little endian byte ordering) + * \param n the number of bytes to read (must be <= 4) + **/ + UWORD32 read_le(unsigned short n); + + /** + * read a string with length len from the file + **/ + std::string readstring(unsigned int len); + + /** + * write one byte to the file + **/ + void write8(BYTE val); + + /** + * write two bytes to the file using little-endian byte ordering + **/ + void write16_le(UWORD16 val); + + /** + * write two bytes to the file using big-endian byte ordering + **/ + void write16_be(UWORD16 val); + + /** + * write four bytes to the file using little-endian byte ordering + **/ + void write32_le(UWORD32 val); + + /** + * write four bytes to the file using big-endian byte ordering + **/ + void write32_be(UWORD32 val); + + /** + * write n bytes of val (little endian byte ordering) + * \param n the number of bytes to write (must be <= 4) + * \param val the value + **/ + void write_le(UWORD32 val, unsigned short n); + + void writestring(const std::string &s); + + /** + * get the underlying cstdio FILE* pointer + **/ + FILE *getStream(void) const { return Stream; }; + + protected: + void setStream(FILE *s) { Stream = s; }; + + void setName(const std::string &fn) { Name = fn; }; + + MODE getMode(void) const { return Mode; }; + + void setMode(MODE m) { Mode = m; }; + + private: + std::string Name; + FILE *Stream; + bool FileOpen; + MODE Mode; + + void init(void); + + void set_open(bool o) { FileOpen = o; }; + + /** + * when opening a file in write mode perform various checks depending on the value of the force + *argument + **/ + void checkForce(const std::string &fn) const; + + /** + * check if the file described by fn exists + * \return true iff a fopen call with fn as file name succeeded + **/ + bool Fileexists(const std::string &fn) const; +}; #endif /* ndef SH_BINARYIO_H */ diff --git a/src/BitString.cc b/src/BitString.cc index 9e1deb5..07fc246 100644 --- a/src/BitString.cc +++ b/src/BitString.cc @@ -18,8 +18,8 @@ * */ -#include "AUtils.h" #include "BitString.h" +#include "AUtils.h" #include "common.h" namespace zlib { @@ -29,432 +29,391 @@ namespace zlib { #define BITPOS(n) (n % 8) #define BYTEPOS(n) (n / 8) -BitString::BitString (EmbValue arity) - : Length(0) -{ - setArity(arity) ; +BitString::BitString(EmbValue arity) : Length(0) { setArity(arity); } + +BitString::BitString(const BitString &bs) { + Length = bs.Length; + Arity = bs.Arity; + ArityNBits = bs.ArityNBits; + Data.resize(bs.Data.size()); + for (unsigned long i = 0; i < bs.Data.size(); i++) { + Data[i] = bs.Data[i]; + } +} + +BitString::BitString(unsigned long l) { + unsigned long nbytes = 0; + if (l % 8 == 0) { + nbytes = l / 8; + } else { + nbytes = (l / 8) + 1; + } + + Data = std::vector(nbytes, 0); // is initialized to zeros in std::vector's constructor + Length = l; + setArity(2); +} + +BitString::BitString(const std::vector &d) : Length(0) { + setArity(2); + append(d); +} + +BitString::BitString(const std::string &d) : Length(0) { + setArity(2); + append(d); } -BitString::BitString (const BitString& bs) -{ - Length = bs.Length ; - Arity = bs.Arity ; - ArityNBits = bs.ArityNBits ; - Data.resize(bs.Data.size()) ; - for (unsigned long i = 0 ; i < bs.Data.size() ; i++) { - Data[i] = bs.Data[i] ; - } -} - -BitString::BitString (unsigned long l) -{ - unsigned long nbytes = 0 ; - if (l % 8 == 0) { - nbytes = l / 8 ; - } - else { - nbytes = (l / 8) + 1 ; - } +void BitString::setArity(EmbValue arity) { + BYTE tmp = Arity = arity; + ArityNBits = 0; + while (tmp > 1) { + myassert(tmp % 2 == 0); // only implemented for arity = 2^i + tmp /= 2; + ArityNBits++; + } +} + +BitString &BitString::clear() { + Data.clear(); + Length = 0; + return *this; +} + +void BitString::_append(BIT v) { + if (Length % 8 == 0) { + Data.push_back(0); + } + Data[BYTEPOS(Length)] |= (v << BITPOS(Length)); + Length++; +} - Data = std::vector (nbytes, 0) ; // is initialized to zeros in std::vector's constructor - Length = l ; - setArity(2) ; -} +BitString &BitString::append(BIT v) { + _append(v); + return *this; +} -BitString::BitString (const std::vector &d) - : Length(0) -{ - setArity(2) ; - append (d) ; +BitString &BitString::append(const BYTE v, const unsigned short n) { + for (unsigned short i = 0; i < n; i++) { + _append((BIT)((v & (1 << i)) >> i)); + } + return *this; } - -BitString::BitString (const std::string &d) - : Length(0) -{ - setArity(2) ; - append (d) ; + +BitString &BitString::append(const UWORD16 v, const unsigned short n) { + for (unsigned short i = 0; i < n; i++) { + _append((BIT)((v & (1 << i)) >> i)); + } + return *this; } -void BitString::setArity (EmbValue arity) -{ - BYTE tmp = Arity = arity ; - ArityNBits = 0 ; - while (tmp > 1) { - myassert (tmp % 2 == 0) ; // only implemented for arity = 2^i - tmp /= 2 ; - ArityNBits++ ; - } -} - -BitString& BitString::clear() -{ - Data.clear() ; - Length = 0 ; - return *this ; -} - -void BitString::_append (BIT v) -{ - if (Length % 8 == 0) { - Data.push_back (0) ; - } - Data[BYTEPOS(Length)] |= (v << BITPOS(Length)) ; - Length++ ; -} - -BitString& BitString::append (BIT v) -{ - _append (v) ; - return *this ; -} - -BitString& BitString::append (const BYTE v, const unsigned short n) -{ - for (unsigned short i = 0 ; i < n ; i++) { - _append ((BIT) ((v & (1 << i)) >> i)) ; - } - return *this ; -} - -BitString& BitString::append (const UWORD16 v, const unsigned short n) -{ - for (unsigned short i = 0 ; i < n ; i++) { - _append ((BIT) ((v & (1 << i)) >> i)) ; - } - return *this ; -} - -BitString& BitString::append (const UWORD32 v, const unsigned short n) -{ - for (unsigned short i = 0 ; i < n ; i++) { - _append ((BIT) ((v & (1 << i)) >> i)) ; - } - return *this ; -} - -BitString& BitString::append (const BitString& v) -{ - for (unsigned long i = 0 ; i < v.getLength() ; i++) { - _append (v[i]) ; - } - return *this ; -} - -BitString& BitString::append (const std::vector& v) -{ - for (std::vector::const_iterator i = v.begin() ; i != v.end() ; i++) { - append (*i) ; - } - return *this ; -} - -BitString& BitString::append (const std::string& v) -{ - for (std::string::const_iterator i = v.begin() ; i != v.end() ; i++) { - append ((BYTE) *i) ; - } - return *this ; -} - -BIT BitString::operator[] (unsigned long i) const -{ - myassert (i < Length) ; - return ((Data[BYTEPOS(i)] >> BITPOS(i)) & 1) ; -} - -BitString& BitString::setBit (unsigned long i, BIT v) -{ - myassert (i < Length) ; - BYTE mask = ~(1 << BITPOS(i)) ; - Data[BYTEPOS(i)] &= mask ; - Data[BYTEPOS(i)] |= (v << BITPOS(i)) ; - return (*this) ; -} - -BitString BitString::getBits (unsigned long s, unsigned long l) const -{ - BitString retval ; - for (unsigned long i = s ; i < s + l ; i++) { - retval.append ((*this)[i]) ; - } - return retval ; -} - -BitString BitString::cutBits (unsigned long s, unsigned long l) -{ - myassert (s + l <= Length) ; - BitString retval ; - for (unsigned long i = s, j = s + l ; i < s + l || j < Length ; i++, j++) { - if (i < s + l) { - retval.append ((*this)[i]) ; - } - if (j < Length) { - setBit(i, (*this)[j]) ; - } - } - Length -= l ; - Data.resize (AUtils::div_roundup (Length, 8)) ; - clearUnused() ; - - return retval ; -} - -UWORD32 BitString::getValue (unsigned long s, unsigned short l) const -{ - myassert (l <= 32) ; - UWORD32 retval = 0 ; - for (unsigned short i = 0 ; i < l ; i++) { - retval |= (*this)[s + i] << i ; - } - return retval ; -} - -const std::vector& BitString::getBytes() const -{ - myassert (Length % 8 == 0) ; - return Data ; -} - -BitString& BitString::truncate (const unsigned long s, const unsigned long e) -{ - unsigned long newsize_i = e - s ; - - for (unsigned long i = 0 ; i < newsize_i ; i++) { - // replace i-th bit with (s+i)-th bit - BIT bit = (*this)[s + i] ; - Data[BYTEPOS(i)] &= (BYTE) ~(1 << BITPOS(i)) ; // delete i-th bit - Data[BYTEPOS(i)] |= (BYTE) (bit << BITPOS(i)) ; - } - Length = newsize_i ; - - clearUnused() ; - - return *this ; -} - -BitString& BitString::pad (unsigned long mult, BIT v) -{ - while (Length % mult != 0) { - _append (v) ; - } - return *this ; -} - -BitString& BitString::padRandom (unsigned long mult) -{ - while (Length % mult != 0) { - append (RndSrc.getBool()) ; - } - return *this ; -} - -BYTE BitString::getNAry (unsigned long p) const -{ - unsigned long pbinary = p * ArityNBits ; - BYTE retval = 0 ; - for (unsigned short i = 0 ; (i < ArityNBits) && (pbinary + i < Length /* Length not a multiple of ArityNBits */) ; i++) { - retval |= (*this)[pbinary + i] << i ; - } - return retval ; -} - -void BitString::appendNAry (BYTE v) -{ - for (unsigned short i = 0 ; i < ArityNBits ; i++) { - _append ((v & (1 << i)) >> i) ; - } -} - -BitString& BitString::compress (int level) -{ - myassert (level >= 1 && level <= 9) ; - pad (8, 0) ; - - // prepare source buffer - zlib::uLong srclen = Data.size() ; - zlib::Byte *srcbuf = new zlib::Byte[srclen] ; - for (unsigned long i = 0 ; i < srclen ; i++) { - srcbuf[i] = Data[i] ; - } - - // prepare dest buffer (see zlib manual for this magic length) - zlib::uLong destlen = ((zlib::uLong) ((Data.size() + 12) * 1.001)) + 1 ; - zlib::Byte* destbuf = new zlib::Byte[destlen] ; - - // do compression - int ret = zlib::compress2 (destbuf, &destlen, (const zlib::Bytef*) srcbuf, srclen, level) ; - if (ret != Z_OK) { - switch (ret) { - case Z_MEM_ERROR: - throw SteghideError (_("could not allocate memory.")) ; - break ; - - default: - throw SteghideError (_("error %d while calling zlib's compress2."), ret) ; - break ; - } - } - - // write compressed data into Data - Data.resize (destlen) ; - for (unsigned long i = 0 ; i < destlen ; i++) { - Data[i] = destbuf[i] ; - } - Length = destlen * 8 ; - - delete[] srcbuf ; - delete[] destbuf ; - return *this ; -} - -BitString& BitString::uncompress (unsigned long idestlen) -{ - myassert (Length % 8 == 0) ; - - // prepare source buffer - zlib::uLong srclen = Length / 8 ; - zlib::Byte* srcbuf = new zlib::Byte[srclen] ; - for (unsigned long i = 0 ; i < srclen ; i++) { - srcbuf[i] = Data[i] ; - } - - // prepare destination buffer - zlib::uLong ydestlen = 0 ; - if (idestlen % 8 == 0) { - ydestlen = idestlen / 8 ; - } - else { - ydestlen = (idestlen / 8) + 1 ; - } - zlib::Byte* destbuf = new zlib::Byte[ydestlen] ; - - // do uncompression - zlib::uLong ydestlen_before = ydestlen ; - int ret = zlib::uncompress (destbuf, &ydestlen, (const zlib::Bytef*) srcbuf, srclen) ; - if (ret != Z_OK) { - switch (ret) { - case Z_MEM_ERROR: - throw SteghideError (_("could not allocate memory.")) ; - break ; - - case Z_DATA_ERROR: - throw SteghideError (_("can not uncompress data. compressed data is corrupted.")) ; - break ; - - default: - throw SteghideError (_("error %d while calling zlib's uncompress."), ret) ; - break ; - } - } - myassert (ydestlen_before == ydestlen) ; // because idestlen must be _exactly_ size in bits - - // write uncompressed data into Data - Data.resize (ydestlen) ; - for (unsigned long i = 0 ; i < ydestlen ; i++) { - Data[i] = destbuf[i] ; - } - Length = idestlen ; - - clearUnused() ; - - delete[] srcbuf ; - delete[] destbuf ; - return *this ; -} - -bool BitString::operator== (const BitString &v) const -{ - bool retval = true ; - - if (v.getLength() == getLength()) { - unsigned int n = getLength() ; - for (unsigned int i = 0 ; i < n ; i++) { - if (v[i] != (*this)[i]) { - retval = false ; - } - } - } - else { - retval = false ; - } - - return retval ; -} - -bool BitString::operator!= (const BitString &v) const -{ - bool retval = false ; - - if (v.getLength() != getLength()) { - retval = true ; - } - else { - for (unsigned int i = 0 ; i < getLength() ; i++) { - if (v[i] != (*this)[i]) { - retval = true ; - break ; - } - } - } - - return retval ; -} - -BitString& BitString::operator^= (const BitString &v) -{ - for (unsigned long i = 0 ; i < Length ; i++) { - unsigned long bytepos = BYTEPOS (i) ; - unsigned int bitpos = BITPOS (i) ; - BIT bit = (Data[bytepos] & (1 << bitpos)) >> bitpos ; - bit ^= v[i] ; - Data[bytepos] = (Data[bytepos] & ~(1 << bitpos)) | (bit << bitpos) ; - } - return *this ; -} - -void BitString::clearUnused () -{ - if (Length % 8 != 0) { - // clear unused part of last byte (_append depends on this) - unsigned short nbitsfilled = Length % 8 ; - BYTE mask = 0x00 ; - for (unsigned short i = 0 ; i < nbitsfilled ; i++) { - mask <<= 1 ; - mask |= 1 ; - } - Data[Data.size() - 1] &= mask ; - } -} - -void BitString::print (unsigned short spc) const -{ - char* space = new char[spc + 1] ; - for (unsigned short i = 0 ; i < spc ; i++) { - space[i] = ' ' ; - } - space[spc] = '\0' ; - std::cerr << space << "Length: " << getLength() << std::endl ; - std::cerr << space << "Data.size(): " << Data.size() << std::endl ; - std::cerr << space << "Data:" << std::endl ; - - std::cerr << space ; - for (unsigned long i = 0 ; i < getLength() ; i++) { - if ((i % 64 == 0) && (i > 0)) { // new line - std::cerr << std::endl << space ; - } - if (i % 8 == 0) { // new byte - std::cerr << " " ; - } - std::cerr << ((*this)[i]) ; - } - std::cerr << std::endl ; +BitString &BitString::append(const UWORD32 v, const unsigned short n) { + for (unsigned short i = 0; i < n; i++) { + _append((BIT)((v & (1 << i)) >> i)); + } + return *this; +} + +BitString &BitString::append(const BitString &v) { + for (unsigned long i = 0; i < v.getLength(); i++) { + _append(v[i]); + } + return *this; +} + +BitString &BitString::append(const std::vector &v) { + for (std::vector::const_iterator i = v.begin(); i != v.end(); i++) { + append(*i); + } + return *this; +} + +BitString &BitString::append(const std::string &v) { + for (std::string::const_iterator i = v.begin(); i != v.end(); i++) { + append((BYTE)*i); + } + return *this; +} + +BIT BitString::operator[](unsigned long i) const { + myassert(i < Length); + return ((Data[BYTEPOS(i)] >> BITPOS(i)) & 1); +} + +BitString &BitString::setBit(unsigned long i, BIT v) { + myassert(i < Length); + BYTE mask = ~(1 << BITPOS(i)); + Data[BYTEPOS(i)] &= mask; + Data[BYTEPOS(i)] |= (v << BITPOS(i)); + return (*this); +} + +BitString BitString::getBits(unsigned long s, unsigned long l) const { + BitString retval; + for (unsigned long i = s; i < s + l; i++) { + retval.append((*this)[i]); + } + return retval; +} + +BitString BitString::cutBits(unsigned long s, unsigned long l) { + myassert(s + l <= Length); + BitString retval; + for (unsigned long i = s, j = s + l; i < s + l || j < Length; i++, j++) { + if (i < s + l) { + retval.append((*this)[i]); + } + if (j < Length) { + setBit(i, (*this)[j]); + } + } + Length -= l; + Data.resize(AUtils::div_roundup(Length, 8)); + clearUnused(); + + return retval; +} + +UWORD32 BitString::getValue(unsigned long s, unsigned short l) const { + myassert(l <= 32); + UWORD32 retval = 0; + for (unsigned short i = 0; i < l; i++) { + retval |= (*this)[s + i] << i; + } + return retval; +} + +const std::vector &BitString::getBytes() const { + myassert(Length % 8 == 0); + return Data; +} + +BitString &BitString::truncate(const unsigned long s, const unsigned long e) { + unsigned long newsize_i = e - s; + + for (unsigned long i = 0; i < newsize_i; i++) { + // replace i-th bit with (s+i)-th bit + BIT bit = (*this)[s + i]; + Data[BYTEPOS(i)] &= (BYTE) ~(1 << BITPOS(i)); // delete i-th bit + Data[BYTEPOS(i)] |= (BYTE)(bit << BITPOS(i)); + } + Length = newsize_i; + + clearUnused(); + + return *this; +} + +BitString &BitString::pad(unsigned long mult, BIT v) { + while (Length % mult != 0) { + _append(v); + } + return *this; +} + +BitString &BitString::padRandom(unsigned long mult) { + while (Length % mult != 0) { + append(RndSrc.getBool()); + } + return *this; +} + +BYTE BitString::getNAry(unsigned long p) const { + unsigned long pbinary = p * ArityNBits; + BYTE retval = 0; + for (unsigned short i = 0; + (i < ArityNBits) && (pbinary + i < Length /* Length not a multiple of ArityNBits */); + i++) { + retval |= (*this)[pbinary + i] << i; + } + return retval; +} + +void BitString::appendNAry(BYTE v) { + for (unsigned short i = 0; i < ArityNBits; i++) { + _append((v & (1 << i)) >> i); + } +} + +BitString &BitString::compress(int level) { + myassert(level >= 1 && level <= 9); + pad(8, 0); + + // prepare source buffer + zlib::uLong srclen = Data.size(); + zlib::Byte *srcbuf = new zlib::Byte[srclen]; + for (unsigned long i = 0; i < srclen; i++) { + srcbuf[i] = Data[i]; + } + + // prepare dest buffer (see zlib manual for this magic length) + zlib::uLong destlen = ((zlib::uLong)((Data.size() + 12) * 1.001)) + 1; + zlib::Byte *destbuf = new zlib::Byte[destlen]; + + // do compression + int ret = zlib::compress2(destbuf, &destlen, (const zlib::Bytef *)srcbuf, srclen, level); + if (ret != Z_OK) { + switch (ret) { + case Z_MEM_ERROR: + throw SteghideError(_("could not allocate memory.")); + break; + + default: + throw SteghideError(_("error %d while calling zlib's compress2."), ret); + break; + } + } + + // write compressed data into Data + Data.resize(destlen); + for (unsigned long i = 0; i < destlen; i++) { + Data[i] = destbuf[i]; + } + Length = destlen * 8; + + delete[] srcbuf; + delete[] destbuf; + return *this; +} + +BitString &BitString::uncompress(unsigned long idestlen) { + myassert(Length % 8 == 0); + + // prepare source buffer + zlib::uLong srclen = Length / 8; + zlib::Byte *srcbuf = new zlib::Byte[srclen]; + for (unsigned long i = 0; i < srclen; i++) { + srcbuf[i] = Data[i]; + } + + // prepare destination buffer + zlib::uLong ydestlen = 0; + if (idestlen % 8 == 0) { + ydestlen = idestlen / 8; + } else { + ydestlen = (idestlen / 8) + 1; + } + zlib::Byte *destbuf = new zlib::Byte[ydestlen]; + + // do uncompression + zlib::uLong ydestlen_before = ydestlen; + int ret = zlib::uncompress(destbuf, &ydestlen, (const zlib::Bytef *)srcbuf, srclen); + if (ret != Z_OK) { + switch (ret) { + case Z_MEM_ERROR: + throw SteghideError(_("could not allocate memory.")); + break; + + case Z_DATA_ERROR: + throw SteghideError(_("can not uncompress data. compressed data is corrupted.")); + break; + + default: + throw SteghideError(_("error %d while calling zlib's uncompress."), ret); + break; + } + } + myassert(ydestlen_before == ydestlen); // because idestlen must be _exactly_ size in bits + + // write uncompressed data into Data + Data.resize(ydestlen); + for (unsigned long i = 0; i < ydestlen; i++) { + Data[i] = destbuf[i]; + } + Length = idestlen; + + clearUnused(); + + delete[] srcbuf; + delete[] destbuf; + return *this; +} + +bool BitString::operator==(const BitString &v) const { + bool retval = true; + + if (v.getLength() == getLength()) { + unsigned int n = getLength(); + for (unsigned int i = 0; i < n; i++) { + if (v[i] != (*this)[i]) { + retval = false; + } + } + } else { + retval = false; + } + + return retval; +} + +bool BitString::operator!=(const BitString &v) const { + bool retval = false; + + if (v.getLength() != getLength()) { + retval = true; + } else { + for (unsigned int i = 0; i < getLength(); i++) { + if (v[i] != (*this)[i]) { + retval = true; + break; + } + } + } + + return retval; +} + +BitString &BitString::operator^=(const BitString &v) { + for (unsigned long i = 0; i < Length; i++) { + unsigned long bytepos = BYTEPOS(i); + unsigned int bitpos = BITPOS(i); + BIT bit = (Data[bytepos] & (1 << bitpos)) >> bitpos; + bit ^= v[i]; + Data[bytepos] = (Data[bytepos] & ~(1 << bitpos)) | (bit << bitpos); + } + return *this; +} + +void BitString::clearUnused() { + if (Length % 8 != 0) { + // clear unused part of last byte (_append depends on this) + unsigned short nbitsfilled = Length % 8; + BYTE mask = 0x00; + for (unsigned short i = 0; i < nbitsfilled; i++) { + mask <<= 1; + mask |= 1; + } + Data[Data.size() - 1] &= mask; + } +} + +void BitString::print(unsigned short spc) const { + char *space = new char[spc + 1]; + for (unsigned short i = 0; i < spc; i++) { + space[i] = ' '; + } + space[spc] = '\0'; + std::cerr << space << "Length: " << getLength() << std::endl; + std::cerr << space << "Data.size(): " << Data.size() << std::endl; + std::cerr << space << "Data:" << std::endl; + + std::cerr << space; + for (unsigned long i = 0; i < getLength(); i++) { + if ((i % 64 == 0) && (i > 0)) { // new line + std::cerr << std::endl << space; + } + if (i % 8 == 0) { // new byte + std::cerr << " "; + } + std::cerr << ((*this)[i]); + } + std::cerr << std::endl; } #ifdef DEBUG -void BitString::printDebug (unsigned short level, unsigned short spc) const -{ - if (RUNDEBUGLEVEL(level)) { - print (spc) ; - } +void BitString::printDebug(unsigned short level, unsigned short spc) const { + if (RUNDEBUGLEVEL(level)) { + print(spc); + } } #endif diff --git a/src/BitString.h b/src/BitString.h index 61f614c..e8bab80 100644 --- a/src/BitString.h +++ b/src/BitString.h @@ -21,8 +21,8 @@ #ifndef SH_BITSTRING_H #define SH_BITSTRING_H -#include #include +#include #include "AUtils.h" #include "common.h" @@ -34,245 +34,242 @@ * This class provides a way to conveniently store and * manipulate a string of bits. Various objects can be * appended to a BitString. - * + * * For data storage a vector of BYTEs is used with little * endian bit encoding, i.e. the first bit is the least * significant bit of the first byte and so on. **/ class BitString { - public: - /** - * construct an empty BitString - **/ - BitString (EmbValue arity = 2) ; - - /** - * copy constructor - **/ - BitString (const BitString& bs) ; - - /** - * construct a BitString containing l bits with value zero - **/ - BitString (const unsigned long l) ; - - /** - * construct a BitString containing the data in d - **/ - BitString (const std::vector& d) ; - - /** - * construct a BitString containing the characters in d as 8 bit unsigned chars - **/ - BitString (const std::string& d) ; - - void setArity (EmbValue arity) ; - - EmbValue getArity (void) const - { return Arity ; } ; - - /** - * get the number of bits in this BitString - **/ - UWORD32 getLength (void) const - { return Length ; } ; - - /** - * get the number of EmbValues in this BitString (using this BitString's arity) - **/ - UWORD32 getNAryLength (void) const - { return AUtils::div_roundup (Length, ArityNBits) ; } ; - - /** - * delete the contents of this Bitstring - **/ - BitString& clear (void) ; - - /** - * append the bit v to this BitString - **/ - BitString& append (const BIT v) ; - - /** - * append n lower order bits of v to this BitString - * \param v the value to be appended - * \param n the number of bits to be appended - **/ - BitString& append (const BYTE v, const unsigned short n = 8) ; - - /** - * append n lower order bits of v to this BitString - * \param v the value to be appended - * \param n the number of bits to be appended - **/ - BitString& append (const UWORD16 v, const unsigned short n = 16) ; - - /** - * append n lower order bits of v to this BitString - * \param v the value to be appended - * \param n the number of bits to be appended - **/ - BitString& append (const UWORD32 v, const unsigned short n = 32) ; - - /** - * append the string v to this BitString - **/ - BitString& append (const std::string& v) ; - - /** - * append the vector v byte-wise to this BitString - **/ - BitString& append (const std::vector& v) ; - - /** - * append the BitString v to this BitString - * \param v the BitString to be appended - **/ - BitString& append (const BitString& v) ; - - /** - * set the p-th bit to v - * \param i the index (must be < getLength()) - * \param v the value - **/ - BitString& setBit (unsigned long i, BIT v) ; - - /** - * get a BitString that is a part of this BitString - * \param s the index of the first bit to be copied from this BitString - * \param l the total number of bits to be used for the return value - * \return the BitString containing of the bits [s...s+(l-1)] of this BitString - **/ - BitString getBits (const unsigned long s, const unsigned long l) const ; - - /** - * cut some bits out of this BitString - * \param s the index of the first bit to be removed from this BitString - * \param l the total number of bits to be removed - * \return the BitString containing of the bits [s...s+(l-1)] of this BitString - * - * After calling cutBits, this BitString consists of the bits 0,...,s-1,s+l,... . - **/ - BitString cutBits (const unsigned long s, const unsigned long l) ; - - /** - * return a value composed from bits in this BitString - * \param s the index of the first bit to be used for the return value - * \param l the total number of bits to be used for the return value (must be <= 32) - * \return the value (*this)[s],...,(*this)[s+l-1] - **/ - UWORD32 getValue (const unsigned long s, const unsigned short l) const ; - - /** - * get the contents of this BitString as vector of bytes - * \return the contents of this BitString as vector of bytes - * - * getLength() % 8 must be 0 to call this function - **/ - const std::vector& getBytes (void) const ; - - /** - * truncate this BitString - * \param s start - * \param e end - * \return this BitString modified to contain only (*this)[s]...(*this)[e - 1] - **/ - BitString& truncate (const unsigned long s, const unsigned long e) ; - - /** - * pad this BitString with the value in v - * \param mult this BitString is padded until size is a multiple of mult (given in bits) - * \param v the value this BitString should be padded with - **/ - BitString& pad (const unsigned long mult, const BIT v) ; - - /** - * pad this BitString with random data - * \param mult this BitString is padded until size is a multiple of mult (given in bits) - **/ - BitString& padRandom (const unsigned long mult) ; - - /** - * get an n-ary digit from this BitString - * \param p the position (in the n-ary representation of this BitString) - * \return the p-th n-ary digit - **/ - BYTE getNAry (unsigned long p) const ; - - /** - * append an n-ary digit to this BitString - * \param v the n-ary value to be appended - **/ - void appendNAry (BYTE v) ; - - /** - * compress this BitString using zlib's compress2 function - * \param level the compression level (ranging from 1 (best speed) to 9 (best compression) - * - * As zlib operates on byte vectors and not on bit vectors, this BitString is padded - * with zeros until the next byte boundary before starting the compression. - **/ - BitString& compress (int level) ; - - /** - * uncompress this BitString using zlib's uncompress function - * \param idestlen the length of the uncompressed data (in bits) - * \return this BitString modified to contain exactly idestlen uncompressed bits - * - * idestlen must be the size of the uncompressed data (in bits) to make - * it possible to allocate a destination buffer and to give information - * about the length of the uncompressed data without padding. - * - * A precondition for calling this function is that this BitString actually - * contains data that has been compressed by the BitString::compress function, - * and especially that the Length % 8 is 0. - **/ - BitString& uncompress (unsigned long idestlen) ; - - /** - * get the value of the i-th bit - **/ - BIT operator[] (const unsigned long i) const ; - - /** - * xor v with this BitString, saving the result in this Bitstring. - * The result has the same length as this BitString. - **/ - BitString& operator^= (const BitString &v) ; - - /** - * compare this BitString with the BitString v - * \return true iff the lengths are equal and for every valid index the value is equal - **/ - bool operator== (const BitString& v) const ; - - /** - * compare this BitString with the BitString v - * \return true iff the lengths are not equal or there exists an index with different values - **/ - bool operator!= (const BitString& v) const ; - - void print (unsigned short spc = 0) const ; + public: + /** + * construct an empty BitString + **/ + BitString(EmbValue arity = 2); + + /** + * copy constructor + **/ + BitString(const BitString &bs); + + /** + * construct a BitString containing l bits with value zero + **/ + BitString(const unsigned long l); + + /** + * construct a BitString containing the data in d + **/ + BitString(const std::vector &d); + + /** + * construct a BitString containing the characters in d as 8 bit unsigned chars + **/ + BitString(const std::string &d); + + void setArity(EmbValue arity); + + EmbValue getArity(void) const { return Arity; }; + + /** + * get the number of bits in this BitString + **/ + UWORD32 getLength(void) const { return Length; }; + + /** + * get the number of EmbValues in this BitString (using this BitString's arity) + **/ + UWORD32 getNAryLength(void) const { return AUtils::div_roundup(Length, ArityNBits); }; + + /** + * delete the contents of this Bitstring + **/ + BitString &clear(void); + + /** + * append the bit v to this BitString + **/ + BitString &append(const BIT v); + + /** + * append n lower order bits of v to this BitString + * \param v the value to be appended + * \param n the number of bits to be appended + **/ + BitString &append(const BYTE v, const unsigned short n = 8); + + /** + * append n lower order bits of v to this BitString + * \param v the value to be appended + * \param n the number of bits to be appended + **/ + BitString &append(const UWORD16 v, const unsigned short n = 16); + + /** + * append n lower order bits of v to this BitString + * \param v the value to be appended + * \param n the number of bits to be appended + **/ + BitString &append(const UWORD32 v, const unsigned short n = 32); + + /** + * append the string v to this BitString + **/ + BitString &append(const std::string &v); + + /** + * append the vector v byte-wise to this BitString + **/ + BitString &append(const std::vector &v); + + /** + * append the BitString v to this BitString + * \param v the BitString to be appended + **/ + BitString &append(const BitString &v); + + /** + * set the p-th bit to v + * \param i the index (must be < getLength()) + * \param v the value + **/ + BitString &setBit(unsigned long i, BIT v); + + /** + * get a BitString that is a part of this BitString + * \param s the index of the first bit to be copied from this BitString + * \param l the total number of bits to be used for the return value + * \return the BitString containing of the bits [s...s+(l-1)] of this BitString + **/ + BitString getBits(const unsigned long s, const unsigned long l) const; + + /** + * cut some bits out of this BitString + * \param s the index of the first bit to be removed from this BitString + * \param l the total number of bits to be removed + * \return the BitString containing of the bits [s...s+(l-1)] of this BitString + * + * After calling cutBits, this BitString consists of the bits 0,...,s-1,s+l,... . + **/ + BitString cutBits(const unsigned long s, const unsigned long l); + + /** + * return a value composed from bits in this BitString + * \param s the index of the first bit to be used for the return value + * \param l the total number of bits to be used for the return value (must be <= 32) + * \return the value (*this)[s],...,(*this)[s+l-1] + **/ + UWORD32 getValue(const unsigned long s, const unsigned short l) const; + + /** + * get the contents of this BitString as vector of bytes + * \return the contents of this BitString as vector of bytes + * + * getLength() % 8 must be 0 to call this function + **/ + const std::vector &getBytes(void) const; + + /** + * truncate this BitString + * \param s start + * \param e end + * \return this BitString modified to contain only (*this)[s]...(*this)[e - 1] + **/ + BitString &truncate(const unsigned long s, const unsigned long e); + + /** + * pad this BitString with the value in v + * \param mult this BitString is padded until size is a multiple of mult (given in bits) + * \param v the value this BitString should be padded with + **/ + BitString &pad(const unsigned long mult, const BIT v); + + /** + * pad this BitString with random data + * \param mult this BitString is padded until size is a multiple of mult (given in bits) + **/ + BitString &padRandom(const unsigned long mult); + + /** + * get an n-ary digit from this BitString + * \param p the position (in the n-ary representation of this BitString) + * \return the p-th n-ary digit + **/ + BYTE getNAry(unsigned long p) const; + + /** + * append an n-ary digit to this BitString + * \param v the n-ary value to be appended + **/ + void appendNAry(BYTE v); + + /** + * compress this BitString using zlib's compress2 function + * \param level the compression level (ranging from 1 (best speed) to 9 (best compression) + * + * As zlib operates on byte vectors and not on bit vectors, this BitString is padded + * with zeros until the next byte boundary before starting the compression. + **/ + BitString &compress(int level); + + /** + * uncompress this BitString using zlib's uncompress function + * \param idestlen the length of the uncompressed data (in bits) + * \return this BitString modified to contain exactly idestlen uncompressed bits + * + * idestlen must be the size of the uncompressed data (in bits) to make + * it possible to allocate a destination buffer and to give information + * about the length of the uncompressed data without padding. + * + * A precondition for calling this function is that this BitString actually + * contains data that has been compressed by the BitString::compress function, + * and especially that the Length % 8 is 0. + **/ + BitString &uncompress(unsigned long idestlen); + + /** + * get the value of the i-th bit + **/ + BIT operator[](const unsigned long i) const; + + /** + * xor v with this BitString, saving the result in this Bitstring. + * The result has the same length as this BitString. + **/ + BitString &operator^=(const BitString &v); + + /** + * compare this BitString with the BitString v + * \return true iff the lengths are equal and for every valid index the value is equal + **/ + bool operator==(const BitString &v) const; + + /** + * compare this BitString with the BitString v + * \return true iff the lengths are not equal or there exists an index with different values + **/ + bool operator!=(const BitString &v) const; + + void print(unsigned short spc = 0) const; #ifdef DEBUG - void printDebug (unsigned short level, unsigned short spc = 0) const ; + void printDebug(unsigned short level, unsigned short spc = 0) const; #endif - private: - /// the number of bits in Data - UWORD32 Length ; - /// the arity that will be used for getLength/getNAry/appendNAry - EmbValue Arity ; - /// the number of Bits per n-ary digit (where n is Arity) - unsigned short ArityNBits ; - /// the actual data - std::vector Data ; - - void _append (BIT v) ; - - /** - * clear unused part of last byte (_append depends on this) - **/ - void clearUnused (void) ; -} ; + private: + /// the number of bits in Data + UWORD32 Length; + /// the arity that will be used for getLength/getNAry/appendNAry + EmbValue Arity; + /// the number of Bits per n-ary digit (where n is Arity) + unsigned short ArityNBits; + /// the actual data + std::vector Data; + + void _append(BIT v); + + /** + * clear unused part of last byte (_append depends on this) + **/ + void clearUnused(void); +}; #endif // ndef SH_BITSTRING_H diff --git a/src/BmpFile.cc b/src/BmpFile.cc index 5373272..3a4beae 100644 --- a/src/BmpFile.cc +++ b/src/BmpFile.cc @@ -23,826 +23,862 @@ #include "AUtils.h" #include "BFSAPHeuristic.h" +#include "BmpFile.h" +#include "BmpPaletteSampleValue.h" +#include "BmpRGBSampleValue.h" #include "ColorPalette.h" #include "CvrStgFile.h" #include "DFSAPHeuristic.h" #include "DMDConstructionHeuristic.h" -#include "BmpFile.h" -#include "BmpPaletteSampleValue.h" -#include "BmpRGBSampleValue.h" -#include "SampleValueAdjacencyList.h" #include "SMDConstructionHeuristic.h" +#include "SampleValueAdjacencyList.h" #include "WKSConstructionHeuristic.h" #include "common.h" #include "error.h" -BmpFile::BmpFile (BinaryIO *io) - : CvrStgFile() -{ - read (io) ; -} +BmpFile::BmpFile(BinaryIO *io) : CvrStgFile() { read(io); } -BmpFile::~BmpFile () -{ - delete Palette ; -} +BmpFile::~BmpFile() { delete Palette; } -BmpFile::SUBFORMAT BmpFile::getSubformat () const -{ - return subformat ; -} +BmpFile::SUBFORMAT BmpFile::getSubformat() const { return subformat; } -void BmpFile::read (BinaryIO *io) -{ - CvrStgFile::read (io) ; - Palette = NULL ; +void BmpFile::read(BinaryIO *io) { + CvrStgFile::read(io); + Palette = NULL; - readheaders() ; - readdata() ; + readheaders(); + readdata(); } -void BmpFile::write () -{ - CvrStgFile::write() ; +void BmpFile::write() { + CvrStgFile::write(); - writeheaders() ; - writedata() ; + writeheaders(); + writedata(); } -std::list BmpFile::getProperties () const -{ - std::list retval ; +std::list BmpFile::getProperties() const { + std::list retval; - // format - std::string formatstring ; - switch (getSubformat()) { - case WIN: - formatstring = _("Windows 3.x bitmap") ; - break ; + // format + std::string formatstring; + switch (getSubformat()) { + case WIN: + formatstring = _("Windows 3.x bitmap"); + break; - case OS2: - formatstring = _("OS/2 1.x bitmap") ; - break ; - } - retval.push_back (CvrStgFile::Property (_("format"), formatstring)) ; + case OS2: + formatstring = _("OS/2 1.x bitmap"); + break; + } + retval.push_back(CvrStgFile::Property(_("format"), formatstring)); - return retval ; + return retval; } -std::vector BmpFile::getMatchingAlgorithms (Graph* g, Matching* m) const -{ - std::vector retval ; - if (getBitCount() == 24) { - retval.push_back (new SMDConstructionHeuristic (g, m)) ; - } - else { - retval.push_back (new SMDConstructionHeuristic (g, m)) ; - } - return retval ; +std::vector BmpFile::getMatchingAlgorithms(Graph *g, Matching *m) const { + std::vector retval; + if (getBitCount() == 24) { + retval.push_back(new SMDConstructionHeuristic(g, m)); + } else { + retval.push_back(new SMDConstructionHeuristic(g, m)); + } + return retval; } -unsigned long BmpFile::getNumSamples() const -{ - unsigned long retval = 0 ; - switch (getSubformat()) { - case WIN: { - retval = bmih.biWidth * bmih.biHeight ; - break ; } - - case OS2: { - retval = bmch.bcWidth * bmch.bcHeight ; - break ; } - } - return retval ; +unsigned long BmpFile::getNumSamples() const { + unsigned long retval = 0; + switch (getSubformat()) { + case WIN: { + retval = bmih.biWidth * bmih.biHeight; + break; + } + + case OS2: { + retval = bmch.bcWidth * bmch.bcHeight; + break; + } + } + return retval; } -void BmpFile::replaceSample (const SamplePos pos, const SampleValue* s) -{ - unsigned long index = 0 ; - unsigned short firstbit = 0 ; - calcIndex (pos, &index, &firstbit) ; - - unsigned short bitcount = getBitCount() ; - switch (bitcount) { - case 1: case 4: case 8: { - const BmpPaletteSampleValue* sample = dynamic_cast (s) ; - myassert (sample) ; - - for (unsigned short i = 0 ; i < bitcount ; i++) { - BitmapData[index] = BitmapData[index] & (~(1 << (firstbit + i))) ; - BitmapData[index] = BitmapData[index] | ((sample->getIndex() & (1 << i)) << firstbit) ; - } - break ; } - - case 24: { - const BmpRGBSampleValue* sample = dynamic_cast (s) ; - myassert (sample) ; - - BitmapData[index] = sample->getBlue() ; - BitmapData[index + 1] = sample->getGreen() ; - BitmapData[index + 2] = sample->getRed() ; - break ; } - } +void BmpFile::replaceSample(const SamplePos pos, const SampleValue *s) { + unsigned long index = 0; + unsigned short firstbit = 0; + calcIndex(pos, &index, &firstbit); + + unsigned short bitcount = getBitCount(); + switch (bitcount) { + case 1: + case 4: + case 8: { + const BmpPaletteSampleValue *sample = dynamic_cast(s); + myassert(sample); + + for (unsigned short i = 0; i < bitcount; i++) { + BitmapData[index] = BitmapData[index] & (~(1 << (firstbit + i))); + BitmapData[index] = BitmapData[index] | ((sample->getIndex() & (1 << i)) << firstbit); + } + break; + } + + case 24: { + const BmpRGBSampleValue *sample = dynamic_cast(s); + myassert(sample); + + BitmapData[index] = sample->getBlue(); + BitmapData[index + 1] = sample->getGreen(); + BitmapData[index + 2] = sample->getRed(); + break; + } + } } -SampleValue *BmpFile::getSampleValue (SamplePos pos) const -{ - unsigned long index = 0 ; - unsigned short firstbit = 0 ; - calcIndex (pos, &index, &firstbit) ; - - unsigned short bitcount = getBitCount() ; - SampleValue *retval = NULL ; - switch (bitcount) { - case 1: case 4: case 8: { - BYTE idx_pal = 0 ; - for (unsigned short i = 0 ; i < bitcount ; i++) { - idx_pal |= ((BitmapData[index] & (1 << (firstbit + i))) >> firstbit) ; - } - retval = (SampleValue*) new BmpPaletteSampleValue (idx_pal) ; - break ; } - - case 24: { - retval = (SampleValue*) new BmpRGBSampleValue (BitmapData[index + 2], BitmapData[index + 1], BitmapData[index]) ; - break ; } - } - return retval ; +SampleValue *BmpFile::getSampleValue(SamplePos pos) const { + unsigned long index = 0; + unsigned short firstbit = 0; + calcIndex(pos, &index, &firstbit); + + unsigned short bitcount = getBitCount(); + SampleValue *retval = NULL; + switch (bitcount) { + case 1: + case 4: + case 8: { + BYTE idx_pal = 0; + for (unsigned short i = 0; i < bitcount; i++) { + idx_pal |= ((BitmapData[index] & (1 << (firstbit + i))) >> firstbit); + } + retval = (SampleValue *)new BmpPaletteSampleValue(idx_pal); + break; + } + + case 24: { + retval = (SampleValue *)new BmpRGBSampleValue(BitmapData[index + 2], BitmapData[index + 1], + BitmapData[index]); + break; + } + } + return retval; } -std::vector BmpFile::calcSVAdjacencyLists (const std::vector& svs) const -{ - if (getBitCount() == 24) { - EmbValue m = getEmbValueModulus() ; - UWORD32 r = getRadius() ; - - // create svalists - std::vector lists (m) ; - for (EmbValue i = 0 ; i < m ; i++) { - lists[i] = new SampleValueAdjacencyList (svs.size()) ; - } - - // redmap contains all sample values in a 3-dimensional RGB-tree - typedef std::map BlueMap ; - typedef std::map GreenMap ; - typedef std::map RedMap ; - RedMap redmap ; - for (std::vector::const_iterator svit = svs.begin() ; svit != svs.end() ; svit++) { - BmpRGBSampleValue* rgbsv = (BmpRGBSampleValue*) (*svit) ; - redmap[rgbsv->getRed()][rgbsv->getGreen()][rgbsv->getBlue()] = rgbsv ; - } - - // create hemisphere matrix (will contain a discrete hemisphere with radius getRadius()) - unsigned short r_eucl = (unsigned short) sqrt (r) ; // the euclidean radius (not squared) - rounded to next lower natural number - short hemisphere[2 * r_eucl + 1][2 * r_eucl + 1] ; - for (short dr = -r_eucl ; dr <= r_eucl ; dr++) { - for (short dg = -r_eucl ; dg <= r_eucl ; dg++) { - short db_sq = r_eucl*r_eucl - dr*dr - dg*dg ; - if (db_sq >= 0) { - // round hemishpere points to next lower natural numbers - hemisphere[dr + r_eucl][dg + r_eucl] = (short) sqrt (db_sq) ; - } - else { - hemisphere[dr + r_eucl][dg + r_eucl] = -1 ; - } - } - } - - // - // fill adjacency lists - // - - // create reservoir - for every i reservoir[i] contains the sample values that are neighbourss of - // the sample value with label i and have a lower label (and have already been found) - // This is necessary to use collapsing trees together with bucket sort (without huge increase in memory usage) - std::vector reservoir[svs.size()] ; - - // neighbours sorted by distance (for the current source sample value) - std::vector neighbours_byd[r + 1] ; - - for (std::vector::const_iterator srcsvit = svs.begin() ; srcsvit != svs.end() ; srcsvit++) { - BmpRGBSampleValue* srcsv = (BmpRGBSampleValue*) (*srcsvit) ; - - // sort reservoir into neighbours_byd - for (std::vector::const_iterator it = reservoir[srcsv->getLabel()].begin() ; - it != reservoir[srcsv->getLabel()].end() ; it++) { - neighbours_byd[srcsv->calcDistance(*it)].push_back (*it) ; - } - - unsigned short r_abs_start = AUtils::bminus (srcsv->getRed(), r_eucl) ; - unsigned short r_abs_end = AUtils::bplus (srcsv->getRed(), r_eucl) ; - unsigned short g_abs_start = AUtils::bminus (srcsv->getGreen(), r_eucl) ; - unsigned short g_abs_end = AUtils::bplus (srcsv->getGreen(), r_eucl) ; - - RedMap::iterator rit = redmap.lower_bound (r_abs_start) ; - while ((rit != redmap.end()) && (rit->first <= r_abs_end)) { - GreenMap& greenmap = rit->second ; - - if (greenmap.empty()) { - RedMap::iterator delme = rit ; - rit++ ; - redmap.erase (delme) ; - } - else { - GreenMap::iterator git = greenmap.lower_bound (g_abs_start) ; - while ((git != greenmap.end()) && (git->first <= g_abs_end)) { - unsigned short red_index = (rit->first - srcsv->getRed()) + r_eucl ; - unsigned short green_index = (git->first - srcsv->getGreen()) + r_eucl ; - short delta_b = hemisphere[red_index][green_index] ; - - if (delta_b < 0) { // this blue map has no sample values in sphere - git++ ; - } - else { - BlueMap& bluemap = git->second ; - if (bluemap.empty()) { - GreenMap::iterator delme = git ; - git++ ; - greenmap.erase (delme) ; - } - else { - unsigned short b_abs_start = AUtils::bminus (srcsv->getBlue(), delta_b) ; - unsigned short b_abs_end = AUtils::bplus (srcsv->getBlue(), delta_b) ; - BlueMap::iterator bit = bluemap.lower_bound (b_abs_start) ; - while ((bit != bluemap.end()) && (bit->first <= b_abs_end)) { - if (srcsv->getLabel() < bit->second->getLabel()) { - neighbours_byd[srcsv->calcDistance(bit->second)].push_back (bit->second) ; - reservoir[bit->second->getLabel()].push_back (srcsv) ; - bit++ ; - } - else { - BlueMap::iterator delme = bit ; - bit++ ; - bluemap.erase (delme) ; - } - } - git++ ; - } - } - } // end of git loop - - rit++ ; - } - } // end of rit loop - - for (unsigned short d = 0 ; d <= r ; d++) { - if (!neighbours_byd[d].empty()) { - for (std::vector::const_iterator it = neighbours_byd[d].begin() ; - it != neighbours_byd[d].end() ; it++) { - (*(lists[(*it)->getEmbeddedValue()]))[srcsv].push_back (*it) ; - } - neighbours_byd[d].clear() ; - } - } - } // end of svs for loop - - return lists ; - } - else { - return CvrStgFile::calcSVAdjacencyLists(svs) ; - } +std::vector +BmpFile::calcSVAdjacencyLists(const std::vector &svs) const { + if (getBitCount() == 24) { + EmbValue m = getEmbValueModulus(); + UWORD32 r = getRadius(); + + // create svalists + std::vector lists(m); + for (EmbValue i = 0; i < m; i++) { + lists[i] = new SampleValueAdjacencyList(svs.size()); + } + + // redmap contains all sample values in a 3-dimensional RGB-tree + typedef std::map BlueMap; + typedef std::map GreenMap; + typedef std::map RedMap; + RedMap redmap; + for (std::vector::const_iterator svit = svs.begin(); svit != svs.end(); + svit++) { + BmpRGBSampleValue *rgbsv = (BmpRGBSampleValue *)(*svit); + redmap[rgbsv->getRed()][rgbsv->getGreen()][rgbsv->getBlue()] = rgbsv; + } + + // create hemisphere matrix (will contain a discrete hemisphere with radius + // getRadius()) + unsigned short r_eucl = (unsigned short)sqrt(r); // the euclidean radius (not squared) - + // rounded to next lower natural number + short hemisphere[2 * r_eucl + 1][2 * r_eucl + 1]; + for (short dr = -r_eucl; dr <= r_eucl; dr++) { + for (short dg = -r_eucl; dg <= r_eucl; dg++) { + short db_sq = r_eucl * r_eucl - dr * dr - dg * dg; + if (db_sq >= 0) { + // round hemishpere points to next lower natural numbers + hemisphere[dr + r_eucl][dg + r_eucl] = (short)sqrt(db_sq); + } else { + hemisphere[dr + r_eucl][dg + r_eucl] = -1; + } + } + } + + // + // fill adjacency lists + // + + // create reservoir - for every i reservoir[i] contains the sample values + // that are neighbourss of the sample value with label i and have a lower + // label (and have already been found) This is necessary to use collapsing + // trees together with bucket sort (without huge increase in memory usage) + std::vector reservoir[svs.size()]; + + // neighbours sorted by distance (for the current source sample value) + std::vector neighbours_byd[r + 1]; + + for (std::vector::const_iterator srcsvit = svs.begin(); srcsvit != svs.end(); + srcsvit++) { + BmpRGBSampleValue *srcsv = (BmpRGBSampleValue *)(*srcsvit); + + // sort reservoir into neighbours_byd + for (std::vector::const_iterator it = + reservoir[srcsv->getLabel()].begin(); + it != reservoir[srcsv->getLabel()].end(); it++) { + neighbours_byd[srcsv->calcDistance(*it)].push_back(*it); + } + + unsigned short r_abs_start = AUtils::bminus(srcsv->getRed(), r_eucl); + unsigned short r_abs_end = AUtils::bplus(srcsv->getRed(), r_eucl); + unsigned short g_abs_start = AUtils::bminus(srcsv->getGreen(), r_eucl); + unsigned short g_abs_end = + AUtils::bplus(srcsv->getGreen(), r_eucl); + + RedMap::iterator rit = redmap.lower_bound(r_abs_start); + while ((rit != redmap.end()) && (rit->first <= r_abs_end)) { + GreenMap &greenmap = rit->second; + + if (greenmap.empty()) { + RedMap::iterator delme = rit; + rit++; + redmap.erase(delme); + } else { + GreenMap::iterator git = greenmap.lower_bound(g_abs_start); + while ((git != greenmap.end()) && (git->first <= g_abs_end)) { + unsigned short red_index = (rit->first - srcsv->getRed()) + r_eucl; + unsigned short green_index = (git->first - srcsv->getGreen()) + r_eucl; + short delta_b = hemisphere[red_index][green_index]; + + if (delta_b < 0) { // this blue map has no sample values in sphere + git++; + } else { + BlueMap &bluemap = git->second; + if (bluemap.empty()) { + GreenMap::iterator delme = git; + git++; + greenmap.erase(delme); + } else { + unsigned short b_abs_start = + AUtils::bminus(srcsv->getBlue(), delta_b); + unsigned short b_abs_end = + AUtils::bplus(srcsv->getBlue(), delta_b); + BlueMap::iterator bit = bluemap.lower_bound(b_abs_start); + while ((bit != bluemap.end()) && (bit->first <= b_abs_end)) { + if (srcsv->getLabel() < bit->second->getLabel()) { + neighbours_byd[srcsv->calcDistance(bit->second)].push_back( + bit->second); + reservoir[bit->second->getLabel()].push_back(srcsv); + bit++; + } else { + BlueMap::iterator delme = bit; + bit++; + bluemap.erase(delme); + } + } + git++; + } + } + } // end of git loop + + rit++; + } + } // end of rit loop + + for (unsigned short d = 0; d <= r; d++) { + if (!neighbours_byd[d].empty()) { + for (std::vector::const_iterator it = + neighbours_byd[d].begin(); + it != neighbours_byd[d].end(); it++) { + (*(lists[(*it)->getEmbeddedValue()]))[srcsv].push_back(*it); + } + neighbours_byd[d].clear(); + } + } + } // end of svs for loop + + return lists; + } else { + return CvrStgFile::calcSVAdjacencyLists(svs); + } } -void BmpFile::calcIndex (SamplePos pos, unsigned long* index, unsigned short* firstbit) const -{ - unsigned long width = getWidth(), bitcount = getBitCount() ; - - unsigned long bytesperline_nonpadded = 0 ; - if (width * bitcount % 8 == 0) { - bytesperline_nonpadded = (width * bitcount) / 8 ; - } - else { - bytesperline_nonpadded = (width * bitcount) / 8 + 1 ; - } - - unsigned long row = pos / width ; - pos = pos % width ; - - unsigned long column = 0 ; - switch (bitcount) { - case 1: case 4: case 8: - { - unsigned short samplesperbyte = 8 / bitcount ; - - column = pos / samplesperbyte ; - - // to account for the order pixels are stored in one byte: - *firstbit = (samplesperbyte - (pos % samplesperbyte) - 1) * bitcount ; - - myassert (*firstbit < 8) ; - } - break ; - - case 24: - column = pos * 3 ; - *firstbit = 0 ; - break ; - - default: - myassert(false) ; - break ; - } - - *index = bytesperline_nonpadded * row + column ; -} +void BmpFile::calcIndex(SamplePos pos, unsigned long *index, unsigned short *firstbit) const { + unsigned long width = getWidth(), bitcount = getBitCount(); -unsigned short BmpFile::getBitCount() const -{ - unsigned short retval = 0 ; - switch (getSubformat()) { - case WIN: { - retval = bmih.biBitCount ; - break ; } - - case OS2: { - retval = bmch.bcBitCount ; - break ; } - } - myassert (retval == 1 || retval == 4 || retval == 8 || retval == 24) ; - return retval ; -} + unsigned long bytesperline_nonpadded = 0; + if (width * bitcount % 8 == 0) { + bytesperline_nonpadded = (width * bitcount) / 8; + } else { + bytesperline_nonpadded = (width * bitcount) / 8 + 1; + } + + unsigned long row = pos / width; + pos = pos % width; + + unsigned long column = 0; + switch (bitcount) { + case 1: + case 4: + case 8: { + unsigned short samplesperbyte = 8 / bitcount; + + column = pos / samplesperbyte; + + // to account for the order pixels are stored in one byte: + *firstbit = (samplesperbyte - (pos % samplesperbyte) - 1) * bitcount; + + myassert(*firstbit < 8); + } break; -unsigned long BmpFile::getWidth() const -{ - unsigned long retval = 0 ; - switch (getSubformat()) { - case WIN: - retval = bmih.biWidth ; - break ; - - case OS2: - retval = bmch.bcWidth ; - break ; - } - return retval ; + case 24: + column = pos * 3; + *firstbit = 0; + break; + + default: + myassert(false); + break; + } + + *index = bytesperline_nonpadded * row + column; } -unsigned long BmpFile::getHeight() const -{ - unsigned long retval = 0 ; - switch (getSubformat()) { - case WIN: { - retval = bmih.biHeight ; - break ; } +unsigned short BmpFile::getBitCount() const { + unsigned short retval = 0; + switch (getSubformat()) { + case WIN: { + retval = bmih.biBitCount; + break; + } + + case OS2: { + retval = bmch.bcBitCount; + break; + } + } + myassert(retval == 1 || retval == 4 || retval == 8 || retval == 24); + return retval; +} - case OS2: { - retval = bmch.bcHeight ; - break ; } - } +unsigned long BmpFile::getWidth() const { + unsigned long retval = 0; + switch (getSubformat()) { + case WIN: + retval = bmih.biWidth; + break; + + case OS2: + retval = bmch.bcWidth; + break; + } + return retval; +} - return retval ; +unsigned long BmpFile::getHeight() const { + unsigned long retval = 0; + switch (getSubformat()) { + case WIN: { + retval = bmih.biHeight; + break; + } + + case OS2: { + retval = bmch.bcHeight; + break; + } + } + + return retval; } -ColorPalette *BmpFile::getPalette() const -{ - myassert (getBitCount() != 24) ; - myassert (Palette) ; - return Palette ; +ColorPalette *BmpFile::getPalette() const { + myassert(getBitCount() != 24); + myassert(Palette); + return Palette; } /* reads the headers of a bmp file from disk */ -void BmpFile::readheaders () -{ - try { - bmfh.bfType = IdBm ; - bmfh.bfSize = getBinIO()->read32_le() ; - bmfh.bfReserved1 = getBinIO()->read16_le() ; - bmfh.bfReserved2 = getBinIO()->read16_le() ; - bmfh.bfOffBits = getBinIO()->read32_le() ; - - unsigned long tmpSize = getBinIO()->read32_le() ; - switch (tmpSize) { - case SizeBMINFOHEADER: { - // this file is in the Windows bmp format - subformat = WIN ; - bmpwin_readheaders () ; - break ; } - - case SizeBMCOREHEADER: { - // this file is in the OS/2 bmp format - subformat = OS2 ; - bmpos2_readheaders () ; - break ; } - - default: { - if (getBinIO()->is_std()) { - throw NotImplementedError (_("the bmp data from standard input has a format that is not supported (biSize: %lu)."), tmpSize) ; - } - else { - throw NotImplementedError (_("the bmp file \"%s\" has a format that is not supported (biSize: %lu)."), getBinIO()->getName().c_str(), tmpSize) ; - } - break ; } - } - } - catch (BinaryInputError e) { - switch (e.getType()) { - case BinaryInputError::FILE_ERR: { - throw SteghideError (_("an error occurred while reading the bmp headers from the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryInputError::FILE_EOF: { - throw SteghideError (_("premature end of file \"%s\" while reading bmp headers."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryInputError::STDIN_ERR: { - throw SteghideError (_("an error occurred while reading the bmp headers from standard input.")) ; - break ; } - - case BinaryInputError::STDIN_EOF: { - throw SteghideError (_("premature end of data from standard input while reading bmp headers.")) ; - break ; } - } - } +void BmpFile::readheaders() { + try { + bmfh.bfType = IdBm; + bmfh.bfSize = getBinIO()->read32_le(); + bmfh.bfReserved1 = getBinIO()->read16_le(); + bmfh.bfReserved2 = getBinIO()->read16_le(); + bmfh.bfOffBits = getBinIO()->read32_le(); + + unsigned long tmpSize = getBinIO()->read32_le(); + switch (tmpSize) { + case SizeBMINFOHEADER: { + // this file is in the Windows bmp format + subformat = WIN; + bmpwin_readheaders(); + break; + } + + case SizeBMCOREHEADER: { + // this file is in the OS/2 bmp format + subformat = OS2; + bmpos2_readheaders(); + break; + } + + default: { + if (getBinIO()->is_std()) { + throw NotImplementedError(_("the bmp data from standard input has a format that is " + "not supported (biSize: %lu)."), + tmpSize); + } else { + throw NotImplementedError( + _("the bmp file \"%s\" has a format that is not supported (biSize: %lu)."), + getBinIO()->getName().c_str(), tmpSize); + } + break; + } + } + } catch (BinaryInputError e) { + switch (e.getType()) { + case BinaryInputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while reading the bmp headers from the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::FILE_EOF: { + throw SteghideError(_("premature end of file \"%s\" while reading bmp headers."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::STDIN_ERR: { + throw SteghideError( + _("an error occurred while reading the bmp headers from standard input.")); + break; + } + + case BinaryInputError::STDIN_EOF: { + throw SteghideError( + _("premature end of data from standard input while reading bmp headers.")); + break; + } + } + } } -void BmpFile::bmpwin_readheaders () -{ - bmih.biSize = SizeBMINFOHEADER ; - bmih.biWidth = getBinIO()->read32_le () ; - bmih.biHeight = getBinIO()->read32_le () ; - bmih.biPlanes = getBinIO()->read16_le () ; - myassert (bmih.biPlanes == 1) ; - bmih.biBitCount = getBinIO()->read16_le () ; - switch (bmih.biBitCount) { - case 1: - setSamplesPerVertex (SamplesPerVertex_SmallPalette) ; - setEmbValueModulus (EmbValueModulus_SmallPalette) ; - setRadius (Radius_Palette) ; - break ; - - case 4: - setSamplesPerVertex (SamplesPerVertex_SmallPalette) ; - setEmbValueModulus (EmbValueModulus_SmallPalette) ; - setRadius (Radius_Palette) ; - break ; - - case 8: - setSamplesPerVertex (SamplesPerVertex_LargePalette) ; - setEmbValueModulus (EmbValueModulus_LargePalette) ; - setRadius (Radius_Palette) ; - break ; - - case 24: - setSamplesPerVertex (SamplesPerVertex_RGB) ; - setEmbValueModulus (EmbValueModulus_RGB) ; - setRadius (Radius_RGB) ; - break ; - - default: - if (getBinIO()->is_std()) { - throw NotImplementedError (_("the bmp data from standard input has a format that is not supported (biBitCount: %d)."), bmih.biBitCount) ; - } - else { - throw NotImplementedError (_("the bmp file \"%s\" has a format that is not supported (biBitCount: %d)."), getBinIO()->getName().c_str(), bmih.biBitCount) ; - } - break ; - } - bmih.biCompression = getBinIO()->read32_le () ; - if (bmih.biCompression != COMPRESSION_BI_RGB) { - if (getBinIO()->is_std()) { - throw NotImplementedError (_("the bitmap data from standard input is compressed which is not supported.")) ; - } - else { - throw NotImplementedError (_("the bitmap data in \"%s\" is compressed which is not supported."), getBinIO()->getName().c_str()) ; - } - } - bmih.biSizeImage = getBinIO()->read32_le () ; - bmih.biXPelsPerMeter = getBinIO()->read32_le () ; - bmih.biYPelsPerMeter = getBinIO()->read32_le () ; - bmih.biClrUsed = getBinIO()->read32_le () ; - bmih.biClrImportant = getBinIO()->read32_le () ; - - if (bmih.biBitCount != 24) { - /* a color table exists */ - Palette = new ColorPalette() ; - unsigned int ncolors = 0 ; - switch (bmih.biBitCount) { - case 1: { - if (Args.Command.getValue() == EMBED) { - Warning w (_("using a black/white bitmap as cover is very insecure!")) ; - w.printMessage() ; - } - ncolors = 2 ; - break ; } - - case 4: { - if (Args.Command.getValue() == EMBED) { - Warning w (_("using a 16-color bitmap as cover is very insecure!")) ; - w.printMessage() ; - } - ncolors = 16 ; - break ; } - - case 8: { - ncolors = 256 ; - break ; } - - default: { - myassert (0) ; - break ; } - } - if (bmih.biClrUsed != 0) { - ncolors = bmih.biClrUsed ; - } - - for (unsigned int i = 0 ; i < ncolors ; i++) { - unsigned char b = getBinIO()->read8() ; - unsigned char g = getBinIO()->read8() ; - unsigned char r = getBinIO()->read8() ; - if (getBinIO()->read8() != 0) { - Warning w (_("maybe corrupted windows bmp data (Reserved in RGBQUAD is non-zero).")) ; - w.printMessage() ; - } - Palette->addEntry(r, g, b) ; - } - } +void BmpFile::bmpwin_readheaders() { + bmih.biSize = SizeBMINFOHEADER; + bmih.biWidth = getBinIO()->read32_le(); + bmih.biHeight = getBinIO()->read32_le(); + bmih.biPlanes = getBinIO()->read16_le(); + myassert(bmih.biPlanes == 1); + bmih.biBitCount = getBinIO()->read16_le(); + switch (bmih.biBitCount) { + case 1: + setSamplesPerVertex(SamplesPerVertex_SmallPalette); + setEmbValueModulus(EmbValueModulus_SmallPalette); + setRadius(Radius_Palette); + break; + + case 4: + setSamplesPerVertex(SamplesPerVertex_SmallPalette); + setEmbValueModulus(EmbValueModulus_SmallPalette); + setRadius(Radius_Palette); + break; + + case 8: + setSamplesPerVertex(SamplesPerVertex_LargePalette); + setEmbValueModulus(EmbValueModulus_LargePalette); + setRadius(Radius_Palette); + break; + + case 24: + setSamplesPerVertex(SamplesPerVertex_RGB); + setEmbValueModulus(EmbValueModulus_RGB); + setRadius(Radius_RGB); + break; + + default: + if (getBinIO()->is_std()) { + throw NotImplementedError(_("the bmp data from standard input has a format that is not " + "supported (biBitCount: %d)."), + bmih.biBitCount); + } else { + throw NotImplementedError(_("the bmp file \"%s\" has a format that is " + "not supported (biBitCount: %d)."), + getBinIO()->getName().c_str(), bmih.biBitCount); + } + break; + } + bmih.biCompression = getBinIO()->read32_le(); + if (bmih.biCompression != COMPRESSION_BI_RGB) { + if (getBinIO()->is_std()) { + throw NotImplementedError(_("the bitmap data from standard input is " + "compressed which is not supported.")); + } else { + throw NotImplementedError( + _("the bitmap data in \"%s\" is compressed which is not supported."), + getBinIO()->getName().c_str()); + } + } + bmih.biSizeImage = getBinIO()->read32_le(); + bmih.biXPelsPerMeter = getBinIO()->read32_le(); + bmih.biYPelsPerMeter = getBinIO()->read32_le(); + bmih.biClrUsed = getBinIO()->read32_le(); + bmih.biClrImportant = getBinIO()->read32_le(); + + if (bmih.biBitCount != 24) { + /* a color table exists */ + Palette = new ColorPalette(); + unsigned int ncolors = 0; + switch (bmih.biBitCount) { + case 1: { + if (Args.Command.getValue() == EMBED) { + Warning w(_("using a black/white bitmap as cover is very insecure!")); + w.printMessage(); + } + ncolors = 2; + break; + } + + case 4: { + if (Args.Command.getValue() == EMBED) { + Warning w(_("using a 16-color bitmap as cover is very insecure!")); + w.printMessage(); + } + ncolors = 16; + break; + } + + case 8: { + ncolors = 256; + break; + } + + default: { + myassert(0); + break; + } + } + if (bmih.biClrUsed != 0) { + ncolors = bmih.biClrUsed; + } + + for (unsigned int i = 0; i < ncolors; i++) { + unsigned char b = getBinIO()->read8(); + unsigned char g = getBinIO()->read8(); + unsigned char r = getBinIO()->read8(); + if (getBinIO()->read8() != 0) { + Warning w(_("maybe corrupted windows bmp data (Reserved in RGBQUAD is " + "non-zero).")); + w.printMessage(); + } + Palette->addEntry(r, g, b); + } + } } -void BmpFile::bmpos2_readheaders () -{ - bmch.bcSize = SizeBMCOREHEADER ; - bmch.bcWidth = getBinIO()->read16_le () ; - bmch.bcHeight = getBinIO()->read16_le () ; - bmch.bcPlanes = getBinIO()->read16_le () ; - myassert (bmch.bcPlanes == 1) ; - bmch.bcBitCount = getBinIO()->read16_le () ; - switch (bmch.bcBitCount) { - case 1: - setSamplesPerVertex (SamplesPerVertex_SmallPalette) ; - setEmbValueModulus (EmbValueModulus_SmallPalette) ; - setRadius (Radius_Palette) ; - break ; - - case 4: - setSamplesPerVertex (SamplesPerVertex_SmallPalette) ; - setEmbValueModulus (EmbValueModulus_SmallPalette) ; - setRadius (Radius_Palette) ; - break ; - - case 8: - setSamplesPerVertex (SamplesPerVertex_LargePalette) ; - setEmbValueModulus (EmbValueModulus_LargePalette) ; - setRadius (Radius_Palette) ; - break ; - - case 24: - setSamplesPerVertex (SamplesPerVertex_RGB) ; - setEmbValueModulus (EmbValueModulus_RGB) ; - setRadius (Radius_RGB) ; - break ; - - default: - if (getBinIO()->is_std()) { - throw NotImplementedError (_("the bmp data from standard input has a format that is not supported (bcBitCount: %d)."), bmch.bcBitCount) ; - } - else { - throw NotImplementedError (_("the bmp file \"%s\" has a format that is not supported (bcBitCount: %d)."), getBinIO()->getName().c_str(), bmch.bcBitCount) ; - } - break ; - } - - if (bmch.bcBitCount != 24) { - /* a color table exists */ - unsigned int ncolors = 0 ; - Palette = new ColorPalette() ; - switch (bmch.bcBitCount) { - case 1: { - if (Args.Command.getValue() == EMBED) { - Warning w (_("using a black/white bitmap as cover is very insecure!")) ; - w.printMessage() ; - } - ncolors = 2 ; - break ; } - - case 4: { - if (Args.Command.getValue() == EMBED) { - Warning w (_("using a 16-color bitmap as cover is very insecure!")) ; - w.printMessage() ; - } - ncolors = 16 ; - break ; } - - case 8: { - ncolors = 256 ; - break ; } - - default: { - myassert (0) ; - break ; } - } - - for (unsigned int i = 0 ; i < ncolors ; i++) { - unsigned char b = getBinIO()->read8() ; - unsigned char g = getBinIO()->read8() ; - unsigned char r = getBinIO()->read8() ; - Palette->addEntry (r, g, b) ; - } - } +void BmpFile::bmpos2_readheaders() { + bmch.bcSize = SizeBMCOREHEADER; + bmch.bcWidth = getBinIO()->read16_le(); + bmch.bcHeight = getBinIO()->read16_le(); + bmch.bcPlanes = getBinIO()->read16_le(); + myassert(bmch.bcPlanes == 1); + bmch.bcBitCount = getBinIO()->read16_le(); + switch (bmch.bcBitCount) { + case 1: + setSamplesPerVertex(SamplesPerVertex_SmallPalette); + setEmbValueModulus(EmbValueModulus_SmallPalette); + setRadius(Radius_Palette); + break; + + case 4: + setSamplesPerVertex(SamplesPerVertex_SmallPalette); + setEmbValueModulus(EmbValueModulus_SmallPalette); + setRadius(Radius_Palette); + break; + + case 8: + setSamplesPerVertex(SamplesPerVertex_LargePalette); + setEmbValueModulus(EmbValueModulus_LargePalette); + setRadius(Radius_Palette); + break; + + case 24: + setSamplesPerVertex(SamplesPerVertex_RGB); + setEmbValueModulus(EmbValueModulus_RGB); + setRadius(Radius_RGB); + break; + + default: + if (getBinIO()->is_std()) { + throw NotImplementedError(_("the bmp data from standard input has a format that is not " + "supported (bcBitCount: %d)."), + bmch.bcBitCount); + } else { + throw NotImplementedError(_("the bmp file \"%s\" has a format that is " + "not supported (bcBitCount: %d)."), + getBinIO()->getName().c_str(), bmch.bcBitCount); + } + break; + } + + if (bmch.bcBitCount != 24) { + /* a color table exists */ + unsigned int ncolors = 0; + Palette = new ColorPalette(); + switch (bmch.bcBitCount) { + case 1: { + if (Args.Command.getValue() == EMBED) { + Warning w(_("using a black/white bitmap as cover is very insecure!")); + w.printMessage(); + } + ncolors = 2; + break; + } + + case 4: { + if (Args.Command.getValue() == EMBED) { + Warning w(_("using a 16-color bitmap as cover is very insecure!")); + w.printMessage(); + } + ncolors = 16; + break; + } + + case 8: { + ncolors = 256; + break; + } + + default: { + myassert(0); + break; + } + } + + for (unsigned int i = 0; i < ncolors; i++) { + unsigned char b = getBinIO()->read8(); + unsigned char g = getBinIO()->read8(); + unsigned char r = getBinIO()->read8(); + Palette->addEntry(r, g, b); + } + } } /* writes the headers of a bmp file to disk */ -void BmpFile::writeheaders () -{ - try { - getBinIO()->write16_le (bmfh.bfType) ; - getBinIO()->write32_le (bmfh.bfSize) ; - getBinIO()->write16_le (bmfh.bfReserved1) ; - getBinIO()->write16_le (bmfh.bfReserved2) ; - getBinIO()->write32_le (bmfh.bfOffBits) ; - - switch (getSubformat()) { - case WIN: { - bmpwin_writeheaders() ; - break ; } - - case OS2: { - bmpos2_writeheaders() ; - break ; } - - default: { - myassert (0) ; - break ; } - } - } - catch (BinaryOutputError e) { - switch (e.getType()) { - case BinaryOutputError::FILE_ERR: { - throw SteghideError (_("an error occurred while writing the bmp headers to the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryOutputError::STDOUT_ERR: { - throw SteghideError (_("an error occurred while writing the bmp headers to standard output.")) ; - break ; } - } - } +void BmpFile::writeheaders() { + try { + getBinIO()->write16_le(bmfh.bfType); + getBinIO()->write32_le(bmfh.bfSize); + getBinIO()->write16_le(bmfh.bfReserved1); + getBinIO()->write16_le(bmfh.bfReserved2); + getBinIO()->write32_le(bmfh.bfOffBits); + + switch (getSubformat()) { + case WIN: { + bmpwin_writeheaders(); + break; + } + + case OS2: { + bmpos2_writeheaders(); + break; + } + + default: { + myassert(0); + break; + } + } + } catch (BinaryOutputError e) { + switch (e.getType()) { + case BinaryOutputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while writing the bmp headers to the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryOutputError::STDOUT_ERR: { + throw SteghideError( + _("an error occurred while writing the bmp headers to standard output.")); + break; + } + } + } } -void BmpFile::bmpwin_writeheaders () -{ - getBinIO()->write32_le (bmih.biSize) ; - getBinIO()->write32_le (bmih.biWidth) ; - getBinIO()->write32_le (bmih.biHeight) ; - getBinIO()->write16_le (bmih.biPlanes) ; - getBinIO()->write16_le (bmih.biBitCount) ; - getBinIO()->write32_le (bmih.biCompression) ; - getBinIO()->write32_le (bmih.biSizeImage) ; - getBinIO()->write32_le (bmih.biXPelsPerMeter) ; - getBinIO()->write32_le (bmih.biYPelsPerMeter) ; - getBinIO()->write32_le (bmih.biClrUsed) ; - getBinIO()->write32_le (bmih.biClrImportant) ; - - if (Palette != NULL) { - for (unsigned int i = 0 ; i < Palette->getSize() ; i++) { - getBinIO()->write8 ((*Palette)[i].Blue) ; - getBinIO()->write8 ((*Palette)[i].Green) ; - getBinIO()->write8 ((*Palette)[i].Red) ; - getBinIO()->write8 (0) ; - } - } +void BmpFile::bmpwin_writeheaders() { + getBinIO()->write32_le(bmih.biSize); + getBinIO()->write32_le(bmih.biWidth); + getBinIO()->write32_le(bmih.biHeight); + getBinIO()->write16_le(bmih.biPlanes); + getBinIO()->write16_le(bmih.biBitCount); + getBinIO()->write32_le(bmih.biCompression); + getBinIO()->write32_le(bmih.biSizeImage); + getBinIO()->write32_le(bmih.biXPelsPerMeter); + getBinIO()->write32_le(bmih.biYPelsPerMeter); + getBinIO()->write32_le(bmih.biClrUsed); + getBinIO()->write32_le(bmih.biClrImportant); + + if (Palette != NULL) { + for (unsigned int i = 0; i < Palette->getSize(); i++) { + getBinIO()->write8((*Palette)[i].Blue); + getBinIO()->write8((*Palette)[i].Green); + getBinIO()->write8((*Palette)[i].Red); + getBinIO()->write8(0); + } + } } -void BmpFile::bmpos2_writeheaders () -{ - getBinIO()->write32_le (bmch.bcSize) ; - getBinIO()->write16_le (bmch.bcWidth) ; - getBinIO()->write16_le (bmch.bcHeight) ; - getBinIO()->write16_le (bmch.bcPlanes) ; - getBinIO()->write16_le (bmch.bcBitCount) ; - - if (Palette != NULL) { - for (unsigned int i = 0 ; i < Palette->getSize() ; i++) { - getBinIO()->write8 ((*Palette)[i].Blue) ; - getBinIO()->write8 ((*Palette)[i].Green) ; - getBinIO()->write8 ((*Palette)[i].Red) ; - } - } +void BmpFile::bmpos2_writeheaders() { + getBinIO()->write32_le(bmch.bcSize); + getBinIO()->write16_le(bmch.bcWidth); + getBinIO()->write16_le(bmch.bcHeight); + getBinIO()->write16_le(bmch.bcPlanes); + getBinIO()->write16_le(bmch.bcBitCount); + + if (Palette != NULL) { + for (unsigned int i = 0; i < Palette->getSize(); i++) { + getBinIO()->write8((*Palette)[i].Blue); + getBinIO()->write8((*Palette)[i].Green); + getBinIO()->write8((*Palette)[i].Red); + } + } } /* returns the number of bytes used to store the pixel data of one scan line */ -unsigned long BmpFile::calcLinelength () -{ - unsigned long retval = 0 ; - - switch (getSubformat()) { - case WIN: { - if (bmih.biBitCount * bmih.biWidth % 8 == 0) { - retval = bmih.biBitCount * bmih.biWidth / 8 ; - } - else { - retval = (bmih.biBitCount * bmih.biWidth / 8) + 1; - } - break ; } - - case OS2: { - if (bmch.bcBitCount * bmch.bcWidth % 8 == 0) { - retval = bmch.bcBitCount * bmch.bcWidth / 8 ; - } - else { - retval = (bmch.bcBitCount * bmch.bcWidth / 8) + 1; - } - break ; } - - default: { - myassert (0) ; - break ; } - } - - return retval ; +unsigned long BmpFile::calcLinelength() { + unsigned long retval = 0; + + switch (getSubformat()) { + case WIN: { + if (bmih.biBitCount * bmih.biWidth % 8 == 0) { + retval = bmih.biBitCount * bmih.biWidth / 8; + } else { + retval = (bmih.biBitCount * bmih.biWidth / 8) + 1; + } + break; + } + + case OS2: { + if (bmch.bcBitCount * bmch.bcWidth % 8 == 0) { + retval = bmch.bcBitCount * bmch.bcWidth / 8; + } else { + retval = (bmch.bcBitCount * bmch.bcWidth / 8) + 1; + } + break; + } + + default: { + myassert(0); + break; + } + } + + return retval; } - /* reads a bmp file from disk into a CVRSTGFILE structure */ -void BmpFile::readdata () -{ - try { - unsigned long linelength = calcLinelength () ; - unsigned long height = getHeight () ; - - int paddinglength = 0 ; - if (linelength % 4 == 0) { - paddinglength = 0 ; - } - else { - paddinglength = 4 - (linelength % 4) ; - } - - BitmapData.resize (height * linelength) ; - for (unsigned long line = 0 ; line < height ; line++) { - for (unsigned long posinline = 0 ; posinline < linelength ; posinline++) { - BitmapData[line * linelength + posinline] = getBinIO()->read8() ; - } - - for (int i = 0 ; i < paddinglength ; i++) { - if (getBinIO()->read8() != 0) { - Warning w (_("maybe corrupted bmp data (padding byte at 0x%lx set to non-zero)."), getBinIO()->getPos() - 1) ; - w.printMessage() ; - } - } - } - - atend.clear() ; - while (!getBinIO()->eof()) { - atend.push_back (getBinIO()->read8()) ; - } - } - catch (BinaryInputError e) { - switch (e.getType()) { - case BinaryInputError::FILE_ERR: { - throw SteghideError (_("an error occurred while reading the bmp data from the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryInputError::FILE_EOF: { - throw SteghideError (_("premature end of file \"%s\" while reading bmp data."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryInputError::STDIN_ERR: { - throw SteghideError (_("an error occurred while reading the bmp data from standard input.")) ; - break ; } - - case BinaryInputError::STDIN_EOF: { - throw SteghideError (_("premature end of bmp data from standard input.")) ; - break ; } - } - } +void BmpFile::readdata() { + try { + unsigned long linelength = calcLinelength(); + unsigned long height = getHeight(); + + int paddinglength = 0; + if (linelength % 4 == 0) { + paddinglength = 0; + } else { + paddinglength = 4 - (linelength % 4); + } + + BitmapData.resize(height * linelength); + for (unsigned long line = 0; line < height; line++) { + for (unsigned long posinline = 0; posinline < linelength; posinline++) { + BitmapData[line * linelength + posinline] = getBinIO()->read8(); + } + + for (int i = 0; i < paddinglength; i++) { + if (getBinIO()->read8() != 0) { + Warning w( + _("maybe corrupted bmp data (padding byte at 0x%lx set to non-zero)."), + getBinIO()->getPos() - 1); + w.printMessage(); + } + } + } + + atend.clear(); + while (!getBinIO()->eof()) { + atend.push_back(getBinIO()->read8()); + } + } catch (BinaryInputError e) { + switch (e.getType()) { + case BinaryInputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while reading the bmp data from the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::FILE_EOF: { + throw SteghideError(_("premature end of file \"%s\" while reading bmp data."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::STDIN_ERR: { + throw SteghideError( + _("an error occurred while reading the bmp data from standard input.")); + break; + } + + case BinaryInputError::STDIN_EOF: { + throw SteghideError(_("premature end of bmp data from standard input.")); + break; + } + } + } } -void BmpFile::writedata () -{ - try { - unsigned long linelength = calcLinelength () ; - unsigned long height = getHeight () ; - - unsigned int paddinglength = 0 ; - if (linelength % 4 == 0) { - paddinglength = 0 ; - } - else { - paddinglength = 4 - (linelength % 4) ; - } - - for (unsigned long line = 0 ; line < height ; line++) { - for (unsigned long posinline = 0 ; posinline < linelength ; posinline++) { - getBinIO()->write8 (BitmapData[line * linelength + posinline]) ; - } - - // write padding bytes - for (unsigned int i = 0 ; i < paddinglength ; i++) { - getBinIO()->write8 (0) ; - } - } - - for (std::vector::iterator i = atend.begin() ; i != atend.end() ; i++) { - getBinIO()->write8 (*i) ; - } - } - catch (BinaryOutputError e) { - switch (e.getType()) { - case BinaryOutputError::FILE_ERR: { - throw SteghideError (_("an error occurred while writing the bitmap data to the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryOutputError::STDOUT_ERR: { - throw SteghideError (_("an error occurred while writing the bitmap data to standard output.")) ; - break ; } - } - } +void BmpFile::writedata() { + try { + unsigned long linelength = calcLinelength(); + unsigned long height = getHeight(); + + unsigned int paddinglength = 0; + if (linelength % 4 == 0) { + paddinglength = 0; + } else { + paddinglength = 4 - (linelength % 4); + } + + for (unsigned long line = 0; line < height; line++) { + for (unsigned long posinline = 0; posinline < linelength; posinline++) { + getBinIO()->write8(BitmapData[line * linelength + posinline]); + } + + // write padding bytes + for (unsigned int i = 0; i < paddinglength; i++) { + getBinIO()->write8(0); + } + } + + for (std::vector::iterator i = atend.begin(); i != atend.end(); i++) { + getBinIO()->write8(*i); + } + } catch (BinaryOutputError e) { + switch (e.getType()) { + case BinaryOutputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while writing the bitmap data to the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryOutputError::STDOUT_ERR: { + throw SteghideError( + _("an error occurred while writing the bitmap data to standard output.")); + break; + } + } + } } diff --git a/src/BmpFile.h b/src/BmpFile.h index cec9bf2..59f6dc1 100644 --- a/src/BmpFile.h +++ b/src/BmpFile.h @@ -25,125 +25,129 @@ #include "CvrStgFile.h" -class BinaryIO ; -class ColorPalette ; +class BinaryIO; +class ColorPalette; class BmpFile : public CvrStgFile { - public: - BmpFile (void) ; - BmpFile (BinaryIO *io) ; - ~BmpFile (void) ; - - void read (BinaryIO *io) ; - void write (void) ; - - std::list getProperties (void) const ; - std::vector getMatchingAlgorithms (Graph* g, Matching* m) const ; - - unsigned long getNumSamples (void) const ; - void replaceSample (const SamplePos pos, const SampleValue* s) ; - SampleValue* getSampleValue (SamplePos pos) const ; - - std::vector calcSVAdjacencyLists (const std::vector& svs) const ; - - unsigned short getBitCount (void) const ; - unsigned long getWidth (void) const ; - unsigned long getHeight (void) const ; - ColorPalette *getPalette (void) const ; - - protected: - typedef struct struct_BITMAPFILEHEADER { - unsigned short bfType ; - unsigned long bfSize ; - unsigned short bfReserved1 ; - unsigned short bfReserved2 ; - unsigned long bfOffBits ; - } BITMAPFILEHEADER ; - - /* windows bmp file format */ - typedef struct struct_BITMAPINFOHEADER { - unsigned long biSize ; - signed long biWidth ; - signed long biHeight ; - unsigned short biPlanes ; - unsigned short biBitCount ; - unsigned long biCompression ; - unsigned long biSizeImage ; - signed long biXPelsPerMeter ; - signed long biYPelsPerMeter ; - unsigned long biClrUsed ; - unsigned long biClrImportant ; - } BITMAPINFOHEADER ; - - /* os/2 bmp file format */ - typedef struct struct_BITMAPCOREHEADER { - unsigned long bcSize; - unsigned short bcWidth; - unsigned short bcHeight; - unsigned short bcPlanes; - unsigned short bcBitCount; - } BITMAPCOREHEADER ; - - private: - static const unsigned int IdBm = 19778 ; - static const unsigned short SizeBMFILEHEADER = 14 ; - static const unsigned short SizeBMINFOHEADER = 40 ; - static const unsigned short SizeBMCOREHEADER = 12 ; - static const unsigned int COMPRESSION_BI_RGB = 0 ; - - static const unsigned short SamplesPerVertex_SmallPalette = 2 ; - static const unsigned short SamplesPerVertex_LargePalette = 3 ; - static const unsigned short SamplesPerVertex_RGB = 2 ; - /// the default radius for palette images (400 = 20^2) - static const UWORD32 Radius_Palette = 400 ; - /// the default radius for RGB images (100 = 10^2) - static const UWORD32 Radius_RGB = 100 ; - - static const EmbValue EmbValueModulus_SmallPalette = 2 ; - static const EmbValue EmbValueModulus_LargePalette = 4 ; - static const EmbValue EmbValueModulus_RGB = 4 ; // if changed here - also change BmpRGBSampleValue::calcEValue - - enum SUBFORMAT { WIN, OS2 } ; - - SUBFORMAT subformat ; - BITMAPFILEHEADER bmfh ; - BITMAPINFOHEADER bmih ; - BITMAPCOREHEADER bmch ; - ColorPalette* Palette ; - /** - * contains the bitmap in the following format - * bitmap[i] is the pixel data of the i-th row of the bitmap - * bitmap[i][j] is the j-th byte of the pixel data of the i-th row of the bitmap - * if bitcount is < 8 then bitmap[i][j] contains the pixels as read in from the file (i.e. in the "wrong" direction) - * this is taken care of in the calcRCB function - **/ - std::vector > bitmap ; - - /** - * contains the bitmap data in the same order as read from file (but without padding bytes) - **/ - std::vector BitmapData ; - - /// contains bytes that are appended at the end of the bitmap data (some image editors apparently do this) - std::vector atend ; - - void readheaders () ; - void bmpwin_readheaders () ; - void bmpos2_readheaders () ; - void writeheaders () ; - void bmpwin_writeheaders () ; - void bmpos2_writeheaders () ; - void readdata () ; - void writedata () ; - /** - * translate a sample position into a pair "pointing" into the BitmapData array - * \param pos a sample position - * \param index a pointer to a variable that will contain the array index used to access the pos-th sample - * \param firstbit the firstbit in BitmapData[index] that belongs to the sample with the given position - **/ - void calcIndex (SamplePos pos, unsigned long* index, unsigned short* firstbit) const ; - unsigned long calcLinelength () ; - SUBFORMAT getSubformat (void) const ; -} ; + public: + BmpFile(void); + BmpFile(BinaryIO *io); + ~BmpFile(void); + + void read(BinaryIO *io); + void write(void); + + std::list getProperties(void) const; + std::vector getMatchingAlgorithms(Graph *g, Matching *m) const; + + unsigned long getNumSamples(void) const; + void replaceSample(const SamplePos pos, const SampleValue *s); + SampleValue *getSampleValue(SamplePos pos) const; + + std::vector + calcSVAdjacencyLists(const std::vector &svs) const; + + unsigned short getBitCount(void) const; + unsigned long getWidth(void) const; + unsigned long getHeight(void) const; + ColorPalette *getPalette(void) const; + + protected: + typedef struct struct_BITMAPFILEHEADER { + unsigned short bfType; + unsigned long bfSize; + unsigned short bfReserved1; + unsigned short bfReserved2; + unsigned long bfOffBits; + } BITMAPFILEHEADER; + + /* windows bmp file format */ + typedef struct struct_BITMAPINFOHEADER { + unsigned long biSize; + signed long biWidth; + signed long biHeight; + unsigned short biPlanes; + unsigned short biBitCount; + unsigned long biCompression; + unsigned long biSizeImage; + signed long biXPelsPerMeter; + signed long biYPelsPerMeter; + unsigned long biClrUsed; + unsigned long biClrImportant; + } BITMAPINFOHEADER; + + /* os/2 bmp file format */ + typedef struct struct_BITMAPCOREHEADER { + unsigned long bcSize; + unsigned short bcWidth; + unsigned short bcHeight; + unsigned short bcPlanes; + unsigned short bcBitCount; + } BITMAPCOREHEADER; + + private: + static const unsigned int IdBm = 19778; + static const unsigned short SizeBMFILEHEADER = 14; + static const unsigned short SizeBMINFOHEADER = 40; + static const unsigned short SizeBMCOREHEADER = 12; + static const unsigned int COMPRESSION_BI_RGB = 0; + + static const unsigned short SamplesPerVertex_SmallPalette = 2; + static const unsigned short SamplesPerVertex_LargePalette = 3; + static const unsigned short SamplesPerVertex_RGB = 2; + /// the default radius for palette images (400 = 20^2) + static const UWORD32 Radius_Palette = 400; + /// the default radius for RGB images (100 = 10^2) + static const UWORD32 Radius_RGB = 100; + + static const EmbValue EmbValueModulus_SmallPalette = 2; + static const EmbValue EmbValueModulus_LargePalette = 4; + static const EmbValue EmbValueModulus_RGB = + 4; // if changed here - also change BmpRGBSampleValue::calcEValue + + enum SUBFORMAT { WIN, OS2 }; + + SUBFORMAT subformat; + BITMAPFILEHEADER bmfh; + BITMAPINFOHEADER bmih; + BITMAPCOREHEADER bmch; + ColorPalette *Palette; + /** + * contains the bitmap in the following format + * bitmap[i] is the pixel data of the i-th row of the bitmap + * bitmap[i][j] is the j-th byte of the pixel data of the i-th row of the bitmap + * if bitcount is < 8 then bitmap[i][j] contains the pixels as read in from the file (i.e. in + *the "wrong" direction) this is taken care of in the calcRCB function + **/ + std::vector> bitmap; + + /** + * contains the bitmap data in the same order as read from file (but without padding bytes) + **/ + std::vector BitmapData; + + /// contains bytes that are appended at the end of the bitmap data (some image editors + /// apparently do this) + std::vector atend; + + void readheaders(); + void bmpwin_readheaders(); + void bmpos2_readheaders(); + void writeheaders(); + void bmpwin_writeheaders(); + void bmpos2_writeheaders(); + void readdata(); + void writedata(); + /** + * translate a sample position into a pair "pointing" into the BitmapData array + * \param pos a sample position + * \param index a pointer to a variable that will contain the array index used to access the + *pos-th sample \param firstbit the firstbit in BitmapData[index] that belongs to the sample + *with the given position + **/ + void calcIndex(SamplePos pos, unsigned long *index, unsigned short *firstbit) const; + unsigned long calcLinelength(); + SUBFORMAT getSubformat(void) const; +}; #endif /* ndef SH_BMPFILE_H */ diff --git a/src/BmpPaletteSampleValue.cc b/src/BmpPaletteSampleValue.cc index eb80108..a71a73f 100644 --- a/src/BmpPaletteSampleValue.cc +++ b/src/BmpPaletteSampleValue.cc @@ -18,46 +18,41 @@ * */ -#include "BmpFile.h" #include "BmpPaletteSampleValue.h" +#include "BmpFile.h" #include "ColorPalette.h" -BmpPaletteSampleValue::BmpPaletteSampleValue (unsigned char i) - : BmpSampleValue(), Index(i) -{ - const BmpFile* bmpfile = dynamic_cast (Globs.TheCvrStgFile) ; - myassert (bmpfile) ; - Palette = bmpfile->getPalette() ; - Key = ((unsigned long) getIndex() << 24) | ((unsigned long) getRed() << 16) | - ((unsigned long) getGreen() << 8) | ((unsigned long) getBlue()) ; - EValue = calcEValue(getIndex()) ; +BmpPaletteSampleValue::BmpPaletteSampleValue(unsigned char i) : BmpSampleValue(), Index(i) { + const BmpFile *bmpfile = dynamic_cast(Globs.TheCvrStgFile); + myassert(bmpfile); + Palette = bmpfile->getPalette(); + Key = ((unsigned long)getIndex() << 24) | ((unsigned long)getRed() << 16) | + ((unsigned long)getGreen() << 8) | ((unsigned long)getBlue()); + EValue = calcEValue(getIndex()); } -SampleValue* BmpPaletteSampleValue::getNearestTargetSampleValue (EmbValue t) const -{ - BmpPaletteSampleValue* sv_mindist = NULL ; - UWORD32 mindist = UWORD32_MAX ; - for (unsigned int i = 0 ; i < Palette->getSize() ; i++) { - if (calcEValue(i) == t) { - BmpPaletteSampleValue* destsv = new BmpPaletteSampleValue (i) ; - UWORD32 curdist = calcDistance (destsv) ; - if (curdist < mindist) { - delete sv_mindist ; - sv_mindist = destsv ; - mindist = curdist ; - } - else { - delete destsv ; - } - } - } - myassert (sv_mindist != NULL) ; - return ((SampleValue*) sv_mindist) ; +SampleValue *BmpPaletteSampleValue::getNearestTargetSampleValue(EmbValue t) const { + BmpPaletteSampleValue *sv_mindist = NULL; + UWORD32 mindist = UWORD32_MAX; + for (unsigned int i = 0; i < Palette->getSize(); i++) { + if (calcEValue(i) == t) { + BmpPaletteSampleValue *destsv = new BmpPaletteSampleValue(i); + UWORD32 curdist = calcDistance(destsv); + if (curdist < mindist) { + delete sv_mindist; + sv_mindist = destsv; + mindist = curdist; + } else { + delete destsv; + } + } + } + myassert(sv_mindist != NULL); + return ((SampleValue *)sv_mindist); } -std::string BmpPaletteSampleValue::getName () const -{ - char buf[128] ; - sprintf (buf, "i%ur%ug%ub%u", getIndex(), getRed(), getGreen(), getBlue()) ; - return std::string (buf) ; +std::string BmpPaletteSampleValue::getName() const { + char buf[128]; + sprintf(buf, "i%ur%ug%ub%u", getIndex(), getRed(), getGreen(), getBlue()); + return std::string(buf); } diff --git a/src/BmpPaletteSampleValue.h b/src/BmpPaletteSampleValue.h index 8c5a088..cc7c364 100644 --- a/src/BmpPaletteSampleValue.h +++ b/src/BmpPaletteSampleValue.h @@ -22,8 +22,8 @@ #define SH_BMPPALETTESAMPLEVALUE_H #include "BmpSampleValue.h" -#include "CvrStgFile.h" #include "ColorPalette.h" +#include "CvrStgFile.h" #include "common.h" /** @@ -31,23 +31,24 @@ * \brief a sample in a bmp palette (i.e. in a 1-,4- or 8-bit) file **/ class BmpPaletteSampleValue : public BmpSampleValue { - public: - BmpPaletteSampleValue (BYTE i) ; + public: + BmpPaletteSampleValue(BYTE i); - SampleValue* getNearestTargetSampleValue (EmbValue t) const ; - std::string getName (void) const ; + SampleValue *getNearestTargetSampleValue(EmbValue t) const; + std::string getName(void) const; - BYTE getIndex (void) const { return Index ; } ; - BYTE getRed (void) const { return (*Palette)[Index].Red ; } ; - BYTE getGreen (void) const { return (*Palette)[Index].Green ; } ; - BYTE getBlue (void) const { return (*Palette)[Index].Blue ; } ; + BYTE getIndex(void) const { return Index; }; + BYTE getRed(void) const { return (*Palette)[Index].Red; }; + BYTE getGreen(void) const { return (*Palette)[Index].Green; }; + BYTE getBlue(void) const { return (*Palette)[Index].Blue; }; - private: - ColorPalette* Palette ; - BYTE Index ; + private: + ColorPalette *Palette; + BYTE Index; - EmbValue calcEValue (BYTE idx) const - { return (idx % Globs.TheCvrStgFile->getEmbValueModulus()) ; } ; -} ; + EmbValue calcEValue(BYTE idx) const { + return (idx % Globs.TheCvrStgFile->getEmbValueModulus()); + }; +}; #endif // ndef SH_BMPPALETTESAMPLEVALUE_H diff --git a/src/BmpRGBSampleValue.cc b/src/BmpRGBSampleValue.cc index 0f6aecc..4dec5a4 100644 --- a/src/BmpRGBSampleValue.cc +++ b/src/BmpRGBSampleValue.cc @@ -20,123 +20,122 @@ #include "BmpRGBSampleValue.h" -BmpRGBSampleValue::BmpRGBSampleValue (BYTE r, BYTE g, BYTE b) - : BmpSampleValue(), Color(r, g, b) -{ - Key = calcKey (Color) ; - EValue = calcEValue (Color) ; +BmpRGBSampleValue::BmpRGBSampleValue(BYTE r, BYTE g, BYTE b) : BmpSampleValue(), Color(r, g, b) { + Key = calcKey(Color); + EValue = calcEValue(Color); } -BmpRGBSampleValue::BmpRGBSampleValue (RGBTriple t) - : BmpSampleValue(), Color(t) -{ - Key = calcKey (Color) ; - EValue = calcEValue (Color) ; +BmpRGBSampleValue::BmpRGBSampleValue(RGBTriple t) : BmpSampleValue(), Color(t) { + Key = calcKey(Color); + EValue = calcEValue(Color); } -UWORD32 BmpRGBSampleValue::calcDistance (const SampleValue *s) const -{ - const BmpRGBSampleValue *sample = (const BmpRGBSampleValue*) s ; - /* If s is not a BmpRGBSampleValue then we get into real trouble here. - But calcDistance is called very often, a dynamic_cast costs a lot of time and - it does not make sense to pass anything but a BmpRGBSampleValue as s anyway. */ - - int dr = (int) Color.Red - (int) sample->Color.Red ; - int dg = (int) Color.Green - (int) sample->Color.Green ; - int db = (int) Color.Blue - (int) sample->Color.Blue ; - return (UWORD32) (dr*dr + dg*dg + db*db) ; +UWORD32 BmpRGBSampleValue::calcDistance(const SampleValue *s) const { + const BmpRGBSampleValue *sample = (const BmpRGBSampleValue *)s; + /* If s is not a BmpRGBSampleValue then we get into real trouble here. + But calcDistance is called very often, a dynamic_cast costs a lot of time and + it does not make sense to pass anything but a BmpRGBSampleValue as s anyway. + */ + + int dr = (int)Color.Red - (int)sample->Color.Red; + int dg = (int)Color.Green - (int)sample->Color.Green; + int db = (int)Color.Blue - (int)sample->Color.Blue; + return (UWORD32)(dr * dr + dg * dg + db * db); } -SampleValue *BmpRGBSampleValue::getNearestTargetSampleValue (EmbValue t) const -{ - std::vector candidates ; - - BYTE cube[3][2] ; - cube[RED][UP] = Color.Red ; cube[RED][DOWN] = Color.Red ; - cube[GREEN][UP] = Color.Green ; cube[GREEN][DOWN] = Color.Green ; - cube[BLUE][UP] = Color.Blue ; cube[BLUE][DOWN] = Color.Blue ; - - do { - cube[RED][UP] = plus(cube[RED][UP], 1) ; - cube[RED][DOWN] = minus(cube[RED][DOWN], 1) ; - cube[GREEN][UP] = plus(cube[GREEN][UP], 1) ; - cube[GREEN][DOWN] = minus(cube[GREEN][DOWN], 1) ; - cube[BLUE][UP] = plus(cube[BLUE][UP], 1) ; - cube[BLUE][DOWN] = minus(cube[BLUE][DOWN], 1) ; - - addNTSVCandidates (candidates, cube, RED, UP, GREEN, BLUE, t) ; - addNTSVCandidates (candidates, cube, RED, DOWN, GREEN, BLUE, t) ; - addNTSVCandidates (candidates, cube, GREEN, UP, RED, BLUE, t) ; - addNTSVCandidates (candidates, cube, GREEN, DOWN, RED, BLUE, t) ; - addNTSVCandidates (candidates, cube, BLUE, UP, RED, GREEN, t) ; - addNTSVCandidates (candidates, cube, BLUE, DOWN, RED, GREEN, t) ; - } while (candidates.empty()) ; - - // calculate minimal distance - UWORD32 mindist = UWORD32_MAX ; - for (std::vector::const_iterator cit = candidates.begin() ; cit != candidates.end() ; cit++) { - UWORD32 curdist = Color.calcDistance(*cit) ; - if (curdist < mindist) { - mindist = curdist ; - } - } - - // choose only from those with the minimal distance - std::vector finalcandidates ; - for (std::vector::const_iterator cit = candidates.begin() ; cit != candidates.end() ; cit++) { - if (Color.calcDistance(*cit) == mindist) { - finalcandidates.push_back(*cit) ; - } - } - - unsigned int rnd = (unsigned int) RndSrc.getValue (finalcandidates.size()) ; - return ((SampleValue*) new BmpRGBSampleValue (finalcandidates[rnd])) ; +SampleValue *BmpRGBSampleValue::getNearestTargetSampleValue(EmbValue t) const { + std::vector candidates; + + BYTE cube[3][2]; + cube[RED][UP] = Color.Red; + cube[RED][DOWN] = Color.Red; + cube[GREEN][UP] = Color.Green; + cube[GREEN][DOWN] = Color.Green; + cube[BLUE][UP] = Color.Blue; + cube[BLUE][DOWN] = Color.Blue; + + do { + cube[RED][UP] = plus(cube[RED][UP], 1); + cube[RED][DOWN] = minus(cube[RED][DOWN], 1); + cube[GREEN][UP] = plus(cube[GREEN][UP], 1); + cube[GREEN][DOWN] = minus(cube[GREEN][DOWN], 1); + cube[BLUE][UP] = plus(cube[BLUE][UP], 1); + cube[BLUE][DOWN] = minus(cube[BLUE][DOWN], 1); + + addNTSVCandidates(candidates, cube, RED, UP, GREEN, BLUE, t); + addNTSVCandidates(candidates, cube, RED, DOWN, GREEN, BLUE, t); + addNTSVCandidates(candidates, cube, GREEN, UP, RED, BLUE, t); + addNTSVCandidates(candidates, cube, GREEN, DOWN, RED, BLUE, t); + addNTSVCandidates(candidates, cube, BLUE, UP, RED, GREEN, t); + addNTSVCandidates(candidates, cube, BLUE, DOWN, RED, GREEN, t); + } while (candidates.empty()); + + // calculate minimal distance + UWORD32 mindist = UWORD32_MAX; + for (std::vector::const_iterator cit = candidates.begin(); cit != candidates.end(); + cit++) { + UWORD32 curdist = Color.calcDistance(*cit); + if (curdist < mindist) { + mindist = curdist; + } + } + + // choose only from those with the minimal distance + std::vector finalcandidates; + for (std::vector::const_iterator cit = candidates.begin(); cit != candidates.end(); + cit++) { + if (Color.calcDistance(*cit) == mindist) { + finalcandidates.push_back(*cit); + } + } + + unsigned int rnd = (unsigned int)RndSrc.getValue(finalcandidates.size()); + return ((SampleValue *)new BmpRGBSampleValue(finalcandidates[rnd])); } -void BmpRGBSampleValue::addNTSVCandidates (std::vector& cands, const BYTE cube[3][2], COLOR fc, DIRECTION fd, COLOR i1, COLOR i2, EmbValue t) const -{ - for (BYTE value1 = cube[i1][DOWN] ; value1 < cube[i1][UP] ; value1++) { - for (BYTE value2 = cube[i2][DOWN] ; value2 < cube[i2][UP] ; value2++) { - // create an RGBTriple - BYTE color[3] ; - color[fc] = cube[fc][fd] ; - color[i1] = value1 ; - color[i2] = value2 ; - RGBTriple rgb (color[RED], color[GREEN], color[BLUE]) ; - if (calcEValue (rgb) == t) { - // add rgb to candidates... - bool found = false ; - for (std::vector::const_iterator cit = cands.begin() ; cit != cands.end() ; cit++) { - if (*cit == rgb) { - found = true ; - } - } - if (!found) { - cands.push_back (rgb) ; - } - } - } - } +void BmpRGBSampleValue::addNTSVCandidates(std::vector &cands, const BYTE cube[3][2], + COLOR fc, DIRECTION fd, COLOR i1, COLOR i2, + EmbValue t) const { + for (BYTE value1 = cube[i1][DOWN]; value1 < cube[i1][UP]; value1++) { + for (BYTE value2 = cube[i2][DOWN]; value2 < cube[i2][UP]; value2++) { + // create an RGBTriple + BYTE color[3]; + color[fc] = cube[fc][fd]; + color[i1] = value1; + color[i2] = value2; + RGBTriple rgb(color[RED], color[GREEN], color[BLUE]); + if (calcEValue(rgb) == t) { + // add rgb to candidates... + bool found = false; + for (std::vector::const_iterator cit = cands.begin(); cit != cands.end(); + cit++) { + if (*cit == rgb) { + found = true; + } + } + if (!found) { + cands.push_back(rgb); + } + } + } + } } -std::string BmpRGBSampleValue::getName () const -{ - char buf[128] ; - sprintf (buf, "r%ug%ub%u", getRed(), getGreen(), getBlue()) ; - return std::string (buf) ; +std::string BmpRGBSampleValue::getName() const { + char buf[128]; + sprintf(buf, "r%ug%ub%u", getRed(), getGreen(), getBlue()); + return std::string(buf); } -BYTE BmpRGBSampleValue::minus (BYTE a, BYTE b) const -{ - BYTE retval = 0 ; - if (a > b) { - retval = a - b ; - } - return retval ; +BYTE BmpRGBSampleValue::minus(BYTE a, BYTE b) const { + BYTE retval = 0; + if (a > b) { + retval = a - b; + } + return retval; } -BYTE BmpRGBSampleValue::plus (BYTE a, BYTE b) const -{ - unsigned int sum = a + b ; - return ((sum <= 255) ? sum : 255) ; +BYTE BmpRGBSampleValue::plus(BYTE a, BYTE b) const { + unsigned int sum = a + b; + return ((sum <= 255) ? sum : 255); } diff --git a/src/BmpRGBSampleValue.h b/src/BmpRGBSampleValue.h index d9ae788..edad94f 100644 --- a/src/BmpRGBSampleValue.h +++ b/src/BmpRGBSampleValue.h @@ -30,51 +30,57 @@ * \brief a sample in a bmp rgb (i.e. 24-bit) file **/ class BmpRGBSampleValue : public BmpSampleValue { - public: - BmpRGBSampleValue (BYTE r, BYTE g, BYTE b) ; - BmpRGBSampleValue (RGBTriple t) ; + public: + BmpRGBSampleValue(BYTE r, BYTE g, BYTE b); + BmpRGBSampleValue(RGBTriple t); - UWORD32 calcDistance (const SampleValue *s) const ; - SampleValue* getNearestTargetSampleValue (EmbValue t) const ; - std::string getName (void) const ; + UWORD32 calcDistance(const SampleValue *s) const; + SampleValue *getNearestTargetSampleValue(EmbValue t) const; + std::string getName(void) const; - BYTE getRed (void) const { return Color.Red ; } ; - BYTE getGreen (void) const { return Color.Green ; } ; - BYTE getBlue (void) const { return Color.Blue ; } ; + BYTE getRed(void) const { return Color.Red; }; + BYTE getGreen(void) const { return Color.Green; }; + BYTE getBlue(void) const { return Color.Blue; }; - private: - RGBTriple Color ; + private: + RGBTriple Color; - UWORD32 calcKey (const RGBTriple& rgb) const - { return (((UWORD32) rgb.Red << 16) | ((UWORD32) rgb.Green << 8) | ((UWORD32) rgb.Blue)) ;} ; + UWORD32 calcKey(const RGBTriple &rgb) const { + return (((UWORD32)rgb.Red << 16) | ((UWORD32)rgb.Green << 8) | ((UWORD32)rgb.Blue)); + }; - EmbValue calcEValue (const RGBTriple& rgb) const - // { /* for Modulus 8 */ return ((EmbValue) (((rgb.Red & 1) << 2) | ((rgb.Green & 1) << 1) | (rgb.Blue & 1))) ; } ; - { /* for Modulus 4 */ return ((EmbValue) ((((rgb.Red & 1) ^ (rgb.Green & 1)) << 1) | ((rgb.Red & 1) ^ (rgb.Blue & 1)))) ; } ; + EmbValue calcEValue(const RGBTriple &rgb) const + // { /* for Modulus 8 */ return ((EmbValue) (((rgb.Red & 1) << 2) | ((rgb.Green & 1) << 1) | + // (rgb.Blue & 1))) ; } ; + { /* for Modulus 4 */ + return ((EmbValue)((((rgb.Red & 1) ^ (rgb.Green & 1)) << 1) | + ((rgb.Red & 1) ^ (rgb.Blue & 1)))); + }; - enum COLOR { RED, GREEN, BLUE } ; - enum DIRECTION { UP, DOWN } ; + enum COLOR { RED, GREEN, BLUE }; + enum DIRECTION { UP, DOWN }; - /** - * add the BYTEs a and b - * \return min(255, a + b) - **/ - BYTE plus (BYTE a, BYTE b) const ; + /** + * add the BYTEs a and b + * \return min(255, a + b) + **/ + BYTE plus(BYTE a, BYTE b) const; - /** - * substract the BYTE b from the BYTE a - * \return max(0, a - b) - **/ - BYTE minus (BYTE a, BYTE b) const ; + /** + * substract the BYTE b from the BYTE a + * \return max(0, a - b) + **/ + BYTE minus(BYTE a, BYTE b) const; - /** - * add candidates for the nearest target sample value - * \param cands the candidates vector - * \param cube the color values describing the current search cube - * \param fc the fixed color - * \param fd the fixed side of the fixed color - **/ - void addNTSVCandidates (std::vector& cands, const BYTE cube[3][2], COLOR fc, DIRECTION fd, COLOR i1, COLOR i2, EmbValue t) const ; -} ; + /** + * add candidates for the nearest target sample value + * \param cands the candidates vector + * \param cube the color values describing the current search cube + * \param fc the fixed color + * \param fd the fixed side of the fixed color + **/ + void addNTSVCandidates(std::vector &cands, const BYTE cube[3][2], COLOR fc, + DIRECTION fd, COLOR i1, COLOR i2, EmbValue t) const; +}; #endif // ndef SH_BMPRGBSAMPLEVALUE_H diff --git a/src/BmpSampleValue.cc b/src/BmpSampleValue.cc index 076fa37..e8d9548 100644 --- a/src/BmpSampleValue.cc +++ b/src/BmpSampleValue.cc @@ -21,15 +21,14 @@ #include "BmpSampleValue.h" #include "common.h" -UWORD32 BmpSampleValue::calcDistance (const SampleValue *s) const -{ - const BmpSampleValue *sample = (const BmpSampleValue*) s ; - /* If s is not a BmpSampleValue then we get into real trouble here. - But calcDistance is called very often, a dynamic_cast costs a lot of time and - it does not make sense to pass anything but a BmpSampleValue as s anyway. */ +UWORD32 BmpSampleValue::calcDistance(const SampleValue *s) const { + const BmpSampleValue *sample = (const BmpSampleValue *)s; + /* If s is not a BmpSampleValue then we get into real trouble here. + But calcDistance is called very often, a dynamic_cast costs a lot of time and + it does not make sense to pass anything but a BmpSampleValue as s anyway. */ - int dr = (int) getRed() - (int) sample->getRed() ; - int dg = (int) getGreen() - (int) sample->getGreen() ; - int db = (int) getBlue() - (int) sample->getBlue() ; - return (UWORD32) (dr*dr + dg*dg + db*db) ; + int dr = (int)getRed() - (int)sample->getRed(); + int dg = (int)getGreen() - (int)sample->getGreen(); + int db = (int)getBlue() - (int)sample->getBlue(); + return (UWORD32)(dr * dr + dg * dg + db * db); } diff --git a/src/BmpSampleValue.h b/src/BmpSampleValue.h index b0df4a9..7387046 100644 --- a/src/BmpSampleValue.h +++ b/src/BmpSampleValue.h @@ -29,26 +29,25 @@ * \brief an (abstract) sample value in a bmp file **/ class BmpSampleValue : public SampleValue { - public: - BmpSampleValue (void) : SampleValue() {} ; - - virtual UWORD32 calcDistance (const SampleValue *s) const ; - - /** - * get the red color component - **/ - virtual unsigned char getRed (void) const = 0 ; - - /** - * get the green color component - **/ - virtual unsigned char getGreen (void) const = 0 ; - - /** - * get the blue color component - **/ - virtual unsigned char getBlue (void) const = 0 ; -} ; + public: + BmpSampleValue(void) : SampleValue(){}; + virtual UWORD32 calcDistance(const SampleValue *s) const; + + /** + * get the red color component + **/ + virtual unsigned char getRed(void) const = 0; + + /** + * get the green color component + **/ + virtual unsigned char getGreen(void) const = 0; + + /** + * get the blue color component + **/ + virtual unsigned char getBlue(void) const = 0; +}; #endif // ndef SH_BMPSAMPLE_H diff --git a/src/ColorPalette.h b/src/ColorPalette.h index 1f82357..880e88b 100644 --- a/src/ColorPalette.h +++ b/src/ColorPalette.h @@ -34,24 +34,21 @@ * some wrappers for exisiting methods. **/ class ColorPalette : public std::vector { - public: - /** - * get the size, i.e. the number of entries of this color palette - **/ - unsigned int getSize (void) const - { return size() ; } ; + public: + /** + * get the size, i.e. the number of entries of this color palette + **/ + unsigned int getSize(void) const { return size(); }; - /** - * add (a copy of) rgb to the end of this color palette - **/ - void addEntry (RGBTriple rgb) - { push_back (rgb) ; } ; + /** + * add (a copy of) rgb to the end of this color palette + **/ + void addEntry(RGBTriple rgb) { push_back(rgb); }; - /** - * add the color r/g/b to the end of this color palette - **/ - void addEntry (BYTE r, BYTE g, BYTE b) - { push_back (RGBTriple (r, g, b)) ; } ; -} ; + /** + * add the color r/g/b to the end of this color palette + **/ + void addEntry(BYTE r, BYTE g, BYTE b) { push_back(RGBTriple(r, g, b)); }; +}; #endif // ndef SH_COLORPALETTE_H diff --git a/src/Cracker.cc b/src/Cracker.cc index 5f2d456..bd6a28d 100644 --- a/src/Cracker.cc +++ b/src/Cracker.cc @@ -1,7 +1,7 @@ /* * Stegseek 0.5 - a steghide cracker * Copyright (C) 2020 Rick de Jager - * + * * Based on the work of Stefan Hetzl * * This program is free software; you can redistribute it and/or @@ -22,190 +22,187 @@ #include "Cracker.h" -#include "error.h" -#include "Utils.h" -#include "common.h" +#include "CvrStgFile.h" #include "EmbData.h" +#include "Extractor.h" #include "MHashPP.h" #include "Selector.h" -#include "Extractor.h" -#include "CvrStgFile.h" +#include "Utils.h" +#include "common.h" +#include "error.h" #include - -Cracker::Cracker () -{ - VerboseMessage vrs ; - // get stegofile - if (Args.StgFn.getValue() != "") { - vrs.setMessage (_("[v] Using stegofile \"%s\"."), Args.StgFn.getValue().c_str()) ; - } else if (Args.StgFn.is_set()) { - vrs.setMessage (_("[v] Reading stegofile from stdin.")) ; - } else { - throw SteghideError("No stegofile specified as input.") ; - } - vrs.printMessage() ; - - // get output file - if (Args.ExtFn.is_set()) { - if (Args.ExtFn.getValue() != "") { - vrs.setMessage (_("[v] Using output file \"%s\"."), Args.ExtFn.getValue().c_str()) ; - } else { - vrs.setMessage (_("[v] Using stdout as output.")) ; - } - vrs.printMessage() ; - } - - // Print threading info - vrs.setMessage (_("[v] Running on %d threads."), Args.Threads.getValue()) ; - vrs.printMessage() ; - - // Load the Stegfile - Globs.TheCvrStgFile = CvrStgFile::readFile (Args.StgFn.getValue().c_str()) ; - - // Look up these parameters once, to prevent function calls for each passphrase attempt - bitsperembvalue = AUtils::log2_ceil (Globs.TheCvrStgFile->getEmbValueModulus()) ; - numSamples = Globs.TheCvrStgFile->getNumSamples() ; - samplesPerVertex = Globs.TheCvrStgFile->getSamplesPerVertex() ; - EmbValueModulus = Globs.TheCvrStgFile->getEmbValueModulus(); - embvaluesRequestedMagic = AUtils::div_roundup (EmbData::NBitsMagic, bitsperembvalue) ; - - // Load the embedded values into a "plain" array for faster lookup - embeddedValues = new EmbValue[numSamples] ; - for (unsigned int i = 0; i < numSamples; i++) { - embeddedValues[i] = Globs.TheCvrStgFile->getEmbeddedValue(i) ; - } - - // init the performace counters - progress = 0 ; - stopped = false ; - success = false ; +Cracker::Cracker() { + VerboseMessage vrs; + // get stegofile + if (Args.StgFn.getValue() != "") { + vrs.setMessage(_("[v] Using stegofile \"%s\"."), Args.StgFn.getValue().c_str()); + } else if (Args.StgFn.is_set()) { + vrs.setMessage(_("[v] Reading stegofile from stdin.")); + } else { + throw SteghideError("No stegofile specified as input."); + } + vrs.printMessage(); + + // get output file + if (Args.ExtFn.is_set()) { + if (Args.ExtFn.getValue() != "") { + vrs.setMessage(_("[v] Using output file \"%s\"."), Args.ExtFn.getValue().c_str()); + } else { + vrs.setMessage(_("[v] Using stdout as output.")); + } + vrs.printMessage(); + } + + // Print threading info + vrs.setMessage(_("[v] Running on %d threads."), Args.Threads.getValue()); + vrs.printMessage(); + + // Load the Stegfile + Globs.TheCvrStgFile = CvrStgFile::readFile(Args.StgFn.getValue().c_str()); + + // Look up these parameters once, to prevent function calls for each + // passphrase attempt + bitsperembvalue = AUtils::log2_ceil(Globs.TheCvrStgFile->getEmbValueModulus()); + numSamples = Globs.TheCvrStgFile->getNumSamples(); + samplesPerVertex = Globs.TheCvrStgFile->getSamplesPerVertex(); + EmbValueModulus = Globs.TheCvrStgFile->getEmbValueModulus(); + embvaluesRequestedMagic = + AUtils::div_roundup(EmbData::NBitsMagic, bitsperembvalue); + + // Load the embedded values into a "plain" array for faster lookup + embeddedValues = new EmbValue[numSamples]; + for (unsigned int i = 0; i < numSamples; i++) { + embeddedValues[i] = Globs.TheCvrStgFile->getEmbeddedValue(i); + } + + // init the performace counters + progress = 0; + stopped = false; + success = false; } -void Cracker::metrics (unsigned long max, const char * unit) -{ - // Make sure "max" is at least 1 (in case of empty wordlist) - max = std::max(max, 1UL) ; - Message msg ; - msg.setNewline(false) ; - - do { - unsigned long a = progress ; - float percentage = 100.0f * ((float) a / (float) max) ; - msg.setMessage("\rProgress: %.2f%% (%lu %s) ", percentage, a, unit) ; - msg.printMessage() ; - std::this_thread::sleep_for(std::chrono::milliseconds(20)) ; - } while (!stopped) ; - // Print 2 newlines before returning - msg.setNewline(true) ; - msg.setMessage("\n") ; - msg.printMessage() ; +void Cracker::metrics(unsigned long max, const char *unit) { + // Make sure "max" is at least 1 (in case of empty wordlist) + max = std::max(max, 1UL); + Message msg; + msg.setNewline(false); + + do { + unsigned long a = progress; + float percentage = 100.0f * ((float)a / (float)max); + msg.setMessage("\rProgress: %.2f%% (%lu %s) ", percentage, a, unit); + msg.printMessage(); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } while (!stopped); + // Print 2 newlines before returning + msg.setNewline(true); + msg.setMessage("\n"); + msg.printMessage(); } -bool Cracker::verifyMagic (std::string Passphrase) -{ - MHASH td = mhash_init(MHASH_MD5); - mhash(td, Passphrase.data(), Passphrase.size() ) ; - - UWORD32 seed = 0; - UWORD32 hash[4] ; - mhash_deinit (td, hash) ; - for (unsigned int i = 0 ; i < 4 ; i++) { - seed ^= hash[i] ; - } - return verifyMagic(seed) ; +bool Cracker::verifyMagic(std::string Passphrase) { + MHASH td = mhash_init(MHASH_MD5); + mhash(td, Passphrase.data(), Passphrase.size()); + + UWORD32 seed = 0; + UWORD32 hash[4]; + mhash_deinit(td, hash); + for (unsigned int i = 0; i < 4; i++) { + seed ^= hash[i]; + } + return verifyMagic(seed); } -bool Cracker::verifyMagic (const char * Passphrase) -{ - MHASH td = mhash_init(MHASH_MD5); - mhash(td, Passphrase, std::strlen(Passphrase)) ; - - UWORD32 seed = 0; - UWORD32 hash[4] ; - mhash_deinit (td, hash) ; - for (unsigned int i = 0 ; i < 4 ; i++) { - seed ^= hash[i] ; - } - return verifyMagic(seed) ; +bool Cracker::verifyMagic(const char *Passphrase) { + MHASH td = mhash_init(MHASH_MD5); + mhash(td, Passphrase, std::strlen(Passphrase)); + + UWORD32 seed = 0; + UWORD32 hash[4]; + mhash_deinit(td, hash); + for (unsigned int i = 0; i < 4; i++) { + seed ^= hash[i]; + } + return verifyMagic(seed); } -bool Cracker::verifyMagic (UWORD32 seed) -{ - // Create a buf to keep track of rng collisions - UWORD32 rngBuf[25*samplesPerVertex] ; - - // Pseudorandom properties - const UWORD32 A = 1367208549 ; - const UWORD32 C = 1 ; - - const int magics[25] = { - // Magic, "shm" in binary LE - 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, - // Code version (0) - 0, - } ; - if (samplesPerVertex * embvaluesRequestedMagic >= numSamples) { - // TODO; In theory, we should error out if we hit this. - // However, I've seen this error happen randomly on valid input files - // so I'm leaving it as a "return false" for now - // throw CorruptDataError (_("the stego data from standard input is too short to contain the embedded data.")) ; - return false ; - } - EmbValue ev = 0 ; - unsigned long sv_idx = 0; - for (unsigned long i = 0 ; i < embvaluesRequestedMagic ; i++) { - for (unsigned int j = 0 ; j < samplesPerVertex ; j++, sv_idx++) { - // Calc next random number - seed = (UWORD32) (seed*A + C) ; - // Get next value index - const UWORD32 valIdx = sv_idx + (((double) seed / (double) 4294967296.0) * ((double) (numSamples-sv_idx))) ; - // Check for RNG collisions. Should be fairly rare as numSample gets larger - for (unsigned long k = 0; k < sv_idx; k++) { - if (rngBuf[k] == valIdx) { - // In case we find an rng collision, just pretend the magic check was successful. - // The stricter steghide extractor will double check our work - // - // This case is rare - return true; - } - } - // Save the value index, to keep track of collisions - rngBuf[sv_idx] = valIdx ; - ev = (ev + embeddedValues[valIdx]) % EmbValueModulus; - } - if (ev != magics[i]) { - return false ; - } - ev = 0; - } - return true; +bool Cracker::verifyMagic(UWORD32 seed) { + // Create a buf to keep track of rng collisions + UWORD32 rngBuf[25 * samplesPerVertex]; + + // Pseudorandom properties + const UWORD32 A = 1367208549; + const UWORD32 C = 1; + + const int magics[25] = {// Magic, "shm" in binary LE + 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, + // Code version (0) + 0}; + + if (samplesPerVertex * embvaluesRequestedMagic >= numSamples) { + // TODO; In theory, we should error out if we hit this. + // However, I've seen this error happen randomly on valid input files + // so I'm leaving it as a "return false" for now + // throw CorruptDataError (_("the stego data from standard input is too + // short to contain the embedded data.")) ; + return false; + } + EmbValue ev = 0; + unsigned long sv_idx = 0; + for (unsigned long i = 0; i < embvaluesRequestedMagic; i++) { + for (unsigned int j = 0; j < samplesPerVertex; j++, sv_idx++) { + // Calc next random number + seed = (UWORD32)(seed * A + C); + // Get next value index + const UWORD32 valIdx = + sv_idx + (((double)seed / (double)4294967296.0) * ((double)(numSamples - sv_idx))); + // Check for RNG collisions. Should be fairly rare as numSample gets + // larger + for (unsigned long k = 0; k < sv_idx; k++) { + if (rngBuf[k] == valIdx) { + // In case we find an rng collision, just pretend the magic check was + // successful. The stricter steghide extractor will double check our + // work + // + // This case is rare + return true; + } + } + // Save the value index, to keep track of collisions + rngBuf[sv_idx] = valIdx; + ev = (ev + embeddedValues[valIdx]) % EmbValueModulus; + } + if (ev != magics[i]) { + return false; + } + ev = 0; + } + return true; } - -void Cracker::extract (EmbData* emb) -{ - std::string origFn = emb->getFileName() ; - std::string outFn = Utils::stripDir(Globs.TheCvrStgFile->getName()) + ".out" ; - if (Args.ExtFn.is_set()) { - outFn = Args.ExtFn.getValue() ; - } - - if (origFn != "") { - Message msg ; - msg.setMessage("[i] Original filename: \"%s\"", origFn.c_str()) ; - msg.printMessage() ; - } - if (outFn != "") { - fprintf(stderr, "[i] Extracting to \"%s\"\n", outFn.c_str()) ; - } else { - fprintf(stderr, "[i] Extracting to stdout\n\n") ; - } - BinaryIO io (outFn, BinaryIO::WRITE) ; - std::vector data = emb->getData() ; - for (std::vector::iterator i = data.begin() ; i != data.end() ; i++) { - io.write8 (*i) ; - } - io.close() ; +void Cracker::extract(EmbData *emb) { + std::string origFn = emb->getFileName(); + std::string outFn = Utils::stripDir(Globs.TheCvrStgFile->getName()) + ".out"; + if (Args.ExtFn.is_set()) { + outFn = Args.ExtFn.getValue(); + } + + if (origFn != "") { + Message msg; + msg.setMessage("[i] Original filename: \"%s\"", origFn.c_str()); + msg.printMessage(); + } + if (outFn != "") { + fprintf(stderr, "[i] Extracting to \"%s\"\n", outFn.c_str()); + } else { + fprintf(stderr, "[i] Extracting to stdout\n\n"); + } + BinaryIO io(outFn, BinaryIO::WRITE); + std::vector data = emb->getData(); + for (std::vector::iterator i = data.begin(); i != data.end(); i++) { + io.write8(*i); + } + io.close(); } diff --git a/src/Cracker.h b/src/Cracker.h index 596e04f..18e0441 100644 --- a/src/Cracker.h +++ b/src/Cracker.h @@ -2,9 +2,9 @@ * * Stegseek 0.5 - a steghide cracker * Copyright (C) 2020 Rick de Jager - * + * * Based on the work of Stefan Hetzl - * + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 @@ -24,49 +24,48 @@ #ifndef SH_CRACKER_H #define SH_CRACKER_H -#include -#include +#include +#include #include -#include #include -#include +#include +#include #include -#include -#include #include +#include +#include #include "EmbData.h" #include "Selector.h" class Cracker { - public: - Cracker () ; - - void crack () ; + public: + Cracker(); - protected: - void metrics (unsigned long max, const char * unit) ; - void finish () ; - void extract (EmbData*) ; - bool verifyMagic (std::string) ; - bool verifyMagic (const char *) ; - bool verifyMagic (UWORD32) ; + void crack(); - // Control variables - bool success ; - bool stopped ; - std::atomic progress ; + protected: + void metrics(unsigned long max, const char *unit); + void finish(); + void extract(EmbData *); + bool verifyMagic(std::string); + bool verifyMagic(const char *); + bool verifyMagic(UWORD32); - // File properties - unsigned short bitsperembvalue ; - unsigned long numSamples ; - unsigned short samplesPerVertex ; - EmbValue EmbValueModulus ; - unsigned long embvaluesRequestedMagic ; + // Control variables + bool success; + bool stopped; + std::atomic progress; - private: - EmbValue* embeddedValues ; + // File properties + unsigned short bitsperembvalue; + unsigned long numSamples; + unsigned short samplesPerVertex; + EmbValue EmbValueModulus; + unsigned long embvaluesRequestedMagic; -} ; + private: + EmbValue *embeddedValues; +}; #endif // ndef SH_CRACKER_H diff --git a/src/CvrStgFile.cc b/src/CvrStgFile.cc index 471d32b..6c46eb7 100644 --- a/src/CvrStgFile.cc +++ b/src/CvrStgFile.cc @@ -22,197 +22,180 @@ #include #include -#include "DFSAPHeuristic.h" -#include "AuFile.h" #include "AUtils.h" +#include "AuFile.h" #include "BmpFile.h" #include "CvrStgFile.h" +#include "DFSAPHeuristic.h" #include "JpegFile.h" #include "SampleValue.h" #include "SampleValueAdjacencyList.h" #include "Utils.h" -#include "WavFile.h" #include "WKSConstructionHeuristic.h" +#include "WavFile.h" #include "common.h" #include "error.h" #include "msg.h" -CvrStgFile::CvrStgFile () - : BinIO(NULL), SamplesPerVertex(0), Radius(0), EmbValueModulus(0) -{ - Globs.TheCvrStgFile = this ; +CvrStgFile::CvrStgFile() : BinIO(NULL), SamplesPerVertex(0), Radius(0), EmbValueModulus(0) { + Globs.TheCvrStgFile = this; } -CvrStgFile::~CvrStgFile (void) -{ - if (BinIO != NULL) { - delete BinIO ; - } +CvrStgFile::~CvrStgFile(void) { + if (BinIO != NULL) { + delete BinIO; + } } -void CvrStgFile::setRadius (UWORD32 r) -{ - if (Args.Radius.is_set()) { - Radius = Args.Radius.getValue() ; - } - else { - Radius = r ; - } +void CvrStgFile::setRadius(UWORD32 r) { + if (Args.Radius.is_set()) { + Radius = Args.Radius.getValue(); + } else { + Radius = r; + } } -void CvrStgFile::read (BinaryIO *io) -{ - setBinIO (io) ; -} +void CvrStgFile::read(BinaryIO *io) { setBinIO(io); } -void CvrStgFile::write (void) -{ -} +void CvrStgFile::write(void) {} -void CvrStgFile::transform (const std::string& stgfn) -{ - delete BinIO ; - BinIO = NULL ; - BinIO = new BinaryIO (stgfn, BinaryIO::WRITE) ; +void CvrStgFile::transform(const std::string &stgfn) { + delete BinIO; + BinIO = NULL; + BinIO = new BinaryIO(stgfn, BinaryIO::WRITE); } -std::vector CvrStgFile::calcSVAdjacencyLists (const std::vector& svs) const -{ - EmbValue m = getEmbValueModulus() ; - std::vector lists (m) ; - for (EmbValue i = 0 ; i < m ; i++) { - lists[i] = new SampleValueAdjacencyList (svs.size()) ; - } - - for (SampleValueLabel i = 0 ; i < svs.size() ; i++) { // to be integrated into lists - SampleValueAdjacencyList* sval = lists[svs[i]->getEmbeddedValue()] ; - for (SampleValueLabel j = 0 ; j < svs.size() ; j++) { // line where integration should happen - if ((svs[i]->isNeighbour(svs[j])) && (i != j)) { - (*sval)[svs[j]].push_back (svs[i]) ; - } - } - } - - for (EmbValue i = 0 ; i < m ; i++) { - lists[i]->sort() ; - } - - return lists ; +std::vector +CvrStgFile::calcSVAdjacencyLists(const std::vector &svs) const { + EmbValue m = getEmbValueModulus(); + std::vector lists(m); + for (EmbValue i = 0; i < m; i++) { + lists[i] = new SampleValueAdjacencyList(svs.size()); + } + + for (SampleValueLabel i = 0; i < svs.size(); i++) { // to be integrated into lists + SampleValueAdjacencyList *sval = lists[svs[i]->getEmbeddedValue()]; + for (SampleValueLabel j = 0; j < svs.size(); j++) { // line where integration should happen + if ((svs[i]->isNeighbour(svs[j])) && (i != j)) { + (*sval)[svs[j]].push_back(svs[i]); + } + } + } + + for (EmbValue i = 0; i < m; i++) { + lists[i]->sort(); + } + + return lists; } -std::vector CvrStgFile::getMatchingAlgorithms (Graph* g, Matching* m) const -{ - std::vector retval ; - retval.push_back (new WKSConstructionHeuristic (g, m)) ; - retval.push_back (new DFSAPHeuristic (g, m)) ; - return retval ; +std::vector CvrStgFile::getMatchingAlgorithms(Graph *g, Matching *m) const { + std::vector retval; + retval.push_back(new WKSConstructionHeuristic(g, m)); + retval.push_back(new DFSAPHeuristic(g, m)); + return retval; } -EmbValue CvrStgFile::getEmbeddedValue (const SamplePos pos) const -{ - SampleValue* sv = getSampleValue(pos) ; - EmbValue retval = sv->getEmbeddedValue() ; - delete sv ; - return retval ; +EmbValue CvrStgFile::getEmbeddedValue(const SamplePos pos) const { + SampleValue *sv = getSampleValue(pos); + EmbValue retval = sv->getEmbeddedValue(); + delete sv; + return retval; } -unsigned long CvrStgFile::getCapacity () const -{ - float maxnvertices = getNumSamples() / getSamplesPerVertex() ; - float maxnbits = maxnvertices * log2(getEmbValueModulus()) ; - return ((unsigned long) (maxnbits / 8)) ; +unsigned long CvrStgFile::getCapacity() const { + float maxnvertices = getNumSamples() / getSamplesPerVertex(); + float maxnbits = maxnvertices * log2(getEmbValueModulus()); + return ((unsigned long)(maxnbits / 8)); } -std::string CvrStgFile::getHRCapacity () const -{ - return Utils::formatHRSize (getCapacity()) ; -} +std::string CvrStgFile::getHRCapacity() const { return Utils::formatHRSize(getCapacity()); } #ifdef DEBUG -std::map* CvrStgFile::getFrequencies () -{ - unsigned long n = getNumSamples() ; - std::map* table = new std::map () ; - - for (unsigned long pos = 0 ; pos < n ; pos++) { - SampleValue *sv = getSampleValue (pos) ; - (*table)[sv->getKey()]++ ; - delete sv ; - } - - return table ; +std::map *CvrStgFile::getFrequencies() { + unsigned long n = getNumSamples(); + std::map *table = new std::map(); + + for (unsigned long pos = 0; pos < n; pos++) { + SampleValue *sv = getSampleValue(pos); + (*table)[sv->getKey()]++; + delete sv; + } + + return table; } -void CvrStgFile::printFrequencies (const std::map& freqs) -{ - for (std::map::const_iterator fit = freqs.begin() ; fit != freqs.end() ; fit++) { - std::cout << fit->first << ": " << fit->second << std::endl ; - } +void CvrStgFile::printFrequencies(const std::map &freqs) { + for (std::map::const_iterator fit = freqs.begin(); fit != freqs.end(); + fit++) { + std::cout << fit->first << ": " << fit->second << std::endl; + } } #endif // def DEBUG -CvrStgFile::FILEFORMAT CvrStgFile::guessff (BinaryIO *io) -{ - char buf[4] = { '\0', '\0', '\0', '\0' } ; - FILEFORMAT retval = UNKNOWN ; - - for (unsigned int i = 0 ; i < 2 ; i++) { - buf[i] = (char) io->read8() ; - } - - if (strncmp ("BM", buf, 2) == 0) { - retval = BMP ; - } - else if ((unsigned char) buf[0] == 0xFF && (unsigned char) buf[1] == 0xD8) { - retval = JPEG ; - } - else { - for (unsigned int i = 2 ; i < 4 ; i++) { - buf[i] = (char) io->read8() ; - } - - if (strncmp (".snd", buf, 4) == 0) { - retval = AU ; - } - else if (strncmp ("RIFF", buf, 4) == 0) { - retval = WAV ; - } - } - - return retval ; +CvrStgFile::FILEFORMAT CvrStgFile::guessff(BinaryIO *io) { + char buf[4] = {'\0', '\0', '\0', '\0'}; + FILEFORMAT retval = UNKNOWN; + + for (unsigned int i = 0; i < 2; i++) { + buf[i] = (char)io->read8(); + } + + if (strncmp("BM", buf, 2) == 0) { + retval = BMP; + } else if ((unsigned char)buf[0] == 0xFF && (unsigned char)buf[1] == 0xD8) { + retval = JPEG; + } else { + for (unsigned int i = 2; i < 4; i++) { + buf[i] = (char)io->read8(); + } + + if (strncmp(".snd", buf, 4) == 0) { + retval = AU; + } else if (strncmp("RIFF", buf, 4) == 0) { + retval = WAV; + } + } + + return retval; } -CvrStgFile* CvrStgFile::readFile (const std::string& fn) -{ - BinaryIO *BinIO = new BinaryIO (fn, BinaryIO::READ) ; - - CvrStgFile *file = NULL ; - switch (guessff (BinIO)) { - case UNKNOWN: { - throw UnSupFileFormat (BinIO) ; - break ; } - - case BMP: { - file = new BmpFile (BinIO) ; - break ; } - - case WAV: { - file = new WavFile (BinIO) ; - break ; } - - case AU: { - file = new AuFile (BinIO) ; - break ; } - - case JPEG: { - file = new JpegFile (BinIO) ; - break ; } - - default: { - myassert(0) ; - break ; } - } - - return file ; +CvrStgFile *CvrStgFile::readFile(const std::string &fn) { + BinaryIO *BinIO = new BinaryIO(fn, BinaryIO::READ); + + CvrStgFile *file = NULL; + switch (guessff(BinIO)) { + case UNKNOWN: { + throw UnSupFileFormat(BinIO); + break; + } + + case BMP: { + file = new BmpFile(BinIO); + break; + } + + case WAV: { + file = new WavFile(BinIO); + break; + } + + case AU: { + file = new AuFile(BinIO); + break; + } + + case JPEG: { + file = new JpegFile(BinIO); + break; + } + + default: { + myassert(0); + break; + } + } + + return file; } diff --git a/src/CvrStgFile.h b/src/CvrStgFile.h index aae3ca8..8542799 100644 --- a/src/CvrStgFile.h +++ b/src/CvrStgFile.h @@ -22,16 +22,16 @@ #define SH_CVRSTGFILE_H #include -#include #include +#include #include "BinaryIO.h" #include "CvrStgObject.h" -class Graph ; -class Matching ; -class MatchingAlgorithm ; -class SampleValue ; -class SampleValueAdjacencyList ; +class Graph; +class Matching; +class MatchingAlgorithm; +class SampleValue; +class SampleValueAdjacencyList; /** * \class CvrStgFile @@ -41,149 +41,143 @@ class SampleValueAdjacencyList ; * CvrStgFile contains a protected set-function (e.g. setSamplesPerVertex), a public * get-function (e.g. getSamplesPerVertex() const) and a private variable. The public get * function does nothing else than returning the private variable, which must be set - * as soon as possible (if it is not set, it will contain a null value set in CvrStgFile::CvrStgFile). + * as soon as possible (if it is not set, it will contain a null value set in + *CvrStgFile::CvrStgFile). **/ class CvrStgFile : public CvrStgObject { - public: - /** - * this function reads the file with name fn and returns - * a *File object of the correct type casted to CvrStgFile. - **/ - static CvrStgFile *readFile (const std::string& fn) ; - - class Property : private std::pair { - public: - Property (std::string key, std::string value) - : std::pair (key, value) {} ; - - std::string getKey (void) const - { return first ; } ; - - std::string getValue (void) const - { return second ; } ; - } ; - - CvrStgFile (void) ; - virtual ~CvrStgFile (void) ; - - virtual void read (BinaryIO *io) ; - virtual void write (void) ; - void transform (const std::string& fn) ; - - virtual std::list getProperties (void) const = 0 ; - - /** - * calculate a vector a SampleValueAdjacencyLists - * \param svs a vector of unique(!) sample values where svs[i]->getLabel() == i holds for all i - * \return a vector of SampleValueAdjacencyLists where retval[i] only contains sample values with getEmbValue() == i - * - * Every row in the adjacency lists must be sorted in the following order: The first sample value has - * the least distance to the source sample value, the last has the largest distance. If two sample values - * in one row have the same distance to the source sample value, the order does not matter. - * - * May be overridden in derived class to provide a faster version. - **/ - virtual std::vector calcSVAdjacencyLists (const std::vector& svs) const ; - - /** - * get recommended list of matching algorithms - * \param m an empty matching - will be used in construction of MatchingAlgorithm objects - * - * The MatchingAlgorithm objects returned by this function should be deleted by the caller - * if they are no longer needed. - **/ - virtual std::vector getMatchingAlgorithms (Graph* g, Matching* m) const ; - - /** - * get the name of this cvrstgfile - **/ - const std::string& getName (void) const - { return getBinIO()->getName() ; } ; - - bool is_std (void) const - { return getBinIO()->is_std() ; } ; - - /** - * get the capacity of this cvrstgfile - * \return the capacity in bytes - **/ - unsigned long getCapacity (void) const ; - - /** - * get the capacity as a human-readable string - **/ - std::string getHRCapacity (void) const ; - - /** - * get the number of samples per vertex (this is a file-format specific constant) - **/ - unsigned short getSamplesPerVertex (void) const - { return SamplesPerVertex ; } ; - /** - * get the neighbourhood radius (this is a file-format specific constant) - **/ - UWORD32 getRadius (void) const - { return Radius ; } ; - /** - * values that are embedded in samples will be in 0...Modulus-1 (this is a file-format specific constant) - **/ - EmbValue getEmbValueModulus (void) const - { return EmbValueModulus ; } ; - - /** - * get the value that is embedded in the Sample pos - * \param pos the position of the sample - * \return the value that is embedded in the sample at the given sample position - * - * This is equivalent to getSample(pos)->getEmbeddedValue() and is implemented here like this. - * - * May be overwritten by derived class to provide a faster version. - **/ - virtual EmbValue getEmbeddedValue (const SamplePos pos) const ; + public: + /** + * this function reads the file with name fn and returns + * a *File object of the correct type casted to CvrStgFile. + **/ + static CvrStgFile *readFile(const std::string &fn); + + class Property : private std::pair { + public: + Property(std::string key, std::string value) + : std::pair(key, value){}; + + std::string getKey(void) const { return first; }; + + std::string getValue(void) const { return second; }; + }; + + CvrStgFile(void); + virtual ~CvrStgFile(void); + + virtual void read(BinaryIO *io); + virtual void write(void); + void transform(const std::string &fn); + + virtual std::list getProperties(void) const = 0; + + /** + * calculate a vector a SampleValueAdjacencyLists + * \param svs a vector of unique(!) sample values where svs[i]->getLabel() == i holds for all i + * \return a vector of SampleValueAdjacencyLists where retval[i] only contains sample values + *with getEmbValue() == i + * + * Every row in the adjacency lists must be sorted in the following order: The first sample + *value has the least distance to the source sample value, the last has the largest distance. If + *two sample values in one row have the same distance to the source sample value, the order does + *not matter. + * + * May be overridden in derived class to provide a faster version. + **/ + virtual std::vector + calcSVAdjacencyLists(const std::vector &svs) const; + + /** + * get recommended list of matching algorithms + * \param m an empty matching - will be used in construction of MatchingAlgorithm objects + * + * The MatchingAlgorithm objects returned by this function should be deleted by the caller + * if they are no longer needed. + **/ + virtual std::vector getMatchingAlgorithms(Graph *g, Matching *m) const; + + /** + * get the name of this cvrstgfile + **/ + const std::string &getName(void) const { return getBinIO()->getName(); }; + + bool is_std(void) const { return getBinIO()->is_std(); }; + + /** + * get the capacity of this cvrstgfile + * \return the capacity in bytes + **/ + unsigned long getCapacity(void) const; + + /** + * get the capacity as a human-readable string + **/ + std::string getHRCapacity(void) const; + + /** + * get the number of samples per vertex (this is a file-format specific constant) + **/ + unsigned short getSamplesPerVertex(void) const { return SamplesPerVertex; }; + /** + * get the neighbourhood radius (this is a file-format specific constant) + **/ + UWORD32 getRadius(void) const { return Radius; }; + /** + * values that are embedded in samples will be in 0...Modulus-1 (this is a file-format specific + *constant) + **/ + EmbValue getEmbValueModulus(void) const { return EmbValueModulus; }; + + /** + * get the value that is embedded in the Sample pos + * \param pos the position of the sample + * \return the value that is embedded in the sample at the given sample position + * + * This is equivalent to getSample(pos)->getEmbeddedValue() and is implemented here like this. + * + * May be overwritten by derived class to provide a faster version. + **/ + virtual EmbValue getEmbeddedValue(const SamplePos pos) const; #ifdef DEBUG - /** - * return a map that contains the absolute sample frequencies indexed by sample key - **/ - virtual std::map* getFrequencies (void) ; - /** - * print the frequency table freqs - * - * This method is meant to be overriden in *File to provide a file-format specific way - * of printing a frequency table. - **/ - virtual void printFrequencies (const std::map& freqs) ; + /** + * return a map that contains the absolute sample frequencies indexed by sample key + **/ + virtual std::map *getFrequencies(void); + /** + * print the frequency table freqs + * + * This method is meant to be overriden in *File to provide a file-format specific way + * of printing a frequency table. + **/ + virtual void printFrequencies(const std::map &freqs); #endif - protected: - void setSamplesPerVertex (unsigned short spv) - { SamplesPerVertex = spv ; } ; - /** - * set Radius to r unless Args.Radius is set (set Radius to Args.Radius.getValue() then) - **/ - void setRadius (UWORD32 r) ; - void setEmbValueModulus (EmbValue m) - { EmbValueModulus = m ; } ; - - void setBinIO (BinaryIO* io) - { BinIO = io ; } ; - - BinaryIO* getBinIO (void) const - { return BinIO ; } ; - - private: - enum FILEFORMAT { UNKNOWN, BMP, WAV, AU, JPEG } ; - - /** - * guesses the file format by looking at the first few bytes - **/ - static FILEFORMAT guessff (BinaryIO *io) ; - - BinaryIO* BinIO ; - - unsigned short SamplesPerVertex ; - UWORD32 Radius ; - EmbValue EmbValueModulus ; -} ; + protected: + void setSamplesPerVertex(unsigned short spv) { SamplesPerVertex = spv; }; + /** + * set Radius to r unless Args.Radius is set (set Radius to Args.Radius.getValue() then) + **/ + void setRadius(UWORD32 r); + void setEmbValueModulus(EmbValue m) { EmbValueModulus = m; }; + + void setBinIO(BinaryIO *io) { BinIO = io; }; + + BinaryIO *getBinIO(void) const { return BinIO; }; + + private: + enum FILEFORMAT { UNKNOWN, BMP, WAV, AU, JPEG }; + + /** + * guesses the file format by looking at the first few bytes + **/ + static FILEFORMAT guessff(BinaryIO *io); + + BinaryIO *BinIO; + + unsigned short SamplesPerVertex; + UWORD32 Radius; + EmbValue EmbValueModulus; +}; #endif /* ndef SH_CVRSTGFILE_H */ diff --git a/src/CvrStgObject.h b/src/CvrStgObject.h index a9105b8..8a55a58 100644 --- a/src/CvrStgObject.h +++ b/src/CvrStgObject.h @@ -23,7 +23,7 @@ #include "common.h" -class SampleValue ; +class SampleValue; /** * \class CvrStgObject @@ -38,30 +38,33 @@ class SampleValue ; * Sample...the smallest data unit in a file (e.g. a RGB triple, a DCT coefficient) **/ class CvrStgObject { - public: - /** - * get the number of samples in this CvrStgObject - **/ - virtual unsigned long getNumSamples (void) const = 0 ; + public: + /** + * get the number of samples in this CvrStgObject + **/ + virtual unsigned long getNumSamples(void) const = 0; - /** - * get the sample at position pos - * \param pos the position of a sample (must be in 0...getNumSamples()-1) - * \return the sample at the given position - * - * The sample object is created in this function and should be deleted by the caller. - * The derived class should check the condition(s) given above in its Implementation of this function. - **/ - virtual SampleValue* getSampleValue (const SamplePos pos) const = 0 ; + /** + * get the sample at position pos + * \param pos the position of a sample (must be in 0...getNumSamples()-1) + * \return the sample at the given position + * + * The sample object is created in this function and should be deleted by the caller. + * The derived class should check the condition(s) given above in its Implementation of this + *function. + **/ + virtual SampleValue *getSampleValue(const SamplePos pos) const = 0; - /** - * replace a sample thus (possibly) altering the value of the bit returned by SampleValue->getBit() - * \param pos the position of the sample (must be in 0...getNumSamples()-1) - * \param s the sample value that should replace the current sample value (must be of correct type for this CvrStgObject) - * - * The derived class should check the condition(s) given above in its Implementation of this function. - **/ - virtual void replaceSample (const SamplePos pos, const SampleValue* s) = 0 ; -} ; + /** + * replace a sample thus (possibly) altering the value of the bit returned by + *SampleValue->getBit() \param pos the position of the sample (must be in 0...getNumSamples()-1) + * \param s the sample value that should replace the current sample value (must be of correct + *type for this CvrStgObject) + * + * The derived class should check the condition(s) given above in its Implementation of this + *function. + **/ + virtual void replaceSample(const SamplePos pos, const SampleValue *s) = 0; +}; -#endif //ndef SH_CVRSTGOBJECT_H +#endif // ndef SH_CVRSTGOBJECT_H diff --git a/src/DFSAPHeuristic.cc b/src/DFSAPHeuristic.cc index 20d5e77..d1a70e8 100644 --- a/src/DFSAPHeuristic.cc +++ b/src/DFSAPHeuristic.cc @@ -25,235 +25,243 @@ #include "Matching.h" #include "common.h" -DFSAPHeuristic::DFSAPHeuristic (Graph* g, Matching* m, float goal, UWORD32 mne, EdgeIterator::ITERATIONMODE mo) - : MatchingAlgorithm (g, m, goal) -{ - unsigned long numvertices = g->getNumVertices() ; +DFSAPHeuristic::DFSAPHeuristic(Graph *g, Matching *m, float goal, UWORD32 mne, + EdgeIterator::ITERATIONMODE mo) + : MatchingAlgorithm(g, m, goal) { + unsigned long numvertices = g->getNumVertices(); - TimeCounter = 0 ; + TimeCounter = 0; - TimeCounters = new UWORD32[numvertices] ; - VertexOnPath = new bool[numvertices] ; - EdgeIterators = new EdgeIterator[numvertices] ; - for (VertexLabel l = 0 ; l < numvertices ; l++) { - TimeCounters[l] = 0 ; - VertexOnPath[l] = false ; - EdgeIterators[l].reset (g->getVertex(l), mo) ; - } - EdgeIterator::setMaxNumEdges (mne) ; + TimeCounters = new UWORD32[numvertices]; + VertexOnPath = new bool[numvertices]; + EdgeIterators = new EdgeIterator[numvertices]; + for (VertexLabel l = 0; l < numvertices; l++) { + TimeCounters[l] = 0; + VertexOnPath[l] = false; + EdgeIterators[l].reset(g->getVertex(l), mo); + } + EdgeIterator::setMaxNumEdges(mne); #ifdef DEBUG - NSuccessful = 0 ; - NUnsuccessful = 0 ; - NEdgesSuccessful = 0 ; - NEdgesUnsuccessful = 0 ; - SuccessString = "" ; + NSuccessful = 0; + NUnsuccessful = 0; + NEdgesSuccessful = 0; + NEdgesUnsuccessful = 0; + SuccessString = ""; #endif } -DFSAPHeuristic::~DFSAPHeuristic () -{ - delete[] EdgeIterators ; - delete[] TimeCounters ; - delete[] VertexOnPath ; +DFSAPHeuristic::~DFSAPHeuristic() { + delete[] EdgeIterators; + delete[] TimeCounters; + delete[] VertexOnPath; } -void DFSAPHeuristic::reset (UWORD32 mne, EdgeIterator::ITERATIONMODE mo) -{ - EdgeIterator::setMaxNumEdges (mne) ; - unsigned long numvertices = TheGraph->getNumVertices() ; - TimeCounter = 0 ; - for (VertexLabel l = 0 ; l < numvertices ; l++) { - VertexOnPath[l] = false ; - TimeCounters[l] = 0 ; - EdgeIterators[l].reset(mo) ; - } +void DFSAPHeuristic::reset(UWORD32 mne, EdgeIterator::ITERATIONMODE mo) { + EdgeIterator::setMaxNumEdges(mne); + unsigned long numvertices = TheGraph->getNumVertices(); + TimeCounter = 0; + for (VertexLabel l = 0; l < numvertices; l++) { + VertexOnPath[l] = false; + TimeCounters[l] = 0; + EdgeIterators[l].reset(mo); + } } -void DFSAPHeuristic::run () -{ - const Edge** path = new const Edge*[TheGraph->getNumVertices()] ; +void DFSAPHeuristic::run() { + const Edge **path = new const Edge *[TheGraph->getNumVertices()]; - const std::list ExposedVertices = TheMatching->getExposedVertices() ; - for (std::list::const_iterator expv = ExposedVertices.begin() ; - (expv != ExposedVertices.end()) && (TheMatching->getCardinality() < CardinalityGoal) ; expv++) { - if (TheMatching->isExposed (*expv)) { - unsigned long pathlength = searchAugmentingPath (*expv, path) ; + const std::list ExposedVertices = TheMatching->getExposedVertices(); + for (std::list::const_iterator expv = ExposedVertices.begin(); + (expv != ExposedVertices.end()) && (TheMatching->getCardinality() < CardinalityGoal); + expv++) { + if (TheMatching->isExposed(*expv)) { + unsigned long pathlength = searchAugmentingPath(*expv, path); #ifdef DEBUG - if (pathlength == 0) { - printDebug (5, "DFSAPHeuristic: could not find augmenting path for vertex %lu", (*expv)->getLabel()) ; - } - else { - if (RUNDEBUGLEVEL(5)) { - std::cerr << "DFSAPHeuristic: found augmenting path for vertex " << (*expv)->getLabel() << ": " ; - for (unsigned long i = 0 ; i < pathlength ; i++) { - std::cerr << path[i]->getVertex1()->getLabel() << "-" << path[i]->getVertex2()->getLabel() ; - if (i != pathlength - 1) { - std::cerr << ", " ; - } - } - std::cerr << std::endl ; - } - } + if (pathlength == 0) { + printDebug(5, "DFSAPHeuristic: could not find augmenting path for vertex %lu", + (*expv)->getLabel()); + } else { + if (RUNDEBUGLEVEL(5)) { + std::cerr << "DFSAPHeuristic: found augmenting path for vertex " + << (*expv)->getLabel() << ": "; + for (unsigned long i = 0; i < pathlength; i++) { + std::cerr << path[i]->getVertex1()->getLabel() << "-" + << path[i]->getVertex2()->getLabel(); + if (i != pathlength - 1) { + std::cerr << ", "; + } + } + std::cerr << std::endl; + } + } #endif - if (pathlength > 0) { - TheMatching->augment ((const Edge**) path, pathlength) ; - } - } - } + if (pathlength > 0) { + TheMatching->augment((const Edge **)path, pathlength); + } + } + } - delete[] path ; + delete[] path; } #ifdef DEBUG -#define pushOnPath(EDGE) \ -printDebug (6, "DFSAPHeuristic: pushing edge on path: %lu - %lu", EDGE->getVertex1()->getLabel(), EDGE->getVertex2()->getLabel()) ; \ -path[pathlen] = EDGE ; \ -pathlen++ ; \ -VertexOnPath[EDGE->getVertex1()->getLabel()] = true ; \ -VertexOnPath[EDGE->getVertex2()->getLabel()] = true ; \ -NEdgesPushed++ ; +#define pushOnPath(EDGE) \ + printDebug(6, "DFSAPHeuristic: pushing edge on path: %lu - %lu", \ + EDGE->getVertex1()->getLabel(), EDGE->getVertex2()->getLabel()); \ + path[pathlen] = EDGE; \ + pathlen++; \ + VertexOnPath[EDGE->getVertex1()->getLabel()] = true; \ + VertexOnPath[EDGE->getVertex2()->getLabel()] = true; \ + NEdgesPushed++; #else -#define pushOnPath(EDGE) \ -path[pathlen] = EDGE ; \ -pathlen++ ; \ -VertexOnPath[EDGE->getVertex1()->getLabel()] = true ; \ -VertexOnPath[EDGE->getVertex2()->getLabel()] = true ; +#define pushOnPath(EDGE) \ + path[pathlen] = EDGE; \ + pathlen++; \ + VertexOnPath[EDGE->getVertex1()->getLabel()] = true; \ + VertexOnPath[EDGE->getVertex2()->getLabel()] = true; #endif -unsigned long DFSAPHeuristic::searchAugmentingPath (Vertex *v0, const Edge** path) -{ +unsigned long DFSAPHeuristic::searchAugmentingPath(Vertex *v0, const Edge **path) { #ifdef DEBUG - printDebug (5, "DFSAPHeuristic: searching augmenting path for vertex with label %lu", v0->getLabel()) ; - unsigned long long NEdgesPushed = 0 ; + printDebug(5, "DFSAPHeuristic: searching augmenting path for vertex with label %lu", + v0->getLabel()); + unsigned long long NEdgesPushed = 0; #endif - TimeCounter++ ; - unsigned long pathlen = 0 ; - const Edge* e = NULL ; + TimeCounter++; + unsigned long pathlen = 0; + const Edge *e = NULL; - while ((e = getNextEdge(v0)) != NULL) { - pushOnPath(e) ; - Vertex *w = e->getOtherVertex (v0) ; + while ((e = getNextEdge(v0)) != NULL) { + pushOnPath(e); + Vertex *w = e->getOtherVertex(v0); - if (TheMatching->isExposed(w)) { + if (TheMatching->isExposed(w)) { #ifdef DEBUG - SuccessString += "+" ; - NSuccessful++ ; - NEdgesSuccessful += NEdgesPushed ; + SuccessString += "+"; + NSuccessful++; + NEdgesSuccessful += NEdgesPushed; #endif - return pathlen ; - } - // add matched edge - markVisited (w) ; - e = TheMatching->getMatchingEdge (w) ; // w is matched (because not exposed) - Vertex *w_next = e->getOtherVertex (w) ; - pushOnPath(e) ; + return pathlen; + } + // add matched edge + markVisited(w); + e = TheMatching->getMatchingEdge(w); // w is matched (because not exposed) + Vertex *w_next = e->getOtherVertex(w); + pushOnPath(e); - while (pathlen > 0) { - const Edge* e_next = getNextEdge (w_next) ; - if (e_next != NULL) { // found next edge - pushOnPath(e_next) ; - w = e_next->getOtherVertex (w_next) ; + while (pathlen > 0) { + const Edge *e_next = getNextEdge(w_next); + if (e_next != NULL) { // found next edge + pushOnPath(e_next); + w = e_next->getOtherVertex(w_next); - if (TheMatching->isExposed(w)) { + if (TheMatching->isExposed(w)) { #ifdef DEBUG - SuccessString += "+" ; - NSuccessful++ ; - NEdgesSuccessful += NEdgesPushed ; + SuccessString += "+"; + NSuccessful++; + NEdgesSuccessful += NEdgesPushed; #endif - return pathlen ; - } - // add matched edge - markVisited (w) ; - e = TheMatching->getMatchingEdge (w) ; // w is matched (because not exposed) - w_next = e->getOtherVertex (w) ; - pushOnPath(e) ; - } - else { // could not find next edge + return pathlen; + } + // add matched edge + markVisited(w); + e = TheMatching->getMatchingEdge(w); // w is matched (because not exposed) + w_next = e->getOtherVertex(w); + pushOnPath(e); + } else { // could not find next edge #ifdef DEBUG - printDebug (6, "DFSAPHeuristic: could not find next edge from vertex with label %lu", w_next->getLabel()) ; - printDebug (6, "DFSAPHeuristic: popping edge %lu - %lu from path", path[pathlen - 1]->getVertex1()->getLabel(), path[pathlen - 1]->getVertex2()->getLabel()) ; - printDebug (6, "DFSAPHeuristic: popping edge %lu - %lu from path", path[pathlen - 2]->getVertex1()->getLabel(), path[pathlen - 2]->getVertex2()->getLabel()) ; + printDebug(6, + "DFSAPHeuristic: could not find next edge from vertex with " + "label %lu", + w_next->getLabel()); + printDebug(6, "DFSAPHeuristic: popping edge %lu - %lu from path", + path[pathlen - 1]->getVertex1()->getLabel(), + path[pathlen - 1]->getVertex2()->getLabel()); + printDebug(6, "DFSAPHeuristic: popping edge %lu - %lu from path", + path[pathlen - 2]->getVertex1()->getLabel(), + path[pathlen - 2]->getVertex2()->getLabel()); #endif - VertexOnPath[e->getVertex1()->getLabel()] = false ; - VertexOnPath[e->getVertex2()->getLabel()] = false ; - - // matched edge: pop from path - myassert (path[pathlen - 1] == e) ; - pathlen-- ; + VertexOnPath[e->getVertex1()->getLabel()] = false; + VertexOnPath[e->getVertex2()->getLabel()] = false; - // unmatched edge: pop from path and delete (has been created only for path) - myassert (!TheMatching->includesEdge(path[pathlen - 1])) ; - pathlen-- ; + // matched edge: pop from path + myassert(path[pathlen - 1] == e); + pathlen--; - // set w,e,w_next to complete backtracking step - if (pathlen > 0) { - e = path[pathlen - 1] ; - const Edge* before_e = path[pathlen - 2] ; - if (before_e->contains (e->getVertex1())) { - w = e->getVertex1() ; - w_next = e->getVertex2() ; - } - else if (before_e->contains (e->getVertex2())) { - w = e->getVertex2() ; - w_next = e->getVertex1() ; - } - else { - myassert(false) ; - } - } - } - } - } + // unmatched edge: pop from path and delete (has been created only for + // path) + myassert(!TheMatching->includesEdge(path[pathlen - 1])); + pathlen--; + + // set w,e,w_next to complete backtracking step + if (pathlen > 0) { + e = path[pathlen - 1]; + const Edge *before_e = path[pathlen - 2]; + if (before_e->contains(e->getVertex1())) { + w = e->getVertex1(); + w_next = e->getVertex2(); + } else if (before_e->contains(e->getVertex2())) { + w = e->getVertex2(); + w_next = e->getVertex1(); + } else { + myassert(false); + } + } + } + } + } #ifdef DEBUG - SuccessString += "-" ; - NUnsuccessful++ ; - NEdgesUnsuccessful += NEdgesPushed ; + SuccessString += "-"; + NUnsuccessful++; + NEdgesUnsuccessful += NEdgesPushed; #endif - return pathlen ; + return pathlen; } -const Edge* DFSAPHeuristic::getNextEdge (Vertex *v) -{ - if (isVisited(v)) { - if (EdgeIterators[v->getLabel()].isFinished()) { - return NULL ; - } - ++(EdgeIterators[v->getLabel()]) ; - } - else { - EdgeIterators[v->getLabel()].reset() ; - markVisited(v) ; - } +const Edge *DFSAPHeuristic::getNextEdge(Vertex *v) { + if (isVisited(v)) { + if (EdgeIterators[v->getLabel()].isFinished()) { + return NULL; + } + ++(EdgeIterators[v->getLabel()]); + } else { + EdgeIterators[v->getLabel()].reset(); + markVisited(v); + } - const Edge* e = NULL ; - bool found = false ; - do { - if (EdgeIterators[v->getLabel()].isFinished()) { - // no more unexamined edges for this vertex + const Edge *e = NULL; + bool found = false; + do { + if (EdgeIterators[v->getLabel()].isFinished()) { + // no more unexamined edges for this vertex #ifdef DEBUG - printDebug (7, "DFSAPHeuristic::getNextEdge: no more unexamined edges for vertex %lu", v->getLabel()) ; + printDebug(7, + "DFSAPHeuristic::getNextEdge: no more unexamined edges for " + "vertex %lu", + v->getLabel()); #endif - found = true ; - } - else { - VertexLabel pvlbl = EdgeIterators[v->getLabel()].getPartnerVertexLabel() ; - if (!(VertexOnPath[pvlbl] && isVisited(pvlbl))) { // edge is admissible - e = *EdgeIterators[v->getLabel()] ; - found = true ; + found = true; + } else { + VertexLabel pvlbl = EdgeIterators[v->getLabel()].getPartnerVertexLabel(); + if (!(VertexOnPath[pvlbl] && isVisited(pvlbl))) { // edge is admissible + e = *EdgeIterators[v->getLabel()]; + found = true; #ifdef DEBUG - printDebug (7, "DFSAPHeuristic::getNextEdge: admissible edge for vertex %lu goes to vertex %lu", v->getLabel(), pvlbl) ; + printDebug(7, + "DFSAPHeuristic::getNextEdge: admissible edge for vertex " + "%lu goes to vertex %lu", + v->getLabel(), pvlbl); #endif - } - else { - ++(EdgeIterators[v->getLabel()]) ; - } - } - } while (!found) ; - return e ; + } else { + ++(EdgeIterators[v->getLabel()]); + } + } + } while (!found); + return e; } diff --git a/src/DFSAPHeuristic.h b/src/DFSAPHeuristic.h index dbf5d22..fe9eaac 100644 --- a/src/DFSAPHeuristic.h +++ b/src/DFSAPHeuristic.h @@ -25,9 +25,9 @@ #include "MatchingAlgorithm.h" #include "Vertex.h" -class Edge ; +class Edge; #include "Graph.h" -class Matching ; +class Matching; /** * \class DFSAPHeuristic @@ -38,70 +38,68 @@ class Matching ; * Matching: Heuristic Search for Augmenting Paths". **/ class DFSAPHeuristic : public MatchingAlgorithm { - public: - /** - * construct an DFSAPHeuristic object - * \param g the graph on which this heuristic should run - * \param m the matching to start with - * \param goal the percentage of matched vertices that should be reached - * \param mne the maximum number of edges that should be considered for every vertex - * \param mo the mode for edge iteration - **/ - DFSAPHeuristic (Graph* g, Matching* m, float goal = 100.0, UWORD32 mne = UWORD32_MAX, EdgeIterator::ITERATIONMODE mo = EdgeIterator::SAMPLEOCCURENCE) ; - - virtual ~DFSAPHeuristic (void) ; - - const char* getName (void) const - { return "DFS Augmenting Path Heuristic" ; } ; - - /** - * reset the state of this DFSAPHeuristic, esp. the EdgeIterators - * \param mne the maximum number of edges that should be considered for every vertex for now on - **/ - void reset (UWORD32 mne = UWORD32_MAX, EdgeIterator::ITERATIONMODE mo = EdgeIterator::SAMPLEOCCURENCE) ; - - void run (void) ; - - private: - /** - * \param v0 an exposed vertex - * \param path an array of Edge pointers where the path will be put - * \return the length of the path (the number of valid edges in path) - **/ - unsigned long searchAugmentingPath (Vertex* v0, const Edge** path) ; - - const Edge* getNextEdge (Vertex *v) ; - - void markVisited (Vertex *v) - { TimeCounters[v->getLabel()] = TimeCounter ; } ; - - /** - * returns true iff v has already been visited in this - * iteration, i.e. in the current call of searchAugmentingPath - **/ - bool isVisited (Vertex *v) const - { return isVisited(v->getLabel()) ; } ; - - bool isVisited (VertexLabel vlbl) const - { return (TimeCounters[vlbl] == TimeCounter) ; } ; - - UWORD32 TimeCounter ; - UWORD32* TimeCounters ; - bool* VertexOnPath ; - EdgeIterator* EdgeIterators ; + public: + /** + * construct an DFSAPHeuristic object + * \param g the graph on which this heuristic should run + * \param m the matching to start with + * \param goal the percentage of matched vertices that should be reached + * \param mne the maximum number of edges that should be considered for every vertex + * \param mo the mode for edge iteration + **/ + DFSAPHeuristic(Graph *g, Matching *m, float goal = 100.0, UWORD32 mne = UWORD32_MAX, + EdgeIterator::ITERATIONMODE mo = EdgeIterator::SAMPLEOCCURENCE); + + virtual ~DFSAPHeuristic(void); + + const char *getName(void) const { return "DFS Augmenting Path Heuristic"; }; + + /** + * reset the state of this DFSAPHeuristic, esp. the EdgeIterators + * \param mne the maximum number of edges that should be considered for every vertex for now on + **/ + void reset(UWORD32 mne = UWORD32_MAX, + EdgeIterator::ITERATIONMODE mo = EdgeIterator::SAMPLEOCCURENCE); + + void run(void); + + private: + /** + * \param v0 an exposed vertex + * \param path an array of Edge pointers where the path will be put + * \return the length of the path (the number of valid edges in path) + **/ + unsigned long searchAugmentingPath(Vertex *v0, const Edge **path); + + const Edge *getNextEdge(Vertex *v); + + void markVisited(Vertex *v) { TimeCounters[v->getLabel()] = TimeCounter; }; + + /** + * returns true iff v has already been visited in this + * iteration, i.e. in the current call of searchAugmentingPath + **/ + bool isVisited(Vertex *v) const { return isVisited(v->getLabel()); }; + + bool isVisited(VertexLabel vlbl) const { return (TimeCounters[vlbl] == TimeCounter); }; + + UWORD32 TimeCounter; + UWORD32 *TimeCounters; + bool *VertexOnPath; + EdgeIterator *EdgeIterators; #ifdef DEBUG - /// the number of edges that have been examined in all successful searches - unsigned long long NEdgesSuccessful ; - /// the number of edges that have been examined in all unsuccessful searches - unsigned long long NEdgesUnsuccessful ; - /// the number of calls to searchAugmentingPath that have been sucessful - unsigned long NSuccessful ; - /// the number of calls to searchAugmentingPath that have been unsuccessful - unsigned long NUnsuccessful ; - /// string indicating if n-th search was successful - std::string SuccessString ; + /// the number of edges that have been examined in all successful searches + unsigned long long NEdgesSuccessful; + /// the number of edges that have been examined in all unsuccessful searches + unsigned long long NEdgesUnsuccessful; + /// the number of calls to searchAugmentingPath that have been sucessful + unsigned long NSuccessful; + /// the number of calls to searchAugmentingPath that have been unsuccessful + unsigned long NUnsuccessful; + /// string indicating if n-th search was successful + std::string SuccessString; #endif -} ; +}; #endif // ndef SH_DFSAPHEURISTIC diff --git a/src/DMDConstructionHeuristic.cc b/src/DMDConstructionHeuristic.cc index da204d6..00780ef 100644 --- a/src/DMDConstructionHeuristic.cc +++ b/src/DMDConstructionHeuristic.cc @@ -24,47 +24,44 @@ #include "Matching.h" #include "Vertex.h" -DMDConstructionHeuristic::DMDConstructionHeuristic (Graph* g, Matching* m, float goal) - : MatchingAlgorithm (g, m, goal) -{ - AvailableVertices = std::vector (g->getNumVertices()) ; - for (VertexLabel l = 0 ; l < g->getNumVertices() ; l++) { - AvailableVertices[l] = g->getVertex(l) ; - } +DMDConstructionHeuristic::DMDConstructionHeuristic(Graph *g, Matching *m, float goal) + : MatchingAlgorithm(g, m, goal) { + AvailableVertices = std::vector(g->getNumVertices()); + for (VertexLabel l = 0; l < g->getNumVertices(); l++) { + AvailableVertices[l] = g->getVertex(l); + } } -void DMDConstructionHeuristic::run (void) -{ - VertexLabel mdi = MinDegNotFound ; - while ((mdi = findMinDegIndex (AvailableVertices)) != MinDegNotFound) { - Vertex* v1 = AvailableVertices[mdi] ; - v1->updateShortestEdge() ; - Edge* e = v1->getShortestEdge() ; - Vertex* v2 = e->getOtherVertex(v1) ; +void DMDConstructionHeuristic::run(void) { + VertexLabel mdi = MinDegNotFound; + while ((mdi = findMinDegIndex(AvailableVertices)) != MinDegNotFound) { + Vertex *v1 = AvailableVertices[mdi]; + v1->updateShortestEdge(); + Edge *e = v1->getShortestEdge(); + Vertex *v2 = e->getOtherVertex(v1); - TheMatching->addEdge(*e) ; + TheMatching->addEdge(*e); - v1->markDeleted() ; - v2->markDeleted() ; - AvailableVertices[v1->getLabel()] = NULL ; - AvailableVertices[v2->getLabel()] = NULL ; - } + v1->markDeleted(); + v2->markDeleted(); + AvailableVertices[v1->getLabel()] = NULL; + AvailableVertices[v2->getLabel()] = NULL; + } - TheGraph->unmarkDeletedAllVertices() ; + TheGraph->unmarkDeletedAllVertices(); } -VertexLabel DMDConstructionHeuristic::findMinDegIndex (const std::vector& vertices) -{ - VertexLabel mdi = MinDegNotFound ; - UWORD32 mindeg = UWORD32_MAX ; - for (VertexLabel l = 0 ; l < vertices.size() ; l++) { - if (vertices[l] != NULL) { - UWORD32 curdeg = vertices[l]->getDegree() ; - if (0 < curdeg && curdeg < mindeg) { - mdi = l ; - mindeg = curdeg ; - } - } - } - return mdi ; +VertexLabel DMDConstructionHeuristic::findMinDegIndex(const std::vector &vertices) { + VertexLabel mdi = MinDegNotFound; + UWORD32 mindeg = UWORD32_MAX; + for (VertexLabel l = 0; l < vertices.size(); l++) { + if (vertices[l] != NULL) { + UWORD32 curdeg = vertices[l]->getDegree(); + if (0 < curdeg && curdeg < mindeg) { + mdi = l; + mindeg = curdeg; + } + } + } + return mdi; } diff --git a/src/DMDConstructionHeuristic.h b/src/DMDConstructionHeuristic.h index 24f33b0..4b7e205 100644 --- a/src/DMDConstructionHeuristic.h +++ b/src/DMDConstructionHeuristic.h @@ -22,7 +22,7 @@ #define SH_DMDCONSTRUCTIONHEURISTIC_H #include "MatchingAlgorithm.h" -class Vertex ; +class Vertex; #include "common.h" /** @@ -30,22 +30,21 @@ class Vertex ; * \brief an implementation of the "dynamic minimum degree" heuristic for contruction a matching **/ class DMDConstructionHeuristic : public MatchingAlgorithm { - public: - DMDConstructionHeuristic (Graph* g, Matching* m, float goal = 100.0) ; + public: + DMDConstructionHeuristic(Graph *g, Matching *m, float goal = 100.0); - virtual ~DMDConstructionHeuristic (void) {} ; + virtual ~DMDConstructionHeuristic(void){}; - const char* getName (void) const - { return "Dynamic Minimum Degree Construction Heuristic" ; } ; + const char *getName(void) const { return "Dynamic Minimum Degree Construction Heuristic"; }; - void run (void) ; + void run(void); - private: - static const VertexLabel MinDegNotFound = VERTEXLABEL_MAX ; + private: + static const VertexLabel MinDegNotFound = VERTEXLABEL_MAX; - std::vector AvailableVertices ; + std::vector AvailableVertices; - VertexLabel findMinDegIndex (const std::vector& vertices) ; -} ; + VertexLabel findMinDegIndex(const std::vector &vertices); +}; #endif // ndef SH_DMDCONSTRUCTIONHEURISTIC_H diff --git a/src/Edge.cc b/src/Edge.cc index 2121934..4009f08 100644 --- a/src/Edge.cc +++ b/src/Edge.cc @@ -23,165 +23,141 @@ #include "Vertex.h" #include "common.h" -Edge::Edge (Vertex *v1, unsigned short idx1, Vertex *v2, unsigned short idx2) - : Vertex1(v1), Index1(idx1), Vertex2(v2), Index2(idx2), Weight(UWORD32_MAX) -{ - myassert (v1->getLabel() != v2->getLabel()) ; +Edge::Edge(Vertex *v1, unsigned short idx1, Vertex *v2, unsigned short idx2) + : Vertex1(v1), Index1(idx1), Vertex2(v2), Index2(idx2), Weight(UWORD32_MAX) { + myassert(v1->getLabel() != v2->getLabel()); } -Edge::Edge (const Edge& e) -{ - Vertex1 = e.Vertex1 ; - Index1 = e.Index1 ; - Vertex2 = e.Vertex2 ; - Index2 = e.Index2 ; - Weight = e.Weight ; +Edge::Edge(const Edge &e) { + Vertex1 = e.Vertex1; + Index1 = e.Index1; + Vertex2 = e.Vertex2; + Index2 = e.Index2; + Weight = e.Weight; } -UWORD32 Edge::getWeight () -{ - if (Weight == UWORD32_MAX) { - Weight = Vertex1->getSampleValue(Index1)->calcDistance(Vertex2->getSampleValue(Index2)) ; - } - return Weight ; +UWORD32 Edge::getWeight() { + if (Weight == UWORD32_MAX) { + Weight = Vertex1->getSampleValue(Index1)->calcDistance(Vertex2->getSampleValue(Index2)); + } + return Weight; } -void Edge::set (Vertex* v1, unsigned short idx1, Vertex* v2, unsigned short idx2) -{ - Vertex1 = v1 ; - Index1 = idx1 ; - Vertex2 = v2 ; - Index2 = idx2 ; - Weight = UWORD32_MAX ; +void Edge::set(Vertex *v1, unsigned short idx1, Vertex *v2, unsigned short idx2) { + Vertex1 = v1; + Index1 = idx1; + Vertex2 = v2; + Index2 = idx2; + Weight = UWORD32_MAX; } -void Edge::set1 (Vertex* v1, unsigned short idx1) -{ - Vertex1 = v1 ; - Index1 = idx1 ; - Weight = UWORD32_MAX ; +void Edge::set1(Vertex *v1, unsigned short idx1) { + Vertex1 = v1; + Index1 = idx1; + Weight = UWORD32_MAX; } -void Edge::set2 (Vertex* v2, unsigned short idx2) -{ - Vertex2 = v2 ; - Index2 = idx2 ; - Weight = UWORD32_MAX ; +void Edge::set2(Vertex *v2, unsigned short idx2) { + Vertex2 = v2; + Index2 = idx2; + Weight = UWORD32_MAX; } -bool Edge::operator== (const Edge& e) const -{ - if ((Vertex1->getLabel() == e.Vertex1->getLabel()) && (Vertex2->getLabel() == e.Vertex2->getLabel()) && - (Index1 == e.Index1) && (Index2 == e.Index2)) { - return true ; - } - if ((Vertex1->getLabel() == e.Vertex2->getLabel()) && (Vertex2->getLabel() == e.Vertex1->getLabel()) && - (Index1 == e.Index2) && (Index2 == e.Index1)) { - return true ; - } - return false ; +bool Edge::operator==(const Edge &e) const { + if ((Vertex1->getLabel() == e.Vertex1->getLabel()) && + (Vertex2->getLabel() == e.Vertex2->getLabel()) && (Index1 == e.Index1) && + (Index2 == e.Index2)) { + return true; + } + if ((Vertex1->getLabel() == e.Vertex2->getLabel()) && + (Vertex2->getLabel() == e.Vertex1->getLabel()) && (Index1 == e.Index2) && + (Index2 == e.Index1)) { + return true; + } + return false; } -bool Edge::operator!= (const Edge& e) const -{ - return (!operator==(e)) ; -} +bool Edge::operator!=(const Edge &e) const { return (!operator==(e)); } -void Edge::swap (void) -{ - Vertex* v_tmp = Vertex1 ; - Vertex1 = Vertex2 ; - Vertex2 = v_tmp ; +void Edge::swap(void) { + Vertex *v_tmp = Vertex1; + Vertex1 = Vertex2; + Vertex2 = v_tmp; - unsigned short idx_tmp = Index1 ; - Index1 = Index2 ; - Index2 = idx_tmp ; + unsigned short idx_tmp = Index1; + Index1 = Index2; + Index2 = idx_tmp; } -bool Edge::contains (const Vertex* v) const -{ - return ((v->getLabel() == Vertex1->getLabel()) || (v->getLabel() == Vertex2->getLabel())) ; +bool Edge::contains(const Vertex *v) const { + return ((v->getLabel() == Vertex1->getLabel()) || (v->getLabel() == Vertex2->getLabel())); } -Vertex *Edge::getOtherVertex (const Vertex *v) const -{ - Vertex *retval = NULL ; - if (v->getLabel() == Vertex1->getLabel()) { - retval = Vertex2 ; - } - else if (v->getLabel() == Vertex2->getLabel()) { - retval = Vertex1 ; - } - else { - myassert (0) ; - } - return retval ; +Vertex *Edge::getOtherVertex(const Vertex *v) const { + Vertex *retval = NULL; + if (v->getLabel() == Vertex1->getLabel()) { + retval = Vertex2; + } else if (v->getLabel() == Vertex2->getLabel()) { + retval = Vertex1; + } else { + myassert(0); + } + return retval; } -SamplePos Edge::getSamplePos (Vertex *v) const -{ - SamplePos retval = 0 ; - if (v->getLabel() == Vertex1->getLabel()) { - retval = Vertex1->getSamplePos (Index1) ; - } - else if (v->getLabel() == Vertex2->getLabel()) { - retval = Vertex2->getSamplePos (Index2) ; - } - else { - myassert (0) ; - } - return retval ; +SamplePos Edge::getSamplePos(Vertex *v) const { + SamplePos retval = 0; + if (v->getLabel() == Vertex1->getLabel()) { + retval = Vertex1->getSamplePos(Index1); + } else if (v->getLabel() == Vertex2->getLabel()) { + retval = Vertex2->getSamplePos(Index2); + } else { + myassert(0); + } + return retval; } -SampleValue *Edge::getOriginalSampleValue (Vertex *v) const -{ - unsigned short index = 0 ; - if (v->getLabel() == Vertex1->getLabel()) { - index = Index1 ; - } - else if (v->getLabel() == Vertex2->getLabel()) { - index = Index2 ; - } - else { - myassert (0) ; - } - return v->getSampleValue (index) ; +SampleValue *Edge::getOriginalSampleValue(Vertex *v) const { + unsigned short index = 0; + if (v->getLabel() == Vertex1->getLabel()) { + index = Index1; + } else if (v->getLabel() == Vertex2->getLabel()) { + index = Index2; + } else { + myassert(0); + } + return v->getSampleValue(index); } -SampleValue *Edge::getReplacingSampleValue (Vertex *v) const -{ - SampleValue *retval = NULL ; - if (v->getLabel() == Vertex1->getLabel()) { - retval = Vertex2->getSampleValue (Index2) ; - } - else if (v->getLabel() == Vertex2->getLabel()) { - retval = Vertex1->getSampleValue (Index1) ; - } - else { - myassert (0) ; - } - return retval ; +SampleValue *Edge::getReplacingSampleValue(Vertex *v) const { + SampleValue *retval = NULL; + if (v->getLabel() == Vertex1->getLabel()) { + retval = Vertex2->getSampleValue(Index2); + } else if (v->getLabel() == Vertex2->getLabel()) { + retval = Vertex1->getSampleValue(Index1); + } else { + myassert(0); + } + return retval; } -void Edge::print (unsigned short spc) const -{ - char* space = new char[spc + 1] ; - for (unsigned short i = 0 ; i < spc ; i++) { - space[i] = ' ' ; - } - space[spc] = '\0' ; - - std::cerr << space << "Edge:" << std::endl ; - Vertex1->print (spc + 1) ; - std::cerr << space << " Index1: " << Index1 << std::endl ; - Vertex2->print (spc + 1) ; - std::cerr << space << " Index2: " << Index2 << std::endl ; - std::cerr << space << " Weight: " ; - if (Weight == UWORD32_MAX) { - std::cerr << "not calculated" ; - } - else { - std::cerr << Weight ; - } - std::cerr << std::endl ; +void Edge::print(unsigned short spc) const { + char *space = new char[spc + 1]; + for (unsigned short i = 0; i < spc; i++) { + space[i] = ' '; + } + space[spc] = '\0'; + + std::cerr << space << "Edge:" << std::endl; + Vertex1->print(spc + 1); + std::cerr << space << " Index1: " << Index1 << std::endl; + Vertex2->print(spc + 1); + std::cerr << space << " Index2: " << Index2 << std::endl; + std::cerr << space << " Weight: "; + if (Weight == UWORD32_MAX) { + std::cerr << "not calculated"; + } else { + std::cerr << Weight; + } + std::cerr << std::endl; } diff --git a/src/Edge.h b/src/Edge.h index 4d75b10..48d099b 100644 --- a/src/Edge.h +++ b/src/Edge.h @@ -26,95 +26,92 @@ #include "common.h" class Edge { - public: - /** - * default constructor - does not create a useful object - **/ - Edge (void) - : Vertex1(NULL), Index1(0), Vertex2(NULL), Index2(0), Weight(UWORD32_MAX) {} ; + public: + /** + * default constructor - does not create a useful object + **/ + Edge(void) : Vertex1(NULL), Index1(0), Vertex2(NULL), Index2(0), Weight(UWORD32_MAX){}; - /** - * constructs an edge object - **/ - Edge (Vertex *v1, unsigned short idx1, Vertex *v2, unsigned short idx2) ; + /** + * constructs an edge object + **/ + Edge(Vertex *v1, unsigned short idx1, Vertex *v2, unsigned short idx2); - /** - * copy constructor - **/ - Edge (const Edge& e) ; + /** + * copy constructor + **/ + Edge(const Edge &e); - Vertex *getVertex1 (void) const - { return Vertex1 ; } ; + Vertex *getVertex1(void) const { return Vertex1; }; - void setVertex1 (Vertex* v) - { Vertex1 = v ; } ; + void setVertex1(Vertex *v) { Vertex1 = v; }; - Vertex *getVertex2 (void) const - { return Vertex2 ; } ; + Vertex *getVertex2(void) const { return Vertex2; }; - unsigned short getIndex1 (void) const - { return Index1 ; } ; + unsigned short getIndex1(void) const { return Index1; }; - void setIndex1 (unsigned short i) - { Index1 = i ; } ; + void setIndex1(unsigned short i) { Index1 = i; }; - unsigned short getIndex2 (void) const - { return Index2 ; } ; + unsigned short getIndex2(void) const { return Index2; }; - UWORD32 getWeight (void) ; + UWORD32 getWeight(void); - void set (Vertex* v1, unsigned short idx1, Vertex* v2, unsigned short idx2) ; + void set(Vertex *v1, unsigned short idx1, Vertex *v2, unsigned short idx2); - void set1 (Vertex* v1, unsigned short idx1) ; + void set1(Vertex *v1, unsigned short idx1); - void set2 (Vertex* v2, unsigned short idx2) ; + void set2(Vertex *v2, unsigned short idx2); - bool operator== (const Edge& e) const ; + bool operator==(const Edge &e) const; - bool operator!= (const Edge& e) const ; + bool operator!=(const Edge &e) const; - /** - * swap vertices 1 and 2 in this edge (weight is not altered) - **/ - void swap (void) ; + /** + * swap vertices 1 and 2 in this edge (weight is not altered) + **/ + void swap(void); - /** - * \return true iff this edge contains the vertex v - **/ - bool contains (const Vertex *v) const ; + /** + * \return true iff this edge contains the vertex v + **/ + bool contains(const Vertex *v) const; - /** - * get the vertex on this edge that is not equal to v - **/ - Vertex *getOtherVertex (const Vertex *v) const ; + /** + * get the vertex on this edge that is not equal to v + **/ + Vertex *getOtherVertex(const Vertex *v) const; - /** - * get the position of the sample that should be changed to embed the bit represented by the vertex v - **/ - SamplePos getSamplePos (Vertex* v) const ; + /** + * get the position of the sample that should be changed to embed the bit represented by the + *vertex v + **/ + SamplePos getSamplePos(Vertex *v) const; - /** - * get the old sample value that will be replaced to embed the bit represented by the vertex v - **/ - SampleValue *getOriginalSampleValue (Vertex *v) const ; + /** + * get the old sample value that will be replaced to embed the bit represented by the vertex v + **/ + SampleValue *getOriginalSampleValue(Vertex *v) const; - /** - * get the sample value that should replace the previous sample value to embed the bit represented by the vertex v - **/ - SampleValue *getReplacingSampleValue (Vertex *v) const ; + /** + * get the sample value that should replace the previous sample value to embed the bit + *represented by the vertex v + **/ + SampleValue *getReplacingSampleValue(Vertex *v) const; - void print (unsigned short spc = 0) const ; - - private: - Vertex *Vertex1 ; - /// contains the index of the sample (of those in Vertex1) that will be changed (if this edge is used) - unsigned short Index1 ; - - Vertex *Vertex2 ; - /// contains the index of the sample (of those in Vertex2) that will be changed (if this edge is used) - unsigned short Index2 ; + void print(unsigned short spc = 0) const; - UWORD32 Weight ; -} ; + private: + Vertex *Vertex1; + /// contains the index of the sample (of those in Vertex1) that will be changed (if this edge is + /// used) + unsigned short Index1; + + Vertex *Vertex2; + /// contains the index of the sample (of those in Vertex2) that will be changed (if this edge is + /// used) + unsigned short Index2; + + UWORD32 Weight; +}; #endif // ndef SH_EDGE_H diff --git a/src/EdgeIterator.cc b/src/EdgeIterator.cc index 8b4c85f..ba051a9 100644 --- a/src/EdgeIterator.cc +++ b/src/EdgeIterator.cc @@ -18,182 +18,177 @@ * */ -#include "Edge.h" #include "EdgeIterator.h" +#include "Edge.h" #include "Graph.h" #include "SampleOccurence.h" #include "Vertex.h" #include "common.h" -EdgeIterator::EdgeIterator () - : SVALIndices(NULL) -{ - SVALIndices = new unsigned long[Globs.TheCvrStgFile->getSamplesPerVertex()] ; -} - -EdgeIterator::EdgeIterator (Vertex *v, ITERATIONMODE m) -{ - SVALIndices = new unsigned long[Globs.TheCvrStgFile->getSamplesPerVertex()] ; - reset(v, m) ; +EdgeIterator::EdgeIterator() : SVALIndices(NULL) { + SVALIndices = new unsigned long[Globs.TheCvrStgFile->getSamplesPerVertex()]; } -EdgeIterator::EdgeIterator (const EdgeIterator& eit) -{ - CurrentEdge = eit.CurrentEdge ; - Mode = eit.Mode ; - SVALIndices = new unsigned long[Globs.TheCvrStgFile->getSamplesPerVertex()] ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - SVALIndices[i] = eit.SVALIndices[i] ; - } - Finished = eit.Finished ; - SampleOccurenceIt = eit.SampleOccurenceIt ; +EdgeIterator::EdgeIterator(Vertex *v, ITERATIONMODE m) { + SVALIndices = new unsigned long[Globs.TheCvrStgFile->getSamplesPerVertex()]; + reset(v, m); } -EdgeIterator::~EdgeIterator () -{ - delete[] SVALIndices ; +EdgeIterator::EdgeIterator(const EdgeIterator &eit) { + CurrentEdge = eit.CurrentEdge; + Mode = eit.Mode; + SVALIndices = new unsigned long[Globs.TheCvrStgFile->getSamplesPerVertex()]; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + SVALIndices[i] = eit.SVALIndices[i]; + } + Finished = eit.Finished; + SampleOccurenceIt = eit.SampleOccurenceIt; } -void EdgeIterator::operator++ () -{ - myassert (!Finished) ; - - Vertex* srcv = CurrentEdge.getVertex1() ; - unsigned short srcidx = CurrentEdge.getIndex1() ; - - switch (Mode) { - case SAMPLEOCCURENCE: - { - SampleValue* srcsv = srcv->getSampleValue(srcidx) ; - SampleValue* destsv = (*(Globs.TheGraph->SVALists[srcv->getTargetValue(srcidx)]))[srcsv][SVALIndices[srcidx]] ; - - bool cont = false ; - do { - SampleOccurenceIt++ ; - - cont = false ; - if (SampleOccurenceIt != Globs.TheGraph->SampleOccurences[destsv->getLabel()].end()) { - if ((srcsv->getEmbeddedValue() != SampleOccurenceIt->getVertex()->getTargetValue(SampleOccurenceIt->getIndex())) || (SampleOccurenceIt->getVertex()->getLabel() == srcv->getLabel())) { - cont = true ; - } - } - } while (cont) ; - - if (SampleOccurenceIt == Globs.TheGraph->SampleOccurences[destsv->getLabel()].end()) { - // search new destination sample value - SVALIndices[srcidx]++ ; - findNextEdge() ; - } - break ; - } - case SAMPLEVALUE: - { - SVALIndices[srcidx]++ ; - findNextEdge() ; - break ; - } - } - - // increment EdgeIndex while checking that it has not become too high - if (++EdgeIndex >= MaxNumEdges) { - Finished = true ; - } - - if (!Finished) { - CurrentEdge.set2 (SampleOccurenceIt->getVertex(), SampleOccurenceIt->getIndex()) ; - } +EdgeIterator::~EdgeIterator() { delete[] SVALIndices; } + +void EdgeIterator::operator++() { + myassert(!Finished); + + Vertex *srcv = CurrentEdge.getVertex1(); + unsigned short srcidx = CurrentEdge.getIndex1(); + + switch (Mode) { + case SAMPLEOCCURENCE: { + SampleValue *srcsv = srcv->getSampleValue(srcidx); + SampleValue *destsv = + (*(Globs.TheGraph->SVALists[srcv->getTargetValue(srcidx)]))[srcsv][SVALIndices[srcidx]]; + + bool cont = false; + do { + SampleOccurenceIt++; + + cont = false; + if (SampleOccurenceIt != Globs.TheGraph->SampleOccurences[destsv->getLabel()].end()) { + if ((srcsv->getEmbeddedValue() != SampleOccurenceIt->getVertex()->getTargetValue( + SampleOccurenceIt->getIndex())) || + (SampleOccurenceIt->getVertex()->getLabel() == srcv->getLabel())) { + cont = true; + } + } + } while (cont); + + if (SampleOccurenceIt == Globs.TheGraph->SampleOccurences[destsv->getLabel()].end()) { + // search new destination sample value + SVALIndices[srcidx]++; + findNextEdge(); + } + break; + } + case SAMPLEVALUE: { + SVALIndices[srcidx]++; + findNextEdge(); + break; + } + } + + // increment EdgeIndex while checking that it has not become too high + if (++EdgeIndex >= MaxNumEdges) { + Finished = true; + } + + if (!Finished) { + CurrentEdge.set2(SampleOccurenceIt->getVertex(), SampleOccurenceIt->getIndex()); + } } -void EdgeIterator::reset (ITERATIONMODE m) -{ - Mode = m ; - Finished = false ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - SVALIndices[i] = 0 ; - } - findNextEdge() ; - EdgeIndex = 0 ; - if (!Finished) { - CurrentEdge.set2 (SampleOccurenceIt->getVertex(), SampleOccurenceIt->getIndex()) ; - } +void EdgeIterator::reset(ITERATIONMODE m) { + Mode = m; + Finished = false; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + SVALIndices[i] = 0; + } + findNextEdge(); + EdgeIndex = 0; + if (!Finished) { + CurrentEdge.set2(SampleOccurenceIt->getVertex(), SampleOccurenceIt->getIndex()); + } } -void EdgeIterator::reset (Vertex* v, ITERATIONMODE m) -{ - CurrentEdge.setVertex1 (v) ; - reset(m) ; +void EdgeIterator::reset(Vertex *v, ITERATIONMODE m) { + CurrentEdge.setVertex1(v); + reset(m); } -void EdgeIterator::findNextEdge () -{ - UWORD32 mindist = UWORD32_MAX ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - Vertex* srcv = CurrentEdge.getVertex1() ; - SampleValue* srcsv = srcv->getSampleValue(i) ; - SampleValue* destsv = NULL ; - std::list::const_iterator soccit_candidate ; - - // increment SVALIndices[i] until it points to a valid destination sample value - while (SVALIndices[i] < (*(Globs.TheGraph->SVALists[srcv->getTargetValue(i)]))[srcsv].size()) { - destsv = (*(Globs.TheGraph->SVALists[srcv->getTargetValue(i)]))[srcsv][SVALIndices[i]] ; - - // look for a sample occurence of destsv - thereby setting soccit_candidate - bool found = false ; - const std::list& socc = Globs.TheGraph->SampleOccurences[destsv->getLabel()] ; - soccit_candidate = socc.begin() ; - while (!found && soccit_candidate != socc.end()) { - if ((soccit_candidate->getVertex()->getLabel() == srcv->getLabel()) || - (srcsv->getEmbeddedValue() != soccit_candidate->getVertex()->getTargetValue(soccit_candidate->getIndex()))) { - soccit_candidate++ ; - } - else { - found = true ; - } - } - - if (found) { - break ; - } - else { - SVALIndices[i]++ ; - } - } - - // test if the destination sample value leads to edge with (until now) minimal distance - thereby setting CurrentEdge.Index1 and SampleOccurenceIt - if (SVALIndices[i] < (*(Globs.TheGraph->SVALists[srcv->getTargetValue(i)]))[srcsv].size()) { - UWORD32 thisdist = srcsv->calcDistance(destsv) ; - if (thisdist < mindist) { - mindist = thisdist ; - CurrentEdge.setIndex1(i) ; - SampleOccurenceIt = soccit_candidate ; - } - } - } - - if (mindist == UWORD32_MAX) { - // no edge has been found - Finished = true ; - } +void EdgeIterator::findNextEdge() { + UWORD32 mindist = UWORD32_MAX; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + Vertex *srcv = CurrentEdge.getVertex1(); + SampleValue *srcsv = srcv->getSampleValue(i); + SampleValue *destsv = NULL; + std::list::const_iterator soccit_candidate; + + // increment SVALIndices[i] until it points to a valid destination sample + // value + while (SVALIndices[i] < + (*(Globs.TheGraph->SVALists[srcv->getTargetValue(i)]))[srcsv].size()) { + destsv = (*(Globs.TheGraph->SVALists[srcv->getTargetValue(i)]))[srcsv][SVALIndices[i]]; + + // look for a sample occurence of destsv - thereby setting + // soccit_candidate + bool found = false; + const std::list &socc = + Globs.TheGraph->SampleOccurences[destsv->getLabel()]; + soccit_candidate = socc.begin(); + while (!found && soccit_candidate != socc.end()) { + if ((soccit_candidate->getVertex()->getLabel() == srcv->getLabel()) || + (srcsv->getEmbeddedValue() != + soccit_candidate->getVertex()->getTargetValue(soccit_candidate->getIndex()))) { + soccit_candidate++; + } else { + found = true; + } + } + + if (found) { + break; + } else { + SVALIndices[i]++; + } + } + + // test if the destination sample value leads to edge with (until now) + // minimal distance - thereby setting CurrentEdge.Index1 and + // SampleOccurenceIt + if (SVALIndices[i] < (*(Globs.TheGraph->SVALists[srcv->getTargetValue(i)]))[srcsv].size()) { + UWORD32 thisdist = srcsv->calcDistance(destsv); + if (thisdist < mindist) { + mindist = thisdist; + CurrentEdge.setIndex1(i); + SampleOccurenceIt = soccit_candidate; + } + } + } + + if (mindist == UWORD32_MAX) { + // no edge has been found + Finished = true; + } } #ifdef DEBUG -void EdgeIterator::print (unsigned short spc) const -{ - char* space = new char[spc + 1] ; - for (unsigned short i = 0 ; i < spc ; i++) { - space[i] = ' ' ; - } - space[spc] = '\0' ; - - std::cerr << space << "Current Edge:" << std::endl ; - CurrentEdge.print(spc + 1) ; - std::cerr << space << "SampleOccurenceIt: <" << SampleOccurenceIt->getVertex()->getLabel() << "," << SampleOccurenceIt->getIndex() << ">" << std::endl ; - std::cerr << space << "Finished: " << Finished << std::endl ; - std::cerr << space << "EdgeIndex: " << EdgeIndex << std::endl ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - std::cerr << space << "SVALIndices[" << i << "]: " << SVALIndices[i] << std::endl ; - } +void EdgeIterator::print(unsigned short spc) const { + char *space = new char[spc + 1]; + for (unsigned short i = 0; i < spc; i++) { + space[i] = ' '; + } + space[spc] = '\0'; + + std::cerr << space << "Current Edge:" << std::endl; + CurrentEdge.print(spc + 1); + std::cerr << space << "SampleOccurenceIt: <" << SampleOccurenceIt->getVertex()->getLabel() + << "," << SampleOccurenceIt->getIndex() << ">" << std::endl; + std::cerr << space << "Finished: " << Finished << std::endl; + std::cerr << space << "EdgeIndex: " << EdgeIndex << std::endl; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + std::cerr << space << "SVALIndices[" << i << "]: " << SVALIndices[i] << std::endl; + } } #endif -UWORD32 EdgeIterator::MaxNumEdges = UWORD32_MAX ; +UWORD32 EdgeIterator::MaxNumEdges = UWORD32_MAX; diff --git a/src/EdgeIterator.h b/src/EdgeIterator.h index 17fdc11..8c7564b 100644 --- a/src/EdgeIterator.h +++ b/src/EdgeIterator.h @@ -24,10 +24,10 @@ #include #include "Edge.h" -class Graph ; +class Graph; #include "SampleOccurence.h" -class SampleValue ; -class Vertex ; +class SampleValue; +class Vertex; /** * \class EdgeIterator @@ -49,110 +49,111 @@ class Vertex ; * This means that it must be set correctly before using any method of an EdgeIterator object. **/ class EdgeIterator { - public: - enum ITERATIONMODE { - SAMPLEOCCURENCE, // incrementing increments to next sample occurence (possibly of the same sample value) thus using every edge of the source vertex - SAMPLEVALUE // incrementing increments to the next sample value thus not using all edges in general - } ; - - /** - * the default contructor - does not create a valid object - **/ - EdgeIterator (void) ; - - /** - * \param v the source vertex - **/ - EdgeIterator (Vertex *v, ITERATIONMODE m = SAMPLEOCCURENCE) ; - - /** - * the copy constructor - **/ - EdgeIterator (const EdgeIterator& eit) ; - - ~EdgeIterator (void) ; - - /** - * get the current edge - * \return the edge that is described by the current status of this EdgeIterator - **/ - const Edge* operator* (void) const - { return ((Finished) ? NULL : &CurrentEdge) ; } - - /** - * set this iterator to next edge - **/ - void operator++ (void) ; - - /** - * set this iterator to first (shortest) edge of vertex v - * \param v new vertex (don't change if it is NULL) - **/ - void reset (Vertex* v, ITERATIONMODE m = SAMPLEOCCURENCE) ; - - /** - * reset this iterator to first (shortest) edge - **/ - void reset (ITERATIONMODE m = SAMPLEOCCURENCE) ; - - /** - * \return true iff this EdgeIterator points to the end of the list of edges of SrcVertex - **/ - bool isFinished (void) const - { return Finished ; } ; - - /** - * get the label of the partner vertex - * \return the label of the vertex that builds the edge returned by operator* together with SrcVertex - **/ - VertexLabel getPartnerVertexLabel (void) const - { return SampleOccurenceIt->getVertex()->getLabel() ; } ; - - static UWORD32 getMaxNumEdges (void) - { return MaxNumEdges ; } ; - - static void setMaxNumEdges (UWORD32 mne) - { MaxNumEdges = mne ; } ; - - void print (unsigned short spc = 0) const ; - - private: - /// the current edge (is returned by operator*) - Edge CurrentEdge ; - - /// mode of iteration - ITERATIONMODE Mode ; - - /// contains (for every sample value) an index to the current opposite neighbour - unsigned long* SVALIndices ; - - /// the maximum number of edges the EdgeIterator should iterate through - static UWORD32 MaxNumEdges ; - - /// the index/number of the edge that is currently returned by operator* - UWORD32 EdgeIndex ; - - /// is true iff there are no more edges for this source vertex - bool Finished ; - - /** - * contains the iterator pointing to the sample occurence that constitutes - * the edge together with SourceVertex/SourceSamleValueIndex - **/ - std::list::const_iterator SampleOccurenceIt ; - - /** - * find the shortest edge, starting the search at SVOppNeighsIndices[0...k] - * set the private variables accordingly - * is only called to find a new destination sample value, i.e. if one of the - * SVOppNeighsIndices[i] is changed - **/ - void findNextEdge (void) ; - - /** - * \return true iff there is a sample with value sv that is part of an edge starting at SrcVertex - **/ - bool isDestSampleValueOK (const SampleValue *sv) ; -} ; + public: + enum ITERATIONMODE { + SAMPLEOCCURENCE, // incrementing increments to next sample occurence (possibly of the same + // sample value) thus using every edge of the source vertex + SAMPLEVALUE // incrementing increments to the next sample value thus not using all edges in + // general + }; + + /** + * the default contructor - does not create a valid object + **/ + EdgeIterator(void); + + /** + * \param v the source vertex + **/ + EdgeIterator(Vertex *v, ITERATIONMODE m = SAMPLEOCCURENCE); + + /** + * the copy constructor + **/ + EdgeIterator(const EdgeIterator &eit); + + ~EdgeIterator(void); + + /** + * get the current edge + * \return the edge that is described by the current status of this EdgeIterator + **/ + const Edge *operator*(void) const { return ((Finished) ? NULL : &CurrentEdge); } + + /** + * set this iterator to next edge + **/ + void operator++(void); + + /** + * set this iterator to first (shortest) edge of vertex v + * \param v new vertex (don't change if it is NULL) + **/ + void reset(Vertex *v, ITERATIONMODE m = SAMPLEOCCURENCE); + + /** + * reset this iterator to first (shortest) edge + **/ + void reset(ITERATIONMODE m = SAMPLEOCCURENCE); + + /** + * \return true iff this EdgeIterator points to the end of the list of edges of SrcVertex + **/ + bool isFinished(void) const { return Finished; }; + + /** + * get the label of the partner vertex + * \return the label of the vertex that builds the edge returned by operator* together with + *SrcVertex + **/ + VertexLabel getPartnerVertexLabel(void) const { + return SampleOccurenceIt->getVertex()->getLabel(); + }; + + static UWORD32 getMaxNumEdges(void) { return MaxNumEdges; }; + + static void setMaxNumEdges(UWORD32 mne) { MaxNumEdges = mne; }; + + void print(unsigned short spc = 0) const; + + private: + /// the current edge (is returned by operator*) + Edge CurrentEdge; + + /// mode of iteration + ITERATIONMODE Mode; + + /// contains (for every sample value) an index to the current opposite neighbour + unsigned long *SVALIndices; + + /// the maximum number of edges the EdgeIterator should iterate through + static UWORD32 MaxNumEdges; + + /// the index/number of the edge that is currently returned by operator* + UWORD32 EdgeIndex; + + /// is true iff there are no more edges for this source vertex + bool Finished; + + /** + * contains the iterator pointing to the sample occurence that constitutes + * the edge together with SourceVertex/SourceSamleValueIndex + **/ + std::list::const_iterator SampleOccurenceIt; + + /** + * find the shortest edge, starting the search at SVOppNeighsIndices[0...k] + * set the private variables accordingly + * is only called to find a new destination sample value, i.e. if one of the + * SVOppNeighsIndices[i] is changed + **/ + void findNextEdge(void); + + /** + * \return true iff there is a sample with value sv that is part of an edge starting at + *SrcVertex + **/ + bool isDestSampleValueOK(const SampleValue *sv); +}; #endif // ndef SH_EDGEITERATOR_H diff --git a/src/EmbData.cc b/src/EmbData.cc index e30735a..c3f347d 100644 --- a/src/EmbData.cc +++ b/src/EmbData.cc @@ -20,335 +20,305 @@ * - Added file name sanitization to the extractor */ -#include "Utils.h" +#include "EmbData.h" #include "AUtils.h" #include "BinaryIO.h" #include "BitString.h" -#include "EmbData.h" -#include "error.h" #include "MCryptPP.h" #include "MHashPP.h" +#include "Utils.h" #include "common.h" +#include "error.h" -EmbData::EmbData (MODE m, std::string pp, std::string fn) - : Mode(m), Passphrase(pp), FileName(fn) -{ - if (m == EXTRACT) { - NumBitsNeeded = NumBitsRequested = NBitsMagic ; - Version = CodeVersion ; - State = READ_MAGIC ; - Reservoir = BitString() ; - } +EmbData::EmbData(MODE m, std::string pp, std::string fn) : Mode(m), Passphrase(pp), FileName(fn) { + if (m == EXTRACT) { + NumBitsNeeded = NumBitsRequested = NBitsMagic; + Version = CodeVersion; + State = READ_MAGIC; + Reservoir = BitString(); + } } -bool EmbData::finished () -{ - myassert (Mode == EXTRACT) ; - return (State == END) ; +bool EmbData::finished() { + myassert(Mode == EXTRACT); + return (State == END); } -unsigned long EmbData::getNumBitsRequested () -{ - myassert (Mode == EXTRACT) ; - return NumBitsRequested ; +unsigned long EmbData::getNumBitsRequested() { + myassert(Mode == EXTRACT); + return NumBitsRequested; } -void EmbData::addBits (BitString addbits) -{ - myassert (Mode == EXTRACT) ; +void EmbData::addBits(BitString addbits) { + myassert(Mode == EXTRACT); #ifdef DEBUG - printDebug (1, "\nEmbData::addBits called with") ; - printDebug (1, " addbits:") ; - addbits.printDebug (1, 2) ; - printDebug (1, " Reservoir:") ; - Reservoir.printDebug (1, 2) ; + printDebug(1, "\nEmbData::addBits called with"); + printDebug(1, " addbits:"); + addbits.printDebug(1, 2); + printDebug(1, " Reservoir:"); + Reservoir.printDebug(1, 2); #endif - Reservoir.append (addbits) ; - BitString bits ; - if (Reservoir.getLength() >= NumBitsNeeded) { - bits = Reservoir.cutBits (0, NumBitsNeeded) ; // take exactly the first NumBitsNeeded bits from Reservoir | addbits - } - else { // Reservoir.getLength() < NumBitsNeeded - myassert(false) ; - } + Reservoir.append(addbits); + BitString bits; + if (Reservoir.getLength() >= NumBitsNeeded) { + bits = Reservoir.cutBits(0, NumBitsNeeded); // take exactly the first NumBitsNeeded bits + // from Reservoir | addbits + } else { // Reservoir.getLength() < NumBitsNeeded + myassert(false); + } #ifdef DEBUG - printDebug (1, "bits is now:") ; - bits.printDebug (1, 2) ; + printDebug(1, "bits is now:"); + bits.printDebug(1, 2); #endif - switch (State) { - case READ_MAGIC: - { + switch (State) { + case READ_MAGIC: { #ifdef DEBUG - printDebug (1, "in the READ_MAGIC state") ; + printDebug(1, "in the READ_MAGIC state"); #endif - if (bits.getValue(0, NBitsMagic) == Magic) { - NumBitsNeeded = 1 ; - NumBitsRequested = AUtils::bminus (NumBitsNeeded, Reservoir.getLength()) ; - State = READ_VERSION ; - } - else { - throw SteghideError (_("could not extract any data with that passphrase!")) ; - } - break ; - } - - case READ_VERSION: - { + if (bits.getValue(0, NBitsMagic) == Magic) { + NumBitsNeeded = 1; + NumBitsRequested = AUtils::bminus(NumBitsNeeded, Reservoir.getLength()); + State = READ_VERSION; + } else { + throw SteghideError(_("could not extract any data with that passphrase!")); + } + break; + } + + case READ_VERSION: { #ifdef DEBUG - printDebug (1, "in the READ_VERSION state") ; + printDebug(1, "in the READ_VERSION state"); #endif - if (bits[0] == true) { - Version++ ; - NumBitsNeeded = AUtils::bminus ((UWORD32) 1, Reservoir.getLength()) ; - } - else { - if (Version > CodeVersion) { - throw CorruptDataError (_("attempting to read an embedding of version %d but steghide %s only supports embeddings of version %d."), Version, VERSION, CodeVersion) ; - } - NumBitsNeeded = EncryptionAlgorithm::IRep_size + EncryptionMode::IRep_size ; - NumBitsRequested = AUtils::bminus (NumBitsNeeded, Reservoir.getLength()) ; - State = READ_ENCINFO ; - } - break ; - } - - case READ_ENCINFO: { + if (bits[0] == true) { + Version++; + NumBitsNeeded = AUtils::bminus((UWORD32)1, Reservoir.getLength()); + } else { + if (Version > CodeVersion) { + throw CorruptDataError( + _("attempting to read an embedding of version %d but steghide %s " + "only supports embeddings of version %d."), + Version, VERSION, CodeVersion); + } + NumBitsNeeded = EncryptionAlgorithm::IRep_size + EncryptionMode::IRep_size; + NumBitsRequested = AUtils::bminus(NumBitsNeeded, Reservoir.getLength()); + State = READ_ENCINFO; + } + break; + } + + case READ_ENCINFO: { #ifdef DEBUG - printDebug (1, "in the READ_ENCINFO state") ; + printDebug(1, "in the READ_ENCINFO state"); #endif - unsigned int algo = (unsigned int) bits.getValue (0, EncryptionAlgorithm::IRep_size) ; - if (EncryptionAlgorithm::isValidIntegerRep (algo)) { - EncAlgo.setValue ((EncryptionAlgorithm::IRep) algo) ; - } - unsigned int mode = (unsigned int) bits.getValue (EncryptionAlgorithm::IRep_size, EncryptionMode::IRep_size) ; - if (EncryptionMode::isValidIntegerRep (mode)) { - EncMode.setValue ((EncryptionMode::IRep) mode) ; - } + unsigned int algo = (unsigned int)bits.getValue(0, EncryptionAlgorithm::IRep_size); + if (EncryptionAlgorithm::isValidIntegerRep(algo)) { + EncAlgo.setValue((EncryptionAlgorithm::IRep)algo); + } + unsigned int mode = + (unsigned int)bits.getValue(EncryptionAlgorithm::IRep_size, EncryptionMode::IRep_size); + if (EncryptionMode::isValidIntegerRep(mode)) { + EncMode.setValue((EncryptionMode::IRep)mode); + } - NumBitsNeeded = NBitsNPlainBits ; - NumBitsRequested = AUtils::bminus (NumBitsNeeded, Reservoir.getLength()) ; - State = READ_NPLAINBITS ; + NumBitsNeeded = NBitsNPlainBits; + NumBitsRequested = AUtils::bminus(NumBitsNeeded, Reservoir.getLength()); + State = READ_NPLAINBITS; - break ; } + break; + } - case READ_NPLAINBITS: { + case READ_NPLAINBITS: { #ifdef DEBUG - printDebug (1, "in the READ_NPLAINBITS state") ; + printDebug(1, "in the READ_NPLAINBITS state"); #endif - - NPlainBits = bits.getValue (0, NBitsNPlainBits) ; - NumBitsNeeded = (UWORD32) MCryptPP::getEncryptedSize (EncAlgo, EncMode, NPlainBits) ; - NumBitsRequested = AUtils::bminus (NumBitsNeeded, Reservoir.getLength()) ; + NPlainBits = bits.getValue(0, NBitsNPlainBits); - State = READ_ENCRYPTED ; - break ; } + NumBitsNeeded = (UWORD32)MCryptPP::getEncryptedSize(EncAlgo, EncMode, NPlainBits); + NumBitsRequested = AUtils::bminus(NumBitsNeeded, Reservoir.getLength()); - case READ_ENCRYPTED: { + State = READ_ENCRYPTED; + break; + } + + case READ_ENCRYPTED: { #ifdef DEBUG - printDebug (1, "in the READ_ENCRYPTED state") ; + printDebug(1, "in the READ_ENCRYPTED state"); #endif - BitString plain ; - if (EncAlgo.getIntegerRep() == EncryptionAlgorithm::NONE) { - plain = bits ; - } - else { - MCryptPP crypto (EncAlgo, EncMode) ; - plain = crypto.decrypt (bits, Passphrase) ; - } + BitString plain; + if (EncAlgo.getIntegerRep() == EncryptionAlgorithm::NONE) { + plain = bits; + } else { + MCryptPP crypto(EncAlgo, EncMode); + plain = crypto.decrypt(bits, Passphrase); + } - plain.truncate (0, NPlainBits) ; // cut off random padding used to achieve full number of encryption blocks + plain.truncate(0, NPlainBits); // cut off random padding used to achieve + // full number of encryption blocks - unsigned long pos = 0 ; + unsigned long pos = 0; - // read Compression (and uncompress) - Compression = ((plain[pos++]) ? 9 : 0) ; // to make compression contain a value that makes sense + // read Compression (and uncompress) + Compression = + ((plain[pos++]) ? 9 : 0); // to make compression contain a value that makes sense #ifdef DEBUG - printDebug (2, " compression: %d\n", plain[pos - 1]) ; + printDebug(2, " compression: %d\n", plain[pos - 1]); #endif - if (Compression > 0) { - UWORD32 NUncompressedBits = plain.getValue (pos, NBitsNUncompressedBits) ; + if (Compression > 0) { + UWORD32 NUncompressedBits = plain.getValue(pos, NBitsNUncompressedBits); #ifdef DEBUG - printDebug (2, " nuncobits: %lu\n", NUncompressedBits) ; + printDebug(2, " nuncobits: %lu\n", NUncompressedBits); #endif - pos += NBitsNUncompressedBits ; + pos += NBitsNUncompressedBits; - plain.truncate (pos, plain.getLength()) ; - pos = 0 ; - plain.uncompress (NUncompressedBits) ; - } + plain.truncate(pos, plain.getLength()); + pos = 0; + plain.uncompress(NUncompressedBits); + } - // read Checksum - Checksum = plain[pos++] ; + // read Checksum + Checksum = plain[pos++]; #ifdef DEBUG - printDebug (2, " checksum: %d\n", plain[pos - 1]) ; + printDebug(2, " checksum: %d\n", plain[pos - 1]); #endif - if (Checksum) { - CRC32 = plain.getValue (pos, NBitsCrc32) ; + if (Checksum) { + CRC32 = plain.getValue(pos, NBitsCrc32); #ifdef DEBUG - printDebug (2, " crc32: 0x%x\n", CRC32) ; + printDebug(2, " crc32: 0x%x\n", CRC32); #endif - pos += NBitsCrc32 ; - } - - // read filename - char curchar = '\0' ; - FileName = "" ; - do { - curchar = (char) plain.getValue (pos, 8) ; - if (curchar != '\0') { - FileName += curchar ; - } - pos += 8 ; - } while (curchar != '\0') ; - - // Strip the directory from the output file - FileName = stripDir (FileName) ; - - // extract data - if ((plain.getLength() - pos) % 8 != 0) { - throw CorruptDataError (_("the embedded data has an invalid length.")) ; - } - const unsigned long extdatalen = (plain.getLength() - pos) / 8 ; - Data.resize (extdatalen) ; - for (unsigned int i = 0 ; i < extdatalen ; i++) { - Data[i] = ((BYTE) plain.getValue (pos, 8)) ; - pos += 8 ; - } - - NumBitsNeeded = 0 ; - NumBitsRequested = 0 ; - State = END ; - break ; } - - case END: - default: { - myassert (0) ; - break ; } - } + pos += NBitsCrc32; + } + + // read filename + char curchar = '\0'; + FileName = ""; + do { + curchar = (char)plain.getValue(pos, 8); + if (curchar != '\0') { + FileName += curchar; + } + pos += 8; + } while (curchar != '\0'); + + // Strip the directory from the output file + FileName = stripDir(FileName); + + // extract data + if ((plain.getLength() - pos) % 8 != 0) { + throw CorruptDataError(_("the embedded data has an invalid length.")); + } + const unsigned long extdatalen = (plain.getLength() - pos) / 8; + Data.resize(extdatalen); + for (unsigned int i = 0; i < extdatalen; i++) { + Data[i] = ((BYTE)plain.getValue(pos, 8)); + pos += 8; + } + + NumBitsNeeded = 0; + NumBitsRequested = 0; + State = END; + break; + } + + case END: + default: { + myassert(0); + break; + } + } } -bool EmbData::checksumOK (void) const -{ - // test if checksum is ok - bool ok = true ; - if (Checksum) { - MHashPP hash (MHASH_CRC32) ; - for (std::vector::const_iterator i = Data.begin() ; i != Data.end() ; i++) { - hash << *i ; - } - hash << MHashPP::endhash ; - unsigned long calccrc32 = hash.getHashBits().getValue(0, NBitsCrc32) ; - - if (calccrc32 == CRC32) { - ok = true ; - } - else { - ok = false ; - } - } - return ok ; +bool EmbData::checksumOK(void) const { + // test if checksum is ok + bool ok = true; + if (Checksum) { + MHashPP hash(MHASH_CRC32); + for (std::vector::const_iterator i = Data.begin(); i != Data.end(); i++) { + hash << *i; + } + hash << MHashPP::endhash; + unsigned long calccrc32 = hash.getHashBits().getValue(0, NBitsCrc32); + + if (calccrc32 == CRC32) { + ok = true; + } else { + ok = false; + } + } + return ok; } -void EmbData::setEncAlgo (EncryptionAlgorithm a) -{ - EncAlgo = a ; -} - -EncryptionAlgorithm EmbData::getEncAlgo () const -{ - return EncAlgo ; -} - -void EmbData::setEncMode (EncryptionMode m) -{ - EncMode = m ; -} - -EncryptionMode EmbData::getEncMode () const -{ - return EncMode ; -} - -void EmbData::setCompression (int c) -{ - Compression = c ; -} - -int EmbData::getCompression (void) const -{ - return Compression ; -} - -void EmbData::setChecksum (bool c) -{ - Checksum = c ; -} - -bool EmbData::getChecksum (void) const -{ - return Checksum ; -} +void EmbData::setEncAlgo(EncryptionAlgorithm a) { EncAlgo = a; } -BitString EmbData::getBitString () -{ - myassert (Mode == EMBED) ; - - // assembling data that can be compressed - BitString compr ; - - compr.append (Checksum) ; - if (Checksum) { - MHashPP hash (MHASH_CRC32) ; - for (std::vector::iterator i = Data.begin() ; i != Data.end() ; i++) { - hash << *i ; - } - hash << MHashPP::endhash ; - compr.append (hash.getHashBits()) ; - } - - compr.append (stripDir (FileName)) ; - compr.append ((BYTE) 0, 8) ; // end of fileame - - compr.append (Data) ; - - // assembling data that can be encrypted - BitString plain ; - plain.append ((Compression > 0) ? true : false) ; - if (Compression > 0) { - plain.append (compr.getLength(), NBitsNUncompressedBits) ; - compr.compress (Compression) ; - } - plain.append (compr) ; - - // put it all together - BitString main ; - main.append(Magic, NBitsMagic) ; - for (unsigned short i = 0 ; i < CodeVersion ; i++) { - main.append(true) ; - } - main.append(false) ; // end of version - main.append((UWORD16) EncAlgo.getIntegerRep(), EncryptionAlgorithm::IRep_size) ; - main.append((UWORD16) EncMode.getIntegerRep(), EncryptionMode::IRep_size) ; - main.append(plain.getLength(), NBitsNPlainBits) ; - - if (EncAlgo.getIntegerRep() != EncryptionAlgorithm::NONE) { - MCryptPP crypto (EncAlgo, EncMode) ; - plain = crypto.encrypt (plain, Passphrase) ; - } - - main.append (plain) ; - - return main ; -} +EncryptionAlgorithm EmbData::getEncAlgo() const { return EncAlgo; } -std::string EmbData::stripDir (std::string s) -{ - return Utils::stripDir(s) ; +void EmbData::setEncMode(EncryptionMode m) { EncMode = m; } + +EncryptionMode EmbData::getEncMode() const { return EncMode; } + +void EmbData::setCompression(int c) { Compression = c; } + +int EmbData::getCompression(void) const { return Compression; } + +void EmbData::setChecksum(bool c) { Checksum = c; } + +bool EmbData::getChecksum(void) const { return Checksum; } + +BitString EmbData::getBitString() { + myassert(Mode == EMBED); + + // assembling data that can be compressed + BitString compr; + + compr.append(Checksum); + if (Checksum) { + MHashPP hash(MHASH_CRC32); + for (std::vector::iterator i = Data.begin(); i != Data.end(); i++) { + hash << *i; + } + hash << MHashPP::endhash; + compr.append(hash.getHashBits()); + } + + compr.append(stripDir(FileName)); + compr.append((BYTE)0, 8); // end of fileame + + compr.append(Data); + + // assembling data that can be encrypted + BitString plain; + plain.append((Compression > 0) ? true : false); + if (Compression > 0) { + plain.append(compr.getLength(), NBitsNUncompressedBits); + compr.compress(Compression); + } + plain.append(compr); + + // put it all together + BitString main; + main.append(Magic, NBitsMagic); + for (unsigned short i = 0; i < CodeVersion; i++) { + main.append(true); + } + main.append(false); // end of version + main.append((UWORD16)EncAlgo.getIntegerRep(), EncryptionAlgorithm::IRep_size); + main.append((UWORD16)EncMode.getIntegerRep(), EncryptionMode::IRep_size); + main.append(plain.getLength(), NBitsNPlainBits); + + if (EncAlgo.getIntegerRep() != EncryptionAlgorithm::NONE) { + MCryptPP crypto(EncAlgo, EncMode); + plain = crypto.encrypt(plain, Passphrase); + } + + main.append(plain); + + return main; } + +std::string EmbData::stripDir(std::string s) { return Utils::stripDir(s); } diff --git a/src/EmbData.h b/src/EmbData.h index ec451e1..1b6f006 100644 --- a/src/EmbData.h +++ b/src/EmbData.h @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * + * * 2020: * - Modified header file to make Magic and NBitsMagic public * @@ -34,104 +34,102 @@ #include "EncryptionMode.h" class EmbData { - public: - enum MODE { EMBED, EXTRACT } ; - enum STATE { READ_MAGIC, READ_VERSION, READ_ENCINFO, READ_NPLAINBITS, READ_ENCRYPTED, END } ; - - /** - * construct a new EmbData object - * \param m the mode (EMBED or EXTRACT) - * \param pp the passphrase - * \param fn the filename (only need for mode EMBED) - **/ - EmbData (MODE m, std::string pp, std::string fn = "") ; - - BitString getBitString (void) ; - - bool finished (void) ; - - /** - * get the minimum length of the BitString that is to be passed to addBits - **/ - unsigned long getNumBitsRequested (void) ; - - void addBits (BitString addbits) ; - - void setEncAlgo (EncryptionAlgorithm a) ; - EncryptionAlgorithm getEncAlgo (void) const ; - - void setEncMode (EncryptionMode m) ; - EncryptionMode getEncMode (void) const ; - - void setCompression (int c) ; - int getCompression (void) const ; - - void setChecksum (bool c) ; - bool getChecksum (void) const ; - - /** - * check if crc32 checksum is ok (needs filled Data and CRC32 fields) - * \return true iff checksum is ok - **/ - bool checksumOK (void) const ; - - void setData (const std::vector data) - { Data = data ; } ; - - std::vector getData (void) const - { return Data ; } ; - - std::string getFileName (void) const - { return FileName ; } ; - - /// the minimum size of the part of the generatred BitString that is not the data - static const unsigned int MinStegoHeaderSize = 50 ; - /// steghide magic to recognize embedded data (the string "shm") - static const UWORD32 Magic = 0x73688DUL ; - /// size (in bits of Magic) - static const unsigned int NBitsMagic = 24 ; - - protected: - std::string stripDir (std::string s) ; - - private: - /// number of bits used to code the number of plain bits - static const unsigned int NBitsNPlainBits = 32 ; - /// number of bits used to code the number of uncompressed bits - static const unsigned int NBitsNUncompressedBits = 32 ; - /// size of a crc32 checksum in bits - static const unsigned int NBitsCrc32 = 32 ; - /// version of this steghide embedding (stego compatibility of EmbData) - static const unsigned short CodeVersion = 0 ; - - MODE Mode ; - STATE State ; - - unsigned long NPlainBits ; - - /// the number of bits that the caller must at least supply to addBits - unsigned long NumBitsRequested ; - /// exactly the number of bits that the next step will consume from Reservoir and addBits together - unsigned long NumBitsNeeded ; - - BitString Reservoir ; - - std::string Passphrase ; - - /// version read from input bitstring - unsigned short Version ; - - EncryptionAlgorithm EncAlgo ; - EncryptionMode EncMode ; - /// compression level: 0(none),1(best speed),...,9(best compression) - int Compression ; - /// will a checksum be embedded ? - bool Checksum ; - /// the checksum - unsigned long CRC32 ; - std::string FileName ; - /// contains the actual message to be embedded - std::vector Data ; -} ; + public: + enum MODE { EMBED, EXTRACT }; + enum STATE { READ_MAGIC, READ_VERSION, READ_ENCINFO, READ_NPLAINBITS, READ_ENCRYPTED, END }; + + /** + * construct a new EmbData object + * \param m the mode (EMBED or EXTRACT) + * \param pp the passphrase + * \param fn the filename (only need for mode EMBED) + **/ + EmbData(MODE m, std::string pp, std::string fn = ""); + + BitString getBitString(void); + + bool finished(void); + + /** + * get the minimum length of the BitString that is to be passed to addBits + **/ + unsigned long getNumBitsRequested(void); + + void addBits(BitString addbits); + + void setEncAlgo(EncryptionAlgorithm a); + EncryptionAlgorithm getEncAlgo(void) const; + + void setEncMode(EncryptionMode m); + EncryptionMode getEncMode(void) const; + + void setCompression(int c); + int getCompression(void) const; + + void setChecksum(bool c); + bool getChecksum(void) const; + + /** + * check if crc32 checksum is ok (needs filled Data and CRC32 fields) + * \return true iff checksum is ok + **/ + bool checksumOK(void) const; + + void setData(const std::vector data) { Data = data; }; + + std::vector getData(void) const { return Data; }; + + std::string getFileName(void) const { return FileName; }; + + /// the minimum size of the part of the generatred BitString that is not the data + static const unsigned int MinStegoHeaderSize = 50; + /// steghide magic to recognize embedded data (the string "shm") + static const UWORD32 Magic = 0x73688DUL; + /// size (in bits of Magic) + static const unsigned int NBitsMagic = 24; + + protected: + std::string stripDir(std::string s); + + private: + /// number of bits used to code the number of plain bits + static const unsigned int NBitsNPlainBits = 32; + /// number of bits used to code the number of uncompressed bits + static const unsigned int NBitsNUncompressedBits = 32; + /// size of a crc32 checksum in bits + static const unsigned int NBitsCrc32 = 32; + /// version of this steghide embedding (stego compatibility of EmbData) + static const unsigned short CodeVersion = 0; + + MODE Mode; + STATE State; + + unsigned long NPlainBits; + + /// the number of bits that the caller must at least supply to addBits + unsigned long NumBitsRequested; + /// exactly the number of bits that the next step will consume from Reservoir and addBits + /// together + unsigned long NumBitsNeeded; + + BitString Reservoir; + + std::string Passphrase; + + /// version read from input bitstring + unsigned short Version; + + EncryptionAlgorithm EncAlgo; + EncryptionMode EncMode; + /// compression level: 0(none),1(best speed),...,9(best compression) + int Compression; + /// will a checksum be embedded ? + bool Checksum; + /// the checksum + unsigned long CRC32; + std::string FileName; + /// contains the actual message to be embedded + std::vector Data; +}; #endif // ndef SH_EMBDATA_H diff --git a/src/Embedder.cc b/src/Embedder.cc index 25f748e..94f9d86 100644 --- a/src/Embedder.cc +++ b/src/Embedder.cc @@ -21,13 +21,13 @@ #include #include -#include "DFSAPHeuristic.h" #include "BitString.h" #include "CvrStgFile.h" +#include "DFSAPHeuristic.h" #include "DMDConstructionHeuristic.h" +#include "Edge.h" #include "EmbData.h" #include "Embedder.h" -#include "Edge.h" #include "Graph.h" #include "Matching.h" #include "ProgressOutput.h" @@ -38,247 +38,246 @@ #include "error.h" #include "msg.h" -Globals Globs ; - -Embedder::Embedder () -{ - // read embfile - VerboseMessage vrs ; - if (Args.EmbFn.getValue() == "") { - vrs.setMessage (_("reading secret data from standard input...")) ; - } - else { - vrs.setMessage (_("reading secret file \"%s\"..."), Args.EmbFn.getValue().c_str()) ; - vrs.setNewline (false) ; - } - vrs.printMessage() ; - - std::vector emb ; - BinaryIO embio (Args.EmbFn.getValue(), BinaryIO::READ) ; - while (!embio.eof()) { - emb.push_back (embio.read8()) ; - } - embio.close() ; - - VerboseMessage vdone (_(" done")) ; - if (Args.EmbFn.getValue() != "") { - vdone.printMessage() ; - } - - // create bitstring to be embedded - std::string fn = "" ; - if (Args.EmbedEmbFn.getValue()) { - fn = Args.EmbFn.getValue() ; - } - EmbData embdata (EmbData::EMBED, Args.Passphrase.getValue(), fn) ; - embdata.setEncAlgo (Args.EncAlgo.getValue()) ; - embdata.setEncMode (Args.EncMode.getValue()) ; - embdata.setCompression (Args.Compression.getValue()) ; - embdata.setChecksum (Args.Checksum.getValue()) ; - embdata.setData (emb) ; - ToEmbed = embdata.getBitString() ; - - // read cover-/stego-file - VerboseMessage vrc ; - if (Args.CvrFn.getValue() == "") { - vrc.setMessage (_("reading cover file from standard input...")) ; - } - else { - vrc.setMessage (_("reading cover file \"%s\"..."), Args.CvrFn.getValue().c_str()) ; - } - vrc.setNewline (false) ; - vrc.printMessage() ; - - CvrStgFile::readFile (Args.CvrFn.getValue()) ; - - vdone.printMessage() ; - - ToEmbed.setArity (Globs.TheCvrStgFile->getEmbValueModulus()) ; - if ((ToEmbed.getNAryLength() * Globs.TheCvrStgFile->getSamplesPerVertex()) > Globs.TheCvrStgFile->getNumSamples()) { - throw SteghideError (_("the cover file is too short to embed the data.")) ; - } - - // create graph - Selector sel (Globs.TheCvrStgFile->getNumSamples(), Args.Passphrase.getValue()) ; - - VerboseMessage v (_("creating the graph...")) ; - v.setNewline (false) ; - v.printMessage() ; - new Graph (Globs.TheCvrStgFile, ToEmbed, sel) ; - Globs.TheGraph->printVerboseInfo() ; - if (Args.Check.getValue()) { - if (!Globs.TheGraph->check()) { - CriticalWarning w ("integrity checking of graph data structures failed!") ; // TODO: internationalize this - w.printMessage() ; - } - } +Globals Globs; + +Embedder::Embedder() { + // read embfile + VerboseMessage vrs; + if (Args.EmbFn.getValue() == "") { + vrs.setMessage(_("reading secret data from standard input...")); + } else { + vrs.setMessage(_("reading secret file \"%s\"..."), Args.EmbFn.getValue().c_str()); + vrs.setNewline(false); + } + vrs.printMessage(); + + std::vector emb; + BinaryIO embio(Args.EmbFn.getValue(), BinaryIO::READ); + while (!embio.eof()) { + emb.push_back(embio.read8()); + } + embio.close(); + + VerboseMessage vdone(_(" done")); + if (Args.EmbFn.getValue() != "") { + vdone.printMessage(); + } + + // create bitstring to be embedded + std::string fn = ""; + if (Args.EmbedEmbFn.getValue()) { + fn = Args.EmbFn.getValue(); + } + EmbData embdata(EmbData::EMBED, Args.Passphrase.getValue(), fn); + embdata.setEncAlgo(Args.EncAlgo.getValue()); + embdata.setEncMode(Args.EncMode.getValue()); + embdata.setCompression(Args.Compression.getValue()); + embdata.setChecksum(Args.Checksum.getValue()); + embdata.setData(emb); + ToEmbed = embdata.getBitString(); + + // read cover-/stego-file + VerboseMessage vrc; + if (Args.CvrFn.getValue() == "") { + vrc.setMessage(_("reading cover file from standard input...")); + } else { + vrc.setMessage(_("reading cover file \"%s\"..."), Args.CvrFn.getValue().c_str()); + } + vrc.setNewline(false); + vrc.printMessage(); + + CvrStgFile::readFile(Args.CvrFn.getValue()); + + vdone.printMessage(); + + ToEmbed.setArity(Globs.TheCvrStgFile->getEmbValueModulus()); + if ((ToEmbed.getNAryLength() * Globs.TheCvrStgFile->getSamplesPerVertex()) > + Globs.TheCvrStgFile->getNumSamples()) { + throw SteghideError(_("the cover file is too short to embed the data.")); + } + + // create graph + Selector sel(Globs.TheCvrStgFile->getNumSamples(), Args.Passphrase.getValue()); + + VerboseMessage v(_("creating the graph...")); + v.setNewline(false); + v.printMessage(); + new Graph(Globs.TheCvrStgFile, ToEmbed, sel); + Globs.TheGraph->printVerboseInfo(); + if (Args.Check.getValue()) { + if (!Globs.TheGraph->check()) { + CriticalWarning w( + "integrity checking of graph data structures failed!"); // TODO: + // internationalize + // this + w.printMessage(); + } + } #ifdef DEBUG - if (Args.DebugCommand.getValue() == PRINTGRAPH) { - Globs.TheGraph->print() ; - exit (EXIT_SUCCESS) ; - } - else if (Args.DebugCommand.getValue() == PRINTGMLGRAPH) { - Globs.TheGraph->print_gml (std::cout) ; - exit (EXIT_SUCCESS) ; - } - else if (Args.DebugCommand.getValue() == PRINTGMLVERTEX) { - std::vector nodeprinted (Globs.TheGraph->getNumVertices()) ; - std::vector edgesprinted (Globs.TheGraph->getNumVertices()) ; - Globs.TheGraph->printPrologue_gml(std::cout) ; - Globs.TheGraph->printVertex_gml (std::cout, Globs.TheGraph->getVertex(Args.GmlStartVertex.getValue()), Args.GmlGraphRecDepth.getValue(), nodeprinted, edgesprinted) ; - Globs.TheGraph->printEpilogue_gml(std::cout) ; - exit (EXIT_SUCCESS) ; - } + if (Args.DebugCommand.getValue() == PRINTGRAPH) { + Globs.TheGraph->print(); + exit(EXIT_SUCCESS); + } else if (Args.DebugCommand.getValue() == PRINTGMLGRAPH) { + Globs.TheGraph->print_gml(std::cout); + exit(EXIT_SUCCESS); + } else if (Args.DebugCommand.getValue() == PRINTGMLVERTEX) { + std::vector nodeprinted(Globs.TheGraph->getNumVertices()); + std::vector edgesprinted(Globs.TheGraph->getNumVertices()); + Globs.TheGraph->printPrologue_gml(std::cout); + Globs.TheGraph->printVertex_gml( + std::cout, Globs.TheGraph->getVertex(Args.GmlStartVertex.getValue()), + Args.GmlGraphRecDepth.getValue(), nodeprinted, edgesprinted); + Globs.TheGraph->printEpilogue_gml(std::cout); + exit(EXIT_SUCCESS); + } #endif } -Embedder::~Embedder () -{ - delete Globs.TheGraph ; - delete Globs.TheCvrStgFile ; +Embedder::~Embedder() { + delete Globs.TheGraph; + delete Globs.TheCvrStgFile; } - -void Embedder::embed () -{ - ProgressOutput* prout = NULL ; - if (Args.Verbosity.getValue() == NORMAL) { - std::string embstring, cvrstring ; - if (Args.EmbFn.getValue() == "") { - embstring = _("standard input") ; - } - else { - embstring = "\"" + Args.EmbFn.getValue() + "\"" ; - } - if (Args.CvrFn.getValue() == "") { - cvrstring = _("standard input") ; - } - else { - cvrstring = "\"" + Args.CvrFn.getValue() + "\"" ; - } - char buf[200] ; - sprintf (buf, _("embedding %s in %s..."), embstring.c_str(), cvrstring.c_str()) ; - - prout = new ProgressOutput (std::string(buf)) ; - } - else if (Args.Verbosity.getValue() == VERBOSE) { - prout = new ProgressOutput () ; - } - - const Matching* M = calculateMatching (prout) ; - - // embed matched edges - const std::list medges = M->getEdges() ; - for (std::list::const_iterator it = medges.begin() ; it != medges.end() ; it++) { - embedEdge (*it) ; - } - - // embed exposed vertices - const std::list *expvertices = M->getExposedVerticesLink() ; - for (std::list::const_iterator it = expvertices->begin() ; it != expvertices->end() ; it++) { - embedExposedVertex (*it) ; - } - - delete M ; - - // write stego file - Globs.TheCvrStgFile->transform (Args.StgFn.getValue()) ; - - bool displaydone = false ; - if (Globs.TheCvrStgFile->is_std()) { - Message ws (_("writing stego file to standard output... ")) ; - ws.printMessage() ; - } - else { - if (Args.StgFn.getValue() != Args.CvrFn.getValue()) { - Message ws (_("writing stego file \"%s\"... "), Globs.TheCvrStgFile->getName().c_str()) ; - ws.setNewline (false) ; - ws.printMessage() ; - displaydone = true ; - } - } - - Globs.TheCvrStgFile->write() ; - - if (displaydone) { - Message wsd (_("done")) ; - wsd.printMessage() ; - } + +void Embedder::embed() { + ProgressOutput *prout = NULL; + if (Args.Verbosity.getValue() == NORMAL) { + std::string embstring, cvrstring; + if (Args.EmbFn.getValue() == "") { + embstring = _("standard input"); + } else { + embstring = "\"" + Args.EmbFn.getValue() + "\""; + } + if (Args.CvrFn.getValue() == "") { + cvrstring = _("standard input"); + } else { + cvrstring = "\"" + Args.CvrFn.getValue() + "\""; + } + char buf[200]; + sprintf(buf, _("embedding %s in %s..."), embstring.c_str(), cvrstring.c_str()); + + prout = new ProgressOutput(std::string(buf)); + } else if (Args.Verbosity.getValue() == VERBOSE) { + prout = new ProgressOutput(); + } + + const Matching *M = calculateMatching(prout); + + // embed matched edges + const std::list medges = M->getEdges(); + for (std::list::const_iterator it = medges.begin(); it != medges.end(); it++) { + embedEdge(*it); + } + + // embed exposed vertices + const std::list *expvertices = M->getExposedVerticesLink(); + for (std::list::const_iterator it = expvertices->begin(); it != expvertices->end(); + it++) { + embedExposedVertex(*it); + } + + delete M; + + // write stego file + Globs.TheCvrStgFile->transform(Args.StgFn.getValue()); + + bool displaydone = false; + if (Globs.TheCvrStgFile->is_std()) { + Message ws(_("writing stego file to standard output... ")); + ws.printMessage(); + } else { + if (Args.StgFn.getValue() != Args.CvrFn.getValue()) { + Message ws(_("writing stego file \"%s\"... "), Globs.TheCvrStgFile->getName().c_str()); + ws.setNewline(false); + ws.printMessage(); + displaydone = true; + } + } + + Globs.TheCvrStgFile->write(); + + if (displaydone) { + Message wsd(_("done")); + wsd.printMessage(); + } } -const Matching* Embedder::calculateMatching (ProgressOutput* prout) -{ - Matching* matching = new Matching (Globs.TheGraph, prout) ; +const Matching *Embedder::calculateMatching(ProgressOutput *prout) { + Matching *matching = new Matching(Globs.TheGraph, prout); - std::vector MatchingAlgos = Globs.TheCvrStgFile->getMatchingAlgorithms (Globs.TheGraph, matching) ; + std::vector MatchingAlgos = + Globs.TheCvrStgFile->getMatchingAlgorithms(Globs.TheGraph, matching); - for (std::vector::const_iterator ait = MatchingAlgos.begin() ; ait != MatchingAlgos.end() ; ait++) { - if (Args.Verbosity.getValue() == VERBOSE) { - prout->setMessage (_("executing %s..."), (*ait)->getName()) ; - } + for (std::vector::const_iterator ait = MatchingAlgos.begin(); + ait != MatchingAlgos.end(); ait++) { + if (Args.Verbosity.getValue() == VERBOSE) { + prout->setMessage(_("executing %s..."), (*ait)->getName()); + } - (*ait)->setGoal (Args.Goal.getValue()) ; - (*ait)->run() ; - delete *ait ; + (*ait)->setGoal(Args.Goal.getValue()); + (*ait)->run(); + delete *ait; - if (Args.Verbosity.getValue() == VERBOSE) { - prout->done (matching->getMatchedRate(), matching->getAvgEdgeWeight()) ; - } - } + if (Args.Verbosity.getValue() == VERBOSE) { + prout->done(matching->getMatchedRate(), matching->getAvgEdgeWeight()); + } + } - if (Args.Check.getValue()) { - if (!matching->check()) { - CriticalWarning w ("integrity checking of matching data structures failed!") ; // TODO: internationalize this - w.printMessage() ; - } - } + if (Args.Check.getValue()) { + if (!matching->check()) { + CriticalWarning w( + "integrity checking of matching data structures failed!"); // TODO: + // internationalize + // this + w.printMessage(); + } + } - matching->printVerboseInfo() ; // only print info for best matching + matching->printVerboseInfo(); // only print info for best matching - if (Args.Verbosity.getValue() == NORMAL) { - prout->done() ; - } + if (Args.Verbosity.getValue() == NORMAL) { + prout->done(); + } - if (prout) { - delete prout ; - } + if (prout) { + delete prout; + } - return matching ; + return matching; } - -void Embedder::embedEdge (Edge *e) -{ - Vertex* v1 = e->getVertex1() ; - Vertex* v2 = e->getVertex2() ; - - Globs.TheCvrStgFile->replaceSample (e->getSamplePos(v1), e->getReplacingSampleValue (v1)) ; - Globs.TheCvrStgFile->replaceSample (e->getSamplePos(v2), e->getReplacingSampleValue (v2)) ; + +void Embedder::embedEdge(Edge *e) { + Vertex *v1 = e->getVertex1(); + Vertex *v2 = e->getVertex2(); + + Globs.TheCvrStgFile->replaceSample(e->getSamplePos(v1), e->getReplacingSampleValue(v1)); + Globs.TheCvrStgFile->replaceSample(e->getSamplePos(v2), e->getReplacingSampleValue(v2)); } -void Embedder::embedExposedVertex (Vertex *v) -{ - SamplePos samplepos = 0 ; - SampleValue *newsample = NULL ; - float mindistance = FLT_MAX ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - SampleValue *curold = v->getSampleValue(i) ; - SampleValue *curnew = v->getSampleValue(i)->getNearestTargetSampleValue(v->getTargetValue(i)) ; - if (curold->calcDistance (curnew) < mindistance) { - samplepos = v->getSamplePos(i) ; - newsample = curnew ; - mindistance = curold->calcDistance (curnew) ; - } - else { - delete curnew ; - } - } +void Embedder::embedExposedVertex(Vertex *v) { + SamplePos samplepos = 0; + SampleValue *newsample = NULL; + float mindistance = FLT_MAX; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + SampleValue *curold = v->getSampleValue(i); + SampleValue *curnew = + v->getSampleValue(i)->getNearestTargetSampleValue(v->getTargetValue(i)); + if (curold->calcDistance(curnew) < mindistance) { + samplepos = v->getSamplePos(i); + newsample = curnew; + mindistance = curold->calcDistance(curnew); + } else { + delete curnew; + } + } #ifdef DEBUG - printDebug (1, "embedding vertex with label %lu by changing sample position %lu.", v->getLabel(), samplepos) ; + printDebug(1, "embedding vertex with label %lu by changing sample position %lu.", v->getLabel(), + samplepos); #endif - EmbValue oldev = Globs.TheCvrStgFile->getEmbeddedValue (samplepos) ; - Globs.TheCvrStgFile->replaceSample (samplepos, newsample) ; - myassert (oldev != Globs.TheCvrStgFile->getEmbeddedValue (samplepos)) ; - delete newsample ; + EmbValue oldev = Globs.TheCvrStgFile->getEmbeddedValue(samplepos); + Globs.TheCvrStgFile->replaceSample(samplepos, newsample); + myassert(oldev != Globs.TheCvrStgFile->getEmbeddedValue(samplepos)); + delete newsample; } diff --git a/src/Embedder.h b/src/Embedder.h index 9b8c1da..6e462b2 100644 --- a/src/Embedder.h +++ b/src/Embedder.h @@ -22,40 +22,40 @@ #define SH_EMBEDDER_H #include "BitString.h" -class Edge ; -class CvrStgFile ; -class Graph ; -class Matching ; -class ProgressOutput ; -class Vertex ; +class Edge; +class CvrStgFile; +class Graph; +class Matching; +class ProgressOutput; +class Vertex; class Embedder { - public: - Embedder (void) ; + public: + Embedder(void); - ~Embedder (void) ; + ~Embedder(void); - void embed (void) ; + void embed(void); - private: - static const unsigned int Default_NConstrHeur = 1 ; + private: + static const unsigned int Default_NConstrHeur = 1; - BitString ToEmbed ; + BitString ToEmbed; - /** - * do the matching algorithms - **/ - const Matching* calculateMatching (ProgressOutput* prout) ; + /** + * do the matching algorithms + **/ + const Matching *calculateMatching(ProgressOutput *prout); - /** - * embed the two bits represented by the two vertices adjacent to e - **/ - void embedEdge (Edge *e) ; + /** + * embed the two bits represented by the two vertices adjacent to e + **/ + void embedEdge(Edge *e); - /** - * embed the bit represented by the Vertex v - **/ - void embedExposedVertex (Vertex *v) ; -} ; + /** + * embed the bit represented by the Vertex v + **/ + void embedExposedVertex(Vertex *v); +}; #endif // ndef SH_EMBEDDER_H diff --git a/src/EncryptionAlgorithm.cc b/src/EncryptionAlgorithm.cc index 83fb8ba..def6c16 100644 --- a/src/EncryptionAlgorithm.cc +++ b/src/EncryptionAlgorithm.cc @@ -18,105 +18,80 @@ * */ -#include "common.h" #include "EncryptionAlgorithm.h" +#include "common.h" -EncryptionAlgorithm::EncryptionAlgorithm () -{ - setValue (NONE) ; -} +EncryptionAlgorithm::EncryptionAlgorithm() { setValue(NONE); } -EncryptionAlgorithm::EncryptionAlgorithm (EncryptionAlgorithm::IRep irep) -{ - setValue (irep) ; -} +EncryptionAlgorithm::EncryptionAlgorithm(EncryptionAlgorithm::IRep irep) { setValue(irep); } -EncryptionAlgorithm::EncryptionAlgorithm (std::string srep) -{ - setValue (translate (srep)) ; -} +EncryptionAlgorithm::EncryptionAlgorithm(std::string srep) { setValue(translate(srep)); } -void EncryptionAlgorithm::setValue (EncryptionAlgorithm::IRep irep) -{ - Value = irep ; -} +void EncryptionAlgorithm::setValue(EncryptionAlgorithm::IRep irep) { Value = irep; } -std::string EncryptionAlgorithm::getStringRep () const -{ - return translate(Value) ; -} +std::string EncryptionAlgorithm::getStringRep() const { return translate(Value); } -EncryptionAlgorithm::IRep EncryptionAlgorithm::getIntegerRep () const -{ - return Value ; -} +EncryptionAlgorithm::IRep EncryptionAlgorithm::getIntegerRep() const { return Value; } -bool EncryptionAlgorithm::isValidStringRep (std::string srep) -{ - bool retval = false ; - for (unsigned int i = 0 ; i < NumValues ; i++) { - if (Translations[i].srep == srep) { - retval = true ; - } - } - return retval ; +bool EncryptionAlgorithm::isValidStringRep(std::string srep) { + bool retval = false; + for (unsigned int i = 0; i < NumValues; i++) { + if (Translations[i].srep == srep) { + retval = true; + } + } + return retval; } -bool EncryptionAlgorithm::isValidIntegerRep (unsigned int irep) -{ - return (irep < NumValues) ; -} +bool EncryptionAlgorithm::isValidIntegerRep(unsigned int irep) { return (irep < NumValues); } -std::string EncryptionAlgorithm::translate (EncryptionAlgorithm::IRep irep) -{ - std::string retval ; - bool found = false ; - for (unsigned int i = 0 ; i < NumValues ; i++) { - if (Translations[i].irep == irep) { - retval = std::string (Translations[i].srep) ; - found = true ; - } - } - myassert (found) ; - return retval ; +std::string EncryptionAlgorithm::translate(EncryptionAlgorithm::IRep irep) { + std::string retval; + bool found = false; + for (unsigned int i = 0; i < NumValues; i++) { + if (Translations[i].irep == irep) { + retval = std::string(Translations[i].srep); + found = true; + } + } + myassert(found); + return retval; } -EncryptionAlgorithm::IRep EncryptionAlgorithm::translate (std::string srep) -{ - IRep retval = NONE ; - bool found = false ; - for (unsigned int i = 0 ; i < NumValues ; i++) { - if (Translations[i].srep == srep) { - retval = Translations[i].irep ; - found = true ; - } - } - myassert (found) ; - return retval ; +EncryptionAlgorithm::IRep EncryptionAlgorithm::translate(std::string srep) { + IRep retval = NONE; + bool found = false; + for (unsigned int i = 0; i < NumValues; i++) { + if (Translations[i].srep == srep) { + retval = Translations[i].irep; + found = true; + } + } + myassert(found); + return retval; } const EncryptionAlgorithm::Translation EncryptionAlgorithm::Translations[] = { - { NONE, "none" }, - { TWOFISH, "twofish" }, - { RIJNDAEL128, "rijndael-128" }, - { RIJNDAEL192, "rijndael-192" }, - { RIJNDAEL256, "rijndael-256" }, - { SAFERPLUS, "saferplus" }, - { RC2, "rc2" }, - { XTEA, "xtea" }, - { SERPENT, "serpent" }, - { SAFERSK64, "safer-sk64" }, - { SAFERSK128, "safer-sk128" }, - { CAST256, "cast-256" }, - { LOKI97, "loki97" }, - { GOST, "gost" }, - { THREEWAY, "threeway" }, - { CAST128, "cast-128" }, - { BLOWFISH, "blowfish" }, - { DES, "des" }, - { TRIPLEDES, "tripledes" }, - { ENIGMA, "enigma" }, - { ARCFOUR, "arcfour" }, - { PANAMA, "panama" }, - { WAKE, "wake" } -} ; + {NONE, "none"}, + {TWOFISH, "twofish"}, + {RIJNDAEL128, "rijndael-128"}, + {RIJNDAEL192, "rijndael-192"}, + {RIJNDAEL256, "rijndael-256"}, + {SAFERPLUS, "saferplus"}, + {RC2, "rc2"}, + {XTEA, "xtea"}, + {SERPENT, "serpent"}, + {SAFERSK64, "safer-sk64"}, + {SAFERSK128, "safer-sk128"}, + {CAST256, "cast-256"}, + {LOKI97, "loki97"}, + {GOST, "gost"}, + {THREEWAY, "threeway"}, + {CAST128, "cast-128"}, + {BLOWFISH, "blowfish"}, + {DES, "des"}, + {TRIPLEDES, "tripledes"}, + {ENIGMA, "enigma"}, + {ARCFOUR, "arcfour"}, + {PANAMA, "panama"}, + {WAKE, "wake"}}; diff --git a/src/EncryptionAlgorithm.h b/src/EncryptionAlgorithm.h index acebef8..f0cbd81 100644 --- a/src/EncryptionAlgorithm.h +++ b/src/EncryptionAlgorithm.h @@ -24,81 +24,80 @@ #include class EncryptionAlgorithm { - public: - /// number of bits needed to code the algorithm - static const unsigned int IRep_size = 5 ; + public: + /// number of bits needed to code the algorithm + static const unsigned int IRep_size = 5; - /// integer representation of encryption algorithm - enum IRep { - NONE = 0, - TWOFISH = 1, - RIJNDAEL128 = 2, - RIJNDAEL192 = 3, - RIJNDAEL256 = 4, - SAFERPLUS = 5, - RC2 = 6, - XTEA = 7, - SERPENT = 8, - SAFERSK64 = 9, - SAFERSK128 = 10, - CAST256 = 11, - LOKI97 = 12, - GOST = 13, - THREEWAY = 14, - CAST128 = 15, - BLOWFISH = 16, - DES = 17, - TRIPLEDES = 18, - ENIGMA = 19, - ARCFOUR = 20, - PANAMA = 21, - WAKE = 22 - } ; + /// integer representation of encryption algorithm + enum IRep { + NONE = 0, + TWOFISH = 1, + RIJNDAEL128 = 2, + RIJNDAEL192 = 3, + RIJNDAEL256 = 4, + SAFERPLUS = 5, + RC2 = 6, + XTEA = 7, + SERPENT = 8, + SAFERSK64 = 9, + SAFERSK128 = 10, + CAST256 = 11, + LOKI97 = 12, + GOST = 13, + THREEWAY = 14, + CAST128 = 15, + BLOWFISH = 16, + DES = 17, + TRIPLEDES = 18, + ENIGMA = 19, + ARCFOUR = 20, + PANAMA = 21, + WAKE = 22 + }; - EncryptionAlgorithm (void) ; - EncryptionAlgorithm (IRep irep) ; - /** - * construct a new EncryptionAlgorithm object from a std::string representation - * \param srep a valid(!) std::string representation - **/ - EncryptionAlgorithm (std::string srep) ; + EncryptionAlgorithm(void); + EncryptionAlgorithm(IRep irep); + /** + * construct a new EncryptionAlgorithm object from a std::string representation + * \param srep a valid(!) std::string representation + **/ + EncryptionAlgorithm(std::string srep); - void setValue (IRep irep) ; + void setValue(IRep irep); - std::string getStringRep (void) const ; - IRep getIntegerRep (void) const ; + std::string getStringRep(void) const; + IRep getIntegerRep(void) const; - bool operator== (const EncryptionAlgorithm& algo) const - { return (Value == algo.Value) ; } ; + bool operator==(const EncryptionAlgorithm &algo) const { return (Value == algo.Value); }; - /** - * check if srep is a valid std::string representation (w.r.t the Translations array) - * \param srep a std::string that maybe represents an encryption algorithm fron the Translations table - * \return true iff the Translations table contains srep - **/ - static bool isValidStringRep (std::string srep) ; + /** + * check if srep is a valid std::string representation (w.r.t the Translations array) + * \param srep a std::string that maybe represents an encryption algorithm fron the Translations + *table \return true iff the Translations table contains srep + **/ + static bool isValidStringRep(std::string srep); - static bool isValidIntegerRep (unsigned int irep) ; + static bool isValidIntegerRep(unsigned int irep); - /** - * translate an integer representation into the corresponding std::string representation - **/ - static std::string translate (IRep irep) ; + /** + * translate an integer representation into the corresponding std::string representation + **/ + static std::string translate(IRep irep); - /** - * translate a valid std::string representation into the corresponding integer representation - **/ - static IRep translate (std::string srep) ; + /** + * translate a valid std::string representation into the corresponding integer representation + **/ + static IRep translate(std::string srep); - private: - static const unsigned int NumValues = 23 ; - IRep Value ; + private: + static const unsigned int NumValues = 23; + IRep Value; - typedef struct struct_Translation { - IRep irep ; - const char* srep ; - } Translation ; - static const Translation Translations[] ; -} ; + typedef struct struct_Translation { + IRep irep; + const char *srep; + } Translation; + static const Translation Translations[]; +}; #endif // ndef SH_ENCALGO_H diff --git a/src/EncryptionMode.cc b/src/EncryptionMode.cc index 9eb5309..211eab8 100644 --- a/src/EncryptionMode.cc +++ b/src/EncryptionMode.cc @@ -18,90 +18,59 @@ * */ -#include "common.h" #include "EncryptionMode.h" +#include "common.h" -EncryptionMode::EncryptionMode () -{ - setValue (ECB) ; -} +EncryptionMode::EncryptionMode() { setValue(ECB); } -EncryptionMode::EncryptionMode (EncryptionMode::IRep irep) -{ - setValue (irep) ; -} +EncryptionMode::EncryptionMode(EncryptionMode::IRep irep) { setValue(irep); } -EncryptionMode::EncryptionMode (std::string srep) -{ - setValue (translate (srep)) ; -} +EncryptionMode::EncryptionMode(std::string srep) { setValue(translate(srep)); } -void EncryptionMode::setValue (EncryptionMode::IRep irep) -{ - Value = irep ; -} +void EncryptionMode::setValue(EncryptionMode::IRep irep) { Value = irep; } -std::string EncryptionMode::getStringRep () const -{ - return translate(Value) ; -} +std::string EncryptionMode::getStringRep() const { return translate(Value); } -EncryptionMode::IRep EncryptionMode::getIntegerRep () const -{ - return Value ; -} +EncryptionMode::IRep EncryptionMode::getIntegerRep() const { return Value; } -bool EncryptionMode::isValidStringRep (std::string srep) -{ - bool retval = false ; - for (unsigned int i = 0 ; i < NumValues ; i++) { - if (Translations[i].srep == srep) { - retval = true ; - } - } - return retval ; +bool EncryptionMode::isValidStringRep(std::string srep) { + bool retval = false; + for (unsigned int i = 0; i < NumValues; i++) { + if (Translations[i].srep == srep) { + retval = true; + } + } + return retval; } -bool EncryptionMode::isValidIntegerRep (unsigned int irep) -{ - return (irep < NumValues) ; -} +bool EncryptionMode::isValidIntegerRep(unsigned int irep) { return (irep < NumValues); } -std::string EncryptionMode::translate (EncryptionMode::IRep irep) -{ - std::string retval ; - bool found = false ; - for (unsigned int i = 0 ; i < NumValues ; i++) { - if (Translations[i].irep == irep) { - retval = std::string (Translations[i].srep) ; - found = true ; - } - } - myassert (found) ; - return retval ; +std::string EncryptionMode::translate(EncryptionMode::IRep irep) { + std::string retval; + bool found = false; + for (unsigned int i = 0; i < NumValues; i++) { + if (Translations[i].irep == irep) { + retval = std::string(Translations[i].srep); + found = true; + } + } + myassert(found); + return retval; } -EncryptionMode::IRep EncryptionMode::translate (std::string srep) -{ - IRep retval = ECB ; - bool found = false ; - for (unsigned int i = 0 ; i < NumValues ; i++) { - if (Translations[i].srep == srep) { - retval = Translations[i].irep ; - found = true ; - } - } - myassert (found) ; - return retval ; +EncryptionMode::IRep EncryptionMode::translate(std::string srep) { + IRep retval = ECB; + bool found = false; + for (unsigned int i = 0; i < NumValues; i++) { + if (Translations[i].srep == srep) { + retval = Translations[i].irep; + found = true; + } + } + myassert(found); + return retval; } const EncryptionMode::Translation EncryptionMode::Translations[] = { - { ECB, "ecb" }, - { CBC, "cbc" }, - { OFB, "ofb" }, - { CFB, "cfb" }, - { NOFB, "nofb" }, - { NCFB, "ncfb" }, - { CTR, "ctr" }, - { STREAM, "stream" } -} ; + {ECB, "ecb"}, {CBC, "cbc"}, {OFB, "ofb"}, {CFB, "cfb"}, + {NOFB, "nofb"}, {NCFB, "ncfb"}, {CTR, "ctr"}, {STREAM, "stream"}}; diff --git a/src/EncryptionMode.h b/src/EncryptionMode.h index f9de77a..21d9fc7 100644 --- a/src/EncryptionMode.h +++ b/src/EncryptionMode.h @@ -24,56 +24,46 @@ #include class EncryptionMode { - public: - /// number of bits needed to code the mode - static const unsigned int IRep_size = 3 ; + public: + /// number of bits needed to code the mode + static const unsigned int IRep_size = 3; - /// integer representation of encryption mode - enum IRep { - ECB = 0, - CBC = 1, - OFB = 2, - CFB = 3, - NOFB = 4, - NCFB = 5, - CTR = 6, - STREAM = 7 - } ; + /// integer representation of encryption mode + enum IRep { ECB = 0, CBC = 1, OFB = 2, CFB = 3, NOFB = 4, NCFB = 5, CTR = 6, STREAM = 7 }; - /** - * construct a new EncryptionMode object setting Value to ECB - **/ - EncryptionMode (void) ; - EncryptionMode (IRep irep) ; - /** - * construct a new EncryptionMode object from a std::string representation - * \param srep a valid(!) std::string representation - **/ - EncryptionMode (std::string srep) ; + /** + * construct a new EncryptionMode object setting Value to ECB + **/ + EncryptionMode(void); + EncryptionMode(IRep irep); + /** + * construct a new EncryptionMode object from a std::string representation + * \param srep a valid(!) std::string representation + **/ + EncryptionMode(std::string srep); - void setValue (IRep irep) ; + void setValue(IRep irep); - std::string getStringRep (void) const ; - IRep getIntegerRep (void) const ; + std::string getStringRep(void) const; + IRep getIntegerRep(void) const; - bool operator== (const EncryptionMode& mode) const - { return (Value == mode.Value) ; } ; + bool operator==(const EncryptionMode &mode) const { return (Value == mode.Value); }; - static bool isValidStringRep (std::string srep) ; - static bool isValidIntegerRep (unsigned int irep) ; + static bool isValidStringRep(std::string srep); + static bool isValidIntegerRep(unsigned int irep); - static std::string translate (IRep irep) ; - static IRep translate (std::string srep) ; + static std::string translate(IRep irep); + static IRep translate(std::string srep); - private: - static const unsigned int NumValues = 8 ; - IRep Value ; + private: + static const unsigned int NumValues = 8; + IRep Value; - typedef struct struct_Translation { - IRep irep ; - const char* srep ; - } Translation ; - static const Translation Translations[] ; -} ; + typedef struct struct_Translation { + IRep irep; + const char *srep; + } Translation; + static const Translation Translations[]; +}; #endif // ndef SH_ENCMODE_H diff --git a/src/Extractor.cc b/src/Extractor.cc index a0d3fa4..9781429 100644 --- a/src/Extractor.cc +++ b/src/Extractor.cc @@ -29,83 +29,88 @@ #include "common.h" #include "error.h" -EmbData* Extractor::extract () -{ - VerboseMessage vrs ; - if (Args.StgFn.getValue() == "") { - vrs.setMessage (_("reading stego file from standard input...")) ; - } - else { - vrs.setMessage (_("reading stego file \"%s\"..."), Args.StgFn.getValue().c_str()) ; - } - vrs.setNewline (false) ; - vrs.printMessage() ; +EmbData *Extractor::extract() { + VerboseMessage vrs; + if (Args.StgFn.getValue() == "") { + vrs.setMessage(_("reading stego file from standard input...")); + } else { + vrs.setMessage(_("reading stego file \"%s\"..."), Args.StgFn.getValue().c_str()); + } + vrs.setNewline(false); + vrs.printMessage(); - Globs.TheCvrStgFile = CvrStgFile::readFile (StegoFileName) ; + Globs.TheCvrStgFile = CvrStgFile::readFile(StegoFileName); - VerboseMessage vd (_(" done")) ; - vd.printMessage() ; + VerboseMessage vd(_(" done")); + vd.printMessage(); - Selector* sel ; - EmbData* embdata ; + Selector *sel; + EmbData *embdata; - // Determine wether we are cracking with or without a passphrase - if (passphraseSet) { - embdata = new EmbData (EmbData::EXTRACT, Passphrase) ; - sel = new Selector (Globs.TheCvrStgFile->getNumSamples(), Passphrase) ; - } else { - // The password is only used for encrypted data. - // We can still extract plain text using only a seed value - embdata = new EmbData (EmbData::EXTRACT, "") ; - sel = new Selector (Globs.TheCvrStgFile->getNumSamples(), seed) ; - } + // Determine wether we are cracking with or without a passphrase + if (passphraseSet) { + embdata = new EmbData(EmbData::EXTRACT, Passphrase); + sel = new Selector(Globs.TheCvrStgFile->getNumSamples(), Passphrase); + } else { + // The password is only used for encrypted data. + // We can still extract plain text using only a seed value + embdata = new EmbData(EmbData::EXTRACT, ""); + sel = new Selector(Globs.TheCvrStgFile->getNumSamples(), seed); + } - VerboseMessage ve (_("extracting data...")) ; - ve.setNewline (false) ; - ve.printMessage() ; + VerboseMessage ve(_("extracting data...")); + ve.setNewline(false); + ve.printMessage(); - unsigned long sv_idx = 0 ; - while (!embdata->finished()) { - unsigned short bitsperembvalue = AUtils::log2_ceil (Globs.TheCvrStgFile->getEmbValueModulus()) ; - unsigned long embvaluesrequested = AUtils::div_roundup (embdata->getNumBitsRequested(), bitsperembvalue) ; - if (sv_idx + (Globs.TheCvrStgFile->getSamplesPerVertex() * embvaluesrequested) >= Globs.TheCvrStgFile->getNumSamples()) { - if (Globs.TheCvrStgFile->is_std()) { - throw CorruptDataError (_("the stego data from standard input is too short to contain the embedded data.")) ; - } - else { - throw CorruptDataError (_("the stego file \"%s\" is too short to contain the embedded data."), Globs.TheCvrStgFile->getName().c_str()) ; - } - } - BitString bits (Globs.TheCvrStgFile->getEmbValueModulus()) ; - for (unsigned long i = 0 ; i < embvaluesrequested ; i++) { - EmbValue ev = 0 ; - for (unsigned int j = 0 ; j < Globs.TheCvrStgFile->getSamplesPerVertex() ; j++, sv_idx++) { - ev = (ev + Globs.TheCvrStgFile->getEmbeddedValue ((*sel)[sv_idx])) % Globs.TheCvrStgFile->getEmbValueModulus() ; - } - bits.appendNAry(ev) ; - } - embdata->addBits (bits) ; - } + unsigned long sv_idx = 0; + while (!embdata->finished()) { + unsigned short bitsperembvalue = + AUtils::log2_ceil(Globs.TheCvrStgFile->getEmbValueModulus()); + unsigned long embvaluesrequested = + AUtils::div_roundup(embdata->getNumBitsRequested(), bitsperembvalue); + if (sv_idx + (Globs.TheCvrStgFile->getSamplesPerVertex() * embvaluesrequested) >= + Globs.TheCvrStgFile->getNumSamples()) { + if (Globs.TheCvrStgFile->is_std()) { + throw CorruptDataError(_("the stego data from standard input is too " + "short to contain the embedded data.")); + } else { + throw CorruptDataError(_("the stego file \"%s\" is too short to " + "contain the embedded data."), + Globs.TheCvrStgFile->getName().c_str()); + } + } + BitString bits(Globs.TheCvrStgFile->getEmbValueModulus()); + for (unsigned long i = 0; i < embvaluesrequested; i++) { + EmbValue ev = 0; + for (unsigned int j = 0; j < Globs.TheCvrStgFile->getSamplesPerVertex(); + j++, sv_idx++) { + ev = (ev + Globs.TheCvrStgFile->getEmbeddedValue((*sel)[sv_idx])) % + Globs.TheCvrStgFile->getEmbValueModulus(); + } + bits.appendNAry(ev); + } + embdata->addBits(bits); + } - delete(sel) ; + delete sel; - vd.printMessage() ; + vd.printMessage(); - // TODO (postponed due to message freeze): rename into "verifying crc32 checksum..." - VerboseMessage vc (_("checking crc32 checksum...")) ; - vc.setNewline (false) ; - vc.printMessage() ; - if (embdata->checksumOK()) { - VerboseMessage vok (_(" ok")) ; - vok.printMessage() ; - } - else { - VerboseMessage vfailed (_(" FAILED!")) ; - vfailed.printMessage() ; + // TODO (postponed due to message freeze): rename into "verifying crc32 + // checksum..." + VerboseMessage vc(_("checking crc32 checksum...")); + vc.setNewline(false); + vc.printMessage(); + if (embdata->checksumOK()) { + VerboseMessage vok(_(" ok")); + vok.printMessage(); + } else { + VerboseMessage vfailed(_(" FAILED!")); + vfailed.printMessage(); - CriticalWarning w (_("crc32 checksum failed! extracted data is probably corrupted.")) ; - w.printMessage() ; - } + CriticalWarning w(_("crc32 checksum failed! extracted data is probably corrupted.")); + w.printMessage(); + } - return embdata ; + return embdata; } diff --git a/src/Extractor.h b/src/Extractor.h index 22476aa..1e09335 100644 --- a/src/Extractor.h +++ b/src/Extractor.h @@ -24,20 +24,20 @@ #include class Extractor { - public: - Extractor (std::string stgfn, std::string pp) - : StegoFileName(stgfn), Passphrase(pp), passphraseSet(true) {} ; + public: + Extractor(std::string stgfn, std::string pp) + : StegoFileName(stgfn), Passphrase(pp), passphraseSet(true){}; - Extractor (std::string stgfn, UWORD32 seed) - : StegoFileName(stgfn), seed(seed), passphraseSet(false) {} ; + Extractor(std::string stgfn, UWORD32 seed) + : StegoFileName(stgfn), seed(seed), passphraseSet(false){}; - EmbData* extract (void) ; + EmbData *extract(void); - private: - std::string StegoFileName ; - std::string Passphrase ; - bool passphraseSet ; - UWORD32 seed ; -} ; + private: + std::string StegoFileName; + std::string Passphrase; + bool passphraseSet; + UWORD32 seed; +}; #endif // ndef SH_EXTRACTOR_H diff --git a/src/Globals.h b/src/Globals.h index 7f0c728..fd29f0d 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -23,8 +23,8 @@ #include -class CvrStgFile ; -class Graph ; +class CvrStgFile; +class Graph; /** * \class Globals @@ -50,27 +50,24 @@ class Graph ; * the unit tests and non-static pointers would need too much memory. **/ class Globals { - public: - Globals (CvrStgFile* f = NULL, Graph* g = NULL) - : TheCvrStgFile(f), TheGraph(g) {} ; + public: + Globals(CvrStgFile *f = NULL, Graph *g = NULL) : TheCvrStgFile(f), TheGraph(g){}; - /// the cover-/stego- file that is operated on (set in CvrStgFile::CvrStgFile) - CvrStgFile* TheCvrStgFile ; + /// the cover-/stego- file that is operated on (set in CvrStgFile::CvrStgFile) + CvrStgFile *TheCvrStgFile; - /// the graph that is built upon the cover-/stego-file (set in Graph::Graph) - Graph* TheGraph ; + /// the graph that is built upon the cover-/stego-file (set in Graph::Graph) + Graph *TheGraph; - void operator= (const Globals& g) - { - TheCvrStgFile = g.TheCvrStgFile ; - TheGraph = g.TheGraph ; - } + void operator=(const Globals &g) { + TheCvrStgFile = g.TheCvrStgFile; + TheGraph = g.TheGraph; + } - void reset (void) - { - TheCvrStgFile = NULL ; - TheGraph = NULL ; - } -} ; + void reset(void) { + TheCvrStgFile = NULL; + TheGraph = NULL; + } +}; #endif // ndef SH_GLOBALS_H diff --git a/src/Graph.cc b/src/Graph.cc index eca61b1..722f8fc 100644 --- a/src/Graph.cc +++ b/src/Graph.cc @@ -18,15 +18,14 @@ * */ +#include #include #include #include -#include #include #include -#include +#include -#include "limits.h" #include "BitString.h" #include "CvrStgFile.h" #include "Edge.h" @@ -34,637 +33,650 @@ #include "Selector.h" #include "Vertex.h" #include "common.h" +#include "limits.h" #include "msg.h" -Graph::Graph (CvrStgFile *cvr, const BitString& emb, Selector& sel) -{ - Globs.TheGraph = this ; +Graph::Graph(CvrStgFile *cvr, const BitString &emb, Selector &sel) { + Globs.TheGraph = this; - File = cvr ; - EmbValueModulus = File->getEmbValueModulus() ; - SamplesPerVertex = File->getSamplesPerVertex() ; + File = cvr; + EmbValueModulus = File->getEmbValueModulus(); + SamplesPerVertex = File->getSamplesPerVertex(); - // construct sposs and tvalues - std::vector sposs ; - std::vector tvalues ; - unsigned long n = emb.getNAryLength() ; - for (unsigned long i = 0 ; i < n ; i++) { - SamplePos *poss = new SamplePos[File->getSamplesPerVertex()] ; + // construct sposs and tvalues + std::vector sposs; + std::vector tvalues; + unsigned long n = emb.getNAryLength(); + for (unsigned long i = 0; i < n; i++) { + SamplePos *poss = new SamplePos[File->getSamplesPerVertex()]; - EmbValue modulosum = 0 ; - for (unsigned int j = 0 ; j < File->getSamplesPerVertex() ; j++) { - poss[j] = sel[(i * File->getSamplesPerVertex()) + j] ; - modulosum = (modulosum + File->getEmbeddedValue(poss[j])) % File->getEmbValueModulus() ; - } + EmbValue modulosum = 0; + for (unsigned int j = 0; j < File->getSamplesPerVertex(); j++) { + poss[j] = sel[(i * File->getSamplesPerVertex()) + j]; + modulosum = (modulosum + File->getEmbeddedValue(poss[j])) % File->getEmbValueModulus(); + } - if (modulosum != emb.getNAry(i)) { - sposs.push_back (poss) ; - tvalues.push_back (emb.getNAry(i)) ; - } - else { - delete[] poss ; - } - } + if (modulosum != emb.getNAry(i)) { + sposs.push_back(poss); + tvalues.push_back(emb.getNAry(i)); + } else { + delete[] poss; + } + } - myassert (sposs.size() == tvalues.size()) ; + myassert(sposs.size() == tvalues.size()); - std::vector svalues ; // will contain pointers to unique sample value objects - constructSamples (sposs, svalues) ; + std::vector svalues; // will contain pointers to unique sample value objects + constructSamples(sposs, svalues); - myassert (sposs.size() == svalues.size()) ; + myassert(sposs.size() == svalues.size()); - constructVertices (sposs, svalues, tvalues) ; + constructVertices(sposs, svalues, tvalues); - constructEdges () ; + constructEdges(); } -void Graph::constructSamples (const std::vector& sposs, std::vector& svalues) -{ - const VertexLabel numvertices = sposs.size() ; - svalues.resize (numvertices) ; - - // fill a hash table with the (unique) sample values and svalues with pointers to them - std::unordered_set SampleValues_set ; - for (unsigned long i = 0 ; i < numvertices ; i++) { - svalues[i] = new SampleValue*[File->getSamplesPerVertex()] ; - for (unsigned short j = 0 ; j < File->getSamplesPerVertex() ; j++) { - SampleValue *sv = File->getSampleValue (sposs[i][j]) ; - std::unordered_set::iterator res = SampleValues_set.find (sv) ; - if (res == SampleValues_set.end()) { // sample has not been found - add it ! - SampleValues_set.insert (sv) ; - svalues[i][j] = sv ; - } - else { // sample value is already in SampleValues_set - delete sv ; - svalues[i][j] = *res ; - } - } - } - - // move the hash_set SampleValues_set into the vector SampleValues, set sample labels - SampleValues = std::vector (SampleValues_set.size()) ; - unsigned long label = 0 ; - for (std::unordered_set::const_iterator i = SampleValues_set.begin() ; i != SampleValues_set.end() ; i++) { - SampleValues[label] = *i ; - SampleValues[label]->setLabel (label) ; - label++ ; - } +void Graph::constructSamples(const std::vector &sposs, + std::vector &svalues) { + const VertexLabel numvertices = sposs.size(); + svalues.resize(numvertices); + + // fill a hash table with the (unique) sample values and svalues with pointers + // to them + std::unordered_set SampleValues_set; + for (unsigned long i = 0; i < numvertices; i++) { + svalues[i] = new SampleValue *[File->getSamplesPerVertex()]; + for (unsigned short j = 0; j < File->getSamplesPerVertex(); j++) { + SampleValue *sv = File->getSampleValue(sposs[i][j]); + std::unordered_set::iterator res = + SampleValues_set.find(sv); + if (res == SampleValues_set.end()) { // sample has not been found - add it ! + SampleValues_set.insert(sv); + svalues[i][j] = sv; + } else { // sample value is already in SampleValues_set + delete sv; + svalues[i][j] = *res; + } + } + } + + // move the hash_set SampleValues_set into the vector SampleValues, set sample + // labels + SampleValues = std::vector(SampleValues_set.size()); + unsigned long label = 0; + for (std::unordered_set::const_iterator i = + SampleValues_set.begin(); + i != SampleValues_set.end(); i++) { + SampleValues[label] = *i; + SampleValues[label]->setLabel(label); + label++; + } } -void Graph::constructVertices (std::vector& sposs, std::vector& svalues, const std::vector& tvalues) -{ - const VertexLabel numvertices = sposs.size() ; - Vertices = std::vector (numvertices) ; - for (VertexLabel i = 0 ; i < numvertices ; i++) { - Vertices[i] = new Vertex (i, sposs[i], svalues[i], tvalues[i]) ; - } +void Graph::constructVertices(std::vector &sposs, std::vector &svalues, + const std::vector &tvalues) { + const VertexLabel numvertices = sposs.size(); + Vertices = std::vector(numvertices); + for (VertexLabel i = 0; i < numvertices; i++) { + Vertices[i] = new Vertex(i, sposs[i], svalues[i], tvalues[i]); + } } -void Graph::constructEdges () -{ - // create SampleValue Adjacency Lists - SVALists = File->calcSVAdjacencyLists (SampleValues) ; - - // allocate memory for SampleOccurences - SampleOccurences = std::vector > (SampleValues.size()) ; - DeletedSampleOccurences = std::vector > (SampleValues.size()) ; - NumSampleOccurences = std::vector (SampleValues.size()) ; - NumDeletedSampleOccurences = std::vector (SampleValues.size()) ; - - for (SampleValueLabel lbl = 0 ; lbl < SampleValues.size() ; lbl++) { - NumSampleOccurences[lbl] = new UWORD32[EmbValueModulus] ; - NumDeletedSampleOccurences[lbl] = new UWORD32[EmbValueModulus] ; - for (unsigned short t = 0 ; t < EmbValueModulus ; t++) { - NumSampleOccurences[lbl][t] = 0 ; - NumDeletedSampleOccurences[lbl][t] = 0 ; - } - } - - // fill SampleOccurences - for (std::vector::iterator vit = Vertices.begin() ; vit != Vertices.end() ; vit++) { - for (unsigned short j = 0 ; j < Globs.TheCvrStgFile->getSamplesPerVertex() ; j++) { - SampleOccurence occ (*vit, j) ; - SampleValueLabel lbl = (*vit)->getSampleValue(j)->getLabel() ; - std::list::iterator occit = SampleOccurences[lbl].insert (SampleOccurences[lbl].end(), occ) ; - NumSampleOccurences[lbl][(*vit)->getTargetValue(j)]++ ; - (*vit)->setSampleOccurenceIt (j, occit) ; - } - } - - // compute NumEdges for all sample values - for (SampleValueLabel srclbl = 0 ; srclbl < SampleValues.size() ; srclbl++) { - for (EmbValue t = 0 ; t < EmbValueModulus ; t++) { - UWORD32 numedges = 0 ; - for (std::vector::const_iterator destsv = (*(SVALists[t]))[srclbl].begin() ; - destsv != (*(SVALists[t]))[srclbl].end() ; destsv++) { - numedges += NumSampleOccurences[(*destsv)->getLabel()][SampleValues[srclbl]->getEmbeddedValue()] ; - } - SampleValues[srclbl]->setNumEdges(t, numedges) ; - } - } +void Graph::constructEdges() { + // create SampleValue Adjacency Lists + SVALists = File->calcSVAdjacencyLists(SampleValues); + + // allocate memory for SampleOccurences + SampleOccurences = std::vector>(SampleValues.size()); + DeletedSampleOccurences = std::vector>(SampleValues.size()); + NumSampleOccurences = std::vector(SampleValues.size()); + NumDeletedSampleOccurences = std::vector(SampleValues.size()); + + for (SampleValueLabel lbl = 0; lbl < SampleValues.size(); lbl++) { + NumSampleOccurences[lbl] = new UWORD32[EmbValueModulus]; + NumDeletedSampleOccurences[lbl] = new UWORD32[EmbValueModulus]; + for (unsigned short t = 0; t < EmbValueModulus; t++) { + NumSampleOccurences[lbl][t] = 0; + NumDeletedSampleOccurences[lbl][t] = 0; + } + } + + // fill SampleOccurences + for (std::vector::iterator vit = Vertices.begin(); vit != Vertices.end(); vit++) { + for (unsigned short j = 0; j < Globs.TheCvrStgFile->getSamplesPerVertex(); j++) { + SampleOccurence occ(*vit, j); + SampleValueLabel lbl = (*vit)->getSampleValue(j)->getLabel(); + std::list::iterator occit = + SampleOccurences[lbl].insert(SampleOccurences[lbl].end(), occ); + NumSampleOccurences[lbl][(*vit)->getTargetValue(j)]++; + (*vit)->setSampleOccurenceIt(j, occit); + } + } + + // compute NumEdges for all sample values + for (SampleValueLabel srclbl = 0; srclbl < SampleValues.size(); srclbl++) { + for (EmbValue t = 0; t < EmbValueModulus; t++) { + UWORD32 numedges = 0; + for (std::vector::const_iterator destsv = + (*(SVALists[t]))[srclbl].begin(); + destsv != (*(SVALists[t]))[srclbl].end(); destsv++) { + numedges += NumSampleOccurences[(*destsv)->getLabel()] + [SampleValues[srclbl]->getEmbeddedValue()]; + } + SampleValues[srclbl]->setNumEdges(t, numedges); + } + } } -Graph::~Graph() -{ - for (std::vector::iterator i = Vertices.begin() ; i != Vertices.end() ; i++) { - delete *i ; - } +Graph::~Graph() { + for (std::vector::iterator i = Vertices.begin(); i != Vertices.end(); i++) { + delete *i; + } - for (std::vector::iterator svit = SampleValues.begin() ; svit != SampleValues.end() ; svit++) { - delete *svit ; - } + for (std::vector::iterator svit = SampleValues.begin(); + svit != SampleValues.end(); svit++) { + delete *svit; + } - for (EmbValue t = 0 ; t < EmbValueModulus ; t++) { - delete SVALists[t] ; - } + for (EmbValue t = 0; t < EmbValueModulus; t++) { + delete SVALists[t]; + } - for (SampleValueLabel lbl = 0 ; lbl < SampleValues.size() ; lbl++) { - delete[] NumSampleOccurences[lbl] ; - delete[] NumDeletedSampleOccurences[lbl] ; - } + for (SampleValueLabel lbl = 0; lbl < SampleValues.size(); lbl++) { + delete[] NumSampleOccurences[lbl]; + delete[] NumDeletedSampleOccurences[lbl]; + } } -void Graph::unmarkDeletedAllVertices () -{ - for (std::vector::iterator it = Vertices.begin() ; it != Vertices.end() ; it++) { - (*it)->unmarkDeleted() ; - } +void Graph::unmarkDeletedAllVertices() { + for (std::vector::iterator it = Vertices.begin(); it != Vertices.end(); it++) { + (*it)->unmarkDeleted(); + } } -std::list::iterator Graph::markDeletedSampleOccurence (std::list::iterator it) -{ - Vertex *v = it->getVertex() ; - unsigned short i = it->getIndex() ; - SampleValueLabel lbl = v->getSampleValue(i)->getLabel() ; - SampleOccurences[lbl].erase (it) ; - NumSampleOccurences[lbl][v->getTargetValue(i)]-- ; - NumDeletedSampleOccurences[lbl][v->getTargetValue(i)]++ ; - return DeletedSampleOccurences[lbl].insert (DeletedSampleOccurences[lbl].end(), SampleOccurence (v, i)) ; +std::list::iterator +Graph::markDeletedSampleOccurence(std::list::iterator it) { + Vertex *v = it->getVertex(); + unsigned short i = it->getIndex(); + SampleValueLabel lbl = v->getSampleValue(i)->getLabel(); + SampleOccurences[lbl].erase(it); + NumSampleOccurences[lbl][v->getTargetValue(i)]--; + NumDeletedSampleOccurences[lbl][v->getTargetValue(i)]++; + return DeletedSampleOccurences[lbl].insert(DeletedSampleOccurences[lbl].end(), + SampleOccurence(v, i)); } -std::list::iterator Graph::unmarkDeletedSampleOccurence (std::list::iterator it) -{ - Vertex *v = it->getVertex() ; - unsigned short i = it->getIndex() ; - SampleValueLabel lbl = v->getSampleValue(i)->getLabel() ; - DeletedSampleOccurences[lbl].erase (it) ; - NumDeletedSampleOccurences[lbl][v->getTargetValue(i)]-- ; - NumSampleOccurences[lbl][v->getTargetValue(i)]++ ; - return SampleOccurences[lbl].insert (SampleOccurences[lbl].end(), SampleOccurence (v, i)) ; +std::list::iterator +Graph::unmarkDeletedSampleOccurence(std::list::iterator it) { + Vertex *v = it->getVertex(); + unsigned short i = it->getIndex(); + SampleValueLabel lbl = v->getSampleValue(i)->getLabel(); + DeletedSampleOccurences[lbl].erase(it); + NumDeletedSampleOccurences[lbl][v->getTargetValue(i)]--; + NumSampleOccurences[lbl][v->getTargetValue(i)]++; + return SampleOccurences[lbl].insert(SampleOccurences[lbl].end(), SampleOccurence(v, i)); } -float Graph::getAvgVertexDegree () const -{ - unsigned long sumdeg = 0 ; - for (std::vector::const_iterator vit = Vertices.begin() ; vit != Vertices.end() ; vit++) { - sumdeg += (*vit)->getDegree() ; - } - return ((float) sumdeg / (float) Vertices.size()) ; +float Graph::getAvgVertexDegree() const { + unsigned long sumdeg = 0; + for (std::vector::const_iterator vit = Vertices.begin(); vit != Vertices.end(); + vit++) { + sumdeg += (*vit)->getDegree(); + } + return ((float)sumdeg / (float)Vertices.size()); } -void Graph::printVerboseInfo() -{ - if (Args.Verbosity.getValue() == VERBOSE || Args.Verbosity.getValue() == STATS) { - unsigned long sumdeg = 0 ; - unsigned long mindeg = ULONG_MAX ; - unsigned long maxdeg = 0 ; - for (std::vector::iterator i = Vertices.begin() ; i != Vertices.end() ; i++) { - unsigned long deg = (*i)->getDegree() ; - - sumdeg += deg ; - if (deg < mindeg) { - mindeg = deg ; - } - if (deg > maxdeg) { - maxdeg = deg ; - } - } - float avgdeg = ((float) sumdeg / (float) Vertices.size()) ; - myassert (sumdeg % 2 == 0) ; - - if (Args.Verbosity.getValue() == STATS) { - printf ("%lu:%lu:%lu:%lu:%lu:%.1f:", - (unsigned long) SampleValues.size(), // number of distinct sample values - (unsigned long) Vertices.size(), // number of vertices - sumdeg / 2, // number of edges - mindeg, // minimum vertex degree - maxdeg, // maximum vertex degree - avgdeg // average vertex degree - ) ; - } - else { // Verbosity is VERBOSE - VerboseMessage vmsg1 (_(" %lu sample values, %lu vertices, %lu edges"), SampleValues.size(), Vertices.size(), sumdeg / 2) ; - vmsg1.printMessage() ; - } - } +void Graph::printVerboseInfo() { + if (Args.Verbosity.getValue() == VERBOSE || Args.Verbosity.getValue() == STATS) { + unsigned long sumdeg = 0; + unsigned long mindeg = ULONG_MAX; + unsigned long maxdeg = 0; + for (std::vector::iterator i = Vertices.begin(); i != Vertices.end(); i++) { + unsigned long deg = (*i)->getDegree(); + + sumdeg += deg; + if (deg < mindeg) { + mindeg = deg; + } + if (deg > maxdeg) { + maxdeg = deg; + } + } + float avgdeg = ((float)sumdeg / (float)Vertices.size()); + myassert(sumdeg % 2 == 0); + + if (Args.Verbosity.getValue() == STATS) { + printf("%lu:%lu:%lu:%lu:%lu:%.1f:", + (unsigned long)SampleValues.size(), // number of distinct sample values + (unsigned long)Vertices.size(), // number of vertices + sumdeg / 2, // number of edges + mindeg, // minimum vertex degree + maxdeg, // maximum vertex degree + avgdeg // average vertex degree + ); + } else { // Verbosity is VERBOSE + VerboseMessage vmsg1(_(" %lu sample values, %lu vertices, %lu edges"), + SampleValues.size(), Vertices.size(), sumdeg / 2); + vmsg1.printMessage(); + } + } } -bool Graph::check (bool verbose) const -{ - bool retval = true ; - retval = check_Vertices(verbose) && retval ; - retval = check_SampleValues(verbose) && retval ; - retval = check_SampleOccurences(verbose) && retval ; - retval = check_SVALists(verbose) && retval ; - return retval ; +bool Graph::check(bool verbose) const { + bool retval = true; + retval = check_Vertices(verbose) && retval; + retval = check_SampleValues(verbose) && retval; + retval = check_SampleOccurences(verbose) && retval; + retval = check_SVALists(verbose) && retval; + return retval; } -bool Graph::check_Vertices (bool verbose) const -{ - bool label_consistency = true ; - for (unsigned long i = 0 ; i < Vertices.size() ; i++) { - label_consistency = (Vertices[i]->getLabel() == i) && label_consistency ; - } - - // check if SampleValue pointers are the same as in SampleValues data structure - bool svuniqueness = true ; - for (unsigned long i = 0 ; i < Vertices.size() ; i++) { - for (unsigned short j = 0 ; j < File->getSamplesPerVertex() ; j++) { - SampleValue* sv = Vertices[i]->getSampleValue(j) ; - svuniqueness = (sv == SampleValues[sv->getLabel()]) && svuniqueness ; - } - } - - return label_consistency && svuniqueness ; +bool Graph::check_Vertices(bool verbose) const { + bool label_consistency = true; + for (unsigned long i = 0; i < Vertices.size(); i++) { + label_consistency = (Vertices[i]->getLabel() == i) && label_consistency; + } + + // check if SampleValue pointers are the same as in SampleValues data + // structure + bool svuniqueness = true; + for (unsigned long i = 0; i < Vertices.size(); i++) { + for (unsigned short j = 0; j < File->getSamplesPerVertex(); j++) { + SampleValue *sv = Vertices[i]->getSampleValue(j); + svuniqueness = (sv == SampleValues[sv->getLabel()]) && svuniqueness; + } + } + + return label_consistency && svuniqueness; } -bool Graph::check_SampleValues (bool verbose) const -{ - unsigned long n = SampleValues.size() ; - - bool label_consistency = true ; - for (unsigned long i = 0 ; i < n ; i++) { - if (SampleValues[i]->getLabel() != i) { - label_consistency = false ; - if (verbose) { - std::cerr << "----- FAILED: check_SampleValues -----" << std::endl ; - std::cerr << "SamplesValue[" << i << "]->getLabel(): " << SampleValues[i]->getLabel() << std::endl ; - std::cerr << "--------------------------------------" << std::endl ; - } - } - } - - bool sv_uniqueness = true ; - for (unsigned long i = 0 ; i < n ; i++) { - for (unsigned long j = 0 ; j < n ; j++) { - if (i != j) { - if (*(SampleValues[i]) == *(SampleValues[j])) { - sv_uniqueness = false ; - if (verbose) { - std::cerr << "----- FAILED: check_SampleValues -----" << std::endl ; - std::cerr << "uniqueness violated with the following two samples:" << std::endl ; - SampleValues[i]->print(1) ; - SampleValues[j]->print(1) ; - std::cerr << "--------------------------------------" << std::endl ; - } - } - } - } - } - - return (label_consistency && sv_uniqueness) ; +bool Graph::check_SampleValues(bool verbose) const { + unsigned long n = SampleValues.size(); + + bool label_consistency = true; + for (unsigned long i = 0; i < n; i++) { + if (SampleValues[i]->getLabel() != i) { + label_consistency = false; + if (verbose) { + std::cerr << "----- FAILED: check_SampleValues -----" << std::endl; + std::cerr << "SamplesValue[" << i + << "]->getLabel(): " << SampleValues[i]->getLabel() << std::endl; + std::cerr << "--------------------------------------" << std::endl; + } + } + } + + bool sv_uniqueness = true; + for (unsigned long i = 0; i < n; i++) { + for (unsigned long j = 0; j < n; j++) { + if (i != j) { + if (*(SampleValues[i]) == *(SampleValues[j])) { + sv_uniqueness = false; + if (verbose) { + std::cerr << "----- FAILED: check_SampleValues -----" << std::endl; + std::cerr << "uniqueness violated with the following two samples:" + << std::endl; + SampleValues[i]->print(1); + SampleValues[j]->print(1); + std::cerr << "--------------------------------------" << std::endl; + } + } + } + } + } + + return (label_consistency && sv_uniqueness); } -bool Graph::check_SampleOccurences (bool verbose) const -{ - bool retval = true ; - retval = check_SampleOccurences_size (verbose) && retval ; - retval = check_SampleOccurences_correctness (verbose) && retval ; - retval = check_SampleOccurences_completeness (verbose) && retval ; - return retval ; +bool Graph::check_SampleOccurences(bool verbose) const { + bool retval = true; + retval = check_SampleOccurences_size(verbose) && retval; + retval = check_SampleOccurences_correctness(verbose) && retval; + retval = check_SampleOccurences_completeness(verbose) && retval; + return retval; } -bool Graph::check_SampleOccurences_size (bool verbose) const -{ - bool size = (SampleOccurences.size() == SampleValues.size()) ; - if (!size && verbose) { - std::cerr << std::endl << "---- FAILED: check_SampleOccurences_size ----" << std::endl ; - std::cerr << "SampleOccurences.size(): " << SampleOccurences.size() << std::endl ; - std::cerr << "SampleValues.size(): " << SampleValues.size() << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - return size ; +bool Graph::check_SampleOccurences_size(bool verbose) const { + bool size = (SampleOccurences.size() == SampleValues.size()); + if (!size && verbose) { + std::cerr << std::endl << "---- FAILED: check_SampleOccurences_size ----" << std::endl; + std::cerr << "SampleOccurences.size(): " << SampleOccurences.size() << std::endl; + std::cerr << "SampleValues.size(): " << SampleValues.size() << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + return size; } -bool Graph::check_SampleOccurences_correctness (bool verbose) const -{ - bool correctness = true ; +bool Graph::check_SampleOccurences_correctness(bool verbose) const { + bool correctness = true; - for (unsigned long lbl = 0 ; lbl < SampleValues.size() ; lbl++) { - for (std::list::const_iterator socit = SampleOccurences[lbl].begin() ; socit != SampleOccurences[lbl].end() ; socit++) { - Vertex *v = socit->getVertex() ; - unsigned short idx = socit->getIndex() ; - correctness = (v->getSampleValue(idx) == SampleValues[lbl]) && correctness ; // pointer equivalence - } - } + for (unsigned long lbl = 0; lbl < SampleValues.size(); lbl++) { + for (std::list::const_iterator socit = SampleOccurences[lbl].begin(); + socit != SampleOccurences[lbl].end(); socit++) { + Vertex *v = socit->getVertex(); + unsigned short idx = socit->getIndex(); + correctness = + (v->getSampleValue(idx) == SampleValues[lbl]) && correctness; // pointer equivalence + } + } - return correctness ; + return correctness; } -bool Graph::check_SampleOccurences_completeness (bool verbose) const -{ - bool completeness = true ; +bool Graph::check_SampleOccurences_completeness(bool verbose) const { + bool completeness = true; - for (unsigned long vlbl = 0 ; vlbl < Vertices.size() ; vlbl++) { - for (unsigned short j = 0 ; j < File->getSamplesPerVertex() ; j++) { - SampleOccurence soc (Vertices[vlbl], j) ; - SampleValueLabel svlbl = Vertices[vlbl]->getSampleValue(j)->getLabel() ; - completeness = (find(SampleOccurences[svlbl].begin(), SampleOccurences[svlbl].end(), soc) != SampleOccurences[svlbl].end()) && completeness ; - } - } + for (unsigned long vlbl = 0; vlbl < Vertices.size(); vlbl++) { + for (unsigned short j = 0; j < File->getSamplesPerVertex(); j++) { + SampleOccurence soc(Vertices[vlbl], j); + SampleValueLabel svlbl = Vertices[vlbl]->getSampleValue(j)->getLabel(); + completeness = (find(SampleOccurences[svlbl].begin(), SampleOccurences[svlbl].end(), + soc) != SampleOccurences[svlbl].end()) && + completeness; + } + } - return completeness ; + return completeness; } -bool Graph::check_SVALists (bool verbose) const -{ - bool retval = true ; - retval = check_SVALists_size (verbose) && retval ; - retval = check_SVALists_soundness (verbose) && retval ; - retval = check_SVALists_sorted (verbose) && retval ; - retval = check_SVALists_uniqueness (verbose) && retval ; - retval = check_SVALists_completeness (verbose) && retval ; - return retval ; +bool Graph::check_SVALists(bool verbose) const { + bool retval = true; + retval = check_SVALists_size(verbose) && retval; + retval = check_SVALists_soundness(verbose) && retval; + retval = check_SVALists_sorted(verbose) && retval; + retval = check_SVALists_uniqueness(verbose) && retval; + retval = check_SVALists_completeness(verbose) && retval; + return retval; } -bool Graph::check_SVALists_size (bool verbose) const -{ - bool size = true ; - for (EmbValue i = 0 ; i < File->getEmbValueModulus() ; i++) { - size = (SVALists[i]->getNumRows() == SampleValues.size()) && size ; - if ((SVALists[i]->getNumRows() != SampleValues.size()) && verbose) { - std::cerr << std::endl << "---- FAILED: check_SVALists_size ----" << std::endl ; - std::cerr << "SVALists[" << i << "]->getNumRows(): " << SVALists[i]->getNumRows() << std::endl ; - std::cerr << "SampleValues.size(): " << SampleValues.size() << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - } - return size ; +bool Graph::check_SVALists_size(bool verbose) const { + bool size = true; + for (EmbValue i = 0; i < File->getEmbValueModulus(); i++) { + size = (SVALists[i]->getNumRows() == SampleValues.size()) && size; + if ((SVALists[i]->getNumRows() != SampleValues.size()) && verbose) { + std::cerr << std::endl << "---- FAILED: check_SVALists_size ----" << std::endl; + std::cerr << "SVALists[" << i << "]->getNumRows(): " << SVALists[i]->getNumRows() + << std::endl; + std::cerr << "SampleValues.size(): " << SampleValues.size() << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + } + return size; } -bool Graph::check_SVALists_soundness (bool verbose) const -{ - unsigned long numsvs = SampleValues.size() ; - - // check if everything in SVALists[i][j] really is a neighbour of j and has the embedded value i - bool target_ok = true ; - bool neigh_ok = true ; - for (EmbValue t = 0 ; t < File->getEmbValueModulus() ; t++) { - for (SampleValueLabel srclbl = 0 ; srclbl < numsvs ; srclbl++) { - SampleValue* srcsv = SampleValues[srclbl] ; - const std::vector &row = (*(SVALists[t]))[srclbl]; - for (std::vector::const_iterator destsv = row.begin() ; destsv != row.end() ; destsv++) { - if ((*destsv)->getEmbeddedValue() != t) { - target_ok = false ; - if (verbose) { - std::cerr << std::endl << "---- FAILED: check_SVALists_soundness ----" << std::endl ; - std::cerr << "in SVALists[" << (int) t << "][" << srclbl << "] is a sv with getEmbeddedValue() == " << (*destsv)->getEmbeddedValue() << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - } - if (!srcsv->isNeighbour(*destsv)) { - neigh_ok = false ; - if (verbose) { - std::cerr << std::endl << "---- FAILED: check_SVALists_soundness ----" << std::endl ; - std::cerr << "in SVALists[" << (int) t << "][" << srclbl << "] is a sv that is not a neighbour of " << srclbl << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - } - } - } - } - - return target_ok && neigh_ok ; +bool Graph::check_SVALists_soundness(bool verbose) const { + unsigned long numsvs = SampleValues.size(); + + // check if everything in SVALists[i][j] really is a neighbour of j and has + // the embedded value i + bool target_ok = true; + bool neigh_ok = true; + for (EmbValue t = 0; t < File->getEmbValueModulus(); t++) { + for (SampleValueLabel srclbl = 0; srclbl < numsvs; srclbl++) { + SampleValue *srcsv = SampleValues[srclbl]; + const std::vector &row = (*(SVALists[t]))[srclbl]; + for (std::vector::const_iterator destsv = row.begin(); + destsv != row.end(); destsv++) { + if ((*destsv)->getEmbeddedValue() != t) { + target_ok = false; + if (verbose) { + std::cerr << std::endl + << "---- FAILED: check_SVALists_soundness ----" << std::endl; + std::cerr << "in SVALists[" << (int)t << "][" << srclbl + << "] is a sv with getEmbeddedValue() == " + << (*destsv)->getEmbeddedValue() << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + } + if (!srcsv->isNeighbour(*destsv)) { + neigh_ok = false; + if (verbose) { + std::cerr << std::endl + << "---- FAILED: check_SVALists_soundness ----" << std::endl; + std::cerr << "in SVALists[" << (int)t << "][" << srclbl + << "] is a sv that is not a neighbour of " << srclbl << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + } + } + } + } + + return target_ok && neigh_ok; } -bool Graph::check_SVALists_sorted (bool verbose) const -{ - unsigned long numsvs = SampleValues.size() ; - - // check if SVALists[t][l][1...n] have increasing distance - bool sorted = true ; - for (EmbValue t = 0 ; t < File->getEmbValueModulus() ; t++) { - for (SampleValueLabel srclbl = 0 ; srclbl < numsvs ; srclbl++) { - SampleValue* srcsv = SampleValues[srclbl] ; - const std::vector &row = (*(SVALists[t]))[srclbl] ; - if (row.size() > 1) { - for (unsigned int i = 0 ; i < (row.size() - 1) ; i++) { - UWORD32 d1 = srcsv->calcDistance (row[i]) ; - UWORD32 d2 = srcsv->calcDistance (row[i + 1]) ; - if (!(d1 <= d2)) { - sorted = false ; - if (verbose) { - std::cerr << std::endl << "---- FAILED: check_SVALists_sorted ----" << std::endl ; - std::cerr << "source sample:" << std::endl ; - srcsv->print(1) ; - std::cerr << "dest sample at position " << i << ":" << std::endl ; - row[i]->print(1) ; - std::cerr << "dest sample at position " << i + 1 << ":" << std::endl ; - row[i + 1]->print(1) ; - std::cerr << "-------------------------------------" << std::endl ; - } - } - } - } - } - } - - return sorted ; +bool Graph::check_SVALists_sorted(bool verbose) const { + unsigned long numsvs = SampleValues.size(); + + // check if SVALists[t][l][1...n] have increasing distance + bool sorted = true; + for (EmbValue t = 0; t < File->getEmbValueModulus(); t++) { + for (SampleValueLabel srclbl = 0; srclbl < numsvs; srclbl++) { + SampleValue *srcsv = SampleValues[srclbl]; + const std::vector &row = (*(SVALists[t]))[srclbl]; + if (row.size() > 1) { + for (unsigned int i = 0; i < (row.size() - 1); i++) { + UWORD32 d1 = srcsv->calcDistance(row[i]); + UWORD32 d2 = srcsv->calcDistance(row[i + 1]); + if (!(d1 <= d2)) { + sorted = false; + if (verbose) { + std::cerr << std::endl + << "---- FAILED: check_SVALists_sorted ----" << std::endl; + std::cerr << "source sample:" << std::endl; + srcsv->print(1); + std::cerr << "dest sample at position " << i << ":" << std::endl; + row[i]->print(1); + std::cerr << "dest sample at position " << i + 1 << ":" << std::endl; + row[i + 1]->print(1); + std::cerr << "-------------------------------------" << std::endl; + } + } + } + } + } + } + + return sorted; } -bool Graph::check_SVALists_uniqueness (bool verbose) const -{ - // check if there is no sample value that has two entries in an SVAList - bool unique = true ; - for (EmbValue t = 0 ; t < File->getEmbValueModulus() ; t++) { - for (SampleValueLabel srclbl = 0 ; srclbl < SampleValues.size() ; srclbl++) { - for (unsigned int i = 0 ; i < (*(SVALists[t]))[srclbl].size() ; i++) { - for (unsigned int j = i + 1 ; j < (*(SVALists[t]))[srclbl].size() ; j++) { - if (*((*(SVALists[t]))[srclbl][i]) == *((*(SVALists[t]))[srclbl][j])) { - unique = false ; - if (verbose) { - std::cerr << std::endl << "---- FAILED: check_SVALists_uniqueness ----" << std::endl ; - std::cerr << "SVALists[" << (int) t << "][" << srclbl << "][" << i << "]->getLabel() == " << (*(SVALists[t]))[srclbl][i]->getLabel() << std::endl ; - std::cerr << "SVALists[" << (int) t << "][" << srclbl << "][" << j << "]->getLabel() == " << (*(SVALists[t]))[srclbl][j]->getLabel() << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - } - } - } - } - } - return unique ; +bool Graph::check_SVALists_uniqueness(bool verbose) const { + // check if there is no sample value that has two entries in an SVAList + bool unique = true; + for (EmbValue t = 0; t < File->getEmbValueModulus(); t++) { + for (SampleValueLabel srclbl = 0; srclbl < SampleValues.size(); srclbl++) { + for (unsigned int i = 0; i < (*(SVALists[t]))[srclbl].size(); i++) { + for (unsigned int j = i + 1; j < (*(SVALists[t]))[srclbl].size(); j++) { + if (*((*(SVALists[t]))[srclbl][i]) == *((*(SVALists[t]))[srclbl][j])) { + unique = false; + if (verbose) { + std::cerr << std::endl + << "---- FAILED: check_SVALists_uniqueness ----" << std::endl; + std::cerr + << "SVALists[" << (int)t << "][" << srclbl << "][" << i + << "]->getLabel() == " << (*(SVALists[t]))[srclbl][i]->getLabel() + << std::endl; + std::cerr + << "SVALists[" << (int)t << "][" << srclbl << "][" << j + << "]->getLabel() == " << (*(SVALists[t]))[srclbl][j]->getLabel() + << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + } + } + } + } + } + return unique; } - -bool Graph::check_SVALists_completeness (bool verbose) const -{ - bool ok = true ; - - unsigned long numsvs = SampleValues.size() ; - for (unsigned long i = 0 ; i < numsvs ; i++) { - SampleValue *svsrc = SampleValues[i] ; - for (unsigned long j = 0 ; j < numsvs ; j++) { - SampleValue *svdest = SampleValues[j] ; - if (svsrc->isNeighbour(svdest) && (svsrc->getLabel() != svdest->getLabel())) { - // svsrc and svdest are neighbours => there must be an entry in SVALists - myassert (svdest->isNeighbour (svsrc)) ; - const std::vector &row = (*(SVALists[svdest->getEmbeddedValue()]))[i] ; - bool found = false ; - for (std::vector::const_iterator k = row.begin() ; k != row.end() ; k++) { - if ((*k)->getLabel() == j) { - found = true ; - } - } - if (!found) { - ok = false ; - if (verbose) { - std::cerr << std::endl << "---- FAILED: check_SVALists_completeness ----" << std::endl ; - std::cerr << "sample values "<< svsrc->getLabel() << " and " << svdest->getLabel() << " are neighbours..." << std::endl ; - std::cerr << "...but SVALists[" << (int) svdest->getEmbeddedValue() << "][" << i << "] does not contain " << j << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - } - } - } - } - - return ok ; +bool Graph::check_SVALists_completeness(bool verbose) const { + bool ok = true; + + unsigned long numsvs = SampleValues.size(); + for (unsigned long i = 0; i < numsvs; i++) { + SampleValue *svsrc = SampleValues[i]; + for (unsigned long j = 0; j < numsvs; j++) { + SampleValue *svdest = SampleValues[j]; + if (svsrc->isNeighbour(svdest) && (svsrc->getLabel() != svdest->getLabel())) { + // svsrc and svdest are neighbours => there must be an entry in SVALists + myassert(svdest->isNeighbour(svsrc)); + const std::vector &row = + (*(SVALists[svdest->getEmbeddedValue()]))[i]; + bool found = false; + for (std::vector::const_iterator k = row.begin(); k != row.end(); + k++) { + if ((*k)->getLabel() == j) { + found = true; + } + } + if (!found) { + ok = false; + if (verbose) { + std::cerr << std::endl + << "---- FAILED: check_SVALists_completeness ----" << std::endl; + std::cerr << "sample values " << svsrc->getLabel() << " and " + << svdest->getLabel() << " are neighbours..." << std::endl; + std::cerr << "...but SVALists[" << (int)svdest->getEmbeddedValue() << "][" + << i << "] does not contain " << j << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + } + } + } + } + + return ok; } #ifdef DEBUG -void Graph::print (void) const -{ - unsigned long sumdeg = 0 ; - for (std::vector::const_iterator i = Vertices.begin() ; i != Vertices.end() ; i++) { - sumdeg += (*i)->getDegree() ; - } - myassert (sumdeg % 2 == 0) ; - std::cout << Vertices.size() << " " << (sumdeg / 2) << " U" << std::endl ; - - for (unsigned long i = 0 ; i < Vertices.size() ; i++) { - std::cout << Vertices[i]->getDegree() << " " << (i + 1) << " 0 0" << std::endl ; - - for (unsigned short j = 0 ; j < File->getSamplesPerVertex() ; j++) { - SampleValue *srcsample = Vertices[i]->getSampleValue(j) ; - EmbValue srctarget = Vertices[i]->getTargetValue(j) ; - for (unsigned long k = 0 ; k != Vertices.size() ; k++) { - if (i != k) { // no loops - for (unsigned short l = 0 ; l < File->getSamplesPerVertex() ; l++) { - SampleValue *destsample = Vertices[k]->getSampleValue(l) ; - EmbValue desttarget = Vertices[k]->getTargetValue(l) ; - - if ((srcsample->isNeighbour(destsample)) && - (srcsample->getEmbeddedValue() == desttarget) && - (destsample->getEmbeddedValue() == srctarget)) { - std::cout << (k + 1) << " 0" << std::endl ; - } - } - } - } - - } - } +void Graph::print(void) const { + unsigned long sumdeg = 0; + for (std::vector::const_iterator i = Vertices.begin(); i != Vertices.end(); i++) { + sumdeg += (*i)->getDegree(); + } + myassert(sumdeg % 2 == 0); + std::cout << Vertices.size() << " " << (sumdeg / 2) << " U" << std::endl; + + for (unsigned long i = 0; i < Vertices.size(); i++) { + std::cout << Vertices[i]->getDegree() << " " << (i + 1) << " 0 0" << std::endl; + + for (unsigned short j = 0; j < File->getSamplesPerVertex(); j++) { + SampleValue *srcsample = Vertices[i]->getSampleValue(j); + EmbValue srctarget = Vertices[i]->getTargetValue(j); + for (unsigned long k = 0; k != Vertices.size(); k++) { + if (i != k) { // no loops + for (unsigned short l = 0; l < File->getSamplesPerVertex(); l++) { + SampleValue *destsample = Vertices[k]->getSampleValue(l); + EmbValue desttarget = Vertices[k]->getTargetValue(l); + + if ((srcsample->isNeighbour(destsample)) && + (srcsample->getEmbeddedValue() == desttarget) && + (destsample->getEmbeddedValue() == srctarget)) { + std::cout << (k + 1) << " 0" << std::endl; + } + } + } + } + } + } } -void Graph::print_gml (std::ostream& out) const -{ - printPrologue_gml(out) ; - srand ((unsigned int) time (NULL)) ; - std::vector nodeprinted (Vertices.size()) ; - std::vector edgesprinted (Vertices.size()) ; - for (unsigned int i = 0 ; i < Vertices.size() ; i++) { - printVertex_gml (out, Vertices[i], 1, nodeprinted, edgesprinted, false) ; - } - printEpilogue_gml(out) ; +void Graph::print_gml(std::ostream &out) const { + printPrologue_gml(out); + srand((unsigned int)time(NULL)); + std::vector nodeprinted(Vertices.size()); + std::vector edgesprinted(Vertices.size()); + for (unsigned int i = 0; i < Vertices.size(); i++) { + printVertex_gml(out, Vertices[i], 1, nodeprinted, edgesprinted, false); + } + printEpilogue_gml(out); } -void Graph::printVertex_gml (std::ostream& out, Vertex* vstart, unsigned int recdepth, std::vector& nodeprinted, std::vector& edgesprinted, bool start) const -{ - const float width = 1300.0 ; - const float height = 1000.0 ; - - if (!nodeprinted[vstart->getLabel()]) { - out << " node [" << std::endl ; - out << " id " << vstart->getLabel() << std::endl ; - std::string vlabel = "" ; - for (unsigned short i = 0 ; i < File->getSamplesPerVertex() ; i++) { - vlabel += vstart->getSampleValue(i)->getName() ; - if (i != File->getSamplesPerVertex() - 1) { - vlabel += "/" ; - } - } - out << " label \"" << vlabel << "\"" << std::endl ; - out << " graphics [" << std::endl ; - out << " x " << (width * (rand() / (RAND_MAX + 1.0))) << std::endl ; - out << " y " << (height * (rand() / (RAND_MAX + 1.0))) << std::endl ; - out << " w 10.0" << std::endl ; - out << " h 10.0" << std::endl ; - out << " type \"rectangle\"" << std::endl ; - out << " width 1.0" << std::endl ; - if (start) { - out << " fill \"#00FF00\"" << std::endl ; - } - out << " ]" << std::endl ; - out << " ]" << std::endl ; - } - nodeprinted[vstart->getLabel()] = true ; - - if (recdepth > 0) { - EdgeIterator eit (vstart) ; - while (!eit.isFinished()) { - const Edge* e = *eit ; - Vertex* vnext = e->getOtherVertex(vstart) ; - - if (!edgesprinted[vstart->getLabel()] && !edgesprinted[vnext->getLabel()]) { - out << " edge [" << std::endl ; - out << " source " << e->getVertex1()->getLabel() << std::endl ; - out << " target " << e->getVertex2()->getLabel() << std::endl ; - out << " label \"" ; - out << e->getVertex1()->getSampleValue(e->getIndex1())->getName() << "/" ; - out << e->getVertex2()->getSampleValue(e->getIndex2())->getName() << "\"" << std::endl ; - out << " ]" << std::endl ; - } - - ++eit ; - } - - edgesprinted[vstart->getLabel()] = true ; - - eit.reset() ; - while (!eit.isFinished()) { - const Edge* e = *eit ; - Vertex* vnext = e->getOtherVertex(vstart) ; - - printVertex_gml (out, vnext, recdepth - 1, nodeprinted, edgesprinted, false) ; - - ++eit ; - } - } +void Graph::printVertex_gml(std::ostream &out, Vertex *vstart, unsigned int recdepth, + std::vector &nodeprinted, std::vector &edgesprinted, + bool start) const { + const float width = 1300.0; + const float height = 1000.0; + + if (!nodeprinted[vstart->getLabel()]) { + out << " node [" << std::endl; + out << " id " << vstart->getLabel() << std::endl; + std::string vlabel = ""; + for (unsigned short i = 0; i < File->getSamplesPerVertex(); i++) { + vlabel += vstart->getSampleValue(i)->getName(); + if (i != File->getSamplesPerVertex() - 1) { + vlabel += "/"; + } + } + out << " label \"" << vlabel << "\"" << std::endl; + out << " graphics [" << std::endl; + out << " x " << (width * (rand() / (RAND_MAX + 1.0))) << std::endl; + out << " y " << (height * (rand() / (RAND_MAX + 1.0))) << std::endl; + out << " w 10.0" << std::endl; + out << " h 10.0" << std::endl; + out << " type \"rectangle\"" << std::endl; + out << " width 1.0" << std::endl; + if (start) { + out << " fill \"#00FF00\"" << std::endl; + } + out << " ]" << std::endl; + out << " ]" << std::endl; + } + nodeprinted[vstart->getLabel()] = true; + + if (recdepth > 0) { + EdgeIterator eit(vstart); + while (!eit.isFinished()) { + const Edge *e = *eit; + Vertex *vnext = e->getOtherVertex(vstart); + + if (!edgesprinted[vstart->getLabel()] && !edgesprinted[vnext->getLabel()]) { + out << " edge [" << std::endl; + out << " source " << e->getVertex1()->getLabel() << std::endl; + out << " target " << e->getVertex2()->getLabel() << std::endl; + out << " label \""; + out << e->getVertex1()->getSampleValue(e->getIndex1())->getName() << "/"; + out << e->getVertex2()->getSampleValue(e->getIndex2())->getName() << "\"" + << std::endl; + out << " ]" << std::endl; + } + + ++eit; + } + + edgesprinted[vstart->getLabel()] = true; + + eit.reset(); + while (!eit.isFinished()) { + const Edge *e = *eit; + Vertex *vnext = e->getOtherVertex(vstart); + + printVertex_gml(out, vnext, recdepth - 1, nodeprinted, edgesprinted, false); + + ++eit; + } + } } -void Graph::printPrologue_gml (std::ostream& out) const -{ - out << "graph [" << std::endl ; - out << " directed 0" << std::endl ; +void Graph::printPrologue_gml(std::ostream &out) const { + out << "graph [" << std::endl; + out << " directed 0" << std::endl; } -void Graph::printEpilogue_gml (std::ostream& out) const -{ - out << "]" << std::endl ; -} +void Graph::printEpilogue_gml(std::ostream &out) const { out << "]" << std::endl; } + +void Graph::print_Vertices(unsigned short spc) const { + char *space = new char[spc + 1]; + for (unsigned short i = 0; i < spc; i++) { + space[i] = ' '; + } + space[spc] = '\0'; -void Graph::print_Vertices (unsigned short spc) const -{ - char* space = new char[spc + 1] ; - for (unsigned short i = 0 ; i < spc ; i++) { - space[i] = ' ' ; - } - space[spc] = '\0' ; - - std::cerr << space << "Vertices:" << std::endl ; - for (std::vector::const_iterator vit = Vertices.begin() ; vit != Vertices.end() ; vit++) { - (*vit)->print(spc + 1) ; - } + std::cerr << space << "Vertices:" << std::endl; + for (std::vector::const_iterator vit = Vertices.begin(); vit != Vertices.end(); + vit++) { + (*vit)->print(spc + 1); + } } #endif diff --git a/src/Graph.h b/src/Graph.h index 59e3f5b..458a68b 100644 --- a/src/Graph.h +++ b/src/Graph.h @@ -25,19 +25,19 @@ #include #include #include -#include #include +#include #include "EdgeIterator.h" #include "SampleValueAdjacencyList.h" #include "common.h" -class BitString ; -class SampleOccurence ; -class Selector ; -class Vertex ; -class VertexContent ; -struct VertexContentsEqual ; +class BitString; +class SampleOccurence; +class Selector; +class Vertex; +class VertexContent; +struct VertexContentsEqual; /** * \class Graph @@ -49,161 +49,168 @@ struct VertexContentsEqual ; * thus have direct access to the private data structures. **/ class Graph { - public: - /** - * construct a graph - * \param cvr the underlying cover file - * \param emb the bitstring to be embedded (with correct arity already set) - **/ - Graph (CvrStgFile* cvr, const BitString& emb, Selector& sel) ; - - /** - * destructor - **/ - ~Graph (void) ; - - /** - * get the number of vertices in this graph - **/ - unsigned long getNumVertices (void) const - { return Vertices.size() ; } ; - - /** - * get a vertex - * \param l the vertex label (index) of the vertex to be returned (must be < getNumVertices()) - * \return the vertex with label l - **/ - Vertex* getVertex (VertexLabel l) const - { return Vertices[l] ; } ; - - void unmarkDeletedAllVertices (void) ; - - /** - * calculate and return the average vertex degree - **/ - float getAvgVertexDegree (void) const ; - - void printVerboseInfo (void) ; - - /** - * check the integrity of all data structures, - * only used for debugging and testing - **/ - bool check (bool verbose = false) const ; - /** - * check the integrity of the Vertices data structure, - * only used for debugging and testing - **/ - bool check_Vertices (bool verbose = false) const ; - /** - * check the integrity of the SampleValues data structure, - * only used for debugging and testing - **/ - bool check_SampleValues (bool verbose = false) const ; - /** - * check the integrity of the SampleOccurences data structure, - * it is assumed that DeletedSampleOccurences is empty, - * only used for debugging and testing - **/ - bool check_SampleOccurences (bool verbose = false) const ; - /** - * check the integrity of the SVALists data structure, - * only used for debugging and testing - **/ - bool check_SVALists (bool verbose = false) const ; + public: + /** + * construct a graph + * \param cvr the underlying cover file + * \param emb the bitstring to be embedded (with correct arity already set) + **/ + Graph(CvrStgFile *cvr, const BitString &emb, Selector &sel); + + /** + * destructor + **/ + ~Graph(void); + + /** + * get the number of vertices in this graph + **/ + unsigned long getNumVertices(void) const { return Vertices.size(); }; + + /** + * get a vertex + * \param l the vertex label (index) of the vertex to be returned (must be < getNumVertices()) + * \return the vertex with label l + **/ + Vertex *getVertex(VertexLabel l) const { return Vertices[l]; }; + + void unmarkDeletedAllVertices(void); + + /** + * calculate and return the average vertex degree + **/ + float getAvgVertexDegree(void) const; + + void printVerboseInfo(void); + + /** + * check the integrity of all data structures, + * only used for debugging and testing + **/ + bool check(bool verbose = false) const; + /** + * check the integrity of the Vertices data structure, + * only used for debugging and testing + **/ + bool check_Vertices(bool verbose = false) const; + /** + * check the integrity of the SampleValues data structure, + * only used for debugging and testing + **/ + bool check_SampleValues(bool verbose = false) const; + /** + * check the integrity of the SampleOccurences data structure, + * it is assumed that DeletedSampleOccurences is empty, + * only used for debugging and testing + **/ + bool check_SampleOccurences(bool verbose = false) const; + /** + * check the integrity of the SVALists data structure, + * only used for debugging and testing + **/ + bool check_SVALists(bool verbose = false) const; #ifdef DEBUG - /** - * prints graph in a format suitable as input to the C implementation - * of Gabow's non-weighted matching algorithm by E. Rothberg to stdout - * (available at: ftp://ftp.zib.de/pub/Packages/mathprog/matching/index.html - **/ - void print (void) const ; - - void print_gml (std::ostream& out) const ; - void printVertex_gml (std::ostream& out, Vertex* v, unsigned int recdepth, std::vector& nodeprinted, std::vector& edgesprinted, bool start = true) const ; - void printPrologue_gml (std::ostream& out) const ; - void printEpilogue_gml (std::ostream& out) const ; - - void print_Vertices (unsigned short spc = 0) const ; + /** + * prints graph in a format suitable as input to the C implementation + * of Gabow's non-weighted matching algorithm by E. Rothberg to stdout + * (available at: ftp://ftp.zib.de/pub/Packages/mathprog/matching/index.html + **/ + void print(void) const; + + void print_gml(std::ostream &out) const; + void printVertex_gml(std::ostream &out, Vertex *v, unsigned int recdepth, + std::vector &nodeprinted, std::vector &edgesprinted, + bool start = true) const; + void printPrologue_gml(std::ostream &out) const; + void printEpilogue_gml(std::ostream &out) const; + + void print_Vertices(unsigned short spc = 0) const; #endif - private: - // - // friend-declarations - // - friend class WKSConstructionHeuristic ; - friend class EdgeIterator ; - friend class SampleValueAdjacencyList ; - friend class Vertex ; - - /// contains the vertices in this graph - Vertices[l] is the vertex with label l - std::vector Vertices ; - - /// contains the list of (unique) sample values - SampleValues[l] is the sample value with label l - std::vector SampleValues ; - - /// contains the sample value adjacency lists (SVALists[v] contains only sample values with embedded value v) - std::vector SVALists ; - - /// SampleOccurences[l] contains all occurences of the sample value with label l - std::vector > SampleOccurences ; - - /** - * NumSampleOccurences[l][t] contains the number vertices that contain the sample value with label l and associated target t - **/ - std::vector NumSampleOccurences ; - - /// contains those sample occurences that have been marked as deleted from SampleOccurences - std::vector > DeletedSampleOccurences ; - std::vector NumDeletedSampleOccurences ; - - std::list::iterator markDeletedSampleOccurence (std::list::iterator it) ; - std::list::iterator unmarkDeletedSampleOccurence (std::list::iterator it) ; - - // - // end of friend-declarations - // Note: private members of Graph that are declared beyond this point should - // not be used by friends. - // - - /** - * construct sample-related data structures - * - * needs: sposs(unsorted) - * provides: svalues(unsorted,unique), SampleValues - **/ - void constructSamples (const std::vector &sposs, std::vector& svalues) ; - - /** - * construct vertex-related data structures - * - * needs: sposs(unsorted), svalues(unsorted,unique), tvalues - * provides: sposs(sorted), Vertices (except SampleOccurenceIts) - **/ - void constructVertices (std::vector& sposs, std::vector& svalues, const std::vector& tvalues) ; - - /** - * construct edge-related data structures - * - * needs: SampleValues, Vertices (except SampleOccurenceIts) - * provides: SVALists, SampleOccurences, Vertices (SampleOccurenceIts) - **/ - void constructEdges (void) ; - - CvrStgFile *File ; - EmbValue EmbValueModulus ; - unsigned short SamplesPerVertex ; - - bool check_SampleOccurences_size (bool verbose = false) const ; - bool check_SampleOccurences_correctness (bool verbose = false) const ; - bool check_SampleOccurences_completeness (bool verbose = false) const ; - - bool check_SVALists_size (bool verbose = false) const ; - bool check_SVALists_soundness (bool verbose = false) const ; - bool check_SVALists_sorted (bool verbose = false) const ; - bool check_SVALists_uniqueness (bool verbose = false) const ; - bool check_SVALists_completeness (bool verbose = false) const ; -} ; + private: + // + // friend-declarations + // + friend class WKSConstructionHeuristic; + friend class EdgeIterator; + friend class SampleValueAdjacencyList; + friend class Vertex; + + /// contains the vertices in this graph - Vertices[l] is the vertex with label l + std::vector Vertices; + + /// contains the list of (unique) sample values - SampleValues[l] is the sample value with label + /// l + std::vector SampleValues; + + /// contains the sample value adjacency lists (SVALists[v] contains only sample values with + /// embedded value v) + std::vector SVALists; + + /// SampleOccurences[l] contains all occurences of the sample value with label l + std::vector> SampleOccurences; + + /** + * NumSampleOccurences[l][t] contains the number vertices that contain the sample value with + *label l and associated target t + **/ + std::vector NumSampleOccurences; + + /// contains those sample occurences that have been marked as deleted from SampleOccurences + std::vector> DeletedSampleOccurences; + std::vector NumDeletedSampleOccurences; + + std::list::iterator + markDeletedSampleOccurence(std::list::iterator it); + std::list::iterator + unmarkDeletedSampleOccurence(std::list::iterator it); + + // + // end of friend-declarations + // Note: private members of Graph that are declared beyond this point should + // not be used by friends. + // + + /** + * construct sample-related data structures + * + * needs: sposs(unsorted) + * provides: svalues(unsorted,unique), SampleValues + **/ + void constructSamples(const std::vector &sposs, + std::vector &svalues); + + /** + * construct vertex-related data structures + * + * needs: sposs(unsorted), svalues(unsorted,unique), tvalues + * provides: sposs(sorted), Vertices (except SampleOccurenceIts) + **/ + void constructVertices(std::vector &sposs, std::vector &svalues, + const std::vector &tvalues); + + /** + * construct edge-related data structures + * + * needs: SampleValues, Vertices (except SampleOccurenceIts) + * provides: SVALists, SampleOccurences, Vertices (SampleOccurenceIts) + **/ + void constructEdges(void); + + CvrStgFile *File; + EmbValue EmbValueModulus; + unsigned short SamplesPerVertex; + + bool check_SampleOccurences_size(bool verbose = false) const; + bool check_SampleOccurences_correctness(bool verbose = false) const; + bool check_SampleOccurences_completeness(bool verbose = false) const; + + bool check_SVALists_size(bool verbose = false) const; + bool check_SVALists_soundness(bool verbose = false) const; + bool check_SVALists_sorted(bool verbose = false) const; + bool check_SVALists_uniqueness(bool verbose = false) const; + bool check_SVALists_completeness(bool verbose = false) const; +}; #endif // ndef SH_GRAPH_H diff --git a/src/JpegFile.cc b/src/JpegFile.cc index 49fef96..37821d2 100644 --- a/src/JpegFile.cc +++ b/src/JpegFile.cc @@ -30,218 +30,208 @@ #include "SMDConstructionHeuristic.h" #include "error.h" -JpegFile::JpegFile (BinaryIO* io) - : CvrStgFile() -{ - setSamplesPerVertex (SamplesPerVertex) ; - setRadius (Radius) ; - setEmbValueModulus (EmbValueModulus) ; - HeightInBlocks = NULL ; - WidthInBlocks = NULL ; - read (io) ; +JpegFile::JpegFile(BinaryIO *io) : CvrStgFile() { + setSamplesPerVertex(SamplesPerVertex); + setRadius(Radius); + setEmbValueModulus(EmbValueModulus); + HeightInBlocks = NULL; + WidthInBlocks = NULL; + read(io); } -JpegFile::~JpegFile () -{ - if (WidthInBlocks) { - delete[] WidthInBlocks ; - } - if (HeightInBlocks) { - delete[] HeightInBlocks ; - } +JpegFile::~JpegFile() { + if (WidthInBlocks) { + delete[] WidthInBlocks; + } + if (HeightInBlocks) { + delete[] HeightInBlocks; + } } -std::list JpegFile::getProperties () const -{ - std::list retval ; +std::list JpegFile::getProperties() const { + std::list retval; - // format - retval.push_back (CvrStgFile::Property (_("format"), "jpeg")) ; + // format + retval.push_back(CvrStgFile::Property(_("format"), "jpeg")); - return retval ; + return retval; } -void JpegFile::read (BinaryIO* io) -{ - CvrStgFile::read (io) ; - - // TODO - use BinaryIO (or similar class) as input/output module for libjpeg (to avoid the NotImplementedError and using FILE* here) - FILE *infile = NULL ; - if (io->is_std()) { - throw NotImplementedError (_("can not use standard input as source for jpeg files with libjpeg.")) ; - } - else { - infile = io->getStream() ; - rewind (infile) ; - } - - struct jpeg_error_mgr errmgr ; - DeCInfo.err = jpeg_std_error (&errmgr) ; - jpeg_create_decompress (&DeCInfo) ; - jpeg_stdio_src (&DeCInfo, infile) ; - jpeg_read_header (&DeCInfo, TRUE) ; - - DctCoeffs = jpeg_read_coefficients (&DeCInfo) ; - - // fill HeightInBlocks and WidthInBlocks - unsigned short max_v_samp_factor = 0 ; - unsigned short max_h_samp_factor = 0 ; - for (unsigned short icomp = 0 ; icomp < DeCInfo.num_components ; icomp++) { - max_v_samp_factor = AUtils::max (max_v_samp_factor, DeCInfo.comp_info[icomp].v_samp_factor) ; - max_h_samp_factor = AUtils::max (max_h_samp_factor, DeCInfo.comp_info[icomp].h_samp_factor) ; - } - HeightInBlocks = new unsigned int[DeCInfo.num_components] ; - WidthInBlocks = new unsigned int[DeCInfo.num_components] ; - for (unsigned short icomp = 0 ; icomp < DeCInfo.num_components ; icomp++) { - HeightInBlocks[icomp] = AUtils::div_roundup (DeCInfo.image_height * DeCInfo.comp_info[icomp].v_samp_factor, - 8 * max_v_samp_factor) ; - WidthInBlocks[icomp] = AUtils::div_roundup (DeCInfo.image_width * DeCInfo.comp_info[icomp].h_samp_factor, - 8 * max_h_samp_factor) ; - } - - // resize LinDctCoeffs to size that is enough to contain all dct coeffs - unsigned long totalnumcoeffs = 0 ; - for (unsigned short icomp = 0 ; icomp < DeCInfo.num_components ; icomp++) { - totalnumcoeffs += CoeffPerBlock * (HeightInBlocks[icomp] * WidthInBlocks[icomp]) ; - } - LinDctCoeffs.resize (totalnumcoeffs) ; - - // read data from jpeglib's virtual array into LinDctCoeffs and StegoIndices - UWORD32 linindex = 0 ; - for (unsigned short icomp = 0 ; icomp < DeCInfo.num_components ; icomp++) { - unsigned int currow = 0 ; - while (currow < HeightInBlocks[icomp]) { - unsigned int naccess = 1 ; - JBLOCKARRAY array = (*(DeCInfo.mem->access_virt_barray)) - ((j_common_ptr) &DeCInfo, DctCoeffs[icomp], currow, naccess, FALSE) ; - for (unsigned int irow = 0 ; irow < naccess ; irow++) { - for (unsigned int iblock = 0 ; iblock < WidthInBlocks[icomp] ; iblock++) { - for (unsigned int icoeff = 0 ; icoeff < CoeffPerBlock ; icoeff++) { - LinDctCoeffs[linindex] = array[irow][iblock][icoeff] ; - - // don't use zero dct coefficients to embed data - if (LinDctCoeffs[linindex] != 0) { - StegoIndices.push_back (linindex) ; - } - linindex++ ; - } - } - } - currow += naccess ; - } - } +void JpegFile::read(BinaryIO *io) { + CvrStgFile::read(io); + + // TODO - use BinaryIO (or similar class) as input/output module for libjpeg + // (to avoid the NotImplementedError and using FILE* here) + FILE *infile = NULL; + if (io->is_std()) { + throw NotImplementedError( + _("can not use standard input as source for jpeg files with libjpeg.")); + } else { + infile = io->getStream(); + rewind(infile); + } + + struct jpeg_error_mgr errmgr; + DeCInfo.err = jpeg_std_error(&errmgr); + jpeg_create_decompress(&DeCInfo); + jpeg_stdio_src(&DeCInfo, infile); + jpeg_read_header(&DeCInfo, TRUE); + + DctCoeffs = jpeg_read_coefficients(&DeCInfo); + + // fill HeightInBlocks and WidthInBlocks + unsigned short max_v_samp_factor = 0; + unsigned short max_h_samp_factor = 0; + for (unsigned short icomp = 0; icomp < DeCInfo.num_components; icomp++) { + max_v_samp_factor = + AUtils::max(max_v_samp_factor, DeCInfo.comp_info[icomp].v_samp_factor); + max_h_samp_factor = + AUtils::max(max_h_samp_factor, DeCInfo.comp_info[icomp].h_samp_factor); + } + HeightInBlocks = new unsigned int[DeCInfo.num_components]; + WidthInBlocks = new unsigned int[DeCInfo.num_components]; + for (unsigned short icomp = 0; icomp < DeCInfo.num_components; icomp++) { + HeightInBlocks[icomp] = AUtils::div_roundup( + DeCInfo.image_height * DeCInfo.comp_info[icomp].v_samp_factor, 8 * max_v_samp_factor); + WidthInBlocks[icomp] = AUtils::div_roundup( + DeCInfo.image_width * DeCInfo.comp_info[icomp].h_samp_factor, 8 * max_h_samp_factor); + } + + // resize LinDctCoeffs to size that is enough to contain all dct coeffs + unsigned long totalnumcoeffs = 0; + for (unsigned short icomp = 0; icomp < DeCInfo.num_components; icomp++) { + totalnumcoeffs += CoeffPerBlock * (HeightInBlocks[icomp] * WidthInBlocks[icomp]); + } + LinDctCoeffs.resize(totalnumcoeffs); + + // read data from jpeglib's virtual array into LinDctCoeffs and StegoIndices + UWORD32 linindex = 0; + for (unsigned short icomp = 0; icomp < DeCInfo.num_components; icomp++) { + unsigned int currow = 0; + while (currow < HeightInBlocks[icomp]) { + unsigned int naccess = 1; + JBLOCKARRAY array = (*(DeCInfo.mem->access_virt_barray))( + (j_common_ptr)&DeCInfo, DctCoeffs[icomp], currow, naccess, FALSE); + for (unsigned int irow = 0; irow < naccess; irow++) { + for (unsigned int iblock = 0; iblock < WidthInBlocks[icomp]; iblock++) { + for (unsigned int icoeff = 0; icoeff < CoeffPerBlock; icoeff++) { + LinDctCoeffs[linindex] = array[irow][iblock][icoeff]; + + // don't use zero dct coefficients to embed data + if (LinDctCoeffs[linindex] != 0) { + StegoIndices.push_back(linindex); + } + linindex++; + } + } + } + currow += naccess; + } + } } -void JpegFile::write () -{ - CvrStgFile::write() ; - - FILE* outfile = getBinIO()->getStream() ; - - // prepare for writing - jpeg_create_compress (&CInfo) ; - jpeg_copy_critical_parameters (&DeCInfo, &CInfo) ; - struct jpeg_error_mgr jerr2 ; - CInfo.err = jpeg_std_error(&jerr2) ; - jpeg_stdio_dest (&CInfo, outfile) ; - - // write file header - jpeg_write_coefficients (&CInfo, DctCoeffs) ; - - UWORD32 linindex = 0 ; - for (unsigned short icomp = 0 ; icomp < CInfo.num_components ; icomp++) { - - unsigned int currow = 0 ; - while (currow < HeightInBlocks[icomp]) { - unsigned int naccess = 1 ; - JBLOCKARRAY array = (*(CInfo.mem->access_virt_barray)) - ((j_common_ptr) &CInfo, DctCoeffs[icomp], currow, naccess, TRUE) ; - for (unsigned int irow = 0 ; irow < naccess ; irow++) { - for (unsigned int iblock = 0 ; iblock < WidthInBlocks[icomp] ; iblock++) { - for (unsigned int icoeff = 0 ; icoeff < CoeffPerBlock ; icoeff++) { - array[irow][iblock][icoeff] = LinDctCoeffs[linindex] ; - linindex++ ; - } - } - } - currow += naccess ; - } - } - - // write and deallocate everything (writing is possible only once) - jpeg_finish_compress (&CInfo) ; - jpeg_destroy_compress(&CInfo); - jpeg_finish_decompress (&DeCInfo) ; - jpeg_destroy_decompress(&DeCInfo); +void JpegFile::write() { + CvrStgFile::write(); + + FILE *outfile = getBinIO()->getStream(); + + // prepare for writing + jpeg_create_compress(&CInfo); + jpeg_copy_critical_parameters(&DeCInfo, &CInfo); + struct jpeg_error_mgr jerr2; + CInfo.err = jpeg_std_error(&jerr2); + jpeg_stdio_dest(&CInfo, outfile); + + // write file header + jpeg_write_coefficients(&CInfo, DctCoeffs); + + UWORD32 linindex = 0; + for (unsigned short icomp = 0; icomp < CInfo.num_components; icomp++) { + + unsigned int currow = 0; + while (currow < HeightInBlocks[icomp]) { + unsigned int naccess = 1; + JBLOCKARRAY array = (*(CInfo.mem->access_virt_barray))( + (j_common_ptr)&CInfo, DctCoeffs[icomp], currow, naccess, TRUE); + for (unsigned int irow = 0; irow < naccess; irow++) { + for (unsigned int iblock = 0; iblock < WidthInBlocks[icomp]; iblock++) { + for (unsigned int icoeff = 0; icoeff < CoeffPerBlock; icoeff++) { + array[irow][iblock][icoeff] = LinDctCoeffs[linindex]; + linindex++; + } + } + } + currow += naccess; + } + } + + // write and deallocate everything (writing is possible only once) + jpeg_finish_compress(&CInfo); + jpeg_destroy_compress(&CInfo); + jpeg_finish_decompress(&DeCInfo); + jpeg_destroy_decompress(&DeCInfo); } -unsigned long JpegFile::getNumSamples (void) const -{ - return StegoIndices.size() ; -} +unsigned long JpegFile::getNumSamples(void) const { return StegoIndices.size(); } -SampleValue* JpegFile::getSampleValue (const SamplePos pos) const -{ - myassert (pos < StegoIndices.size()) ; - return new JpegSampleValue (LinDctCoeffs[StegoIndices[pos]]) ; +SampleValue *JpegFile::getSampleValue(const SamplePos pos) const { + myassert(pos < StegoIndices.size()); + return new JpegSampleValue(LinDctCoeffs[StegoIndices[pos]]); } -void JpegFile::replaceSample (const SamplePos pos, const SampleValue* s) -{ - const JpegSampleValue* sample = dynamic_cast (s) ; - myassert (sample != NULL) ; - myassert (pos <= StegoIndices.size()) ; - LinDctCoeffs[StegoIndices[pos]] = sample->getDctCoeff() ; +void JpegFile::replaceSample(const SamplePos pos, const SampleValue *s) { + const JpegSampleValue *sample = dynamic_cast(s); + myassert(sample != NULL); + myassert(pos <= StegoIndices.size()); + LinDctCoeffs[StegoIndices[pos]] = sample->getDctCoeff(); } -EmbValue JpegFile::getEmbeddedValue (const SamplePos pos) const -{ - myassert (pos < StegoIndices.size()) ; - return JpegSampleValue::calcEValue (LinDctCoeffs[StegoIndices[pos]]) ; +EmbValue JpegFile::getEmbeddedValue(const SamplePos pos) const { + myassert(pos < StegoIndices.size()); + return JpegSampleValue::calcEValue(LinDctCoeffs[StegoIndices[pos]]); } -std::vector JpegFile::getMatchingAlgorithms (Graph* g, Matching* m) const -{ - std::vector retval ; - retval.push_back (new SMDConstructionHeuristic (g, m)) ; - return retval ; +std::vector JpegFile::getMatchingAlgorithms(Graph *g, Matching *m) const { + std::vector retval; + retval.push_back(new SMDConstructionHeuristic(g, m)); + return retval; } #ifdef DEBUG -std::map* JpegFile::getFrequencies () -{ - unsigned long n = LinDctCoeffs.size() ; - std::map* table = new std::map () ; - - for (unsigned long pos = 0 ; pos < n ; pos++) { - SampleValue *sv = (SampleValue*) new JpegSampleValue (LinDctCoeffs[pos]) ; - (*table)[sv->getKey()]++ ; - delete sv ; - } - - return table ; +std::map *JpegFile::getFrequencies() { + unsigned long n = LinDctCoeffs.size(); + std::map *table = new std::map(); + + for (unsigned long pos = 0; pos < n; pos++) { + SampleValue *sv = (SampleValue *)new JpegSampleValue(LinDctCoeffs[pos]); + (*table)[sv->getKey()]++; + delete sv; + } + + return table; } -void JpegFile::printFrequencies (const std::map& freqs) -{ - std::list output ; - - // insert the positive dct coeffs into output list - for (std::map::const_iterator pit = freqs.begin() ; pit->first < 2147483648UL /* 2^31 */ ; pit++) { - char buf[30] ; - sprintf (buf, "%ld: %lu", (long) pit->first, pit->second) ; - output.push_back (std::string(buf)) ; - } - - // insert the negative dct coeffs into output list - for (std::map::const_reverse_iterator nit = freqs.rbegin() ; nit->first > 2147483648UL /* 2^31 */ ; nit++) { - char buf[30] ; - sprintf (buf, "%ld: %lu", (long) nit->first, nit->second) ; - output.push_front (std::string(buf)) ; - } - - for (std::list::const_iterator it = output.begin() ; it != output.end() ; it++) { - std::cout << *it << std::endl ; - } +void JpegFile::printFrequencies(const std::map &freqs) { + std::list output; + + // insert the positive dct coeffs into output list + for (std::map::const_iterator pit = freqs.begin(); + pit->first < 2147483648UL /* 2^31 */; pit++) { + char buf[30]; + sprintf(buf, "%ld: %lu", (long)pit->first, pit->second); + output.push_back(std::string(buf)); + } + + // insert the negative dct coeffs into output list + for (std::map::const_reverse_iterator nit = freqs.rbegin(); + nit->first > 2147483648UL /* 2^31 */; nit++) { + char buf[30]; + sprintf(buf, "%ld: %lu", (long)nit->first, nit->second); + output.push_front(std::string(buf)); + } + + for (std::list::const_iterator it = output.begin(); it != output.end(); it++) { + std::cout << *it << std::endl; + } } #endif // def DEBUG diff --git a/src/JpegFile.h b/src/JpegFile.h index b7130d8..9eda8a1 100644 --- a/src/JpegFile.h +++ b/src/JpegFile.h @@ -26,13 +26,13 @@ #include extern "C" { -#include #include +#include } -class BinaryIO ; +class BinaryIO; #include "CvrStgFile.h" -class SampleValue ; +class SampleValue; /** * \class JpegFile @@ -41,48 +41,48 @@ class SampleValue ; * This class uses the JPEG library by the IJG for access to jpeg files. **/ class JpegFile : public CvrStgFile { - public: - JpegFile (BinaryIO* io) ; - ~JpegFile (void) ; + public: + JpegFile(BinaryIO *io); + ~JpegFile(void); + + void read(BinaryIO *io); + void write(void); - void read (BinaryIO* io) ; - void write (void) ; + std::list getProperties(void) const; + std::vector getMatchingAlgorithms(Graph *g, Matching *m) const; - std::list getProperties (void) const ; - std::vector getMatchingAlgorithms (Graph* g, Matching* m) const ; - - unsigned long getNumSamples (void) const ; - void replaceSample (const SamplePos pos, const SampleValue* s) ; - SampleValue* getSampleValue (const SamplePos pos) const ; - EmbValue getEmbeddedValue (const SamplePos pos) const ; + unsigned long getNumSamples(void) const; + void replaceSample(const SamplePos pos, const SampleValue *s); + SampleValue *getSampleValue(const SamplePos pos) const; + EmbValue getEmbeddedValue(const SamplePos pos) const; #ifdef DEBUG - std::map* getFrequencies (void) ; - /** - * SampleKey is unsigned, jpeg dct coefficients are signed data. This function is a specialization - * of printFrequencies that converts the SampleKeys back to dct coefficient values before printing - * them and also prints the values starting from the lowest (negative) and ending with the highest - * (positive). - **/ - void printFrequencies (const std::map& freqs) ; + std::map *getFrequencies(void); + /** + * SampleKey is unsigned, jpeg dct coefficients are signed data. This function is a + *specialization of printFrequencies that converts the SampleKeys back to dct coefficient values + *before printing them and also prints the values starting from the lowest (negative) and ending + *with the highest (positive). + **/ + void printFrequencies(const std::map &freqs); #endif - private: - /// the number of dct coefficients per block - static const unsigned int CoeffPerBlock = 64 ; + private: + /// the number of dct coefficients per block + static const unsigned int CoeffPerBlock = 64; - static const unsigned short SamplesPerVertex = 3 ; - static const UWORD32 Radius = 1 ; - static const EmbValue EmbValueModulus = 2 ; + static const unsigned short SamplesPerVertex = 3; + static const UWORD32 Radius = 1; + static const EmbValue EmbValueModulus = 2; - struct jpeg_compress_struct CInfo ; - struct jpeg_decompress_struct DeCInfo ; - unsigned int* HeightInBlocks ; - unsigned int* WidthInBlocks ; - jvirt_barray_ptr* DctCoeffs ; + struct jpeg_compress_struct CInfo; + struct jpeg_decompress_struct DeCInfo; + unsigned int *HeightInBlocks; + unsigned int *WidthInBlocks; + jvirt_barray_ptr *DctCoeffs; - std::vector LinDctCoeffs ; - std::vector StegoIndices ; -} ; + std::vector LinDctCoeffs; + std::vector StegoIndices; +}; #endif // ndef SH_JPEGFILE_H diff --git a/src/JpegSampleValue.cc b/src/JpegSampleValue.cc index 9342642..a1e7205 100644 --- a/src/JpegSampleValue.cc +++ b/src/JpegSampleValue.cc @@ -18,81 +18,71 @@ * */ -#include #include +#include -#include "common.h" #include "JpegSampleValue.h" +#include "common.h" -JpegSampleValue::JpegSampleValue (int c) - : SampleValue(), DctCoeff (c) -{ - Key = (UWORD32) DctCoeff ; - EValue = calcEValue (DctCoeff) ; +JpegSampleValue::JpegSampleValue(int c) : SampleValue(), DctCoeff(c) { + Key = (UWORD32)DctCoeff; + EValue = calcEValue(DctCoeff); } -SampleValue *JpegSampleValue::getNearestTargetSampleValue (EmbValue t) const -{ - SWORD16 minvalue = 0, maxvalue = 0 ; +SampleValue *JpegSampleValue::getNearestTargetSampleValue(EmbValue t) const { + SWORD16 minvalue = 0, maxvalue = 0; - if (DctCoeff > 0) { - minvalue = 1 ; - maxvalue = SWORD16_MAX ; - } - else if (DctCoeff < 0) { - minvalue = SWORD16_MIN ; - maxvalue = -1 ; - } - else { - myassert(false) ; - } + if (DctCoeff > 0) { + minvalue = 1; + maxvalue = SWORD16_MAX; + } else if (DctCoeff < 0) { + minvalue = SWORD16_MIN; + maxvalue = -1; + } else { + myassert(false); + } - SWORD16 dctc_up = DctCoeff, dctc_down = DctCoeff, dctc_new = 0 ; - bool found = false ; - do { - if (dctc_up < maxvalue) { - dctc_up++ ; - } - if (dctc_down > minvalue) { - dctc_down-- ; - } + SWORD16 dctc_up = DctCoeff, dctc_down = DctCoeff, dctc_new = 0; + bool found = false; + do { + if (dctc_up < maxvalue) { + dctc_up++; + } + if (dctc_down > minvalue) { + dctc_down--; + } - if (calcEValue(dctc_up) == t && calcEValue(dctc_down) == t) { - if (RndSrc.getBool()) { - dctc_new = dctc_up ; - } - else { - dctc_new = dctc_down ; - } - found = true ; - } - else if (calcEValue(dctc_up) == t) { - dctc_new = dctc_up ; - found = true ; - } - else if (calcEValue(dctc_down) == t) { - dctc_new = dctc_down ; - found = true ; - } - } while (!found) ; + if (calcEValue(dctc_up) == t && calcEValue(dctc_down) == t) { + if (RndSrc.getBool()) { + dctc_new = dctc_up; + } else { + dctc_new = dctc_down; + } + found = true; + } else if (calcEValue(dctc_up) == t) { + dctc_new = dctc_up; + found = true; + } else if (calcEValue(dctc_down) == t) { + dctc_new = dctc_down; + found = true; + } + } while (!found); - return ((SampleValue *) new JpegSampleValue (dctc_new)) ; + return ((SampleValue *)new JpegSampleValue(dctc_new)); } -UWORD32 JpegSampleValue::calcDistance (const SampleValue *s) const -{ - const JpegSampleValue *sample = (const JpegSampleValue*) s ; - /* If s is not a JpegSampleValue then we get into real trouble here. - But calcDistance is called very often, a dynamic_cast costs a lot of time and - it does not make sense to pass anything but a JpegSampleValue as s anyway. */ +UWORD32 JpegSampleValue::calcDistance(const SampleValue *s) const { + const JpegSampleValue *sample = (const JpegSampleValue *)s; + /* If s is not a JpegSampleValue then we get into real trouble here. + But calcDistance is called very often, a dynamic_cast costs a lot of time and + it does not make sense to pass anything but a JpegSampleValue as s anyway. */ - int d = DctCoeff - sample->DctCoeff ; - return ((d >= 0) ? ((UWORD32) d) : ((UWORD32) -d)) ; + int d = DctCoeff - sample->DctCoeff; + return ((d >= 0) ? ((UWORD32)d) : ((UWORD32)-d)); } -std::string JpegSampleValue::getName (void) const -{ - char buf[128] ; - sprintf (buf, "%d", DctCoeff) ; - return std::string (buf) ; +std::string JpegSampleValue::getName(void) const { + char buf[128]; + sprintf(buf, "%d", DctCoeff); + return std::string(buf); } diff --git a/src/JpegSampleValue.h b/src/JpegSampleValue.h index f7bed27..814a5d7 100644 --- a/src/JpegSampleValue.h +++ b/src/JpegSampleValue.h @@ -24,21 +24,19 @@ #include "SampleValue.h" class JpegSampleValue : public SampleValue { - public: - JpegSampleValue (int c) ; + public: + JpegSampleValue(int c); - SampleValue* getNearestTargetSampleValue (EmbValue t) const ; - UWORD32 calcDistance (const SampleValue *s) const ; - std::string getName (void) const ; + SampleValue *getNearestTargetSampleValue(EmbValue t) const; + UWORD32 calcDistance(const SampleValue *s) const; + std::string getName(void) const; - SWORD16 getDctCoeff (void) const - { return DctCoeff ; } ; + SWORD16 getDctCoeff(void) const { return DctCoeff; }; - static EmbValue calcEValue (SWORD16 dctc) - { return (((dctc >= 0) ? dctc : -dctc) % 2) ; } ; + static EmbValue calcEValue(SWORD16 dctc) { return (((dctc >= 0) ? dctc : -dctc) % 2); }; - private: - SWORD16 DctCoeff ; -} ; + private: + SWORD16 DctCoeff; +}; #endif // ndef SH_JPEGSAMPLE_H diff --git a/src/MCryptPP.cc b/src/MCryptPP.cc index 7903de8..24f8a9c 100644 --- a/src/MCryptPP.cc +++ b/src/MCryptPP.cc @@ -22,8 +22,8 @@ #include #include -#include #include +#include #include @@ -34,290 +34,273 @@ #include "MHashKeyGen.h" #include "error.h" -MCryptPP::MCryptPP () -{ - ModuleOpen = false ; -} +MCryptPP::MCryptPP() { ModuleOpen = false; } -MCryptPP::MCryptPP (EncryptionAlgorithm a, EncryptionMode m) -{ - open (a, m) ; -} +MCryptPP::MCryptPP(EncryptionAlgorithm a, EncryptionMode m) { open(a, m); } -MCryptPP::~MCryptPP () -{ - if (ModuleOpen) { - close() ; - } +MCryptPP::~MCryptPP() { + if (ModuleOpen) { + close(); + } } -void MCryptPP::open (EncryptionAlgorithm a, EncryptionMode m) -{ - std::string tmp1 = a.getStringRep(), tmp2 = m.getStringRep() ; - char algo[tmp1.size() + 1], mode[tmp2.size() + 1] ; - strcpy (algo, tmp1.c_str()) ; - strcpy (mode, tmp2.c_str()) ; - - if ((MCryptD = mcrypt_module_open (algo, MCRYPTPP_LIBDIR, mode, MCRYPTPP_LIBDIR)) == MCRYPT_FAILED) { - throw SteghideError (_("could not open libmcrypt module \"%s\",\"%s\"."), algo, mode) ; - } - ModuleOpen = true ; +void MCryptPP::open(EncryptionAlgorithm a, EncryptionMode m) { + std::string tmp1 = a.getStringRep(), tmp2 = m.getStringRep(); + char algo[tmp1.size() + 1], mode[tmp2.size() + 1]; + strcpy(algo, tmp1.c_str()); + strcpy(mode, tmp2.c_str()); + + if ((MCryptD = mcrypt_module_open(algo, MCRYPTPP_LIBDIR, mode, MCRYPTPP_LIBDIR)) == + MCRYPT_FAILED) { + throw SteghideError(_("could not open libmcrypt module \"%s\",\"%s\"."), algo, mode); + } + ModuleOpen = true; } -void MCryptPP::close () -{ - mcrypt_module_close (MCryptD) ; - ModuleOpen = false ; +void MCryptPP::close() { + mcrypt_module_close(MCryptD); + ModuleOpen = false; } -BitString MCryptPP::encrypt (BitString p, std::string pp) -{ - p.padRandom (8 * mcrypt_enc_get_block_size (MCryptD)) ; // blocksize is 1 for stream algorithms - std::vector ciphertext = _encrypt (p.getBytes(), pp) ; - return BitString (ciphertext) ; +BitString MCryptPP::encrypt(BitString p, std::string pp) { + p.padRandom(8 * mcrypt_enc_get_block_size(MCryptD)); // blocksize is 1 for stream algorithms + std::vector ciphertext = _encrypt(p.getBytes(), pp); + return BitString(ciphertext); } -BitString MCryptPP::decrypt (BitString c, std::string pp) -{ - myassert (c.getLength() % (8 * mcrypt_enc_get_block_size (MCryptD)) == 0) ; - std::vector plaintext = _decrypt (c.getBytes(), pp) ; - return BitString (plaintext) ; +BitString MCryptPP::decrypt(BitString c, std::string pp) { + myassert(c.getLength() % (8 * mcrypt_enc_get_block_size(MCryptD)) == 0); + std::vector plaintext = _decrypt(c.getBytes(), pp); + return BitString(plaintext); } -void* MCryptPP::createKey (std::string pp) -{ - unsigned int keysize = mcrypt_enc_get_key_size (MCryptD) ; - MHashKeyGen keygen (KEYGEN_MCRYPT, MHASH_MD5, keysize) ; - std::vector key = keygen.createKey (pp) ; - unsigned char *retval = (unsigned char *) s_malloc (keysize) ; - for (unsigned int i = 0 ; i < keysize ; i++) { - retval[i] = key[i] ; - } - return retval ; +void *MCryptPP::createKey(std::string pp) { + unsigned int keysize = mcrypt_enc_get_key_size(MCryptD); + MHashKeyGen keygen(KEYGEN_MCRYPT, MHASH_MD5, keysize); + std::vector key = keygen.createKey(pp); + unsigned char *retval = (unsigned char *)s_malloc(keysize); + for (unsigned int i = 0; i < keysize; i++) { + retval[i] = key[i]; + } + return retval; } -std::vector MCryptPP::_encrypt (std::vector p, std::string pp) -{ - // genereate key and IV (if needed) - void *key = createKey (pp) ; - unsigned char *IV = NULL ; - if (mcrypt_enc_mode_has_iv (MCryptD)) { - unsigned int ivsize = mcrypt_enc_get_iv_size (MCryptD) ; - std::vector rndIV = RndSrc.getBytes (ivsize) ; - IV = (unsigned char *) s_malloc (ivsize) ; - for (unsigned int i = 0 ; i < ivsize ; i++) { - IV[i] = rndIV[i] ; - } - } - - // initialize libmcrypt thread - unsigned int keysize = mcrypt_enc_get_key_size (MCryptD) ; - int err = -1 ; - if ((err = mcrypt_generic_init (MCryptD, key, keysize, IV)) < 0) { - mcrypt_perror (err) ; - throw SteghideError (_("could not initialize libmcrypt encryption. see above error messages if any.")) ; - } - - // copy plaintext - unsigned int plntextlen = p.size() ; - myassert (plntextlen % mcrypt_enc_get_block_size (MCryptD) == 0) ; - unsigned char *plntext = (unsigned char *) s_malloc (plntextlen) ; - for (unsigned int i = 0 ; i < plntextlen ; i++) { - plntext[i] = p[i] ; - } - - // encrypt plaintext - if (mcrypt_generic (MCryptD, plntext, plntextlen) != 0) { - throw SteghideError (_("could not encrypt data.")) ; - } - - // create the return value - std::vector retval ; - unsigned int i = 0 ; - if (mcrypt_enc_mode_has_iv (MCryptD)) { - unsigned int ivsize = mcrypt_enc_get_iv_size (MCryptD) ; - retval = std::vector (ivsize + plntextlen) ; - for ( ; i < ivsize ; i++) { - retval[i] = IV[i] ; - } - } - else { - retval = std::vector (plntextlen) ; - } - for (unsigned int j = 0 ; j < plntextlen ; i++, j++) { - retval[i] = plntext[j] ; - } - - // clean up - if (mcrypt_generic_deinit (MCryptD) < 0) { - throw SteghideError (_("could not finish libmcrypt encryption.")) ; - } - free (plntext) ; - free (key) ; - if (mcrypt_enc_mode_has_iv (MCryptD)) { - free (IV) ; - } - - return retval ; +std::vector MCryptPP::_encrypt(std::vector p, std::string pp) { + // genereate key and IV (if needed) + void *key = createKey(pp); + unsigned char *IV = NULL; + if (mcrypt_enc_mode_has_iv(MCryptD)) { + unsigned int ivsize = mcrypt_enc_get_iv_size(MCryptD); + std::vector rndIV = RndSrc.getBytes(ivsize); + IV = (unsigned char *)s_malloc(ivsize); + for (unsigned int i = 0; i < ivsize; i++) { + IV[i] = rndIV[i]; + } + } + + // initialize libmcrypt thread + unsigned int keysize = mcrypt_enc_get_key_size(MCryptD); + int err = -1; + if ((err = mcrypt_generic_init(MCryptD, key, keysize, IV)) < 0) { + mcrypt_perror(err); + throw SteghideError(_("could not initialize libmcrypt encryption. see " + "above error messages if any.")); + } + + // copy plaintext + unsigned int plntextlen = p.size(); + myassert(plntextlen % mcrypt_enc_get_block_size(MCryptD) == 0); + unsigned char *plntext = (unsigned char *)s_malloc(plntextlen); + for (unsigned int i = 0; i < plntextlen; i++) { + plntext[i] = p[i]; + } + + // encrypt plaintext + if (mcrypt_generic(MCryptD, plntext, plntextlen) != 0) { + throw SteghideError(_("could not encrypt data.")); + } + + // create the return value + std::vector retval; + unsigned int i = 0; + if (mcrypt_enc_mode_has_iv(MCryptD)) { + unsigned int ivsize = mcrypt_enc_get_iv_size(MCryptD); + retval = std::vector(ivsize + plntextlen); + for (; i < ivsize; i++) { + retval[i] = IV[i]; + } + } else { + retval = std::vector(plntextlen); + } + for (unsigned int j = 0; j < plntextlen; i++, j++) { + retval[i] = plntext[j]; + } + + // clean up + if (mcrypt_generic_deinit(MCryptD) < 0) { + throw SteghideError(_("could not finish libmcrypt encryption.")); + } + free(plntext); + free(key); + if (mcrypt_enc_mode_has_iv(MCryptD)) { + free(IV); + } + + return retval; } -std::vector MCryptPP::_decrypt (std::vector c, std::string pp) -{ - // generate key - void *key = createKey (pp) ; - unsigned char *IV = NULL ; - unsigned int cstart = 0 ; - if (mcrypt_enc_mode_has_iv (MCryptD)) { - unsigned int ivsize = mcrypt_enc_get_iv_size (MCryptD) ; - IV = (unsigned char *) s_malloc (ivsize) ; - for (unsigned int i = 0 ; i < ivsize ; i++) { - IV[i] = c[i] ; - } - cstart = ivsize ; - } - - // initialize libmcrypt thread - unsigned int keysize = mcrypt_enc_get_key_size (MCryptD) ; - int err = -1 ; - if ((err = mcrypt_generic_init (MCryptD, key, keysize, IV)) < 0) { - mcrypt_perror (err) ; - throw SteghideError (_("could not initialize libmcrypt decryption. see above error messages if any.")) ; - } - - // copy ciphertext - unsigned long ciphertextlen = c.size() - cstart ; - myassert (ciphertextlen % mcrypt_enc_get_block_size (MCryptD) == 0) ; - unsigned char *ciphertext = (unsigned char *) s_malloc (ciphertextlen) ; - for (unsigned int i = 0 ; i < ciphertextlen ; i++) { - ciphertext[i] = c[cstart + i] ; - } - - // decrypt ciphertext - if (mdecrypt_generic (MCryptD, ciphertext, ciphertextlen) != 0) { - throw SteghideError (_("could not decrypt data.")) ; - } - - // create return value - std::vector retval (ciphertextlen) ; - for (unsigned int i = 0 ; i < ciphertextlen ; i++) { - retval[i] = ciphertext[i] ; - } - - // clean up - if (mcrypt_generic_deinit (MCryptD) < 0) { - throw SteghideError (_("could not finish libmcrypt decryption.")) ; - } - free (ciphertext) ; - free (key) ; - if (mcrypt_enc_mode_has_iv (MCryptD)) { - free (IV) ; - } - - return retval ; +std::vector MCryptPP::_decrypt(std::vector c, std::string pp) { + // generate key + void *key = createKey(pp); + unsigned char *IV = NULL; + unsigned int cstart = 0; + if (mcrypt_enc_mode_has_iv(MCryptD)) { + unsigned int ivsize = mcrypt_enc_get_iv_size(MCryptD); + IV = (unsigned char *)s_malloc(ivsize); + for (unsigned int i = 0; i < ivsize; i++) { + IV[i] = c[i]; + } + cstart = ivsize; + } + + // initialize libmcrypt thread + unsigned int keysize = mcrypt_enc_get_key_size(MCryptD); + int err = -1; + if ((err = mcrypt_generic_init(MCryptD, key, keysize, IV)) < 0) { + mcrypt_perror(err); + throw SteghideError(_("could not initialize libmcrypt decryption. see " + "above error messages if any.")); + } + + // copy ciphertext + unsigned long ciphertextlen = c.size() - cstart; + myassert(ciphertextlen % mcrypt_enc_get_block_size(MCryptD) == 0); + unsigned char *ciphertext = (unsigned char *)s_malloc(ciphertextlen); + for (unsigned int i = 0; i < ciphertextlen; i++) { + ciphertext[i] = c[cstart + i]; + } + + // decrypt ciphertext + if (mdecrypt_generic(MCryptD, ciphertext, ciphertextlen) != 0) { + throw SteghideError(_("could not decrypt data.")); + } + + // create return value + std::vector retval(ciphertextlen); + for (unsigned int i = 0; i < ciphertextlen; i++) { + retval[i] = ciphertext[i]; + } + + // clean up + if (mcrypt_generic_deinit(MCryptD) < 0) { + throw SteghideError(_("could not finish libmcrypt decryption.")); + } + free(ciphertext); + free(key); + if (mcrypt_enc_mode_has_iv(MCryptD)) { + free(IV); + } + + return retval; } -EncryptionAlgorithm MCryptPP::getAlgorithm () const -{ - myassert (ModuleOpen) ; - char *name = mcrypt_enc_get_algorithms_name (MCryptD) ; - return EncryptionAlgorithm (name) ; +EncryptionAlgorithm MCryptPP::getAlgorithm() const { + myassert(ModuleOpen); + char *name = mcrypt_enc_get_algorithms_name(MCryptD); + return EncryptionAlgorithm(name); } -EncryptionMode MCryptPP::getMode () const -{ - myassert (ModuleOpen) ; - char *name = mcrypt_enc_get_modes_name (MCryptD) ; - return EncryptionMode (name) ; +EncryptionMode MCryptPP::getMode() const { + myassert(ModuleOpen); + char *name = mcrypt_enc_get_modes_name(MCryptD); + return EncryptionMode(name); } -unsigned long MCryptPP::getEncryptedSize (EncryptionAlgorithm a, EncryptionMode m, unsigned long plnsize) -{ - unsigned long retval = 0 ; - - if (a.getIntegerRep() == EncryptionAlgorithm::NONE) { - retval = plnsize ; - } - else { - std::string tmp1 = a.getStringRep(), tmp2 = m.getStringRep() ; - char algo[tmp1.size() + 1], mode[tmp2.size() + 1] ; - strcpy (algo, tmp1.c_str()) ; - strcpy (mode, tmp2.c_str()) ; - - MCRYPT td ; - if ((td = mcrypt_module_open (algo, MCRYPTPP_LIBDIR, mode, MCRYPTPP_LIBDIR)) == MCRYPT_FAILED) { - throw SteghideError (_("could not open libmcrypt module \"%s\",\"%s\"."), algo, mode) ; - } - - if (mcrypt_enc_mode_has_iv (td)) { - retval += (8 * mcrypt_enc_get_iv_size(td)) ; - } - - unsigned long blocks = 0 ; - const unsigned long blocksize = 8 * mcrypt_enc_get_block_size(td) ; // is 1 for stream algorithms - if (plnsize % blocksize == 0) { - blocks = plnsize / blocksize ; - } - else { - blocks = (plnsize / blocksize) + 1; - } - retval += (blocks * blocksize) ; - - mcrypt_module_close (td) ; - } - - return retval ; +unsigned long MCryptPP::getEncryptedSize(EncryptionAlgorithm a, EncryptionMode m, + unsigned long plnsize) { + unsigned long retval = 0; + + if (a.getIntegerRep() == EncryptionAlgorithm::NONE) { + retval = plnsize; + } else { + std::string tmp1 = a.getStringRep(), tmp2 = m.getStringRep(); + char algo[tmp1.size() + 1], mode[tmp2.size() + 1]; + strcpy(algo, tmp1.c_str()); + strcpy(mode, tmp2.c_str()); + + MCRYPT td; + if ((td = mcrypt_module_open(algo, MCRYPTPP_LIBDIR, mode, MCRYPTPP_LIBDIR)) == + MCRYPT_FAILED) { + throw SteghideError(_("could not open libmcrypt module \"%s\",\"%s\"."), algo, mode); + } + + if (mcrypt_enc_mode_has_iv(td)) { + retval += (8 * mcrypt_enc_get_iv_size(td)); + } + + unsigned long blocks = 0; + const unsigned long blocksize = + 8 * mcrypt_enc_get_block_size(td); // is 1 for stream algorithms + if (plnsize % blocksize == 0) { + blocks = plnsize / blocksize; + } else { + blocks = (plnsize / blocksize) + 1; + } + retval += (blocks * blocksize); + + mcrypt_module_close(td); + } + + return retval; } -std::vector MCryptPP::getListAlgorithms () -{ - int size = 0 ; - char **list = mcrypt_list_algorithms (MCRYPTPP_LIBDIR, &size) ; - - /** - * There is a bug in libmcrypt, at least in version 2.5.5 that has the - * effect that the algorithm list contains every algorithm twice. - **/ - - std::vector retval ; - for (int i = 0 ; i < size ; i++) { - if ((i == 0) || (strcmp(list[i], list[i - 1]) != 0)) { // workaround for the bug mentioned above - retval.push_back (std::string (list[i])) ; - } - } - mcrypt_free_p (list, size) ; - - return retval ; +std::vector MCryptPP::getListAlgorithms() { + int size = 0; + char **list = mcrypt_list_algorithms(MCRYPTPP_LIBDIR, &size); + + /** + * There is a bug in libmcrypt, at least in version 2.5.5 that has the + * effect that the algorithm list contains every algorithm twice. + **/ + + std::vector retval; + for (int i = 0; i < size; i++) { + if ((i == 0) || + (strcmp(list[i], list[i - 1]) != 0)) { // workaround for the bug mentioned above + retval.push_back(std::string(list[i])); + } + } + mcrypt_free_p(list, size); + + return retval; } -std::vector MCryptPP::getListModes () -{ - int size = 0 ; - char **list = mcrypt_list_modes (MCRYPTPP_LIBDIR, &size) ; +std::vector MCryptPP::getListModes() { + int size = 0; + char **list = mcrypt_list_modes(MCRYPTPP_LIBDIR, &size); - std::vector retval ; - for (int i = 0 ; i < size ; i++) { - retval.push_back (std::string (list[i])) ; - } - mcrypt_free_p (list, size) ; + std::vector retval; + for (int i = 0; i < size; i++) { + retval.push_back(std::string(list[i])); + } + mcrypt_free_p(list, size); - return retval ; + return retval; } -bool MCryptPP::AlgoSupportsMode (EncryptionAlgorithm a, EncryptionMode m) -{ - std::string tmp1 = a.getStringRep(), tmp2 = m.getStringRep() ; - char algo[tmp1.size() + 1], mode[tmp2.size() + 1] ; - strcpy (algo, tmp1.c_str()) ; - strcpy (mode, tmp2.c_str()) ; +bool MCryptPP::AlgoSupportsMode(EncryptionAlgorithm a, EncryptionMode m) { + std::string tmp1 = a.getStringRep(), tmp2 = m.getStringRep(); + char algo[tmp1.size() + 1], mode[tmp2.size() + 1]; + strcpy(algo, tmp1.c_str()); + strcpy(mode, tmp2.c_str()); - return (mcrypt_module_is_block_algorithm (algo, MCRYPTPP_LIBDIR) == - mcrypt_module_is_block_algorithm_mode (mode, MCRYPTPP_LIBDIR)) ; + return (mcrypt_module_is_block_algorithm(algo, MCRYPTPP_LIBDIR) == + mcrypt_module_is_block_algorithm_mode(mode, MCRYPTPP_LIBDIR)); } -void *MCryptPP::s_malloc (size_t size) -{ - void *retval = NULL ; - if ((retval = malloc (size)) == NULL) { - throw SteghideError (_("could not allocate memory.")) ; - } - return retval ; +void *MCryptPP::s_malloc(size_t size) { + void *retval = NULL; + if ((retval = malloc(size)) == NULL) { + throw SteghideError(_("could not allocate memory.")); + } + return retval; } diff --git a/src/MCryptPP.h b/src/MCryptPP.h index beebea9..b9fae66 100644 --- a/src/MCryptPP.h +++ b/src/MCryptPP.h @@ -27,93 +27,92 @@ #include -class BitString ; -class EncryptionAlgorithm ; -class EncryptionMode ; +class BitString; +class EncryptionAlgorithm; +class EncryptionMode; #define MCRYPTPP_LIBDIR NULL class MCryptPP { - public: - MCryptPP (void) ; - MCryptPP (EncryptionAlgorithm a, EncryptionMode m) ; - - ~MCryptPP (void) ; - - /** - * open the libmcrypt module algo/mode - * \param a the encryption algorithm - * \param m the encryption mode (must be supported by the given encryption algorithm) - **/ - void open (EncryptionAlgorithm a, EncryptionMode m) ; - - /** - * close the opened libmcrypt module - **/ - void close (void) ; - - /** - * encrypt p using pp as passphrase - * \param p the plaintext to be encrypted - * \param pp the passphrase - * \return the encrypted data (with the IV as first block (if an IV is used by this mode)) - **/ - BitString encrypt (BitString p, std::string pp) ; - - /** - * decrypt c using pp as passphrase - * \param c the ciphertext to be decrypted (with the IV as first block (if an IV is used by this mode)) - * \param pp the passphrase - * \return the plain data data (without IV) - **/ - BitString decrypt (BitString c, std::string pp) ; - - EncryptionAlgorithm getAlgorithm (void) const ; - EncryptionMode getMode (void) const ; - - /** - * get the size of an encryption result - * \param a the algorithm to be used for encryption - * \param m the mode to be used for encryption - * \param plnsize the size of the plaintext (in bits) - * \return the size the ciphertext would have (in bits and including the IV) - **/ - static unsigned long getEncryptedSize (EncryptionAlgorithm a, EncryptionMode m, unsigned long plnsize) ; - - static std::vector getListModes (void) ; - static std::vector getListAlgorithms (void) ; - - static bool AlgoSupportsMode (EncryptionAlgorithm a, EncryptionMode m) ; - - protected: - void *createKey (std::string pp) ; - - /** - * do the actual encryption - * \param p the plaintext to be encrypted - * \param pp the passphrase - * \return the encrypted data (with the IV as first block (if an IV is used by this mode)) - * - * The size of p must be a multiple of the blocksize of the encryption algorithm. - **/ - std::vector _encrypt (std::vector p, std::string pp) ; - - /** - * do the actual decryption - * \param c the ciphertext to be decrypted (with the IV as first block (if an IV is used by this mode)) - * \param pp the passphrase - * \return the decrypted data - * - * The size of c must be a multiple of the blocksize of the encryption algorithm. - **/ - std::vector _decrypt (std::vector c, std::string pp) ; - - private: - /// true iff CryptD contains a valid encryption descriptor - bool ModuleOpen ; - MCRYPT MCryptD ; - - void *s_malloc (size_t size) ; -} ; + public: + MCryptPP(void); + MCryptPP(EncryptionAlgorithm a, EncryptionMode m); + + ~MCryptPP(void); + + /** + * open the libmcrypt module algo/mode + * \param a the encryption algorithm + * \param m the encryption mode (must be supported by the given encryption algorithm) + **/ + void open(EncryptionAlgorithm a, EncryptionMode m); + + /** + * close the opened libmcrypt module + **/ + void close(void); + + /** + * encrypt p using pp as passphrase + * \param p the plaintext to be encrypted + * \param pp the passphrase + * \return the encrypted data (with the IV as first block (if an IV is used by this mode)) + **/ + BitString encrypt(BitString p, std::string pp); + + /** + * decrypt c using pp as passphrase + * \param c the ciphertext to be decrypted (with the IV as first block (if an IV is used by this + *mode)) \param pp the passphrase \return the plain data data (without IV) + **/ + BitString decrypt(BitString c, std::string pp); + + EncryptionAlgorithm getAlgorithm(void) const; + EncryptionMode getMode(void) const; + + /** + * get the size of an encryption result + * \param a the algorithm to be used for encryption + * \param m the mode to be used for encryption + * \param plnsize the size of the plaintext (in bits) + * \return the size the ciphertext would have (in bits and including the IV) + **/ + static unsigned long getEncryptedSize(EncryptionAlgorithm a, EncryptionMode m, + unsigned long plnsize); + + static std::vector getListModes(void); + static std::vector getListAlgorithms(void); + + static bool AlgoSupportsMode(EncryptionAlgorithm a, EncryptionMode m); + + protected: + void *createKey(std::string pp); + + /** + * do the actual encryption + * \param p the plaintext to be encrypted + * \param pp the passphrase + * \return the encrypted data (with the IV as first block (if an IV is used by this mode)) + * + * The size of p must be a multiple of the blocksize of the encryption algorithm. + **/ + std::vector _encrypt(std::vector p, std::string pp); + + /** + * do the actual decryption + * \param c the ciphertext to be decrypted (with the IV as first block (if an IV is used by this + *mode)) \param pp the passphrase \return the decrypted data + * + * The size of c must be a multiple of the blocksize of the encryption algorithm. + **/ + std::vector _decrypt(std::vector c, std::string pp); + + private: + /// true iff CryptD contains a valid encryption descriptor + bool ModuleOpen; + MCRYPT MCryptD; + + void *s_malloc(size_t size); +}; #endif // ndef SH_MCRYPTPP_H diff --git a/src/MHashKeyGen.cc b/src/MHashKeyGen.cc index c7a764b..4753cb4 100644 --- a/src/MHashKeyGen.cc +++ b/src/MHashKeyGen.cc @@ -18,101 +18,87 @@ * */ -#include #include +#include +#include #include +#include "MHashKeyGen.h" #include "common.h" #include "error.h" -#include "MHashKeyGen.h" -MHashKeyGen::MHashKeyGen () -{ - AlgorithmData.count = 0 ; - AlgorithmData.salt = NULL ; - AlgorithmData.salt_size = 0 ; +MHashKeyGen::MHashKeyGen() { + AlgorithmData.count = 0; + AlgorithmData.salt = NULL; + AlgorithmData.salt_size = 0; } -MHashKeyGen::MHashKeyGen (keygenid kgalgo, hashid halgo, unsigned int keysize) -{ - setKeyGenAlgorithm (kgalgo) ; - setKeySize (keysize) ; - setHashAlgorithm (halgo) ; - AlgorithmData.count = 0 ; - AlgorithmData.salt = NULL ; - AlgorithmData.salt_size = 0 ; +MHashKeyGen::MHashKeyGen(keygenid kgalgo, hashid halgo, unsigned int keysize) { + setKeyGenAlgorithm(kgalgo); + setKeySize(keysize); + setHashAlgorithm(halgo); + AlgorithmData.count = 0; + AlgorithmData.salt = NULL; + AlgorithmData.salt_size = 0; } -MHashKeyGen::~MHashKeyGen () -{ - if (AlgorithmData.salt != NULL) { - free (AlgorithmData.salt) ; - } +MHashKeyGen::~MHashKeyGen() { + if (AlgorithmData.salt != NULL) { + free(AlgorithmData.salt); + } } -std::vector MHashKeyGen::createKey (std::string password) -{ - char *passwd = (char *) s_malloc (password.size() + 1) ; - strcpy (passwd, password.c_str()) ; - int passwdlen = strlen (passwd) ; - unsigned char *key = (unsigned char *) s_malloc (KeySize) ; +std::vector MHashKeyGen::createKey(std::string password) { + char *passwd = (char *)s_malloc(password.size() + 1); + strcpy(passwd, password.c_str()); + int passwdlen = strlen(passwd); + unsigned char *key = (unsigned char *)s_malloc(KeySize); - if (mhash_keygen_ext (Algorithm, AlgorithmData, key, KeySize, (unsigned char *) passwd, passwdlen) < 0) { - throw SteghideError (_("could not generate key using libmhash.")) ; - } + if (mhash_keygen_ext(Algorithm, AlgorithmData, key, KeySize, (unsigned char *)passwd, + passwdlen) < 0) { + throw SteghideError(_("could not generate key using libmhash.")); + } - std::vector retval (KeySize) ; - for (unsigned int i = 0 ; i < KeySize ; i++) { - retval[i] = key[i] ; - } + std::vector retval(KeySize); + for (unsigned int i = 0; i < KeySize; i++) { + retval[i] = key[i]; + } - free (passwd) ; - free (key) ; + free(passwd); + free(key); - return retval ; + return retval; } -void MHashKeyGen::setKeySize (unsigned int keysize) -{ - KeySize = keysize ; -} +void MHashKeyGen::setKeySize(unsigned int keysize) { KeySize = keysize; } -void MHashKeyGen::setKeyGenAlgorithm (keygenid algo) -{ - Algorithm = algo ; -} +void MHashKeyGen::setKeyGenAlgorithm(keygenid algo) { Algorithm = algo; } -void MHashKeyGen::setHashAlgorithm (hashid hashalgo) -{ - AlgorithmData.hash_algorithm[0] = hashalgo ; -} +void MHashKeyGen::setHashAlgorithm(hashid hashalgo) { AlgorithmData.hash_algorithm[0] = hashalgo; } -void MHashKeyGen::setHashAlgorithms (std::vector hashalgos) -{ - myassert (hashalgos.size() <= 2) ; - for (unsigned int i = 0 ; i < hashalgos.size() ; i++) { - AlgorithmData.hash_algorithm[i] = hashalgos[i] ; - } +void MHashKeyGen::setHashAlgorithms(std::vector hashalgos) { + myassert(hashalgos.size() <= 2); + for (unsigned int i = 0; i < hashalgos.size(); i++) { + AlgorithmData.hash_algorithm[i] = hashalgos[i]; + } } -void MHashKeyGen::setSalt (std::vector salt) -{ - AlgorithmData.salt_size = salt.size() ; - if (AlgorithmData.salt != NULL) { - free (AlgorithmData.salt) ; - } - AlgorithmData.salt = s_malloc (AlgorithmData.salt_size) ; - unsigned char *tmp = (unsigned char *) AlgorithmData.salt ; - for (unsigned int i = 0 ; i < AlgorithmData.salt_size ; i++) { - tmp[i] = salt[i] ; - } +void MHashKeyGen::setSalt(std::vector salt) { + AlgorithmData.salt_size = salt.size(); + if (AlgorithmData.salt != NULL) { + free(AlgorithmData.salt); + } + AlgorithmData.salt = s_malloc(AlgorithmData.salt_size); + unsigned char *tmp = (unsigned char *)AlgorithmData.salt; + for (unsigned int i = 0; i < AlgorithmData.salt_size; i++) { + tmp[i] = salt[i]; + } } -void *MHashKeyGen::s_malloc (size_t size) -{ - void *retval = NULL ; - if ((retval = malloc (size)) == NULL) { - throw SteghideError (_("could not allocate memory.")) ; - } - return retval ; +void *MHashKeyGen::s_malloc(size_t size) { + void *retval = NULL; + if ((retval = malloc(size)) == NULL) { + throw SteghideError(_("could not allocate memory.")); + } + return retval; } diff --git a/src/MHashKeyGen.h b/src/MHashKeyGen.h index 0a819cb..fde47c4 100644 --- a/src/MHashKeyGen.h +++ b/src/MHashKeyGen.h @@ -26,26 +26,26 @@ #include class MHashKeyGen { - public: - MHashKeyGen (void) ; - MHashKeyGen (keygenid kgalgo, hashid halgo, unsigned int keysize) ; - ~MHashKeyGen (void) ; - - void setKeySize (unsigned int KeySize) ; - void setKeyGenAlgorithm (keygenid algo) ; - void setHashAlgorithm (hashid hashalgo) ; - void setHashAlgorithms (std::vector hashalgos) ; - void setSalt (std::vector salt) ; - - std::vector createKey (std::string password) ; - - private: - bool ready ; - keygenid Algorithm ; - KEYGEN AlgorithmData ; - unsigned int KeySize ; - - void *s_malloc (size_t size) ; -} ; + public: + MHashKeyGen(void); + MHashKeyGen(keygenid kgalgo, hashid halgo, unsigned int keysize); + ~MHashKeyGen(void); + + void setKeySize(unsigned int KeySize); + void setKeyGenAlgorithm(keygenid algo); + void setHashAlgorithm(hashid hashalgo); + void setHashAlgorithms(std::vector hashalgos); + void setSalt(std::vector salt); + + std::vector createKey(std::string password); + + private: + bool ready; + keygenid Algorithm; + KEYGEN AlgorithmData; + unsigned int KeySize; + + void *s_malloc(size_t size); +}; #endif // ndef SH_MHASHKEYGEN_H diff --git a/src/MHashPP.cc b/src/MHashPP.cc index b10900d..a9098a2 100644 --- a/src/MHashPP.cc +++ b/src/MHashPP.cc @@ -24,122 +24,107 @@ #include #include "BitString.h" +#include "MHashPP.h" #include "common.h" #include "error.h" -#include "MHashPP.h" -MHashPP::MHashPP () -{ - hashing = false ; - HashBytesValid = false ; +MHashPP::MHashPP() { + hashing = false; + HashBytesValid = false; } -MHashPP::MHashPP (hashid id) -{ - init (id) ; -} +MHashPP::MHashPP(hashid id) { init(id); } -void MHashPP::init (hashid id) -{ - if ((HashD = mhash_init (id)) == MHASH_FAILED) { - throw SteghideError (_("could not initialize libmhash %s algorithm."), getAlgorithmName(id).c_str()) ; - } - hashing = true ; - HashBytesValid = false ; +void MHashPP::init(hashid id) { + if ((HashD = mhash_init(id)) == MHASH_FAILED) { + throw SteghideError(_("could not initialize libmhash %s algorithm."), + getAlgorithmName(id).c_str()); + } + hashing = true; + HashBytesValid = false; } -const std::vector& MHashPP::end () -{ - myassert (hashing) ; - - unsigned int n = getHashSize() ; - HashBytes = std::vector (n) ; - BYTE hash[n] ; - mhash_deinit (HashD, hash) ; - hashing = false ; - for (unsigned int i = 0 ; i < n ; i++) { - HashBytes[i] = hash[i] ; - } - - HashBytesValid = true ; - return HashBytes ; +const std::vector &MHashPP::end() { + myassert(hashing); + + unsigned int n = getHashSize(); + HashBytes = std::vector(n); + BYTE hash[n]; + mhash_deinit(HashD, hash); + hashing = false; + for (unsigned int i = 0; i < n; i++) { + HashBytes[i] = hash[i]; + } + + HashBytesValid = true; + return HashBytes; } -unsigned int MHashPP::getHashSize (void) -{ - myassert (hashing) ; - return ((unsigned int) mhash_get_block_size (mhash_get_mhash_algo (HashD))) ; +unsigned int MHashPP::getHashSize(void) { + myassert(hashing); + return ((unsigned int)mhash_get_block_size(mhash_get_mhash_algo(HashD))); } -MHashPP& MHashPP::operator<< (std::string v) -{ - myassert (hashing) ; - mhash (HashD, v.data(), v.size()) ; - return *this ; +MHashPP &MHashPP::operator<<(std::string v) { + myassert(hashing); + mhash(HashD, v.data(), v.size()); + return *this; } -MHashPP& MHashPP::operator<< (BitString v) -{ - myassert (hashing) ; - myassert (v.getLength() % 8 == 0) ; +MHashPP &MHashPP::operator<<(BitString v) { + myassert(hashing); + myassert(v.getLength() % 8 == 0); - unsigned long n = v.getLength() / 8 ; - for (unsigned int i = 0 ; i < n ; i++) { - (*this) << (BYTE) v.getValue (8 * i, 8) ; - } + unsigned long n = v.getLength() / 8; + for (unsigned int i = 0; i < n; i++) { + (*this) << (BYTE)v.getValue(8 * i, 8); + } - return *this ; + return *this; } -MHashPP& MHashPP::operator<< (BYTE v) -{ - myassert (hashing) ; - mhash (HashD, &v, 1) ; - return *this ; +MHashPP &MHashPP::operator<<(BYTE v) { + myassert(hashing); + mhash(HashD, &v, 1); + return *this; } -MHashPP& MHashPP::operator<< (MHashPP::Command c) -{ - switch (c) { - case endhash: - HashBytes = end() ; - break ; - - default: - myassert (0) ; - break ; - } - return *this ; +MHashPP &MHashPP::operator<<(MHashPP::Command c) { + switch (c) { + case endhash: + HashBytes = end(); + break; + + default: + myassert(0); + break; + } + return *this; } -std::string MHashPP::getAlgorithmName () -{ - myassert (hashing) ; - return getAlgorithmName (mhash_get_mhash_algo (HashD)) ; +std::string MHashPP::getAlgorithmName() { + myassert(hashing); + return getAlgorithmName(mhash_get_mhash_algo(HashD)); } -std::string MHashPP::getAlgorithmName (hashid id) -{ - char *name = (char*) mhash_get_hash_name (id) ; - std::string retval ; - if (name == NULL) { - retval = std::string ("") ; - } - else { - retval = std::string (name) ; - } - free (name) ; - return retval ; +std::string MHashPP::getAlgorithmName(hashid id) { + char *name = (char *)mhash_get_hash_name(id); + std::string retval; + if (name == NULL) { + retval = std::string(""); + } else { + retval = std::string(name); + } + free(name); + return retval; } -BitString MHashPP::getHashBits () -{ - myassert (HashBytesValid) ; - return BitString (HashBytes) ; +BitString MHashPP::getHashBits() { + myassert(HashBytesValid); + return BitString(HashBytes); } -const std::vector& MHashPP::getHashBytes() -{ - myassert (HashBytesValid) ; - return HashBytes ; +const std::vector &MHashPP::getHashBytes() { + myassert(HashBytesValid); + return HashBytes; } diff --git a/src/MHashPP.h b/src/MHashPP.h index 82a1502..6bace1d 100644 --- a/src/MHashPP.h +++ b/src/MHashPP.h @@ -25,68 +25,69 @@ #include "common.h" -class BitString ; +class BitString; class MHashPP { - public: - enum Command { endhash } ; - - MHashPP (void) ; - MHashPP (hashid a) ; - - void init (hashid a) ; - - const std::vector& end (void) ; - - /** - * feed the std::string v to the hashing algorithm - * \param v the std::string to be feeded to the hashing algorithm (without '\0' at the end) - **/ - MHashPP& operator<< (std::string v) ; - - /** - * feed the BitString v to the hashing algorithm - * \param v the BitString to be feeded to the hashing algorithm (v.getLength() % 8 == 0 must hold) - **/ - MHashPP& operator<< (BitString v) ; - - /** - * feed the byte v to the hashing algorithm - * \param v the byte to be feeded to the hashing algorithm - **/ - MHashPP& operator<< (BYTE v) ; - - /** - * interpret the command c - * \param c a command (member of MHashPP::Command) - **/ - MHashPP& operator<< (Command c) ; - - /** - * get the hash bits - * \return the hash value of the data that has been passed via << - **/ - BitString getHashBits (void) ; - - const std::vector& getHashBytes (void) ; - - /** - * get the hash size - * \return the size of the value returned by getHashBits in bytes - **/ - unsigned int getHashSize (void) ; - - private: - /// true iff HashD contains a legal hash descriptor and data can be passed via << - bool hashing ; - MHASH HashD ; - - /// true iff HashBytes contains a valid hash value - bool HashBytesValid ; - std::vector HashBytes ; - - std::string getAlgorithmName (void) ; - static std::string getAlgorithmName (hashid id) ; -} ; + public: + enum Command { endhash }; + + MHashPP(void); + MHashPP(hashid a); + + void init(hashid a); + + const std::vector &end(void); + + /** + * feed the std::string v to the hashing algorithm + * \param v the std::string to be feeded to the hashing algorithm (without '\0' at the end) + **/ + MHashPP &operator<<(std::string v); + + /** + * feed the BitString v to the hashing algorithm + * \param v the BitString to be feeded to the hashing algorithm (v.getLength() % 8 == 0 must + *hold) + **/ + MHashPP &operator<<(BitString v); + + /** + * feed the byte v to the hashing algorithm + * \param v the byte to be feeded to the hashing algorithm + **/ + MHashPP &operator<<(BYTE v); + + /** + * interpret the command c + * \param c a command (member of MHashPP::Command) + **/ + MHashPP &operator<<(Command c); + + /** + * get the hash bits + * \return the hash value of the data that has been passed via << + **/ + BitString getHashBits(void); + + const std::vector &getHashBytes(void); + + /** + * get the hash size + * \return the size of the value returned by getHashBits in bytes + **/ + unsigned int getHashSize(void); + + private: + /// true iff HashD contains a legal hash descriptor and data can be passed via << + bool hashing; + MHASH HashD; + + /// true iff HashBytes contains a valid hash value + bool HashBytesValid; + std::vector HashBytes; + + std::string getAlgorithmName(void); + static std::string getAlgorithmName(hashid id); +}; #endif // ndef SH_MHASHPP_H diff --git a/src/Matching.cc b/src/Matching.cc index 9bbf484..c373469 100644 --- a/src/Matching.cc +++ b/src/Matching.cc @@ -18,345 +18,342 @@ * */ +#include "Matching.h" #include "Edge.h" #include "Graph.h" -#include "Matching.h" #include "ProgressOutput.h" #include "common.h" #include "msg.h" #include -Matching::Matching (Graph* g, ProgressOutput* po) - : TheGraph(g), PrOut(po) -{ - unsigned long nvertices = TheGraph->getNumVertices() ; - for (unsigned long i = 0 ; i < nvertices ; i++) { - ExposedVertices.push_back (TheGraph->getVertex (i)) ; - } +Matching::Matching(Graph *g, ProgressOutput *po) : TheGraph(g), PrOut(po) { + unsigned long nvertices = TheGraph->getNumVertices(); + for (unsigned long i = 0; i < nvertices; i++) { + ExposedVertices.push_back(TheGraph->getVertex(i)); + } - VertexInformation.reserve (nvertices) ; - for (std::list::iterator i = ExposedVertices.begin() ; i != ExposedVertices.end() ; i++) { - VertexInformation.push_back (VertexInfo (i)) ; - } + VertexInformation.reserve(nvertices); + for (std::list::iterator i = ExposedVertices.begin(); i != ExposedVertices.end(); + i++) { + VertexInformation.push_back(VertexInfo(i)); + } - Cardinality = 0 ; + Cardinality = 0; } -Matching::~Matching () -{ - for (std::list::iterator edgeit = MatchingEdges.begin() ; edgeit != MatchingEdges.end() ; edgeit++) { - delete (*edgeit) ; - } +Matching::~Matching() { + for (std::list::iterator edgeit = MatchingEdges.begin(); edgeit != MatchingEdges.end(); + edgeit++) { + delete *edgeit; + } } -bool Matching::includesEdge (const Edge& e) const -{ - Vertex* v1 = e.getVertex1() ; - Vertex* v2 = e.getVertex2() ; - bool v1ok = false, v2ok = false ; - - if (VertexInformation[v1->getLabel()].isMatched()) { - if (*(VertexInformation[v1->getLabel()].getMatchingEdge()) == e) { - v1ok = true ; - } - } - if (VertexInformation[v2->getLabel()].isMatched()) { - if (*(VertexInformation[v2->getLabel()].getMatchingEdge()) == e) { - v2ok = true ; - } - } - return (v1ok && v2ok) ; +bool Matching::includesEdge(const Edge &e) const { + Vertex *v1 = e.getVertex1(); + Vertex *v2 = e.getVertex2(); + bool v1ok = false, v2ok = false; + + if (VertexInformation[v1->getLabel()].isMatched()) { + if (*(VertexInformation[v1->getLabel()].getMatchingEdge()) == e) { + v1ok = true; + } + } + if (VertexInformation[v2->getLabel()].isMatched()) { + if (*(VertexInformation[v2->getLabel()].getMatchingEdge()) == e) { + v2ok = true; + } + } + return (v1ok && v2ok); } -void Matching::addEdge (const Edge& e) -{ - VertexLabel vlbl1 = e.getVertex1()->getLabel() ; - VertexLabel vlbl2 = e.getVertex2()->getLabel() ; +void Matching::addEdge(const Edge &e) { + VertexLabel vlbl1 = e.getVertex1()->getLabel(); + VertexLabel vlbl2 = e.getVertex2()->getLabel(); - myassert (VertexInformation[vlbl1].isExposed()) ; - myassert (VertexInformation[vlbl2].isExposed()) ; - std::list::iterator edgeit = MatchingEdges.insert (MatchingEdges.end(), new Edge (e)) ; + myassert(VertexInformation[vlbl1].isExposed()); + myassert(VertexInformation[vlbl2].isExposed()); + std::list::iterator edgeit = MatchingEdges.insert(MatchingEdges.end(), new Edge(e)); - ExposedVertices.erase (VertexInformation[vlbl1].getExposedIterator()) ; - ExposedVertices.erase (VertexInformation[vlbl2].getExposedIterator()) ; - VertexInformation[vlbl1].setMatched (edgeit) ; - VertexInformation[vlbl2].setMatched (edgeit) ; + ExposedVertices.erase(VertexInformation[vlbl1].getExposedIterator()); + ExposedVertices.erase(VertexInformation[vlbl2].getExposedIterator()); + VertexInformation[vlbl1].setMatched(edgeit); + VertexInformation[vlbl2].setMatched(edgeit); - setCardinality (Cardinality + 1) ; + setCardinality(Cardinality + 1); } -void Matching::removeEdge (const Edge& e) -{ - Vertex* v1 = e.getVertex1() ; - Vertex* v2 = e.getVertex2() ; - VertexLabel vlbl1 = v1->getLabel() ; - VertexLabel vlbl2 = v2->getLabel() ; - - // assert: matching contains e - myassert (VertexInformation[vlbl1].isMatched()) ; - myassert (VertexInformation[vlbl2].isMatched()) ; - - // delete e from MatchingEdges - std::list::iterator eit1 = VertexInformation[vlbl1].getMatchedIterator() ; - std::list::iterator eit2 = VertexInformation[vlbl2].getMatchedIterator() ; - myassert (eit1 == eit2) ; - delete (*eit1) ; - MatchingEdges.erase (eit1) ; - - // add v1,v2 to ExposedVertices - std::list::iterator expvit1 = ExposedVertices.insert (ExposedVertices.end(), v1) ; - VertexInformation[vlbl1].setExposed (expvit1) ; - std::list::iterator expvit2 = ExposedVertices.insert (ExposedVertices.end(), v2) ; - VertexInformation[vlbl2].setExposed (expvit2) ; - - setCardinality (Cardinality - 1) ; +void Matching::removeEdge(const Edge &e) { + Vertex *v1 = e.getVertex1(); + Vertex *v2 = e.getVertex2(); + VertexLabel vlbl1 = v1->getLabel(); + VertexLabel vlbl2 = v2->getLabel(); + + // assert: matching contains e + myassert(VertexInformation[vlbl1].isMatched()); + myassert(VertexInformation[vlbl2].isMatched()); + + // delete e from MatchingEdges + std::list::iterator eit1 = VertexInformation[vlbl1].getMatchedIterator(); + std::list::iterator eit2 = VertexInformation[vlbl2].getMatchedIterator(); + myassert(eit1 == eit2); + delete *eit1; + MatchingEdges.erase(eit1); + + // add v1,v2 to ExposedVertices + std::list::iterator expvit1 = ExposedVertices.insert(ExposedVertices.end(), v1); + VertexInformation[vlbl1].setExposed(expvit1); + std::list::iterator expvit2 = ExposedVertices.insert(ExposedVertices.end(), v2); + VertexInformation[vlbl2].setExposed(expvit2); + + setCardinality(Cardinality - 1); } -Matching& Matching::augment (const Edge** path, unsigned long len) -{ - // TODO - rewrite this to use structure like: while (+--+==+ -> +==+--+); +--+ -> +==+ where == is matched edge - myassert (len % 2 == 1) ; - bool e_was_matched = false ; - Edge *e = NULL ; - Edge *e_before = NULL ; - for (unsigned int i = 0 ; i < len ; i++) { - // give e the correct orientation (using pointer equivalence of vertices(!)) - e = new Edge (*(path[i])) ; - if (e_before == NULL) { - if (len > 1) { - // e is the first, but not the only edge in path - if ((e->getVertex1() == path[1]->getVertex1()) || (e->getVertex1() == path[1]->getVertex2())) { - e->swap() ; - } - } - } - else { - if (e->getVertex1() != e_before->getVertex2()) { - e->swap() ; - } - myassert (e->getVertex1() == e_before->getVertex2()) ; - } - - // make changes in VertexInformation, ExposedVertices and MatchingEdges - if (e_was_matched) { // at the time this is called, v1 is matched with "v0" - Vertex *v2 = e->getVertex2() ; - VertexLabel v2lbl = v2->getLabel() ; - - // remove old edge from matching - delete (*(VertexInformation[v2lbl].getMatchedIterator())) ; - MatchingEdges.erase (VertexInformation[v2lbl].getMatchedIterator()) ; - - // v2 is exposed now (for one iteration) - std::list::iterator expvit2 = ExposedVertices.insert (ExposedVertices.end(), v2) ; - VertexInformation[v2lbl].setExposed (expvit2) ; - } - else { - Vertex *v1 = e->getVertex1() ; - Vertex *v2 = e->getVertex2() ; - VertexLabel v1lbl = v1->getLabel() ; - VertexLabel v2lbl = v2->getLabel() ; - - // v1 is no longer exposed - ExposedVertices.erase (VertexInformation[v1lbl].getExposedIterator()) ; - - // add new edge to matching - std::list::iterator edgeit = MatchingEdges.insert (MatchingEdges.end(), e) ; - VertexInformation[v1lbl].setMatched (edgeit) ; - VertexInformation[v2lbl].setMatched (edgeit) ; - } - - e_was_matched = !e_was_matched ; - e_before = e ; - } - - ExposedVertices.erase (VertexInformation[e->getVertex2()->getLabel()].getExposedIterator()) ; - VertexInformation[e->getVertex2()->getLabel()].setMatched (find (MatchingEdges.begin(), MatchingEdges.end(), e)) ; - - setCardinality (Cardinality + 1) ; - - return *this ; +Matching &Matching::augment(const Edge **path, unsigned long len) { + // TODO - rewrite this to use structure like: while (+--+==+ -> +==+--+); +--+ + // -> +==+ where == is matched edge + myassert(len % 2 == 1); + bool e_was_matched = false; + Edge *e = NULL; + Edge *e_before = NULL; + for (unsigned int i = 0; i < len; i++) { + // give e the correct orientation (using pointer equivalence of vertices(!)) + e = new Edge(*(path[i])); + if (e_before == NULL) { + if (len > 1) { + // e is the first, but not the only edge in path + if ((e->getVertex1() == path[1]->getVertex1()) || + (e->getVertex1() == path[1]->getVertex2())) { + e->swap(); + } + } + } else { + if (e->getVertex1() != e_before->getVertex2()) { + e->swap(); + } + myassert(e->getVertex1() == e_before->getVertex2()); + } + + // make changes in VertexInformation, ExposedVertices and MatchingEdges + if (e_was_matched) { // at the time this is called, v1 is matched with "v0" + Vertex *v2 = e->getVertex2(); + VertexLabel v2lbl = v2->getLabel(); + + // remove old edge from matching + delete *(VertexInformation[v2lbl].getMatchedIterator()); + MatchingEdges.erase(VertexInformation[v2lbl].getMatchedIterator()); + + // v2 is exposed now (for one iteration) + std::list::iterator expvit2 = + ExposedVertices.insert(ExposedVertices.end(), v2); + VertexInformation[v2lbl].setExposed(expvit2); + } else { + Vertex *v1 = e->getVertex1(); + Vertex *v2 = e->getVertex2(); + VertexLabel v1lbl = v1->getLabel(); + VertexLabel v2lbl = v2->getLabel(); + + // v1 is no longer exposed + ExposedVertices.erase(VertexInformation[v1lbl].getExposedIterator()); + + // add new edge to matching + std::list::iterator edgeit = MatchingEdges.insert(MatchingEdges.end(), e); + VertexInformation[v1lbl].setMatched(edgeit); + VertexInformation[v2lbl].setMatched(edgeit); + } + + e_was_matched = !e_was_matched; + e_before = e; + } + + ExposedVertices.erase(VertexInformation[e->getVertex2()->getLabel()].getExposedIterator()); + VertexInformation[e->getVertex2()->getLabel()].setMatched( + find(MatchingEdges.begin(), MatchingEdges.end(), e)); + + setCardinality(Cardinality + 1); + + return *this; } -Matching& Matching::augment (const std::vector& path) -{ - unsigned long len = path.size() ; - const Edge** p = new const Edge*[len] ; - for (unsigned long i = 0 ; i < len ; i++) { - p[i] = path[i] ; - } - return augment (p, len) ; +Matching &Matching::augment(const std::vector &path) { + unsigned long len = path.size(); + const Edge **p = new const Edge *[len]; + for (unsigned long i = 0; i < len; i++) { + p[i] = path[i]; + } + return augment(p, len); } -void Matching::printVerboseInfo (void) const -{ - // only used for STATS output - - if (Args.Verbosity.getValue() == STATS) { - float sumweights = 0 ; - for (std::list::const_iterator it = MatchingEdges.begin() ; it != MatchingEdges.end() ; it++) { - sumweights += (*it)->getWeight() ; - } - - printf ("%.4f:%.1f:", - 1.0 - (((float) (getCardinality() * 2)) / ((float) TheGraph->getNumVertices())), // percentage of unmatched vertices - ((float) sumweights / (float) getCardinality()) // average edge weight - ) ; - } +void Matching::printVerboseInfo(void) const { + // only used for STATS output + + if (Args.Verbosity.getValue() == STATS) { + float sumweights = 0; + for (std::list::const_iterator it = MatchingEdges.begin(); + it != MatchingEdges.end(); it++) { + sumweights += (*it)->getWeight(); + } + + printf("%.4f:%.1f:", + 1.0 - (((float)(getCardinality() * 2)) / + ((float)TheGraph->getNumVertices())), // percentage of unmatched vertices + ((float)sumweights / (float)getCardinality()) // average edge weight + ); + } } -float Matching::getMatchedRate (void) const -{ - return (((float) (2 * Cardinality)) / ((float) TheGraph->getNumVertices())) ; +float Matching::getMatchedRate(void) const { + return (((float)(2 * Cardinality)) / ((float)TheGraph->getNumVertices())); } -float Matching::getAvgEdgeWeight (void) const -{ - float sumweights = 0 ; - for (std::list::const_iterator it = MatchingEdges.begin() ; it != MatchingEdges.end() ; it++) { - sumweights += (*it)->getWeight() ; - } - return (sumweights / (float) getCardinality()) ; +float Matching::getAvgEdgeWeight(void) const { + float sumweights = 0; + for (std::list::const_iterator it = MatchingEdges.begin(); it != MatchingEdges.end(); + it++) { + sumweights += (*it)->getWeight(); + } + return (sumweights / (float)getCardinality()); } -void Matching::setCardinality (unsigned long c) -{ - Cardinality = c ; - if (PrOut) { - PrOut->update (getMatchedRate()) ; - } +void Matching::setCardinality(unsigned long c) { + Cardinality = c; + if (PrOut) { + PrOut->update(getMatchedRate()); + } } -bool Matching::check () const -{ - bool retval = true ; - retval = check_MatchingEdges_vs_VertexInformation() && retval ; - retval = check_ExposedVertices_vs_VertexInformation() && retval ; - retval = check_VertexInformation_Integrity() && retval ; - return retval ; +bool Matching::check() const { + bool retval = true; + retval = check_MatchingEdges_vs_VertexInformation() && retval; + retval = check_ExposedVertices_vs_VertexInformation() && retval; + retval = check_VertexInformation_Integrity() && retval; + return retval; } -bool Matching::check_MatchingEdges_vs_VertexInformation () const -{ - bool err = false ; - // for every e = (v1,v2) in MatchingEdges: isMatched(v1) && isMatched(v2) - for (std::list::const_iterator it = MatchingEdges.begin() ; it != MatchingEdges.end() ; it++) { - Vertex *v1 = (*it)->getVertex1() ; - Vertex *v2 = (*it)->getVertex2() ; - if (VertexInformation[v1->getLabel()].isExposed() || VertexInformation[v2->getLabel()].isExposed()) { - err = true ; - break ; - } - } - - if (err) { - std::cerr << "FAILED: There is an edge in MatchingEdges that is adjacent to a vertex marked as exposed." << std::endl ; - } - - return !err ; +bool Matching::check_MatchingEdges_vs_VertexInformation() const { + bool err = false; + // for every e = (v1,v2) in MatchingEdges: isMatched(v1) && isMatched(v2) + for (std::list::const_iterator it = MatchingEdges.begin(); it != MatchingEdges.end(); + it++) { + Vertex *v1 = (*it)->getVertex1(); + Vertex *v2 = (*it)->getVertex2(); + if (VertexInformation[v1->getLabel()].isExposed() || + VertexInformation[v2->getLabel()].isExposed()) { + err = true; + break; + } + } + + if (err) { + std::cerr << "FAILED: There is an edge in MatchingEdges that is adjacent " + "to a vertex marked as exposed." + << std::endl; + } + + return !err; } -bool Matching::check_ExposedVertices_vs_VertexInformation () const -{ - bool err = false ; - - // for every exposed vertex v: isExposed(v) - for (std::list::const_iterator it = ExposedVertices.begin() ; it != ExposedVertices.end() ; it++) { - if (VertexInformation[(*it)->getLabel()].isMatched()) { - err = true ; - break ; - } - } - - if (err) { - std::cerr << "FAILED: There is a vertex in ExposedVertices that is marked matched." << std::endl ; - } - - return !err ; +bool Matching::check_ExposedVertices_vs_VertexInformation() const { + bool err = false; + + // for every exposed vertex v: isExposed(v) + for (std::list::const_iterator it = ExposedVertices.begin(); + it != ExposedVertices.end(); it++) { + if (VertexInformation[(*it)->getLabel()].isMatched()) { + err = true; + break; + } + } + + if (err) { + std::cerr << "FAILED: There is a vertex in ExposedVertices that is marked " + "matched." + << std::endl; + } + + return !err; } -bool Matching::check_VertexInformation_Integrity () const -{ - bool err_matched = false ; - - for (unsigned long vlbl = 0 ; vlbl < VertexInformation.size() ; vlbl++) { - if (VertexInformation[vlbl].isMatched()) { - Edge* e = *(VertexInformation[vlbl].getMatchedIterator()) ; - if ((e->getVertex1()->getLabel() != vlbl) && (e->getVertex2()->getLabel() != vlbl)) { - if (vlbl == 16) { std::cerr << "FAILED, printing edge:" << std::endl ; e->print() ; } - err_matched = true ; - break ; - } - } - } - - if (err_matched) { - std::cerr << "FAILED: There is a shortest edge that is not adjacent to its vertex." << std::endl ; - } - - return !err_matched ; +bool Matching::check_VertexInformation_Integrity() const { + bool err_matched = false; + + for (unsigned long vlbl = 0; vlbl < VertexInformation.size(); vlbl++) { + if (VertexInformation[vlbl].isMatched()) { + Edge *e = *(VertexInformation[vlbl].getMatchedIterator()); + if ((e->getVertex1()->getLabel() != vlbl) && (e->getVertex2()->getLabel() != vlbl)) { + if (vlbl == 16) { + std::cerr << "FAILED, printing edge:" << std::endl; + e->print(); + } + err_matched = true; + break; + } + } + } + + if (err_matched) { + std::cerr << "FAILED: There is a shortest edge that is not adjacent to its " + "vertex." + << std::endl; + } + + return !err_matched; } -bool Matching::check_ValidAugPath (const std::vector& path) const -{ - // check cohesion - bool cohesion = true ; - std::vector vertices ; - Vertex* lastvertex = NULL ; - if (path[1]->contains (path[0]->getVertex1())) { - vertices.push_back (path[0]->getVertex2()) ; - vertices.push_back (path[0]->getVertex1()) ; - lastvertex = path[0]->getVertex1() ; - } - else if (path[1]->contains (path[0]->getVertex2())) { - vertices.push_back (path[0]->getVertex1()) ; - vertices.push_back (path[0]->getVertex2()) ; - lastvertex = path[0]->getVertex2() ; - } - else { - cohesion = false ; - } - - std::vector::const_iterator it = path.begin() ; - for (it++ ; it != path.end() ; it++) { - if ((*it)->getVertex1() == lastvertex) { - vertices.push_back ((*it)->getVertex2()) ; - lastvertex = (*it)->getVertex2() ; - } - else if ((*it)->getVertex2() == lastvertex) { - vertices.push_back ((*it)->getVertex1()) ; - lastvertex = (*it)->getVertex1() ; - } - else { - cohesion = false ; - } - } - - myassert (vertices.size() - 1 == path.size()) ; - - // check that path has no loop - bool hasloop = false ; - unsigned long nvertices = vertices.size() ; - for (unsigned long i = 0 ; i < nvertices ; i++) { - for (unsigned long j = i + 1 ; j < nvertices ; j++) { - if (vertices[i] == vertices[j]) { - hasloop = true ; - } - } - } - - // check that path is augmenting w.r.t. the matching - bool isaugmenting = true ; - bool shouldinclude = false ; - for (std::vector::const_iterator it = path.begin() ; it != path.end() ; it++) { - if (shouldinclude) { - isaugmenting = includesEdge(*it) && isaugmenting ; - } - else { - isaugmenting = !includesEdge(*it) && isaugmenting ; - } - shouldinclude = !shouldinclude ; - } - - return cohesion && !hasloop && isaugmenting ; +bool Matching::check_ValidAugPath(const std::vector &path) const { + // check cohesion + bool cohesion = true; + std::vector vertices; + Vertex *lastvertex = NULL; + if (path[1]->contains(path[0]->getVertex1())) { + vertices.push_back(path[0]->getVertex2()); + vertices.push_back(path[0]->getVertex1()); + lastvertex = path[0]->getVertex1(); + } else if (path[1]->contains(path[0]->getVertex2())) { + vertices.push_back(path[0]->getVertex1()); + vertices.push_back(path[0]->getVertex2()); + lastvertex = path[0]->getVertex2(); + } else { + cohesion = false; + } + + std::vector::const_iterator it = path.begin(); + for (it++; it != path.end(); it++) { + if ((*it)->getVertex1() == lastvertex) { + vertices.push_back((*it)->getVertex2()); + lastvertex = (*it)->getVertex2(); + } else if ((*it)->getVertex2() == lastvertex) { + vertices.push_back((*it)->getVertex1()); + lastvertex = (*it)->getVertex1(); + } else { + cohesion = false; + } + } + + myassert(vertices.size() - 1 == path.size()); + + // check that path has no loop + bool hasloop = false; + unsigned long nvertices = vertices.size(); + for (unsigned long i = 0; i < nvertices; i++) { + for (unsigned long j = i + 1; j < nvertices; j++) { + if (vertices[i] == vertices[j]) { + hasloop = true; + } + } + } + + // check that path is augmenting w.r.t. the matching + bool isaugmenting = true; + bool shouldinclude = false; + for (std::vector::const_iterator it = path.begin(); it != path.end(); it++) { + if (shouldinclude) { + isaugmenting = includesEdge(*it) && isaugmenting; + } else { + isaugmenting = !includesEdge(*it) && isaugmenting; + } + shouldinclude = !shouldinclude; + } + + return cohesion && !hasloop && isaugmenting; } diff --git a/src/Matching.h b/src/Matching.h index 04c2105..0658169 100644 --- a/src/Matching.h +++ b/src/Matching.h @@ -27,8 +27,8 @@ #include "Vertex.h" #include "common.h" -class Edge ; -class ProgressOutput ; +class Edge; +class ProgressOutput; /** * \class Matching @@ -39,196 +39,186 @@ class ProgressOutput ; * pointers. **/ class Matching { - public: - /** - * create an empty matching that is ready for adding and augmenting - * \param g the underlying graph - * \param po a ProgressOutput object that will print the number of matched vertices (in percent) - **/ - Matching (Graph* g, ProgressOutput* po = NULL) ; - - ~Matching (void) ; - - /** - * returns true iff the vertex v is matched in this matching. - **/ - bool isMatched (Vertex *v) const - { return VertexInformation[v->getLabel()].isMatched() ; } ; - - /** - * returns true iff the vertex with the label vlbl is matched in this matching. - **/ - bool isMatched (VertexLabel vlbl) const - { return VertexInformation[vlbl].isMatched() ; } ; - - /** - * returns true iff the vertex v is exposed (not matched) in this matching. - **/ - bool isExposed (Vertex *v) const - { return VertexInformation[v->getLabel()].isExposed() ; } ; - - /** - * returns true iff the vertex with the label vlbl is exposed (not matched) in this matching. - **/ - bool isExposed (VertexLabel vlbl) const - { return VertexInformation[vlbl].isExposed() ; } ; - - /** - * get the edge that is in the matching and adjacent to v - * \return the matched edge or NULL if v is exposed - **/ - const Edge* getMatchingEdge (Vertex *v) const - { return VertexInformation[v->getLabel()].getMatchingEdge() ; } ; - - /** - * does this matching include the edge e ? - * \return true iff the edge e is element of this matching - **/ - bool includesEdge (const Edge* e) const { return includesEdge(*e) ; } ; - bool includesEdge (const Edge& e) const ; - - /** - * get the cardinality (the number of matched edges) - **/ - unsigned long getCardinality (void) const - { return Cardinality ; } ; - - const std::list& getExposedVertices (void) const - { return ExposedVertices ; } ; - - /** - * get the rate of vertices of the underlying graph that are currently matched in this matching - * \return a value between 0 and 1 - **/ - float getMatchedRate (void) const ; - - /** - * get the average weight of all edges that are in this matching - **/ - float getAvgEdgeWeight (void) const ; - - /** - * get access to the std::list of exposed vertices - * \return a pointer to the std::list of exposed vertices in this matching. - * - * The std::list that is pointed to by return value contains the exposed vertices - * even after augment has been called (it is the ExposedVertices member) an - * arbitrary number of times. - **/ - const std::list *getExposedVerticesLink (void) const - { return &ExposedVertices ; } ; - - /** - * add an edge to the matching - * \param e the edge to add. - * - * For e=(v1,v2): neither v1 nor v2 are allowed to be adjacent - * to an edge that is already in the matching, - **/ - void addEdge (const Edge& e) ; - void addEdge (Edge* e) { addEdge(*e) ; } ; - - /** - * remove an edge from the matching - * \param e the edge to remove - * - * The edge e _must_ be in this matching - **/ - void removeEdge (const Edge& e) ; - - /** - * get the list of all edges in this matching - **/ - const std::list& getEdges (void) const - { return MatchingEdges ; } ; - - /** - * augment this matching along the given augmenting path - * \param path an augmenting path - * \param len the length (number of edges) of the augmenting path - * - * An augementing path is a path where edges with odd indices (the first, third,...) are not - * in the matching and edges with even indices are and the path has - * an odd length. - **/ - Matching& augment (const Edge** path, unsigned long len) ; - - Matching& augment (const std::vector& path) ; - - void printVerboseInfo (void) const ; - - private: - /** - * \class VertexInfo - * \brief contains information about a vertex that is possibly in a matching - **/ - class VertexInfo { - public: - VertexInfo (std::list::iterator mit) - { setMatched (mit) ; } ; - - VertexInfo (std::list::iterator eit) - { setExposed (eit) ; } ; - - bool isExposed (void) const - { return !Matched ; } ; - - bool isMatched (void) const - { return Matched ; } ; - - Edge *getMatchingEdge (void) const - { return *MatchedIterator ; } ; - - std::list::iterator getMatchedIterator (void) const - { return MatchedIterator ; } ; - - std::list::iterator getExposedIterator (void) const - { return ExposedIterator ; } ; - - void setMatched (std::list::iterator mit) - { Matched = true ; MatchedIterator = mit ; } ; - - void setExposed (std::list::iterator eit) - { Matched = false ; ExposedIterator = eit ; } ; - - private: - bool Matched ; - /// an iterator into the list of matched edges (only valid if this vertex is matched) - std::list::iterator MatchedIterator ; - /// an iterator into the list of exposed vertices (only valid if this vertex is exposed) - std::list::iterator ExposedIterator ; - } ; - - /// contains a VertexInfo object for every vertex - std::vector VertexInformation ; - - /// the std::list of all exposed vertices - std::list ExposedVertices ; - - /// the std::list of all edges in the matching - std::list MatchingEdges ; - - /// the number of edges in the matching - unsigned long Cardinality ; - - /// the graph underlying this Matching - Graph* TheGraph ; - - /// the ProgressOutput object that will print the number of matched vertices (as percentage) - ProgressOutput* PrOut ; - - /** - * set the cardinality (thereby updating PrOut) - **/ - void setCardinality (unsigned long c) ; - - public: - bool check (void) const ; - bool check_MatchingEdges_vs_VertexInformation (void) const ; - bool check_ExposedVertices_vs_VertexInformation (void) const ; - bool check_VertexInformation_Integrity (void) const ; - - bool check_ValidAugPath (const std::vector& path) const ; -} ; + public: + /** + * create an empty matching that is ready for adding and augmenting + * \param g the underlying graph + * \param po a ProgressOutput object that will print the number of matched vertices (in percent) + **/ + Matching(Graph *g, ProgressOutput *po = NULL); + + ~Matching(void); + + /** + * returns true iff the vertex v is matched in this matching. + **/ + bool isMatched(Vertex *v) const { return VertexInformation[v->getLabel()].isMatched(); }; + + /** + * returns true iff the vertex with the label vlbl is matched in this matching. + **/ + bool isMatched(VertexLabel vlbl) const { return VertexInformation[vlbl].isMatched(); }; + + /** + * returns true iff the vertex v is exposed (not matched) in this matching. + **/ + bool isExposed(Vertex *v) const { return VertexInformation[v->getLabel()].isExposed(); }; + + /** + * returns true iff the vertex with the label vlbl is exposed (not matched) in this matching. + **/ + bool isExposed(VertexLabel vlbl) const { return VertexInformation[vlbl].isExposed(); }; + + /** + * get the edge that is in the matching and adjacent to v + * \return the matched edge or NULL if v is exposed + **/ + const Edge *getMatchingEdge(Vertex *v) const { + return VertexInformation[v->getLabel()].getMatchingEdge(); + }; + + /** + * does this matching include the edge e ? + * \return true iff the edge e is element of this matching + **/ + bool includesEdge(const Edge *e) const { return includesEdge(*e); }; + bool includesEdge(const Edge &e) const; + + /** + * get the cardinality (the number of matched edges) + **/ + unsigned long getCardinality(void) const { return Cardinality; }; + + const std::list &getExposedVertices(void) const { return ExposedVertices; }; + + /** + * get the rate of vertices of the underlying graph that are currently matched in this matching + * \return a value between 0 and 1 + **/ + float getMatchedRate(void) const; + + /** + * get the average weight of all edges that are in this matching + **/ + float getAvgEdgeWeight(void) const; + + /** + * get access to the std::list of exposed vertices + * \return a pointer to the std::list of exposed vertices in this matching. + * + * The std::list that is pointed to by return value contains the exposed vertices + * even after augment has been called (it is the ExposedVertices member) an + * arbitrary number of times. + **/ + const std::list *getExposedVerticesLink(void) const { return &ExposedVertices; }; + + /** + * add an edge to the matching + * \param e the edge to add. + * + * For e=(v1,v2): neither v1 nor v2 are allowed to be adjacent + * to an edge that is already in the matching, + **/ + void addEdge(const Edge &e); + void addEdge(Edge *e) { addEdge(*e); }; + + /** + * remove an edge from the matching + * \param e the edge to remove + * + * The edge e _must_ be in this matching + **/ + void removeEdge(const Edge &e); + + /** + * get the list of all edges in this matching + **/ + const std::list &getEdges(void) const { return MatchingEdges; }; + + /** + * augment this matching along the given augmenting path + * \param path an augmenting path + * \param len the length (number of edges) of the augmenting path + * + * An augementing path is a path where edges with odd indices (the first, third,...) are not + * in the matching and edges with even indices are and the path has + * an odd length. + **/ + Matching &augment(const Edge **path, unsigned long len); + + Matching &augment(const std::vector &path); + + void printVerboseInfo(void) const; + + private: + /** + * \class VertexInfo + * \brief contains information about a vertex that is possibly in a matching + **/ + class VertexInfo { + public: + VertexInfo(std::list::iterator mit) { setMatched(mit); }; + + VertexInfo(std::list::iterator eit) { setExposed(eit); }; + + bool isExposed(void) const { return !Matched; }; + + bool isMatched(void) const { return Matched; }; + + Edge *getMatchingEdge(void) const { return *MatchedIterator; }; + + std::list::iterator getMatchedIterator(void) const { return MatchedIterator; }; + + std::list::iterator getExposedIterator(void) const { return ExposedIterator; }; + + void setMatched(std::list::iterator mit) { + Matched = true; + MatchedIterator = mit; + }; + + void setExposed(std::list::iterator eit) { + Matched = false; + ExposedIterator = eit; + }; + + private: + bool Matched; + /// an iterator into the list of matched edges (only valid if this vertex is matched) + std::list::iterator MatchedIterator; + /// an iterator into the list of exposed vertices (only valid if this vertex is exposed) + std::list::iterator ExposedIterator; + }; + + /// contains a VertexInfo object for every vertex + std::vector VertexInformation; + + /// the std::list of all exposed vertices + std::list ExposedVertices; + + /// the std::list of all edges in the matching + std::list MatchingEdges; + + /// the number of edges in the matching + unsigned long Cardinality; + + /// the graph underlying this Matching + Graph *TheGraph; + + /// the ProgressOutput object that will print the number of matched vertices (as percentage) + ProgressOutput *PrOut; + + /** + * set the cardinality (thereby updating PrOut) + **/ + void setCardinality(unsigned long c); + + public: + bool check(void) const; + bool check_MatchingEdges_vs_VertexInformation(void) const; + bool check_ExposedVertices_vs_VertexInformation(void) const; + bool check_VertexInformation_Integrity(void) const; + + bool check_ValidAugPath(const std::vector &path) const; +}; #endif // ndef SH_MATCHING_H diff --git a/src/MatchingAlgorithm.cc b/src/MatchingAlgorithm.cc index 14d63c6..abf508a 100644 --- a/src/MatchingAlgorithm.cc +++ b/src/MatchingAlgorithm.cc @@ -18,18 +18,17 @@ * */ -#include "Graph.h" #include "MatchingAlgorithm.h" +#include "Graph.h" -MatchingAlgorithm::MatchingAlgorithm (Graph* g, Matching* m, float goal) - : TheGraph(g), TheMatching(m) -{ - setGoal(goal) ; +MatchingAlgorithm::MatchingAlgorithm(Graph *g, Matching *m, float goal) + : TheGraph(g), TheMatching(m) { + setGoal(goal); } -void MatchingAlgorithm::setGoal (float goal) -{ - // if goal is 100.0 and the graph has an odd number of vertices the algorithm won't spend time - // searching an edge for the last vertex as / rounds down to the next smaller integer - CardinalityGoal = (unsigned long) (((float) TheGraph->getNumVertices()) * (goal / 100.0)) / 2 ; +void MatchingAlgorithm::setGoal(float goal) { + // if goal is 100.0 and the graph has an odd number of vertices the algorithm + // won't spend time searching an edge for the last vertex as / rounds down to + // the next smaller integer + CardinalityGoal = (unsigned long)(((float)TheGraph->getNumVertices()) * (goal / 100.0)) / 2; } diff --git a/src/MatchingAlgorithm.h b/src/MatchingAlgorithm.h index 840a260..c35f865 100644 --- a/src/MatchingAlgorithm.h +++ b/src/MatchingAlgorithm.h @@ -21,27 +21,26 @@ #ifndef SH_MATCHINGALGORITHM_H #define SH_MATCHINGALGORITHM_H -class Graph ; -class Matching ; +class Graph; +class Matching; class MatchingAlgorithm { - public: - MatchingAlgorithm (Graph* g, Matching* m, float goal) ; - virtual ~MatchingAlgorithm (void) {} ; + public: + MatchingAlgorithm(Graph *g, Matching *m, float goal); + virtual ~MatchingAlgorithm(void){}; - virtual void run (void) = 0 ; + virtual void run(void) = 0; - Matching* getMatching (void) const - { return TheMatching ; } ; + Matching *getMatching(void) const { return TheMatching; }; - void setGoal (float goal) ; + void setGoal(float goal); - virtual const char* getName (void) const = 0 ; + virtual const char *getName(void) const = 0; - protected: - Graph* TheGraph ; - Matching* TheMatching ; - unsigned long CardinalityGoal ; -} ; + protected: + Graph *TheGraph; + Matching *TheMatching; + unsigned long CardinalityGoal; +}; #endif // ndef SH_MATCHINGALGORITHM diff --git a/src/PasswordCracker.cc b/src/PasswordCracker.cc index d1b4c39..c8cdf79 100644 --- a/src/PasswordCracker.cc +++ b/src/PasswordCracker.cc @@ -1,7 +1,7 @@ /* * Stegseek 0.5 - a steghide cracker * Copyright (C) 2020 Rick de Jager - * + * * Based on the work of Stefan Hetzl * * This program is free software; you can redistribute it and/or @@ -22,188 +22,188 @@ #include "PasswordCracker.h" -#include "error.h" -#include "Utils.h" -#include "common.h" +#include "CvrStgFile.h" #include "EmbData.h" -#include "Selector.h" #include "Extractor.h" -#include "CvrStgFile.h" - +#include "Selector.h" +#include "Utils.h" +#include "common.h" +#include "error.h" -PasswordCracker::PasswordCracker () -{ - VerboseMessage vrs ; - vrs.setMessage (_("[v] Using wordlist file \"%s\"."), Args.WordlistFn.getValue().c_str()) ; - vrs.printMessage() ; +PasswordCracker::PasswordCracker() { + VerboseMessage vrs; + vrs.setMessage(_("[v] Using wordlist file \"%s\"."), Args.WordlistFn.getValue().c_str()); + vrs.printMessage(); } -void PasswordCracker::crack () -{ - - unsigned int threads = Args.Threads.getValue() ; - - // First stat the word list to get the file length - struct stat wordlistStats ; - if (stat(Args.WordlistFn.getValue().c_str(), &wordlistStats) != 0) { - throw SteghideError("could not open the wordlist \"%s\".", Args.WordlistFn.getValue().c_str()) ; - } - - // Initialize threads - std::vector ThreadPool ; - bool metricsEnabled = Args.Verbosity.getValue() != QUIET ; - - // Add a thread to keep track of metrics - if (metricsEnabled) { - ThreadPool.push_back(std::thread([this, wordlistStats] {metrics(wordlistStats.st_size, "bytes"); })) ; - } - - // Add n worker threads - // A part must have at least len 1, otherwise no words will be read when threads > size - unsigned long part = std::max(wordlistStats.st_size / threads, 1L) ; - for (unsigned int i = 0; i < threads; i++) { - ThreadPool.push_back(std::thread([this, i, part, metricsEnabled] { - consume(i*part, (i+1)*part, metricsEnabled); - })) ; - } - - // Join all worker threads - for (unsigned int i = 0; i < threads; i++) { - ThreadPool.back().join() ; - ThreadPool.pop_back() ; - } - - // Set stopped flag and terminate the metrics thread - stopped = true ; - if (metricsEnabled) { - ThreadPool.back().join() ; - ThreadPool.pop_back() ; - } - - if (!success) { - // On failure, send the message directly to stderr so it will be printed in quiet mode as well - fprintf(stderr, "[!] Could not find a valid passphrase.\n") ; - } else { - // Re-extract the data with the confirmed passphrase. - // This does mean we're throwing away one valid "embdata" object, but - // that's not a bad trade-off to be able to use steghide's structure - fprintf(stderr, "[i] --> Found passphrase: \"%s\"\n", foundPassphrase.c_str()) ; - extract(foundPassphrase) ; - } +void PasswordCracker::crack() { + + unsigned int threads = Args.Threads.getValue(); + + // First stat the word list to get the file length + struct stat wordlistStats; + if (stat(Args.WordlistFn.getValue().c_str(), &wordlistStats) != 0) { + throw SteghideError("could not open the wordlist \"%s\".", + Args.WordlistFn.getValue().c_str()); + } + + // Initialize threads + std::vector ThreadPool; + bool metricsEnabled = Args.Verbosity.getValue() != QUIET; + + // Add a thread to keep track of metrics + if (metricsEnabled) { + ThreadPool.push_back( + std::thread([this, wordlistStats] { metrics(wordlistStats.st_size, "bytes"); })); + } + + // Add n worker threads + // A part must have at least len 1, otherwise no words will be read when + // threads > size + unsigned long part = std::max(wordlistStats.st_size / threads, 1L); + for (unsigned int i = 0; i < threads; i++) { + ThreadPool.push_back(std::thread([this, i, part, metricsEnabled] { + consume(i * part, (i + 1) * part, metricsEnabled); + })); + } + + // Join all worker threads + for (unsigned int i = 0; i < threads; i++) { + ThreadPool.back().join(); + ThreadPool.pop_back(); + } + + // Set stopped flag and terminate the metrics thread + stopped = true; + if (metricsEnabled) { + ThreadPool.back().join(); + ThreadPool.pop_back(); + } + + if (!success) { + // On failure, send the message directly to stderr so it will be printed in + // quiet mode as well + fprintf(stderr, "[!] Could not find a valid passphrase.\n"); + } else { + // Re-extract the data with the confirmed passphrase. + // This does mean we're throwing away one valid "embdata" object, but + // that's not a bad trade-off to be able to use steghide's structure + fprintf(stderr, "[i] --> Found passphrase: \"%s\"\n", foundPassphrase.c_str()); + extract(foundPassphrase); + } } // Take jobs and crack 'em -void PasswordCracker::consume (unsigned long i, unsigned long stop, bool metricsEnabled) -{ - // We want one thread to try a few "fun" ctf passwords first - if (i == 0 && ! Args.SkipDefaultGuesses.getValue()) { - sillyCtfGuesses() ; - } - // Next, load the wordlist file - FILE * pWordList ; - pWordList = fopen(Args.WordlistFn.getValue().c_str(), "r") ; - // Skip to our section - fseek(pWordList, i, SEEK_SET) ; - - // Dedicating 512 chars should give us a max wordlength of 128 unicode characters, worst case - char line[512] ; - // We allow for some overlap here (i.e. thread n might repeat a password from thread n+1) - // The reason for this is that we don't know where the linebreaks are without reading the entire - // file first, which would hold up (n-1) threads from actually doing useful things. - // - // Instead, we start n threads at different points in the wordlist, possibly in the middle of a password. - // this is fine, since the "previous" thread will always repeat the first password assigned to this thread. - // - while (!stopped && fgets(line, sizeof(line), pWordList)) { - // Strip \n and \r, \rn - line[strcspn(line, "\r\n")] = 0 ; - - // Try extracting with this passphrase - if (tryPassphrase(line)) - { - // Tell the other threads that they should stop - stopped = true ; - success = true ; - foundPassphrase = std::string(line); - break ; - } - - // Incrementing an atomic int is quite costly, so don't do it if no one cares about its value - if (metricsEnabled) { - // Add 1, since the newline was stripped, but is present in the file size - progress += std::strlen(line) + 1; - } - - // If we've overshot the end of our section (by one word), we can stop - if (ftell(pWordList) > stop) { - break ; - } - } - - fclose(pWordList) ; +void PasswordCracker::consume(unsigned long i, unsigned long stop, bool metricsEnabled) { + // We want one thread to try a few "fun" ctf passwords first + if (i == 0 && !Args.SkipDefaultGuesses.getValue()) { + sillyCtfGuesses(); + } + // Next, load the wordlist file + FILE *pWordList; + pWordList = fopen(Args.WordlistFn.getValue().c_str(), "r"); + // Skip to our section + fseek(pWordList, i, SEEK_SET); + + // Dedicating 512 chars should give us a max wordlength of 128 unicode + // characters, worst case + char line[512]; + // We allow for some overlap here (i.e. thread n might repeat a password from + // thread n+1) The reason for this is that we don't know where the linebreaks + // are without reading the entire file first, which would hold up (n-1) + // threads from actually doing useful things. + // + // Instead, we start n threads at different points in the wordlist, possibly + // in the middle of a password. this is fine, since the "previous" thread will + // always repeat the first password assigned to this thread. + // + while (!stopped && fgets(line, sizeof(line), pWordList)) { + // Strip \n and \r, \rn + line[strcspn(line, "\r\n")] = 0; + + // Try extracting with this passphrase + if (tryPassphrase(line)) { + // Tell the other threads that they should stop + stopped = true; + success = true; + foundPassphrase = std::string(line); + break; + } + + // Incrementing an atomic int is quite costly, so don't do it if no one + // cares about its value + if (metricsEnabled) { + // Add 1, since the newline was stripped, but is present in the file size + progress += std::strlen(line) + 1; + } + + // If we've overshot the end of our section (by one word), we can stop + if (ftell(pWordList) > stop) { + break; + } + } + + fclose(pWordList); } -bool PasswordCracker::tryPassphrase (const char * Passphrase) -{ - // We first check if the file magic makes sense - if (! verifyMagic(Passphrase)) { - return false ; - } - - std::string PassphraseStr(Passphrase) ; - - // In case the magic checks out, we have to do a proper extract attempt. - // This does re-do the magic, but it's rare enough that that won't matter. - - EmbData embdata (EmbData::EXTRACT, PassphraseStr) ; - Selector sel (numSamples, PassphraseStr) ; - - - unsigned long sv_idx = 0 ; - while (!embdata.finished()) { - unsigned long embvaluesrequested = AUtils::div_roundup (embdata.getNumBitsRequested(), bitsperembvalue) ; - if (sv_idx + (samplesPerVertex * embvaluesrequested) >= numSamples) { - // TODO; In theory, we should error out if we hit this. - // However, I've seen this error happen randomly on valid input files - // so I'm leaving it as a "return false" for now - // throw CorruptDataError (_("the stego data from standard input is too short to contain the embedded data.")) ; - return false ; - } - BitString bits (EmbValueModulus) ; - for (unsigned long i = 0 ; i < embvaluesrequested ; i++) { - EmbValue ev = 0 ; - for (unsigned int j = 0 ; j < samplesPerVertex ; j++, sv_idx++) { - ev = (ev + Globs.TheCvrStgFile->getEmbeddedValue (sel[sv_idx])) % EmbValueModulus ; - } - bits.appendNAry(ev) ; - } - - // It's possible that we find wrong passphrase for which we decrypt a valid magic - // Statistically, this only happens once every 256^3 times, but for a large wordlist, - // such as rockyou, this _can_ happen. - try - { - embdata.addBits(bits) ; - } - // Catching other errors here is fine, they should be pretty rare. - // * decompression error - // * failed crc check - catch(const SteghideError&) - { - return false ; - } - } - // We've found a passphrase, for which both the file magic checks out - // and the CRC is valid. :D - return true ; +bool PasswordCracker::tryPassphrase(const char *Passphrase) { + // We first check if the file magic makes sense + if (!verifyMagic(Passphrase)) { + return false; + } + + std::string PassphraseStr(Passphrase); + + // In case the magic checks out, we have to do a proper extract attempt. + // This does re-do the magic, but it's rare enough that that won't matter. + + EmbData embdata(EmbData::EXTRACT, PassphraseStr); + Selector sel(numSamples, PassphraseStr); + + unsigned long sv_idx = 0; + while (!embdata.finished()) { + unsigned long embvaluesrequested = + AUtils::div_roundup(embdata.getNumBitsRequested(), bitsperembvalue); + if (sv_idx + (samplesPerVertex * embvaluesrequested) >= numSamples) { + // TODO; In theory, we should error out if we hit this. + // However, I've seen this error happen randomly on valid input files + // so I'm leaving it as a "return false" for now + // throw CorruptDataError (_("the stego data from standard input is too + // short to contain the embedded data.")) ; + return false; + } + BitString bits(EmbValueModulus); + for (unsigned long i = 0; i < embvaluesrequested; i++) { + EmbValue ev = 0; + for (unsigned int j = 0; j < samplesPerVertex; j++, sv_idx++) { + ev = (ev + Globs.TheCvrStgFile->getEmbeddedValue(sel[sv_idx])) % EmbValueModulus; + } + bits.appendNAry(ev); + } + + // It's possible that we find wrong passphrase for which we decrypt a valid + // magic Statistically, this only happens once every 256^3 times, but for a + // large wordlist, such as rockyou, this _can_ happen. + try { + embdata.addBits(bits); + } + // Catching other errors here is fine, they should be pretty rare. + // * decompression error + // * failed crc check + catch (const SteghideError &) { + return false; + } + } + // We've found a passphrase, for which both the file magic checks out + // and the CRC is valid. :D + return true; } -void PasswordCracker::extract (std::string passphrase) -{ - Extractor ext (Args.StgFn.getValue(), passphrase) ; - EmbData* emb = ext.extract() ; - Cracker::extract(emb) ; - delete(emb) ; +void PasswordCracker::extract(std::string passphrase) { + Extractor ext(Args.StgFn.getValue(), passphrase); + EmbData *emb = ext.extract(); + Cracker::extract(emb); + delete emb; } // Try some guesses that might come up in ctf's, but won't be @@ -211,24 +211,22 @@ void PasswordCracker::extract (std::string passphrase) // * empty passphrase // * filename as passphrase // * stripped filename as passphrase -void PasswordCracker::sillyCtfGuesses () -{ - std::string filename = Utils::stripDir(Args.StgFn.getValue()) ; - std::string strippedFilename = filename.substr(0, filename.find_last_of(".")); - const char * guesses[] = { - "", - filename.c_str(), - strippedFilename.c_str(), - } ; - for (const char * line : guesses) { - // Try extracting with this passphrase - if (tryPassphrase(line)) - { - // Tell the other threads that they should stop - stopped = true ; - success = true ; - foundPassphrase = std::string(line); - break ; - } - } +void PasswordCracker::sillyCtfGuesses() { + std::string filename = Utils::stripDir(Args.StgFn.getValue()); + std::string strippedFilename = filename.substr(0, filename.find_last_of(".")); + const char *guesses[] = { + "", + filename.c_str(), + strippedFilename.c_str(), + }; + for (const char *line : guesses) { + // Try extracting with this passphrase + if (tryPassphrase(line)) { + // Tell the other threads that they should stop + stopped = true; + success = true; + foundPassphrase = std::string(line); + break; + } + } } \ No newline at end of file diff --git a/src/PasswordCracker.h b/src/PasswordCracker.h index d928156..9b64e37 100644 --- a/src/PasswordCracker.h +++ b/src/PasswordCracker.h @@ -2,9 +2,9 @@ * * Stegseek 0.5 - a steghide cracker * Copyright (C) 2020 Rick de Jager - * + * * Based on the work of Stefan Hetzl - * + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 @@ -24,29 +24,28 @@ #ifndef SH_PASSWORDCRACKER_H #define SH_PASSWORDCRACKER_H -#include -#include #include -#include #include +#include +#include +#include #include "Cracker.h" #include "Selector.h" class PasswordCracker : Cracker { - public: - PasswordCracker (void) ; - - void crack (void) ; + public: + PasswordCracker(); + void crack(); - private: - bool tryPassphrase (const char *) ; - void extract (std::string) ; - void consume (unsigned long, unsigned long, bool) ; - void sillyCtfGuesses () ; - std::ifstream wordlist ; - std::string foundPassphrase ; - unsigned long wordlistLength = 0 ; -} ; + private: + bool tryPassphrase(const char *); + void extract(std::string); + void consume(unsigned long, unsigned long, bool); + void sillyCtfGuesses(); + std::ifstream wordlist; + std::string foundPassphrase; + unsigned long wordlistLength = 0; +}; #endif // ndef SH_PASSWORDCRACKER_H diff --git a/src/ProgressOutput.cc b/src/ProgressOutput.cc index 0c75b3e..347bc3b 100644 --- a/src/ProgressOutput.cc +++ b/src/ProgressOutput.cc @@ -23,58 +23,50 @@ #include "ProgressOutput.h" #include "common.h" -ProgressOutput::ProgressOutput () - : Message("__nomessage__") -{ - LastUpdate = time(NULL) - 1 ; // -1 to ensure that message is written first time +ProgressOutput::ProgressOutput() : Message("__nomessage__") { + LastUpdate = time(NULL) - 1; // -1 to ensure that message is written first time } -ProgressOutput::ProgressOutput (const std::string& m) - : Message(m) -{ - LastUpdate = time(NULL) - 1 ; // -1 to ensure that message is written first time +ProgressOutput::ProgressOutput(const std::string &m) : Message(m) { + LastUpdate = time(NULL) - 1; // -1 to ensure that message is written first time } -void ProgressOutput::setMessage (const char *msgfmt, ...) -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +void ProgressOutput::setMessage(const char *msgfmt, ...) { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -std::string ProgressOutput::vcompose (const char *msgfmt, va_list ap) const -{ - char *str = new char[200] ; - vsnprintf (str, 200, msgfmt, ap) ; - std::string retval (str) ; - delete[] str ; - return retval ; +std::string ProgressOutput::vcompose(const char *msgfmt, va_list ap) const { + char *str = new char[200]; + vsnprintf(str, 200, msgfmt, ap); + std::string retval(str); + delete[] str; + return retval; } -void ProgressOutput::update (float rate) -{ - time_t now = time(NULL) ; - if (LastUpdate < now) { - LastUpdate = now ; - printf ("\r%s %.1f%%", Message.c_str(), 100.0 * rate) ; - fflush (stdout) ; - } +void ProgressOutput::update(float rate) { + time_t now = time(NULL); + if (LastUpdate < now) { + LastUpdate = now; + printf("\r%s %.1f%%", Message.c_str(), 100.0 * rate); + fflush(stdout); + } } -void ProgressOutput::done (float rate, float avgweight) const -{ - printf ("\r%s %.1f%%", Message.c_str(), 100.0 * rate) ; - if (avgweight != NoAvgWeight) { - printf (" (%.1f)", avgweight) ; - } - printf (_(" done")) ; - printf (" \n") ; // be sure to overwrite old line (even in a language with one-letter done) - fflush (stdout) ; +void ProgressOutput::done(float rate, float avgweight) const { + printf("\r%s %.1f%%", Message.c_str(), 100.0 * rate); + if (avgweight != NoAvgWeight) { + printf(" (%.1f)", avgweight); + } + printf(_(" done")); + printf(" \n"); // be sure to overwrite old line (even in a language with + // one-letter done) + fflush(stdout); } -void ProgressOutput::done () const -{ - printf ("\r%s", Message.c_str()) ; - printf (_(" done\n")) ; +void ProgressOutput::done() const { + printf("\r%s", Message.c_str()); + printf(_(" done\n")); } diff --git a/src/ProgressOutput.h b/src/ProgressOutput.h index 394939f..05b38ca 100644 --- a/src/ProgressOutput.h +++ b/src/ProgressOutput.h @@ -30,48 +30,47 @@ * \brief prints the progress to stdout **/ class ProgressOutput { - public: - /** - * create an empty ProgressOutput object - **/ - ProgressOutput (void) ; + public: + /** + * create an empty ProgressOutput object + **/ + ProgressOutput(void); - /** - * create a ProgressOutput object - * \param m the message to be displayed - **/ - ProgressOutput (const std::string& m) ; + /** + * create a ProgressOutput object + * \param m the message to be displayed + **/ + ProgressOutput(const std::string &m); - void setMessage (const std::string& m) - { Message = m ; } ; + void setMessage(const std::string &m) { Message = m; }; - void setMessage (const char *msgfmt, ...) ; + void setMessage(const char *msgfmt, ...); - /** - * update the output (taking update frequency into account) with rate as percentage - **/ - void update (float rate) ; + /** + * update the output (taking update frequency into account) with rate as percentage + **/ + void update(float rate); - /** - * update the output appending "done" and a newline (no rate nor average weight) - **/ - void done (void) const ; + /** + * update the output appending "done" and a newline (no rate nor average weight) + **/ + void done(void) const; - /** - * update the output appending rate, [average edge weight], "done" and a newline - * \param rate the rate of matched vertices - * \param avgweight the average edge weight (is not printed if not given) - **/ - void done (float rate, float avgweight = NoAvgWeight) const ; + /** + * update the output appending rate, [average edge weight], "done" and a newline + * \param rate the rate of matched vertices + * \param avgweight the average edge weight (is not printed if not given) + **/ + void done(float rate, float avgweight = NoAvgWeight) const; - static constexpr float NoAvgWeight = -1.0 ; + static constexpr float NoAvgWeight = -1.0; - protected: - std::string vcompose (const char *msgfmt, va_list ap) const ; + protected: + std::string vcompose(const char *msgfmt, va_list ap) const; - private: - std::string Message ; - time_t LastUpdate ; -} ; + private: + std::string Message; + time_t LastUpdate; +}; #endif // ndef SH_PROGRESSOUTPUT_H diff --git a/src/PseudoRandomSource.cc b/src/PseudoRandomSource.cc index 3b19ffe..ec586fd 100644 --- a/src/PseudoRandomSource.cc +++ b/src/PseudoRandomSource.cc @@ -20,10 +20,9 @@ #include "PseudoRandomSource.h" -UWORD32 PseudoRandomSource::getValue (UWORD32 n) -{ - // doing the step of the linear congruential method - Value = A * Value + C ; - // scale value to [0...1) and multiply with n - return (UWORD32) (((double) n) * ((double) Value / (double) 4294967296.0)) ; +UWORD32 PseudoRandomSource::getValue(UWORD32 n) { + // doing the step of the linear congruential method + Value = A * Value + C; + // scale value to [0...1) and multiply with n + return (UWORD32)(((double)n) * ((double)Value / (double)4294967296.0)); } diff --git a/src/PseudoRandomSource.h b/src/PseudoRandomSource.h index 2b45587..5e404ea 100644 --- a/src/PseudoRandomSource.h +++ b/src/PseudoRandomSource.h @@ -31,27 +31,27 @@ * controlled, as UWORD32 is used as datatype which always is 32 bits wide). **/ class PseudoRandomSource { - public: - /** - * construct a PseudoRandomSource object - * \param s the seed - **/ - PseudoRandomSource (UWORD32 s) : Value(s) {} ; + public: + /** + * construct a PseudoRandomSource object + * \param s the seed + **/ + PseudoRandomSource(UWORD32 s) : Value(s){}; - /** - * get a pseudo-random value from {0,...,n-1} - * \param n the range of the random value to be returned - * \return a number >= 0 and <= n - 1 - * - * After calling getValue, the next getValue call will use the next state - * of the random number generator (analogous to the C rand() function) - **/ - UWORD32 getValue (UWORD32 n) ; + /** + * get a pseudo-random value from {0,...,n-1} + * \param n the range of the random value to be returned + * \return a number >= 0 and <= n - 1 + * + * After calling getValue, the next getValue call will use the next state + * of the random number generator (analogous to the C rand() function) + **/ + UWORD32 getValue(UWORD32 n); - private: - static const UWORD32 A = 1367208549 ; - static const UWORD32 C = 1 ; - UWORD32 Value ; -} ; + private: + static const UWORD32 A = 1367208549; + static const UWORD32 C = 1; + UWORD32 Value; +}; #endif // ndef SH_PSEUDORANDOMSOURCE_H diff --git a/src/RGBTriple.cc b/src/RGBTriple.cc index cb48119..af7feff 100644 --- a/src/RGBTriple.cc +++ b/src/RGBTriple.cc @@ -20,20 +20,17 @@ #include "RGBTriple.h" -UWORD32 RGBTriple::calcDistance (const RGBTriple& t) const -{ - int dr = (int) Red - (int) t.Red ; - int dg = (int) Green - (int) t.Green ; - int db = (int) Blue - (int) t.Blue ; - return (UWORD32) (dr*dr + dg*dg + db*db) ; +UWORD32 RGBTriple::calcDistance(const RGBTriple &t) const { + int dr = (int)Red - (int)t.Red; + int dg = (int)Green - (int)t.Green; + int db = (int)Blue - (int)t.Blue; + return (UWORD32)(dr * dr + dg * dg + db * db); } -bool RGBTriple::operator== (const RGBTriple& t) const -{ - return ((Red == t.Red) && (Green == t.Green) && (Blue == t.Blue)) ; +bool RGBTriple::operator==(const RGBTriple &t) const { + return ((Red == t.Red) && (Green == t.Green) && (Blue == t.Blue)); } -bool RGBTriple::operator!= (const RGBTriple& t) const -{ - return ((Red != t.Red) || (Green != t.Green) || (Blue != t.Blue)) ; +bool RGBTriple::operator!=(const RGBTriple &t) const { + return ((Red != t.Red) || (Green != t.Green) || (Blue != t.Blue)); } diff --git a/src/RGBTriple.h b/src/RGBTriple.h index e4e31d2..0876cc4 100644 --- a/src/RGBTriple.h +++ b/src/RGBTriple.h @@ -24,32 +24,30 @@ #include "common.h" class RGBTriple { - public: - RGBTriple (void) - : Red(0), Green(0), Blue(0) {} ; - RGBTriple (BYTE r, BYTE g, BYTE b) - : Red(r), Green(g), Blue(b) {} ; - - /** - * get the squared distance in the RGB cube between this triple and the triple t - * \param t another RGB triple - * \return the square of the euclidean distance between this and t - **/ - UWORD32 calcDistance (const RGBTriple& t) const ; - - /** - * returns true iff this triple and t are equal (i.e. have the same rgb values) - **/ - bool operator== (const RGBTriple& t) const ; - - /** - * return true iff this triple and t are not equal (i.e. have different rgb values) - **/ - bool operator!= (const RGBTriple& t) const ; - - BYTE Red ; - BYTE Green ; - BYTE Blue ; -} ; + public: + RGBTriple(void) : Red(0), Green(0), Blue(0){}; + RGBTriple(BYTE r, BYTE g, BYTE b) : Red(r), Green(g), Blue(b){}; + + /** + * get the squared distance in the RGB cube between this triple and the triple t + * \param t another RGB triple + * \return the square of the euclidean distance between this and t + **/ + UWORD32 calcDistance(const RGBTriple &t) const; + + /** + * returns true iff this triple and t are equal (i.e. have the same rgb values) + **/ + bool operator==(const RGBTriple &t) const; + + /** + * return true iff this triple and t are not equal (i.e. have different rgb values) + **/ + bool operator!=(const RGBTriple &t) const; + + BYTE Red; + BYTE Green; + BYTE Blue; +}; #endif // ndef SH_RGBTRIPLE_H diff --git a/src/RandomSource.cc b/src/RandomSource.cc index cea455e..4c0ffab 100644 --- a/src/RandomSource.cc +++ b/src/RandomSource.cc @@ -22,98 +22,90 @@ #include #include "BitString.h" +#include "RandomSource.h" #include "common.h" #include "error.h" #include "msg.h" -#include "RandomSource.h" // the global RandomSource object -RandomSource RndSrc ; +RandomSource RndSrc; -RandomSource::RandomSource () -{ - RandomBytePos = 8 ; +RandomSource::RandomSource() { + RandomBytePos = 8; #ifdef HAVE_DEV_URANDOM - if ((RandomInput = fopen ("/dev/urandom", "r")) == NULL) { - Warning w (_("could not open /dev/urandom, using standard library random numbers instead.")) ; - w.printMessage() ; - RandomInput = NULL ; - srand ((unsigned int) time (NULL)) ; - } + if ((RandomInput = fopen("/dev/urandom", "r")) == NULL) { + Warning w(_("could not open /dev/urandom, using standard library random " + "numbers instead.")); + w.printMessage(); + RandomInput = NULL; + srand((unsigned int)time(NULL)); + } #else - RandomInput = NULL ; - srand ((unsigned int) time (NULL)) ; + RandomInput = NULL; + srand((unsigned int)time(NULL)); #endif } -RandomSource::~RandomSource() -{ - if (RandomInput != NULL) { - if (fclose (RandomInput) != 0) { - throw SteghideError (_("could not close random input file.")) ; - } - } +RandomSource::~RandomSource() { + if (RandomInput != NULL) { + if (fclose(RandomInput) != 0) { + throw SteghideError(_("could not close random input file.")); + } + } } -BYTE RandomSource::getByte () -{ - BYTE retval = 0 ; +BYTE RandomSource::getByte() { + BYTE retval = 0; #ifndef NORANDOM - if (RandomInput != NULL) { - retval = getc (RandomInput) ; - } - else { - retval = (BYTE) (256.0 * (rand() / (RAND_MAX + 1.0))) ; - } + if (RandomInput != NULL) { + retval = getc(RandomInput); + } else { + retval = (BYTE)(256.0 * (rand() / (RAND_MAX + 1.0))); + } #endif - return retval ; + return retval; } -std::vector RandomSource::getBytes (unsigned int n) -{ - std::vector retval ; - for (unsigned int i = 0 ; i < n ; i++) { - retval.push_back (getByte()) ; - } - return retval ; +std::vector RandomSource::getBytes(unsigned int n) { + std::vector retval; + for (unsigned int i = 0; i < n; i++) { + retval.push_back(getByte()); + } + return retval; } -BitString RandomSource::getBits (unsigned int n) -{ - BitString retval ; - BYTE rndbyte = 0 ; - unsigned int bitsused = 8 ; - while (n > 0) { - if (bitsused == 8) { - rndbyte = getByte() ; - bitsused = 0 ; - } - retval.append ((BIT) (rndbyte & 1)) ; - rndbyte = rndbyte >> 1 ; - bitsused++ ; - n-- ; - } - return retval ; +BitString RandomSource::getBits(unsigned int n) { + BitString retval; + BYTE rndbyte = 0; + unsigned int bitsused = 8; + while (n > 0) { + if (bitsused == 8) { + rndbyte = getByte(); + bitsused = 0; + } + retval.append((BIT)(rndbyte & 1)); + rndbyte = rndbyte >> 1; + bitsused++; + n--; + } + return retval; } -bool RandomSource::getBool() -{ - if (RandomBytePos == 8) { - RandomByte = getByte() ; - RandomBytePos = 0 ; - } - bool retval = (RandomByte & (1 << RandomBytePos)) ; - RandomBytePos++ ; - return retval ; +bool RandomSource::getBool() { + if (RandomBytePos == 8) { + RandomByte = getByte(); + RandomBytePos = 0; + } + bool retval = (RandomByte & (1 << RandomBytePos)); + RandomBytePos++; + return retval; } -unsigned long RandomSource::getValue (unsigned long n) -{ - const unsigned long ceilvalue = 0x1000000UL ; - myassert (n < ceilvalue) ; - unsigned long value = ((unsigned long) (getByte() << 16)) | - ((unsigned long) (getByte() << 8)) | - ((unsigned long) getByte()) ; +unsigned long RandomSource::getValue(unsigned long n) { + const unsigned long ceilvalue = 0x1000000UL; + myassert(n < ceilvalue); + unsigned long value = ((unsigned long)(getByte() << 16)) | ((unsigned long)(getByte() << 8)) | + ((unsigned long)getByte()); - return (unsigned long) ((((double) value) / ((double) ceilvalue)) * ((double) n)) ; + return (unsigned long)((((double)value) / ((double)ceilvalue)) * ((double)n)); } diff --git a/src/RandomSource.h b/src/RandomSource.h index 7d84a50..f763da0 100644 --- a/src/RandomSource.h +++ b/src/RandomSource.h @@ -24,58 +24,58 @@ #include #include -class BitString ; +class BitString; /** * \class RandomSource * \brief objects of this class are used as a source of random (non reproduceable) data **/ class RandomSource { - public: - RandomSource (void) ; - ~RandomSource (void) ; + public: + RandomSource(void); + ~RandomSource(void); - /** - * get a random byte - * \return a random byte - **/ - BYTE getByte (void) ; + /** + * get a random byte + * \return a random byte + **/ + BYTE getByte(void); - /** - * get n random bytes - * \param n the number of requested random bytes - * \return n random bytes - **/ - std::vector getBytes (unsigned int n) ; + /** + * get n random bytes + * \param n the number of requested random bytes + * \return n random bytes + **/ + std::vector getBytes(unsigned int n); - /** - * get n random bits - * \param n the number of requested random bits - * \return a BitString containing n random bits - **/ - BitString getBits (unsigned int n) ; + /** + * get n random bits + * \param n the number of requested random bits + * \return a BitString containing n random bits + **/ + BitString getBits(unsigned int n); - /** - * get a boolean value - * \return true of false with equal probability - **/ - bool getBool (void) ; + /** + * get a boolean value + * \return true of false with equal probability + **/ + bool getBool(void); - /** - * get a random value - * \param n the range of the random value to be returned - * \return a random number in {0,...,n-1} - **/ - unsigned long getValue (unsigned long n) ; + /** + * get a random value + * \param n the range of the random value to be returned + * \return a random number in {0,...,n-1} + **/ + unsigned long getValue(unsigned long n); - private: - unsigned int RandomBytePos ; - BYTE RandomByte ; - /** - * determines the random input - is either opened file pointer to - * /dev/urandom or NULL (the rand() function is then used as random source) - **/ - FILE *RandomInput ; -} ; + private: + unsigned int RandomBytePos; + BYTE RandomByte; + /** + * determines the random input - is either opened file pointer to + * /dev/urandom or NULL (the rand() function is then used as random source) + **/ + FILE *RandomInput; +}; #endif // ndef SH_RANDOMSOURCE_H diff --git a/src/SMDConstructionHeuristic.cc b/src/SMDConstructionHeuristic.cc index c2be01d..f34c61e 100644 --- a/src/SMDConstructionHeuristic.cc +++ b/src/SMDConstructionHeuristic.cc @@ -18,41 +18,39 @@ * */ +#include "SMDConstructionHeuristic.h" #include "Edge.h" #include "Graph.h" #include "Matching.h" -#include "SMDConstructionHeuristic.h" #include "Vertex.h" #include -SMDConstructionHeuristic::SMDConstructionHeuristic (Graph* g, Matching* m, float goal) - : MatchingAlgorithm (g, m, goal) -{ - Vertices = std::vector (g->getNumVertices()) ; - for (VertexLabel l = 0 ; l < g->getNumVertices() ; l++) { - Vertices[l] = g->getVertex(l) ; - myassert (m->isExposed (Vertices[l])) ; - } +SMDConstructionHeuristic::SMDConstructionHeuristic(Graph *g, Matching *m, float goal) + : MatchingAlgorithm(g, m, goal) { + Vertices = std::vector(g->getNumVertices()); + for (VertexLabel l = 0; l < g->getNumVertices(); l++) { + Vertices[l] = g->getVertex(l); + myassert(m->isExposed(Vertices[l])); + } - sort (Vertices.begin(), Vertices.end(), SmallerVertexDegree()) ; + sort(Vertices.begin(), Vertices.end(), SmallerVertexDegree()); } -void SMDConstructionHeuristic::run (void) -{ - for (VertexLabel l = 0 ; l < Vertices.size() ; l++) { - if (TheMatching->isExposed(Vertices[l]) && Vertices[l]->getDegree() > 0) { - Vertex* v1 = Vertices[l] ; - v1->updateShortestEdge() ; - Edge* e = v1->getShortestEdge() ; - Vertex* v2 = e->getOtherVertex (v1) ; +void SMDConstructionHeuristic::run(void) { + for (VertexLabel l = 0; l < Vertices.size(); l++) { + if (TheMatching->isExposed(Vertices[l]) && Vertices[l]->getDegree() > 0) { + Vertex *v1 = Vertices[l]; + v1->updateShortestEdge(); + Edge *e = v1->getShortestEdge(); + Vertex *v2 = e->getOtherVertex(v1); - TheMatching->addEdge(*e) ; + TheMatching->addEdge(*e); - v1->markDeleted() ; - v2->markDeleted() ; - } - } + v1->markDeleted(); + v2->markDeleted(); + } + } - TheGraph->unmarkDeletedAllVertices() ; + TheGraph->unmarkDeletedAllVertices(); } diff --git a/src/SMDConstructionHeuristic.h b/src/SMDConstructionHeuristic.h index 2d3054c..114be6a 100644 --- a/src/SMDConstructionHeuristic.h +++ b/src/SMDConstructionHeuristic.h @@ -30,24 +30,24 @@ * \brief an implementation of the "static minimum degree" heuristic for contructing a matching **/ class SMDConstructionHeuristic : public MatchingAlgorithm { - public: - SMDConstructionHeuristic (Graph* g, Matching* m, float goal = 100.0) ; + public: + SMDConstructionHeuristic(Graph *g, Matching *m, float goal = 100.0); - virtual ~SMDConstructionHeuristic (void) {} ; + virtual ~SMDConstructionHeuristic(void){}; - const char* getName (void) const - { return "Static Minimum Degree Construction Heuristic" ; } ; + const char *getName(void) const { return "Static Minimum Degree Construction Heuristic"; }; - void run (void) ; + void run(void); - private: - class SmallerVertexDegree { - public: - bool operator() (const Vertex* v1, const Vertex* v2) - { return (v1->getDegree() < v2->getDegree()) ; } ; - } ; + private: + class SmallerVertexDegree { + public: + bool operator()(const Vertex *v1, const Vertex *v2) { + return (v1->getDegree() < v2->getDegree()); + }; + }; - std::vector Vertices ; -} ; + std::vector Vertices; +}; #endif // ndef SH_SMDCONSTRUCTIONHEURISTIC_H diff --git a/src/SampleOccurence.h b/src/SampleOccurence.h index 6d7bb0c..41ccbd9 100644 --- a/src/SampleOccurence.h +++ b/src/SampleOccurence.h @@ -24,28 +24,24 @@ #include "Vertex.h" class SampleOccurence { - public: - SampleOccurence (Vertex *v, unsigned short i) - : TheVertex(v), Index(i) {} ; + public: + SampleOccurence(Vertex *v, unsigned short i) : TheVertex(v), Index(i){}; - Vertex *getVertex (void) const - { return TheVertex ; } ; + Vertex *getVertex(void) const { return TheVertex; }; - void setVertex (Vertex* v) - { TheVertex = v ; } ; + void setVertex(Vertex *v) { TheVertex = v; }; - unsigned short getIndex (void) const - { return Index ; } ; + unsigned short getIndex(void) const { return Index; }; - void setIndex (unsigned short i) - { Index = i ; } ; + void setIndex(unsigned short i) { Index = i; }; - bool operator== (const SampleOccurence& soc) const - { return ((TheVertex->getLabel() == soc.TheVertex->getLabel()) && (Index == soc.Index)) ; } ; + bool operator==(const SampleOccurence &soc) const { + return ((TheVertex->getLabel() == soc.TheVertex->getLabel()) && (Index == soc.Index)); + }; - private: - Vertex *TheVertex ; - unsigned short Index ; -} ; + private: + Vertex *TheVertex; + unsigned short Index; +}; #endif // ndef SH_SAMPLEOCCURENCE_H diff --git a/src/SampleValue.cc b/src/SampleValue.cc index 4c240bc..2d45a85 100644 --- a/src/SampleValue.cc +++ b/src/SampleValue.cc @@ -18,50 +18,40 @@ * */ -#include "common.h" #include "SampleValue.h" #include "CvrStgFile.h" +#include "common.h" -SampleValue::SampleValue () - : Label(0) -{ - NumEdges = new UWORD32[Globs.TheCvrStgFile->getEmbValueModulus()] ; +SampleValue::SampleValue() : Label(0) { + NumEdges = new UWORD32[Globs.TheCvrStgFile->getEmbValueModulus()]; } -SampleValue::~SampleValue () -{ - delete[] NumEdges ; -} +SampleValue::~SampleValue() { delete[] NumEdges; } -void SampleValue::incNumEdges (EmbValue t) -{ - NumEdges[t]++ ; -} +void SampleValue::incNumEdges(EmbValue t) { NumEdges[t]++; } -void SampleValue::decNumEdges (EmbValue t) -{ - myassert (NumEdges[t] > 0) ; - NumEdges[t]-- ; +void SampleValue::decNumEdges(EmbValue t) { + myassert(NumEdges[t] > 0); + NumEdges[t]--; } -bool SampleValue::isNeighbour (const SampleValue *s) const -{ +bool SampleValue::isNeighbour(const SampleValue *s) const { #ifdef DEBUG - printDebug (5, "SampleValue::isNeighbour: Distance: %lu, Radius: %lu\n", calcDistance(s), Globs.TheCvrStgFile->getRadius()) ; + printDebug(5, "SampleValue::isNeighbour: Distance: %lu, Radius: %lu\n", calcDistance(s), + Globs.TheCvrStgFile->getRadius()); #endif - return (calcDistance (s) <= Globs.TheCvrStgFile->getRadius()) ; + return (calcDistance(s) <= Globs.TheCvrStgFile->getRadius()); } -void SampleValue::print (unsigned short spc) const -{ - char* space = new char[spc + 1] ; - for (unsigned short i = 0 ; i < spc ; i++) { - space[i] = ' ' ; - } - space[spc] = '\0' ; - std::cerr << space << "SampleValue:" << std::endl ; - std::cerr << space << " Label: " << getLabel() << std::endl ; - std::cerr << space << " Name: " << getName() << std::endl ; - std::cerr << space << " Key(hex): " << std::hex << getKey() << std::dec << std::endl ; - std::cerr << space << " EValue: " << (unsigned int) getEmbeddedValue() << std::endl ; +void SampleValue::print(unsigned short spc) const { + char *space = new char[spc + 1]; + for (unsigned short i = 0; i < spc; i++) { + space[i] = ' '; + } + space[spc] = '\0'; + std::cerr << space << "SampleValue:" << std::endl; + std::cerr << space << " Label: " << getLabel() << std::endl; + std::cerr << space << " Name: " << getName() << std::endl; + std::cerr << space << " Key(hex): " << std::hex << getKey() << std::dec << std::endl; + std::cerr << space << " EValue: " << (unsigned int)getEmbeddedValue() << std::endl; } diff --git a/src/SampleValue.h b/src/SampleValue.h index 872ecb1..f362b74 100644 --- a/src/SampleValue.h +++ b/src/SampleValue.h @@ -26,7 +26,7 @@ #include "common.h" -class CvrStgFile ; +class CvrStgFile; /** * \class SampleValue @@ -44,7 +44,7 @@ class CvrStgFile ; * * s1 and s2 are called neighbours if s1->isNeighbour(s2) is true * - * s1->getKey() == s2->getKey() iff s1 == s2 + * s1->getKey() == s2->getKey() iff s1 == s2 * * s1 == s2 implies s1->getDistance(s2) == 0 * BUT: s1->getDistance(s2) == 0 does not imply s1 == s2 @@ -59,113 +59,105 @@ class CvrStgFile ; * before using any method of a SampleValue (or derived) object. **/ class SampleValue { - public: - SampleValue (void) ; - - virtual ~SampleValue (void) ; - - /** - * get the nearest (with the least distance to this sample value) sample value whose - * embedded value equals the specified target - * \param t the target embedded value - * - * If two or more target sample values have equal distance each of them should be - * returned with equal probability. - * - * The returned SampleValue object should be deleted by the callser. - **/ - virtual SampleValue* getNearestTargetSampleValue (EmbValue t) const = 0 ; - - /** - * calculate the distance between the sample value s and this sample value - * \param s a sample value of the same type as this - * \return the distance - **/ - virtual UWORD32 calcDistance (const SampleValue *s) const = 0 ; - - /** - * return a short name uniquely identifying this sample value - **/ - virtual std::string getName (void) const = 0 ; - - /** - * is the sample value s a neighbour of this sample value ? - * \return true iff this and s are neighbours - * - * This is implemented as (calcDistance() <= Radius) but may be overridden by - * derived classes. - **/ - virtual bool isNeighbour (const SampleValue* s) const ; - - /** - * get the value that is embedded in this sample value (must be >=0 and { - bool operator() (const SampleValue* s1, const SampleValue *s2) const - { - return (*s1 == *s2) ; - } -} ; - -struct SampleValuesLess : public std::binary_function { - bool operator() (const SampleValue* s1, const SampleValue *s2) const - { - return (*s1 < *s2) ; - } -} ; - -struct SampleValueHash : public std::unary_function { - size_t operator() (const SampleValue* s) const - { - std::hash h ; - return h(s->getKey()) ; - } -} ; + public: + SampleValue(void); + + virtual ~SampleValue(void); + + /** + * get the nearest (with the least distance to this sample value) sample value whose + * embedded value equals the specified target + * \param t the target embedded value + * + * If two or more target sample values have equal distance each of them should be + * returned with equal probability. + * + * The returned SampleValue object should be deleted by the callser. + **/ + virtual SampleValue *getNearestTargetSampleValue(EmbValue t) const = 0; + + /** + * calculate the distance between the sample value s and this sample value + * \param s a sample value of the same type as this + * \return the distance + **/ + virtual UWORD32 calcDistance(const SampleValue *s) const = 0; + + /** + * return a short name uniquely identifying this sample value + **/ + virtual std::string getName(void) const = 0; + + /** + * is the sample value s a neighbour of this sample value ? + * \return true iff this and s are neighbours + * + * This is implemented as (calcDistance() <= Radius) but may be overridden by + * derived classes. + **/ + virtual bool isNeighbour(const SampleValue *s) const; + + /** + * get the value that is embedded in this sample value (must be >=0 and { + bool operator()(const SampleValue *s1, const SampleValue *s2) const { return (*s1 == *s2); } +}; + +struct SampleValuesLess : public std::binary_function { + bool operator()(const SampleValue *s1, const SampleValue *s2) const { return (*s1 < *s2); } +}; + +struct SampleValueHash : public std::unary_function { + size_t operator()(const SampleValue *s) const { + std::hash h; + return h(s->getKey()); + } +}; #endif // ndef SH_CVRSTGSAMPLE_H diff --git a/src/SampleValueAdjacencyList.cc b/src/SampleValueAdjacencyList.cc index fa9b3e8..e7442a1 100644 --- a/src/SampleValueAdjacencyList.cc +++ b/src/SampleValueAdjacencyList.cc @@ -31,88 +31,89 @@ #include "WavPCMSampleValue.h" #include "common.h" -SampleValueAdjacencyList::SampleValueAdjacencyList (SampleValueLabel numsvs) -{ - AdjacencyList = std::vector > (numsvs) ; +SampleValueAdjacencyList::SampleValueAdjacencyList(SampleValueLabel numsvs) { + AdjacencyList = std::vector>(numsvs); } -bool SampleValueAdjacencyList::operator== (const SampleValueAdjacencyList& sval) -{ - bool equal = false ; - if (AdjacencyList.size() == sval.AdjacencyList.size()) { - equal = true ; - for (unsigned long i = 0 ; i < AdjacencyList.size() ; i++) { - bool rowequal = false ; - if (AdjacencyList[i].size() == sval.AdjacencyList[i].size()) { - std::set thisset (AdjacencyList[i].begin(), AdjacencyList[i].end()) ; - std::set::const_iterator thisit = thisset.begin() ; - std::set otherset (sval.AdjacencyList[i].begin(), sval.AdjacencyList[i].end()) ; - std::set::const_iterator otherit = otherset.begin() ; - rowequal = true ; - for ( ; thisit != thisset.end() && otherit != otherset.end() ; thisit++, otherit++) { - rowequal = (**thisit == **otherit) ; - } - } +bool SampleValueAdjacencyList::operator==(const SampleValueAdjacencyList &sval) { + bool equal = false; + if (AdjacencyList.size() == sval.AdjacencyList.size()) { + equal = true; + for (unsigned long i = 0; i < AdjacencyList.size(); i++) { + bool rowequal = false; + if (AdjacencyList[i].size() == sval.AdjacencyList[i].size()) { + std::set thisset(AdjacencyList[i].begin(), + AdjacencyList[i].end()); + std::set::const_iterator thisit = thisset.begin(); + std::set otherset(sval.AdjacencyList[i].begin(), + sval.AdjacencyList[i].end()); + std::set::const_iterator otherit = + otherset.begin(); + rowequal = true; + for (; thisit != thisset.end() && otherit != otherset.end(); thisit++, otherit++) { + rowequal = (**thisit == **otherit); + } + } - equal = rowequal && equal ; - } - } - return equal ; + equal = rowequal && equal; + } + } + return equal; } -void SampleValueAdjacencyList::sort () -{ - for (SampleValueLabel lbl = 0 ; lbl < AdjacencyList.size() ; lbl++) { - std::vector& row = AdjacencyList[lbl] ; +void SampleValueAdjacencyList::sort() { + for (SampleValueLabel lbl = 0; lbl < AdjacencyList.size(); lbl++) { + std::vector &row = AdjacencyList[lbl]; - if (row.size() > 0) { - UWORD32* distances = new UWORD32[row.size() + 1] ; - for (unsigned int i = 0 ; i < row.size() ; i++) { - distances[i] = Globs.TheGraph->SampleValues[lbl]->calcDistance (row[i]) ; - } + if (row.size() > 0) { + UWORD32 *distances = new UWORD32[row.size() + 1]; + for (unsigned int i = 0; i < row.size(); i++) { + distances[i] = Globs.TheGraph->SampleValues[lbl]->calcDistance(row[i]); + } - quicksort (row, distances, 0, row.size() - 1) ; + quicksort(row, distances, 0, row.size() - 1); - delete[] distances ; - } - } + delete[] distances; + } + } } -void SampleValueAdjacencyList::quicksort (std::vector& oppneighs, UWORD32* distances, unsigned int l, unsigned int r) -{ - if (l < r) { - unsigned int p = partition (oppneighs, distances, l, r, distances[r]) ; - if (p > 0) { - quicksort (oppneighs, distances, l, p - 1) ; - } - quicksort (oppneighs, distances, p + 1, r) ; - } +void SampleValueAdjacencyList::quicksort(std::vector &oppneighs, UWORD32 *distances, + unsigned int l, unsigned int r) { + if (l < r) { + unsigned int p = partition(oppneighs, distances, l, r, distances[r]); + if (p > 0) { + quicksort(oppneighs, distances, l, p - 1); + } + quicksort(oppneighs, distances, p + 1, r); + } } -unsigned int SampleValueAdjacencyList::partition (std::vector& oppneighs, UWORD32* distances, unsigned int l, unsigned int r, UWORD32 x) -{ - unsigned int i = l, j = r ; - while (i < j) { - while ((distances[i] < x) && (i < r)) { - i++ ; - } - while ((distances[j] >= x) && (j > l)) { - j-- ; - } - if (i < j) { - swap (oppneighs, distances, i, j) ; - } - } - swap (oppneighs, distances, i, r) ; - return i ; +unsigned int SampleValueAdjacencyList::partition(std::vector &oppneighs, + UWORD32 *distances, unsigned int l, unsigned int r, + UWORD32 x) { + unsigned int i = l, j = r; + while (i < j) { + while ((distances[i] < x) && (i < r)) { + i++; + } + while ((distances[j] >= x) && (j > l)) { + j--; + } + if (i < j) { + swap(oppneighs, distances, i, j); + } + } + swap(oppneighs, distances, i, r); + return i; } -void SampleValueAdjacencyList::swap (std::vector& oppneighs, UWORD32* distances, unsigned int i, unsigned int j) -{ - SampleValue* tmp1 = oppneighs[i] ; - UWORD32 tmp2 = distances[i] ; - oppneighs[i] = oppneighs[j] ; - distances[i] = distances[j] ; - oppneighs[j] = tmp1 ; - distances[j] = tmp2 ; +void SampleValueAdjacencyList::swap(std::vector &oppneighs, UWORD32 *distances, + unsigned int i, unsigned int j) { + SampleValue *tmp1 = oppneighs[i]; + UWORD32 tmp2 = distances[i]; + oppneighs[i] = oppneighs[j]; + distances[i] = distances[j]; + oppneighs[j] = tmp1; + distances[j] = tmp2; } diff --git a/src/SampleValueAdjacencyList.h b/src/SampleValueAdjacencyList.h index 047fe46..9f3f659 100644 --- a/src/SampleValueAdjacencyList.h +++ b/src/SampleValueAdjacencyList.h @@ -31,41 +31,46 @@ * \brief an adjacency list-like data structur for sample values **/ class SampleValueAdjacencyList { - public: - /** - * construct a SampleValueAdjacencyList with numsvs rows - **/ - SampleValueAdjacencyList (SampleValueLabel numsvs) ; + public: + /** + * construct a SampleValueAdjacencyList with numsvs rows + **/ + SampleValueAdjacencyList(SampleValueLabel numsvs); - std::vector& operator[] (const SampleValueLabel lbl) - { return AdjacencyList[lbl] ; } ; + std::vector &operator[](const SampleValueLabel lbl) { + return AdjacencyList[lbl]; + }; - std::vector& operator[] (const SampleValue* sv) - { return AdjacencyList[sv->getLabel()] ; } ; + std::vector &operator[](const SampleValue *sv) { + return AdjacencyList[sv->getLabel()]; + }; - unsigned long getNumRows (void) const - { return AdjacencyList.size() ; } ; + unsigned long getNumRows(void) const { return AdjacencyList.size(); }; - /** - * check if every row contains the same set of sample values - **/ - bool operator== (const SampleValueAdjacencyList& sval) ; + /** + * check if every row contains the same set of sample values + **/ + bool operator==(const SampleValueAdjacencyList &sval); - /** - * sort the list in a way that the first entry of a row has the least distance to source sample value - **/ - void sort (void) ; + /** + * sort the list in a way that the first entry of a row has the least distance to source sample + *value + **/ + void sort(void); - private: - std::vector > AdjacencyList ; + private: + std::vector> AdjacencyList; - void quicksort (std::vector& oppneighs, UWORD32* distances, unsigned int l, unsigned int r) ; - /** - * partition oppneighs/distances into those with distances less than and those with distances greater than and equal to x - * \return the index in oppneighs/distances that separates the two - **/ - unsigned int partition (std::vector& oppneighs, UWORD32* distances, unsigned int l, unsigned int r, UWORD32 x) ; - void swap (std::vector& oppneighs, UWORD32* distances, unsigned int i, unsigned int j) ; -} ; + void quicksort(std::vector &oppneighs, UWORD32 *distances, unsigned int l, + unsigned int r); + /** + * partition oppneighs/distances into those with distances less than and those with distances + *greater than and equal to x \return the index in oppneighs/distances that separates the two + **/ + unsigned int partition(std::vector &oppneighs, UWORD32 *distances, + unsigned int l, unsigned int r, UWORD32 x); + void swap(std::vector &oppneighs, UWORD32 *distances, unsigned int i, + unsigned int j); +}; #endif // ndef SH_SAMPLEVALUEADJACENCYLIST_H diff --git a/src/SeedCracker.cc b/src/SeedCracker.cc index 3d077bb..b409d4f 100644 --- a/src/SeedCracker.cc +++ b/src/SeedCracker.cc @@ -1,7 +1,7 @@ /* * Stegseek 0.5 - a steghide cracker * Copyright (C) 2020 Rick de Jager - * + * * Based on the work of Stefan Hetzl * * This program is free software; you can redistribute it and/or @@ -22,169 +22,165 @@ #include "SeedCracker.h" -#include "error.h" -#include "Utils.h" -#include "common.h" -#include "EmbData.h" -#include "Selector.h" -#include "Extractor.h" #include "CvrStgFile.h" -#include "EncryptionMode.h" +#include "EmbData.h" #include "EncryptionAlgorithm.h" +#include "EncryptionMode.h" +#include "Extractor.h" +#include "Selector.h" +#include "Utils.h" +#include "common.h" +#include "error.h" - -void SeedCracker::crack () -{ - // Initialize threads - std::vector ThreadPool ; - unsigned int threads = Args.Threads.getValue() ; - bool metricsEnabled = Args.Verbosity.getValue() != QUIET ; - - // Add a thread to keep track of metrics - if (metricsEnabled) { - ThreadPool.push_back(std::thread([this] {metrics(UWORD32_MAX, "seeds"); })) ; - } - - // Add n worker threads - unsigned int part = UWORD32_MAX / threads ; - for (unsigned int i = 0; i < threads; i++) { - ThreadPool.push_back(std::thread([this, i, part, metricsEnabled] { - consume(i*part, (i+1)*part, metricsEnabled); - })) ; - } - - // Join all worker threads - for (unsigned int i = 0; i < threads; i++) { - ThreadPool.back().join() ; - ThreadPool.pop_back() ; - } - - // Set stopped flag and terminate the metrics thread - stopped = true ; - if (metricsEnabled) { - ThreadPool.back().join() ; - ThreadPool.pop_back() ; - } - - // If we didn't find a passphrase, print a message directly to stderr - if (!success) { - fprintf(stderr, "[!] Could not find a valid seed.\n") ; - } else { - // Output the found seed. At the moment this isn't particularly - // useful to then end-user, it's nice for debugging - Message msg ; - msg.setMessage("[i] --> Found seed: \"%x\"", foundResult.seed) ; - msg.printMessage() ; - finish() ; - } +void SeedCracker::crack() { + // Initialize threads + std::vector ThreadPool; + unsigned int threads = Args.Threads.getValue(); + bool metricsEnabled = Args.Verbosity.getValue() != QUIET; + + // Add a thread to keep track of metrics + if (metricsEnabled) { + ThreadPool.push_back(std::thread([this] { metrics(UWORD32_MAX, "seeds"); })); + } + + // Add n worker threads + unsigned int part = UWORD32_MAX / threads; + for (unsigned int i = 0; i < threads; i++) { + ThreadPool.push_back(std::thread([this, i, part, metricsEnabled] { + consume(i * part, (i + 1) * part, metricsEnabled); + })); + } + + // Join all worker threads + for (unsigned int i = 0; i < threads; i++) { + ThreadPool.back().join(); + ThreadPool.pop_back(); + } + + // Set stopped flag and terminate the metrics thread + stopped = true; + if (metricsEnabled) { + ThreadPool.back().join(); + ThreadPool.pop_back(); + } + + // If we didn't find a passphrase, print a message directly to stderr + if (!success) { + fprintf(stderr, "[!] Could not find a valid seed.\n"); + } else { + // Output the found seed. At the moment this isn't particularly + // useful to then end-user, it's nice for debugging + Message msg; + msg.setMessage("[i] --> Found seed: \"%x\"", foundResult.seed); + msg.printMessage(); + finish(); + } } // Take jobs and crack 'em -void SeedCracker::consume (unsigned int i, unsigned int stop, bool metricsEnabled) -{ - while (!stopped && i < stop) - { - // Try extracting with this seed - if (trySeed(i)) - { - // Tell the other threads that they should stop - stopped = true ; - success = true ; - } - i++ ; - - // Incrementing an atomic int is quite costly, so don't do it if no one cares about its value - if (metricsEnabled) { - // Add to the perf metric - progress ++ ; - } - } +void SeedCracker::consume(unsigned int i, unsigned int stop, bool metricsEnabled) { + while (!stopped && i < stop) { + // Try extracting with this seed + if (trySeed(i)) { + // Tell the other threads that they should stop + stopped = true; + success = true; + } + i++; + + // Incrementing an atomic int is quite costly, so don't do it if no one + // cares about its value + if (metricsEnabled) { + // Add to the perf metric + progress++; + } + } } -bool SeedCracker::trySeed (UWORD32 seed) -{ - // First verify the magic - if (!verifyMagic(seed)) { - return false ; - } - // Next, try to interpret the remaining bits - // magic + enc mode + enc algo + plain size - // We _need_ to check the magic as well, since verifyMagic - // can throw false positives - const unsigned int requestedValues = 25 + 3 + 5 + 32 ; - - // Create a "proper" selector object - Selector sel (numSamples, seed) ; - EmbValue ev = 0 ; - unsigned int encAlgo = 0 ; - unsigned int encMode = 0 ; - unsigned int plainSize = 0 ; - unsigned long sv_idx = 0 ; - const int magics[25] = { - // Magic, "shm" in binary LE - 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, - // Code version (0) - 0, - } ; - for (unsigned int i = 0 ; i < requestedValues ; i++) { - for (unsigned int j = 0 ; j < samplesPerVertex ; j++, sv_idx++) { - ev = (ev + Globs.TheCvrStgFile->getEmbeddedValue (sel[sv_idx])) % EmbValueModulus; - } - // Check magic - if (i < 25) { - if (magics[i] != ev) { - return false ; - } - } - // Get enc algo - if (25 <= i && i < 30) { - encAlgo ^= ev << (i - 25) ; - if (encAlgo > 22) { - return false ; - } - } - // Get enc mode - if (30 <= i && i < 33) { - encMode ^= ev << (i - 30) ; - } - // get Plain size - if (33 <= i && i < 65) { - plainSize ^= ev << (i - 33) ; - if (plainSize * samplesPerVertex > numSamples - requestedValues * samplesPerVertex ) { - // This plain size wouldn't fit, so the seed must be wrong. - return false ; - } - } - ev = 0 ; - } - - // Save the values on success - foundResult = Result { - seed, - plainSize, - encAlgo, - encMode, - } ; - return true ; +bool SeedCracker::trySeed(UWORD32 seed) { + // First verify the magic + if (!verifyMagic(seed)) { + return false; + } + // Next, try to interpret the remaining bits + // magic + enc mode + enc algo + plain size + // We _need_ to check the magic as well, since verifyMagic + // can throw false positives + const unsigned int requestedValues = 25 + 3 + 5 + 32; + + // Create a "proper" selector object + Selector sel(numSamples, seed); + EmbValue ev = 0; + unsigned int encAlgo = 0; + unsigned int encMode = 0; + unsigned int plainSize = 0; + unsigned long sv_idx = 0; + const int magics[25] = {// Magic, "shm" in binary LE + 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, + // Code version (0) + 0}; + + for (unsigned int i = 0; i < requestedValues; i++) { + for (unsigned int j = 0; j < samplesPerVertex; j++, sv_idx++) { + ev = (ev + Globs.TheCvrStgFile->getEmbeddedValue(sel[sv_idx])) % EmbValueModulus; + } + // Check magic + if (i < 25) { + if (magics[i] != ev) { + return false; + } + } + // Get enc algo + if (25 <= i && i < 30) { + encAlgo ^= ev << (i - 25); + if (encAlgo > 22) { + return false; + } + } + // Get enc mode + if (30 <= i && i < 33) { + encMode ^= ev << (i - 30); + } + // get Plain size + if (33 <= i && i < 65) { + plainSize ^= ev << (i - 33); + if (plainSize * samplesPerVertex > numSamples - requestedValues * samplesPerVertex) { + // This plain size wouldn't fit, so the seed must be wrong. + return false; + } + } + ev = 0; + } + + // Save the values on success + foundResult = Result{ + seed, + plainSize, + encAlgo, + encMode, + }; + return true; } -void SeedCracker::finish() -{ - std::string size = Utils::formatHRSize(foundResult.plainSize / 8) ; - // Print directly to stderr s.t. the result will even be printed in quiet mode. - // There is no good reason to run this in quiet mode, and waiting for 5 minutes - // to realise you accidentically set -q would be annoying - fprintf(stderr, "Plain size: %s (compressed)\nEncryption Algorithm: %s\nEncryption Mode: %s\n", - size.c_str(), - EncryptionAlgorithm::translate(EncryptionAlgorithm::IRep(foundResult.encAlgo)).c_str(), - EncryptionMode::translate(EncryptionMode::IRep(foundResult.encMode)).c_str()) ; - - // Data is not encrypted :D - // Let's dump it to a file - if (foundResult.encAlgo == 0) { - Extractor ext (Args.StgFn.getValue(), foundResult.seed) ; - EmbData* emb = ext.extract() ; - extract(emb) ; - delete(emb) ; - } +void SeedCracker::finish() { + std::string size = Utils::formatHRSize(foundResult.plainSize / 8); + // Print directly to stderr s.t. the result will even be printed in quiet + // mode. There is no good reason to run this in quiet mode, and waiting for 5 + // minutes to realise you accidentically set -q would be annoying + fprintf(stderr, + "Plain size: %s (compressed)\n" + "Encryption Algorithm: %s\n" + "Encryption Mode: %s\n", + size.c_str(), + EncryptionAlgorithm::translate(EncryptionAlgorithm::IRep(foundResult.encAlgo)).c_str(), + EncryptionMode::translate(EncryptionMode::IRep(foundResult.encMode)).c_str()); + + // Data is not encrypted :D + // Let's dump it to a file + if (foundResult.encAlgo == 0) { + Extractor ext(Args.StgFn.getValue(), foundResult.seed); + EmbData *emb = ext.extract(); + extract(emb); + delete emb; + } } \ No newline at end of file diff --git a/src/SeedCracker.h b/src/SeedCracker.h index d6d66ca..9f2fa5f 100644 --- a/src/SeedCracker.h +++ b/src/SeedCracker.h @@ -2,9 +2,9 @@ * * Stegseek 0.5 - a steghide cracker * Copyright (C) 2020 Rick de Jager - * + * * Based on the work of Stefan Hetzl - * + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 @@ -24,31 +24,30 @@ #ifndef SH_SEEDCRACKER_H #define SH_SEEDCRACKER_H -#include #include +#include #include "Cracker.h" #include "Selector.h" struct Result { - unsigned int seed ; - unsigned int plainSize ; - unsigned int encAlgo ; - unsigned int encMode ; + unsigned int seed; + unsigned int plainSize; + unsigned int encAlgo; + unsigned int encMode; }; -class SeedCracker : Cracker{ - public: - SeedCracker () {}; - - void crack () ; +class SeedCracker : Cracker { + public: + SeedCracker(){}; - private: - bool trySeed (UWORD32) ; - void consume (unsigned int, unsigned int, bool) ; - void finish () ; - Result foundResult ; -} ; + void crack(); + private: + bool trySeed(UWORD32); + void consume(unsigned int, unsigned int, bool); + void finish(); + Result foundResult; +}; #endif // ndef SH_SEEDCRACKER_H diff --git a/src/Selector.cc b/src/Selector.cc index 4b8292a..b56ad4b 100644 --- a/src/Selector.cc +++ b/src/Selector.cc @@ -18,144 +18,134 @@ * */ +#include "Selector.h" #include "BitString.h" #include "MHashPP.h" #include "PseudoRandomSource.h" -#include "Selector.h" -Selector::Selector (UWORD32 m, std::string pp) - : Maximum(m), NumInArray(0) -{ - UWORD32 seed = 0 ; - MHASH td = mhash_init(MHASH_MD5); - mhash(td, pp.data(), pp.size() ) ; - - UWORD32 hash[4] ; - mhash_deinit (td, hash) ; - for (unsigned int i = 0 ; i < 4 ; i++) { - seed ^= hash[i] ; - } - PRandom = new PseudoRandomSource (seed) ; - - // Reserve some space to prevent many resizes - X.reserve(99) ; - Y.reserve(99) ; +Selector::Selector(UWORD32 m, std::string pp) : Maximum(m), NumInArray(0) { + UWORD32 seed = 0; + MHASH td = mhash_init(MHASH_MD5); + mhash(td, pp.data(), pp.size()); + + UWORD32 hash[4]; + mhash_deinit(td, hash); + for (unsigned int i = 0; i < 4; i++) { + seed ^= hash[i]; + } + PRandom = new PseudoRandomSource(seed); + + // Reserve some space to prevent many resizes + X.reserve(99); + Y.reserve(99); } -Selector::Selector (UWORD32 m, UWORD32 seed) - : Maximum(m), NumInArray(0) -{ - PRandom = new PseudoRandomSource (seed) ; - // Reserve some space to prevent many resizes - X.reserve(99) ; - Y.reserve(99) ; +Selector::Selector(UWORD32 m, UWORD32 seed) : Maximum(m), NumInArray(0) { + PRandom = new PseudoRandomSource(seed); + // Reserve some space to prevent many resizes + X.reserve(99); + Y.reserve(99); } -Selector::Selector (UWORD32 m) -{ - Maximum = m ; - X.resize(m) ; - for (UWORD32 i = 0 ; i < m ; i++) { - X[i] = i ; - } - NumInArray = m ; - PRandom = NULL ; +Selector::Selector(UWORD32 m) { + Maximum = m; + X.resize(m); + for (UWORD32 i = 0; i < m; i++) { + X[i] = i; + } + NumInArray = m; + PRandom = NULL; } -Selector::Selector (const std::vector& retvals) -{ - X = retvals ; - Maximum = retvals.size() ; - NumInArray = retvals.size() ; - PRandom = NULL ; +Selector::Selector(const std::vector &retvals) { + X = retvals; + Maximum = retvals.size(); + NumInArray = retvals.size(); + PRandom = NULL; } -Selector::~Selector () -{ - if (PRandom) { - delete PRandom ; - } +Selector::~Selector() { + if (PRandom) { + delete PRandom; + } } -UWORD32 Selector::operator[] (UWORD32 i) -{ - myassert (i < Maximum) ; - calculate(i + 1) ; - return X[i] ; +UWORD32 Selector::operator[](UWORD32 i) { + myassert(i < Maximum); + calculate(i + 1); + return X[i]; } -void Selector::calculate (UWORD32 m) -{ - UWORD32 j = NumInArray ; - - if (m > NumInArray) { - NumInArray = m ; - // Never downsize the vector - if (NumInArray > X.size()) { - X.resize (NumInArray) ; - Y.resize (NumInArray) ; - } - } - - for ( ; j < m ; j++) { - // k is a number from {j,...,Maximum-1} - UWORD32 k = j + PRandom->getValue(Maximum - j) ; - - UWORD32 i = 0 ; - // First we check whether this random number k has been seen before. - // In case of such a collision, we use 'j' as our "random" k instead. - // - // I think the original idea is that j can't collide with k, because k \in (j, max], - // However, k is actually \in [j, max]. It's still very unlikely to collide, so ¯\_(ツ)_/¯ - // - if (idxX (k, j, &i)) { // there exists i < j with X[i] = k - // use Y[i] instead of k - setX (j, Y[i]) ; - - if (X[j] > j) { // some future k could be X[j] - Y[j] = j ; - } - if (X[i] > j) { // some future k could be X[i] - Y[i] = j ; - UWORD32 l = 0 ; - if (idxX (Y[i], j, &l)) { - Y[i] = Y[l] ; - } - } - } - else { - setX (j, k) ; - Y[j] = j ; - } - - if (X[j] > j) { - UWORD32 i = 0 ; - if (idxX (Y[j], j, &i)) { - Y[j] = Y[i] ; - } - } - } +void Selector::calculate(UWORD32 m) { + UWORD32 j = NumInArray; + + if (m > NumInArray) { + NumInArray = m; + // Never downsize the vector + if (NumInArray > X.size()) { + X.resize(NumInArray); + Y.resize(NumInArray); + } + } + + for (; j < m; j++) { + // k is a number from {j,...,Maximum-1} + UWORD32 k = j + PRandom->getValue(Maximum - j); + + UWORD32 i = 0; + // First we check whether this random number k has been seen before. + // In case of such a collision, we use 'j' as our "random" k instead. + // + // I think the original idea is that j can't collide with k, because k \in + // (j, max], However, k is actually \in [j, max]. It's still very unlikely + // to collide, so ¯\_(ツ)_/¯ + // + if (idxX(k, j, &i)) { // there exists i < j with X[i] = k + // use Y[i] instead of k + setX(j, Y[i]); + + if (X[j] > j) { // some future k could be X[j] + Y[j] = j; + } + if (X[i] > j) { // some future k could be X[i] + Y[i] = j; + UWORD32 l = 0; + if (idxX(Y[i], j, &l)) { + Y[i] = Y[l]; + } + } + } else { + setX(j, k); + Y[j] = j; + } + + if (X[j] > j) { + UWORD32 i = 0; + if (idxX(Y[j], j, &i)) { + Y[j] = Y[i]; + } + } + } } // This function tries to find an index in X, such that X[index] = v. // The index must be in the range [0..m] // -// It is mainly used to check for collisions with previously generated random numbers +// It is mainly used to check for collisions with previously generated random +// numbers // // Random number, Index j, Pointer to i -bool Selector::idxX (UWORD32 v, UWORD32 m, UWORD32* p) const -{ - bool retval = false ; - std::unordered_map::const_iterator it = Xreversed.find (v) ; - if ((it != Xreversed.end()) && (it->second < m)) { - *p = it->second ; - retval = true ; - } - return retval ; +bool Selector::idxX(UWORD32 v, UWORD32 m, UWORD32 *p) const { + bool retval = false; + std::unordered_map::const_iterator it = Xreversed.find(v); + if ((it != Xreversed.end()) && (it->second < m)) { + *p = it->second; + retval = true; + } + return retval; } -void Selector::setX (UWORD32 i, UWORD32 v) -{ - X[i] = v ; - Xreversed[v] = i ; +void Selector::setX(UWORD32 i, UWORD32 v) { + X[i] = v; + Xreversed[v] = i; } \ No newline at end of file diff --git a/src/Selector.h b/src/Selector.h index e924e1f..de57c7e 100644 --- a/src/Selector.h +++ b/src/Selector.h @@ -22,86 +22,85 @@ #define SH_SELECTOR_H #include -#include #include +#include #include "common.h" -class PseudoRandomSource ; +class PseudoRandomSource; /** * \class Selector * \brief a random permutation of a random combination **/ class Selector { - public: - /** - * construct a Selector object - * \param m the range - operator[] will return numbers in {0,...,m-1} - * \param pp a passphrase used to generate the seed - **/ - Selector (UWORD32 m, std::string pp) ; - - /** - * construct a Selector object - * \param m the range - operator[] will return numbers in {0,...,m-1} - * \param seed the seed to use for the selector - **/ - Selector (UWORD32 m, UWORD32 seed) ; - - /** - * construct a Selector object that resembles the identity permutation with range m - * \param m the range - (*this)[i] will be i for i in {0,...,m-1} - **/ - Selector (UWORD32 m) ; - - /** - * construct a Selector object that will return predefined values - * \param retvals the values that operator[] shall return - * - * The Maximum is set to retvals.size(). - **/ - Selector (const std::vector& retvals) ; - - ~Selector (void) ; - - /** - * get the value at the i-th position - * \param i an index - **/ - UWORD32 operator[] (UWORD32 i) ; - - UWORD32 getRange (void) const - { return Maximum ; } ; - - private: - std::vector X ; - std::vector Y ; - std::unordered_map Xreversed ; - /// operator[] will return a value in {0,...,Maximum-1} - UWORD32 Maximum ; - /// the number of calculated positions in the arrays - UWORD32 NumInArray ; - PseudoRandomSource* PRandom ; - - /** - * fill X, Y and Xreversed until but not including index m - **/ - void calculate (UWORD32 m) ; - - /** - * search an index i such that 0 <= i < m and X[i] == v - * \param v the value to be searched for in the X-array - * \param m the upper bound for the index - * \param p a pointer to a variable where the found index can be stored - * \return true iff such an index is found (*p is set to i in this case - **/ - bool idxX (UWORD32 v, UWORD32 m, UWORD32* p) const ; - - /** - * set X[i] to v while maintaining Xreversed - **/ - void setX (UWORD32 i, UWORD32 v) ; -} ; + public: + /** + * construct a Selector object + * \param m the range - operator[] will return numbers in {0,...,m-1} + * \param pp a passphrase used to generate the seed + **/ + Selector(UWORD32 m, std::string pp); + + /** + * construct a Selector object + * \param m the range - operator[] will return numbers in {0,...,m-1} + * \param seed the seed to use for the selector + **/ + Selector(UWORD32 m, UWORD32 seed); + + /** + * construct a Selector object that resembles the identity permutation with range m + * \param m the range - (*this)[i] will be i for i in {0,...,m-1} + **/ + Selector(UWORD32 m); + + /** + * construct a Selector object that will return predefined values + * \param retvals the values that operator[] shall return + * + * The Maximum is set to retvals.size(). + **/ + Selector(const std::vector &retvals); + + ~Selector(void); + + /** + * get the value at the i-th position + * \param i an index + **/ + UWORD32 operator[](UWORD32 i); + + UWORD32 getRange(void) const { return Maximum; }; + + private: + std::vector X; + std::vector Y; + std::unordered_map Xreversed; + /// operator[] will return a value in {0,...,Maximum-1} + UWORD32 Maximum; + /// the number of calculated positions in the arrays + UWORD32 NumInArray; + PseudoRandomSource *PRandom; + + /** + * fill X, Y and Xreversed until but not including index m + **/ + void calculate(UWORD32 m); + + /** + * search an index i such that 0 <= i < m and X[i] == v + * \param v the value to be searched for in the X-array + * \param m the upper bound for the index + * \param p a pointer to a variable where the found index can be stored + * \return true iff such an index is found (*p is set to i in this case + **/ + bool idxX(UWORD32 v, UWORD32 m, UWORD32 *p) const; + + /** + * set X[i] to v while maintaining Xreversed + **/ + void setX(UWORD32 i, UWORD32 v); +}; #endif // ndef SH_SELECTOR_H diff --git a/src/Session.cc b/src/Session.cc index 97d691f..4d4ec52 100644 --- a/src/Session.cc +++ b/src/Session.cc @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * + * * 2020: * - Modified to include StegSeek help and version * @@ -25,363 +25,372 @@ #include #include +#include "CvrStgFile.h" #include "EmbData.h" #include "Embedder.h" -#include "PasswordCracker.h" -#include "SeedCracker.h" #include "Extractor.h" -#include "CvrStgFile.h" #include "MCryptPP.h" +#include "PasswordCracker.h" +#include "SeedCracker.h" #include "Session.h" #include "Utils.h" #include "common.h" #include "error.h" -void Session::run () -{ - switch (Args.Command.getValue()) { - case EMBED: { - Embedder emb ; - emb.embed() ; - break ; } - - case EXTRACT: { - Extractor ext (Args.StgFn.getValue(), Args.Passphrase.getValue()) ; - EmbData* embdata = ext.extract() ; - - // write data - std::string fn ; - if (Args.ExtFn.is_set()) { - if (Args.ExtFn.getValue() == "") { - // write extracted data to stdout - fn = "" ; - } - else { - // file name given by extracting user overrides embedded file name - fn = Args.ExtFn.getValue() ; - } - } - else { - // write extracted data to file with embedded file name - myassert (Args.ExtFn.getValue() == "") ; - fn = embdata->getFileName() ; - if (fn.length() == 0) { - throw SteghideError (_("please specify a file name for the extracted data (there is no name embedded in the stego file).")) ; - } - } - - VerboseMessage vwe ; - bool printdone = true ; - if (fn == "") { - vwe.setMessage (_("writing extracted data to standard output...")) ; - printdone = false ; - } - else { - vwe.setMessage (_("writing extracted data to \"%s\"..."), fn.c_str()) ; - vwe.setNewline (false) ; - } - vwe.printMessage() ; - - BinaryIO io (fn, BinaryIO::WRITE) ; - std::vector data = embdata->getData() ; - for (std::vector::iterator i = data.begin() ; i != data.end() ; i++) { - io.write8 (*i) ; - } - io.close() ; - - if (printdone) { - VerboseMessage vdone (_(" done")) ; - vdone.printMessage() ; - } - - if (Args.Verbosity.getValue() < VERBOSE) { - if (fn != "") { - Message m (_("wrote extracted data to \"%s\"."), fn.c_str()) ; - m.printMessage() ; - } - } - break ; } - - case CRACK: { - printVersion() ; - PasswordCracker pcr ; - pcr.crack() ; - break ; } - - case SEED_CRACK: { - printVersion() ; - SeedCracker scr ; - scr.crack() ; - break ; } - - case INFO: { - printInfo() ; - break ; } - - case ENCINFO: { - printEncInfo() ; - break ; } - - case SHOWVERSION: { - printVersion() ; - break ; } - - case SHOWLICENSE: { - printLicense() ; - break ; } - - case SHOWHELP: { - printHelp() ; - break ; } +void Session::run() { + switch (Args.Command.getValue()) { + case EMBED: { + Embedder emb; + emb.embed(); + break; + } + + case EXTRACT: { + Extractor ext(Args.StgFn.getValue(), Args.Passphrase.getValue()); + EmbData *embdata = ext.extract(); + + // write data + std::string fn; + if (Args.ExtFn.is_set()) { + if (Args.ExtFn.getValue() == "") { + // write extracted data to stdout + fn = ""; + } else { + // file name given by extracting user overrides embedded file name + fn = Args.ExtFn.getValue(); + } + } else { + // write extracted data to file with embedded file name + myassert(Args.ExtFn.getValue() == ""); + fn = embdata->getFileName(); + if (fn.length() == 0) { + throw SteghideError( + _("please specify a file name for the extracted data (there is no " + "name embedded in the stego file).")); + } + } + + VerboseMessage vwe; + bool printdone = true; + if (fn == "") { + vwe.setMessage(_("writing extracted data to standard output...")); + printdone = false; + } else { + vwe.setMessage(_("writing extracted data to \"%s\"..."), fn.c_str()); + vwe.setNewline(false); + } + vwe.printMessage(); + + BinaryIO io(fn, BinaryIO::WRITE); + std::vector data = embdata->getData(); + for (std::vector::iterator i = data.begin(); i != data.end(); i++) { + io.write8(*i); + } + io.close(); + + if (printdone) { + VerboseMessage vdone(_(" done")); + vdone.printMessage(); + } + + if (Args.Verbosity.getValue() < VERBOSE) { + if (fn != "") { + Message m(_("wrote extracted data to \"%s\"."), fn.c_str()); + m.printMessage(); + } + } + break; + } + + case CRACK: { + printVersion(); + PasswordCracker pcr; + pcr.crack(); + break; + } + + case SEED_CRACK: { + printVersion(); + SeedCracker scr; + scr.crack(); + break; + } + + case INFO: { + printInfo(); + break; + } + + case ENCINFO: { + printEncInfo(); + break; + } + + case SHOWVERSION: { + printVersion(); + break; + } + + case SHOWLICENSE: { + printLicense(); + break; + } + + case SHOWHELP: { + printHelp(); + break; + } #ifdef DEBUG - case PRINTFREQS: { - printFrequencies() ; - break ; } + case PRINTFREQS: { + printFrequencies(); + break; + } #endif - default: { - myassert (0) ; - break ; } - } + default: { + myassert(0); + break; + } + } } -void Session::printInfo () -{ - // if file format not supported: exception will be caught in main - CvrStgFile* file = CvrStgFile::readFile (Args.CvrFn.getValue()) ; - - if (Args.CvrFn.getValue() == "") { - printf (_("data from standard input:\n")) ; - } - else { - printf ("\"%s\":\n", Utils::stripDir(Args.CvrFn.getValue()).c_str()) ; - } - - std::list props = file->getProperties() ; - props.push_back (CvrStgFile::Property (_("capacity"), file->getHRCapacity())) ; - for (std::list::const_iterator it = props.begin() ; it != props.end() ; it++) { - printf (" %s: %s\n", it->getKey().c_str(), it->getValue().c_str()) ; - } - - bool printembinfo = Args.Passphrase.is_set() ; - if (!printembinfo) { - Question q (_("Try to get information about embedded data ?")) ; - q.printMessage() ; - printembinfo = q.getAnswer() ; - } - - if (printembinfo) { - try { - std::string pp ; - if (Args.Passphrase.is_set()) { - pp = Args.Passphrase.getValue() ; - } - else { - pp = Args.getPassphrase() ; // ask user for it - } - - Extractor e (Args.CvrFn.getValue(), pp) ; - EmbData* embdata = e.extract() ; - - if (embdata->getFileName() == "") { - printf (_(" embedded data:\n")) ; - } - else { - printf (_(" embedded file \"%s\":\n"), embdata->getFileName().c_str()) ; - } - - printf (_(" size: %s\n"), Utils::formatHRSize(embdata->getData().size()).c_str()) ; - std::string encstring ; - if (embdata->getEncAlgo() == EncryptionAlgorithm(EncryptionAlgorithm::NONE)) { - encstring += _("no") ; - } - else { - encstring += embdata->getEncAlgo().getStringRep() + ", " + embdata->getEncMode().getStringRep() ; - } - printf (_(" encrypted: %s\n"), encstring.c_str()) ; - printf (_(" compressed: %s\n"), ((embdata->getCompression() > 0) ? _("yes") : _("no"))) ; - - delete embdata ; - } - catch (const CorruptDataError&) { - printf (_("could not extract any data with that passphrase!\n")) ; - } - } +void Session::printInfo() { + // if file format not supported: exception will be caught in main + CvrStgFile *file = CvrStgFile::readFile(Args.CvrFn.getValue()); + + if (Args.CvrFn.getValue() == "") { + printf(_("data from standard input:\n")); + } else { + printf("\"%s\":\n", Utils::stripDir(Args.CvrFn.getValue()).c_str()); + } + + std::list props = file->getProperties(); + props.push_back(CvrStgFile::Property(_("capacity"), file->getHRCapacity())); + for (std::list::const_iterator it = props.begin(); it != props.end(); + it++) { + printf(" %s: %s\n", it->getKey().c_str(), it->getValue().c_str()); + } + + bool printembinfo = Args.Passphrase.is_set(); + if (!printembinfo) { + Question q(_("Try to get information about embedded data ?")); + q.printMessage(); + printembinfo = q.getAnswer(); + } + + if (printembinfo) { + try { + std::string pp; + if (Args.Passphrase.is_set()) { + pp = Args.Passphrase.getValue(); + } else { + pp = Args.getPassphrase(); // ask user for it + } + + Extractor e(Args.CvrFn.getValue(), pp); + EmbData *embdata = e.extract(); + + if (embdata->getFileName() == "") { + printf(_(" embedded data:\n")); + } else { + printf(_(" embedded file \"%s\":\n"), embdata->getFileName().c_str()); + } + + printf(_(" size: %s\n"), Utils::formatHRSize(embdata->getData().size()).c_str()); + std::string encstring; + if (embdata->getEncAlgo() == EncryptionAlgorithm(EncryptionAlgorithm::NONE)) { + encstring += _("no"); + } else { + encstring += embdata->getEncAlgo().getStringRep() + ", " + + embdata->getEncMode().getStringRep(); + } + printf(_(" encrypted: %s\n"), encstring.c_str()); + printf(_(" compressed: %s\n"), + ((embdata->getCompression() > 0) ? _("yes") : _("no"))); + + delete embdata; + } catch (const CorruptDataError &) { + printf(_("could not extract any data with that passphrase!\n")); + } + } } -void Session::printEncInfo () -{ - std::vector algos = MCryptPP::getListAlgorithms() ; - std::vector modes = MCryptPP::getListModes() ; - - printf (_("encryption algorithms:\n" - ": ...\n")) ; - - for (std::vector::iterator a = algos.begin() ; a != algos.end() ; a++) { - if (EncryptionAlgorithm::isValidStringRep (*a)) { // invalid if supported by libmcrypt but not by steghide, e.g. blowfish-compat - std::cout << *a << ":" ; - for (std::vector::iterator m = modes.begin() ; m != modes.end() ; m++) { - if (EncryptionMode::isValidStringRep (*m)) { - if (MCryptPP::AlgoSupportsMode (*a, *m)) { - std::cout << " " << *m ; - } - } - } - std::cout << std::endl ; - } - } +void Session::printEncInfo() { + std::vector algos = MCryptPP::getListAlgorithms(); + std::vector modes = MCryptPP::getListModes(); + + printf(_("encryption algorithms:\n" + ": ...\n")); + + for (std::vector::iterator a = algos.begin(); a != algos.end(); a++) { + if (EncryptionAlgorithm::isValidStringRep(*a)) { // invalid if supported by libmcrypt but + // not by steghide, e.g. blowfish-compat + std::cout << *a << ":"; + for (std::vector::iterator m = modes.begin(); m != modes.end(); m++) { + if (EncryptionMode::isValidStringRep(*m)) { + if (MCryptPP::AlgoSupportsMode(*a, *m)) { + std::cout << " " << *m; + } + } + } + std::cout << std::endl; + } + } } - -void Session::printVersion () -{ - fprintf(stderr,"StegSeek version %s\n" , VERSION); - if (Args.Verbosity.getValue() == VERBOSE) { - printSteghideVersion() ; - } +void Session::printVersion() { + fprintf(stderr, "StegSeek version %s\n", VERSION); + if (Args.Verbosity.getValue() == VERBOSE) { + printSteghideVersion(); + } } -void Session::printHelp () -{ - printVersion() ; - printf (_("\n" - "=== StegSeek Help ===\n" - "To crack a stegofile:\n" - "stegseek [stegofile.jpg] [wordlist.txt]\n" - "\n" - "Commands:\n" - " --crack Crack a stego file using a wordlist. This is the default mode.\n" - " --seed Crack a stego file by attempting all embedding patterns.\n" - " This mode can be used to detect a file encoded by steghide.\n" - " In case the file was encoded without encryption, this mode will\n" - " even recover the embedded file.\n" - "Positional arguments:\n" - " --crack [stegofile.jpg] [wordlist.txt] [output.txt]\n" - " --seed [stegofile.jpg] [output.txt]\n" - "\n" - "Keyword arguments:\n" - " -sf, --stegofile select stego file\n" - " -wl, --wordlist select the wordlist file\n" - " -xf, --extractfile select file name for extracted data\n" - " -t, --threads set the number of threads. Defaults to the number of cores.\n" - " -f, --force overwrite existing files\n" - " -v, --verbose display detailed information\n" - " -q, --quiet hide performance metrics (can improve performance)\n" - " -s, --skipdefault don't add guesses to the wordlist (empty password, filename, ...)\n" - "\n" - )) ; - - if (Args.Verbosity.getValue() == VERBOSE) - { - printf("=== Steghide Help ===\n") ; - printSteghideHelp() ; - } - else - { - printf("Use \"stegseek --help -v\" to include steghide's help.\n") ; - } - +void Session::printHelp() { + printVersion(); + printf(_("\n" + "=== StegSeek Help ===\n" + "To crack a stegofile:\n" + "stegseek [stegofile.jpg] [wordlist.txt]\n" + "\n" + "Commands:\n" + " --crack Crack a stego file using a wordlist. This " + "is the default mode.\n" + " --seed Crack a stego file by attempting all " + "embedding patterns.\n" + " This mode can be used to detect a file " + "encoded by steghide.\n" + " In case the file was encoded without " + "encryption, this mode will\n" + " even recover the embedded file.\n" + "Positional arguments:\n" + " --crack [stegofile.jpg] [wordlist.txt] [output.txt]\n" + " --seed [stegofile.jpg] [output.txt]\n" + "\n" + "Keyword arguments:\n" + " -sf, --stegofile select stego file\n" + " -wl, --wordlist select the wordlist file\n" + " -xf, --extractfile select file name for extracted data\n" + " -t, --threads set the number of threads. Defaults to " + "the number of cores.\n" + " -f, --force overwrite existing files\n" + " -v, --verbose display detailed information\n" + " -q, --quiet hide performance metrics (can improve " + "performance)\n" + " -s, --skipdefault don't add guesses to the wordlist (empty " + "password, filename, ...)\n" + "\n")); + + if (Args.Verbosity.getValue() == VERBOSE) { + printf("=== Steghide Help ===\n"); + printSteghideHelp(); + } else { + printf("Use \"stegseek --help -v\" to include steghide's help.\n"); + } } -void Session::printSteghideVersion () -{ - fprintf(stderr, "based on steghide version %s\n", STEGHIDE_VERSION); +void Session::printSteghideVersion() { + fprintf(stderr, "based on steghide version %s\n", STEGHIDE_VERSION); } -void Session::printSteghideHelp () -{ - printf (_("\n" - "the first argument must be one of the following:\n" - " --embed embed data\n" - " --extract extract data\n" - " --info display information about a cover- or stego-file\n" - " --encinfo display a list of supported encryption algorithms\n" - " --version display version information\n" - " --license display StegSeek's license\n" - " --help display this usage information\n" - - "\nembedding options:\n" - " -ef, --embedfile select file to be embedded\n" - " -ef embed the file \n" - " -cf, --coverfile select cover-file\n" - " -cf embed into the file \n" - " -p, --passphrase specify passphrase\n" - " -p use to embed data\n" - " -sf, --stegofile select stego file\n" - " -sf write result to instead of cover-file\n" - " -e, --encryption select encryption parameters\n" - " -e []|[] specify an encryption algorithm and/or mode\n" - " -e none do not encrypt data before embedding\n" - " -z, --compress compress data before embedding (default)\n" - " -z using level (1 best speed...9 best compression)\n" - " -Z, --dontcompress do not compress data before embedding\n" - " -K, --nochecksum do not embed crc32 checksum of embedded data\n" - " -N, --dontembedname do not embed the name of the original file\n" - " -f, --force overwrite existing files\n" - " -q, --quiet suppress information messages\n" - " -v, --verbose display detailed information\n" - - "\nextracting options:\n" - " -sf, --stegofile select stego file\n" - " -sf extract data from \n" - " -p, --passphrase specify passphrase\n" - " -p use to extract data\n" - " -xf, --extractfile select file name for extracted data\n" - " -xf write the extracted data to \n" - " -f, --force overwrite existing files\n" - " -q, --quiet suppress information messages\n" - " -v, --verbose display detailed information\n" - - "\noptions for the info command:\n" - " -p, --passphrase specify passphrase\n" - " -p use to get info about embedded data\n" - - "\nTo embed emb.txt in cvr.jpg: stegseek --embed -cf cvr.jpg -ef emb.txt\n" - "To extract embedded data from stg.jpg: stegseek --extract -sf stg.jpg\n")) ; +void Session::printSteghideHelp() { + printf(_("\n" + "the first argument must be one of the following:\n" + " --embed embed data\n" + " --extract extract data\n" + " --info display information about a cover- or " + "stego-file\n" + " --encinfo display a list of supported encryption " + "algorithms\n" + " --version display version information\n" + " --license display StegSeek's license\n" + " --help display this usage information\n" + + "\nembedding options:\n" + " -ef, --embedfile select file to be embedded\n" + " -ef embed the file \n" + " -cf, --coverfile select cover-file\n" + " -cf embed into the file \n" + " -p, --passphrase specify passphrase\n" + " -p use to embed data\n" + " -sf, --stegofile select stego file\n" + " -sf write result to instead of " + "cover-file\n" + " -e, --encryption select encryption parameters\n" + " -e []|[] specify an encryption algorithm and/or mode\n" + " -e none do not encrypt data before embedding\n" + " -z, --compress compress data before embedding (default)\n" + " -z using level (1 best speed...9 best " + "compression)\n" + " -Z, --dontcompress do not compress data before embedding\n" + " -K, --nochecksum do not embed crc32 checksum of embedded data\n" + " -N, --dontembedname do not embed the name of the original file\n" + " -f, --force overwrite existing files\n" + " -q, --quiet suppress information messages\n" + " -v, --verbose display detailed information\n" + + "\nextracting options:\n" + " -sf, --stegofile select stego file\n" + " -sf extract data from \n" + " -p, --passphrase specify passphrase\n" + " -p use to extract data\n" + " -xf, --extractfile select file name for extracted data\n" + " -xf write the extracted data to \n" + " -f, --force overwrite existing files\n" + " -q, --quiet suppress information messages\n" + " -v, --verbose display detailed information\n" + + "\noptions for the info command:\n" + " -p, --passphrase specify passphrase\n" + " -p use to get info about embedded " + "data\n" + + "\nTo embed emb.txt in cvr.jpg: stegseek --embed -cf cvr.jpg -ef " + "emb.txt\n" + "To extract embedded data from stg.jpg: stegseek --extract -sf " + "stg.jpg\n")); } -void Session::printLicense () -{ - printf ( - "Copyright (C) 2020 Rick de Jager ( https://github.com/rickdejager )\n\n" +void Session::printLicense() { + printf("Copyright (C) 2020 Rick de Jager ( https://github.com/rickdejager )\n\n" - "This program is free software; you can redistribute it and/or\n" - "modify it under the terms of the GNU General Public License\n" - "as published by the Free Software Foundation; either version 2\n" - "of the License, or (at your option) any later version.\n\n" + "This program is free software; you can redistribute it and/or\n" + "modify it under the terms of the GNU General Public License\n" + "as published by the Free Software Foundation; either version 2\n" + "of the License, or (at your option) any later version.\n\n" - "This program is distributed in the hope that it will be useful,\n" - "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" - "GNU General Public License for more details.\n\n" + "This program is distributed in the hope that it will be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + "GNU General Public License for more details.\n\n" - "You should have received a copy of the GNU General Public License\n" - "along with this program; if not, write to the Free Software\n" - "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n") ; + "You should have received a copy of the GNU General Public License\n" + "along with this program; if not, write to the Free Software\n" + "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, " + "USA.\n"); } #ifdef DEBUG -void Session::printFrequencies () -{ - std::map Frequencies ; - const std::list& flist = Args.FileList.getValue() ; - for (std::list::const_iterator fnit = flist.begin() ; fnit != flist.end() ; fnit++) { - CvrStgFile *f = CvrStgFile::readFile (*fnit) ; - addFrequencies (&Frequencies, f->getFrequencies()) ; - delete f ; - } - - // get CvrStgFile in correct format to call printFrequencies - CvrStgFile *f = CvrStgFile::readFile (*(Args.FileList.getValue().begin())) ; - f->printFrequencies (Frequencies) ; - delete f ; +void Session::printFrequencies() { + std::map Frequencies; + const std::list &flist = Args.FileList.getValue(); + for (std::list::const_iterator fnit = flist.begin(); fnit != flist.end(); fnit++) { + CvrStgFile *f = CvrStgFile::readFile(*fnit); + addFrequencies(&Frequencies, f->getFrequencies()); + delete f; + } + + // get CvrStgFile in correct format to call printFrequencies + CvrStgFile *f = CvrStgFile::readFile(*(Args.FileList.getValue().begin())); + f->printFrequencies(Frequencies); + delete f; } -void Session::addFrequencies (std::map* f1, const std::map* f2) -{ - for (std::map::const_iterator fit = f2->begin() ; fit != f2->end() ; fit++) { - (*f1)[fit->first] += fit->second ; - } +void Session::addFrequencies(std::map *f1, + const std::map *f2) { + for (std::map::const_iterator fit = f2->begin(); fit != f2->end(); + fit++) { + (*f1)[fit->first] += fit->second; + } } #endif // def DEBUG diff --git a/src/Session.h b/src/Session.h index 6b9d4ef..dbbc066 100644 --- a/src/Session.h +++ b/src/Session.h @@ -27,25 +27,26 @@ #include "common.h" class Session { - public: - Session (void) {} ; + public: + Session(void){}; - void run (void) ; + void run(void); - private: - void printInfo (void) ; - void printEncInfo (void) ; - void printLicense (void) ; - void printSteghideHelp (void) ; - void printSteghideVersion (void) ; - void printHelp (void) ; - void printVersion (void) ; + private: + void printInfo(void); + void printEncInfo(void); + void printLicense(void); + void printSteghideHelp(void); + void printSteghideVersion(void); + void printHelp(void); + void printVersion(void); #ifdef DEBUG - void printFrequencies (void) ; - /** - * add the frequencies in f2 to those in f1 (changing only f1 - like f1 += f2) - **/ - void addFrequencies (std::map* f1, const std::map* f2) ; + void printFrequencies(void); + /** + * add the frequencies in f2 to those in f1 (changing only f1 - like f1 += f2) + **/ + void addFrequencies(std::map *f1, + const std::map *f2); #endif -} ; -#endif //ndef SH_SESSION_H +}; +#endif // ndef SH_SESSION_H diff --git a/src/SteghideError.cc b/src/SteghideError.cc index 2dbe1c3..747f071 100644 --- a/src/SteghideError.cc +++ b/src/SteghideError.cc @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * + * * 2020: * - Changed steghide branding to stegseek. * @@ -26,26 +26,16 @@ #include "SteghideError.h" #include "common.h" -SteghideError::SteghideError (void) - : MessageBase(_("error, exiting. (no error message defined).")) -{ -} +SteghideError::SteghideError(void) + : MessageBase(_("error, exiting. (no error message defined).")) {} -SteghideError::SteghideError(std::string msg) - : MessageBase(msg) -{ -} +SteghideError::SteghideError(std::string msg) : MessageBase(msg) {} -SteghideError::SteghideError (const char *msgfmt, ...) - : MessageBase() -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +SteghideError::SteghideError(const char *msgfmt, ...) : MessageBase() { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void SteghideError::printMessage () const -{ - std::cerr << "stegseek: " << getMessage() << std::endl ; -} +void SteghideError::printMessage() const { std::cerr << "stegseek: " << getMessage() << std::endl; } diff --git a/src/SteghideError.h b/src/SteghideError.h index 3b4e03d..d5640fd 100644 --- a/src/SteghideError.h +++ b/src/SteghideError.h @@ -26,12 +26,12 @@ #include "msg.h" class SteghideError : public MessageBase { - public: - SteghideError (void) ; - SteghideError (std::string msg) ; - SteghideError (const char *msgfmt, ...) ; + public: + SteghideError(void); + SteghideError(std::string msg); + SteghideError(const char *msgfmt, ...); - virtual void printMessage (void) const ; -} ; + virtual void printMessage(void) const; +}; #endif // ndef SH_STEGHIDEERROR_H diff --git a/src/Terminal.cc b/src/Terminal.cc index e4a602d..1668a7b 100644 --- a/src/Terminal.cc +++ b/src/Terminal.cc @@ -20,53 +20,49 @@ #include +#include "Terminal.h" #include "common.h" #include "error.h" -#include "Terminal.h" #ifdef HAVE_TERMIOS_H -Terminal::Terminal () -{ - if ((tcgetattr (STDIN_FILENO, &InitAttr)) != 0) { - throw SteghideError (_("could not get terminal attributes.")) ; - } +Terminal::Terminal() { + if ((tcgetattr(STDIN_FILENO, &InitAttr)) != 0) { + throw SteghideError(_("could not get terminal attributes.")); + } } -void Terminal::EchoOff () -{ - struct termios curattr ; - if ((tcgetattr (STDIN_FILENO, &curattr)) != 0) { - throw SteghideError (_("could not get terminal attributes.")) ; - } - - curattr.c_lflag &= ~ECHO ; +void Terminal::EchoOff() { + struct termios curattr; + if ((tcgetattr(STDIN_FILENO, &curattr)) != 0) { + throw SteghideError(_("could not get terminal attributes.")); + } + + curattr.c_lflag &= ~ECHO; - if ((tcsetattr (STDIN_FILENO, TCSAFLUSH, &curattr)) != 0) { - throw SteghideError (_("could not set terminal attributes.")) ; - } + if ((tcsetattr(STDIN_FILENO, TCSAFLUSH, &curattr)) != 0) { + throw SteghideError(_("could not set terminal attributes.")); + } } -void Terminal::SingleKeyOn () -{ - struct termios curattr ; - if ((tcgetattr (STDIN_FILENO, &curattr)) != 0) { - throw SteghideError (_("could not get terminal attributes.")) ; - } +void Terminal::SingleKeyOn() { + struct termios curattr; + if ((tcgetattr(STDIN_FILENO, &curattr)) != 0) { + throw SteghideError(_("could not get terminal attributes.")); + } - curattr.c_lflag &= ~ICANON ; - curattr.c_cc[VTIME] = 0 ; - curattr.c_cc[VMIN] = 1 ; + curattr.c_lflag &= ~ICANON; + curattr.c_cc[VTIME] = 0; + curattr.c_cc[VMIN] = 1; - if ((tcsetattr (STDIN_FILENO, TCSAFLUSH, &curattr)) != 0) { - throw SteghideError (_("could not set terminal attributes.")) ; - } + if ((tcsetattr(STDIN_FILENO, TCSAFLUSH, &curattr)) != 0) { + throw SteghideError(_("could not set terminal attributes.")); + } } -void Terminal::reset () -{ - if ((tcsetattr (STDIN_FILENO, TCSANOW, &InitAttr)) != 0) { - throw SteghideError (_("could not set terminal attributes.")) ; - } +void Terminal::reset() { + if ((tcsetattr(STDIN_FILENO, TCSANOW, &InitAttr)) != 0) { + throw SteghideError(_("could not set terminal attributes.")); + } } #else // TODO - do something that makes more sense - especially on Windows systems diff --git a/src/Terminal.h b/src/Terminal.h index b053cc7..dc821a1 100644 --- a/src/Terminal.h +++ b/src/Terminal.h @@ -32,18 +32,18 @@ * \brief provides some terminal access **/ class Terminal { - public: - Terminal (void) ; + public: + Terminal(void); - void EchoOff (void) ; - void SingleKeyOn (void) ; - void reset (void) ; + void EchoOff(void); + void SingleKeyOn(void); + void reset(void); - private: + private: #if HAVE_TERMIOS_H - /// contains the attributes of the terminal when this object was constructed - struct termios InitAttr ; + /// contains the attributes of the terminal when this object was constructed + struct termios InitAttr; #endif -} ; +}; #endif // ndef SH_TERMINAL_H diff --git a/src/Utils.cc b/src/Utils.cc index 20df476..28ac036 100644 --- a/src/Utils.cc +++ b/src/Utils.cc @@ -22,37 +22,34 @@ #include "Utils.h" -std::string Utils::formatHRSize (unsigned long size) -{ - float s = (float) size ; +std::string Utils::formatHRSize(unsigned long size) { + float s = (float)size; - std::string unit = "Byte(s)" ; - if (s > 1024.0) { - s /= 1024.0 ; - unit = "KB" ; - } - if (s > 1024.0) { - s /= 1024.0 ; - unit = "MB" ; - } - if (s > 1024.0) { - s /= 1024.0 ; - unit = "GB" ; - } + std::string unit = "Byte(s)"; + if (s > 1024.0) { + s /= 1024.0; + unit = "KB"; + } + if (s > 1024.0) { + s /= 1024.0; + unit = "MB"; + } + if (s > 1024.0) { + s /= 1024.0; + unit = "GB"; + } - char buf[15] ; - sprintf (buf, "%.1f %s", s, unit.c_str()) ; - return std::string (buf) ; + char buf[15]; + sprintf(buf, "%.1f %s", s, unit.c_str()); + return std::string(buf); } -std::string Utils::stripDir (std::string s) -{ - unsigned int start = 0 ; - if ((start = s.find_last_of ("/\\")) == std::string::npos) { - start = 0 ; - } - else { - start += 1 ; - } - return s.substr (start, std::string::npos) ; +std::string Utils::stripDir(std::string s) { + unsigned int start = 0; + if ((start = s.find_last_of("/\\")) == std::string::npos) { + start = 0; + } else { + start += 1; + } + return s.substr(start, std::string::npos); } diff --git a/src/Utils.h b/src/Utils.h index b7588b5..342e09e 100644 --- a/src/Utils.h +++ b/src/Utils.h @@ -24,12 +24,12 @@ #include class Utils { - public: - /** - * gets a number of bytes and returns a human-readable string like e.g. "3,5 KB" - **/ - static std::string formatHRSize (unsigned long size) ; - static std::string stripDir (std::string) ; -} ; + public: + /** + * gets a number of bytes and returns a human-readable string like e.g. "3,5 KB" + **/ + static std::string formatHRSize(unsigned long size); + static std::string stripDir(std::string); +}; #endif // ndef SH_UTILS_H diff --git a/src/Vertex.cc b/src/Vertex.cc index e616425..c3546d0 100644 --- a/src/Vertex.cc +++ b/src/Vertex.cc @@ -18,186 +18,185 @@ * */ +#include "Vertex.h" #include "AUtils.h" #include "Edge.h" #include "EdgeIterator.h" #include "Graph.h" -#include "Vertex.h" #include "common.h" -Vertex::Vertex (VertexLabel l, SamplePos* sposs, SampleValue** svalues, EmbValue t) -{ - setLabel (l) ; - SamplePositions = sposs ; - SampleValues = svalues ; - - SampleOccurenceIts = new std::list::iterator[Globs.TheCvrStgFile->getSamplesPerVertex()] ; - ShortestEdge = NULL ; - valid = true ; - - // calculate sample target values... - TargetValues = new EmbValue[Globs.TheCvrStgFile->getSamplesPerVertex()] ; - EmbValue msum = 0 ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { // fill TargetValues with source values temporarily - TargetValues[i] = SampleValues[i]->getEmbeddedValue() ; - msum = (msum + TargetValues[i]) % Globs.TheCvrStgFile->getEmbValueModulus() ; - } - - // ...by solving msum + d = t (mod m)... - if (t < msum) { - t += Globs.TheCvrStgFile->getEmbValueModulus() ; - } - EmbValue d = t - msum ; - - // ...and adding d to source values to produce target values - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - TargetValues[i] = (TargetValues[i] + d) % Globs.TheCvrStgFile->getEmbValueModulus() ; - } - - // calculate SelfDegree - SelfDegree = 0 ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - for (unsigned short j = i + 1 ; j < Globs.TheCvrStgFile->getSamplesPerVertex() ; j++) { - if (SampleValues[i]->isNeighbour(SampleValues[j])) { - if (TargetValues[i] == SampleValues[j]->getEmbeddedValue() && - TargetValues[j] == SampleValues[i]->getEmbeddedValue()) { - SelfDegree += 2 ; // 2 because i->j and j->i would be counted otherwise - } - } - } - } +Vertex::Vertex(VertexLabel l, SamplePos *sposs, SampleValue **svalues, EmbValue t) { + setLabel(l); + SamplePositions = sposs; + SampleValues = svalues; + + SampleOccurenceIts = + new std::list::iterator[Globs.TheCvrStgFile->getSamplesPerVertex()]; + ShortestEdge = NULL; + valid = true; + + // calculate sample target values... + TargetValues = new EmbValue[Globs.TheCvrStgFile->getSamplesPerVertex()]; + EmbValue msum = 0; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); + i++) { // fill TargetValues with source values temporarily + TargetValues[i] = SampleValues[i]->getEmbeddedValue(); + msum = (msum + TargetValues[i]) % Globs.TheCvrStgFile->getEmbValueModulus(); + } + + // ...by solving msum + d = t (mod m)... + if (t < msum) { + t += Globs.TheCvrStgFile->getEmbValueModulus(); + } + EmbValue d = t - msum; + + // ...and adding d to source values to produce target values + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + TargetValues[i] = (TargetValues[i] + d) % Globs.TheCvrStgFile->getEmbValueModulus(); + } + + // calculate SelfDegree + SelfDegree = 0; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + for (unsigned short j = i + 1; j < Globs.TheCvrStgFile->getSamplesPerVertex(); j++) { + if (SampleValues[i]->isNeighbour(SampleValues[j])) { + if (TargetValues[i] == SampleValues[j]->getEmbeddedValue() && + TargetValues[j] == SampleValues[i]->getEmbeddedValue()) { + SelfDegree += 2; // 2 because i->j and j->i would be counted otherwise + } + } + } + } } -Vertex::~Vertex () -{ - delete[] TargetValues ; - delete[] SampleOccurenceIts ; - delete[] SamplePositions ; - delete[] SampleValues ; - delete ShortestEdge ; +Vertex::~Vertex() { + delete[] TargetValues; + delete[] SampleOccurenceIts; + delete[] SamplePositions; + delete[] SampleValues; + delete ShortestEdge; } -void Vertex::markDeleted () -{ +void Vertex::markDeleted() { #ifdef DEBUG - printDebug (2, "marking vertex with label %lu as deleted.", getLabel()) ; + printDebug(2, "marking vertex with label %lu as deleted.", getLabel()); #endif - if (valid) { - // decrement neighbour degrees - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - std::vector& potneighs = (*(Globs.TheGraph->SVALists[TargetValues[i]]))[SampleValues[i]] ; - for (std::vector::iterator svit = potneighs.begin() ; svit != potneighs.end() ; svit++) { - (*svit)->decNumEdges (SampleValues[i]->getEmbeddedValue()) ; - } - } - - // delete from sample occurences in graph - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - SampleOccurenceIts[i] = Globs.TheGraph->markDeletedSampleOccurence (SampleOccurenceIts[i]) ; - } - - valid = false ; - } + if (valid) { + // decrement neighbour degrees + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + std::vector &potneighs = + (*(Globs.TheGraph->SVALists[TargetValues[i]]))[SampleValues[i]]; + for (std::vector::iterator svit = potneighs.begin(); + svit != potneighs.end(); svit++) { + (*svit)->decNumEdges(SampleValues[i]->getEmbeddedValue()); + } + } + + // delete from sample occurences in graph + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + SampleOccurenceIts[i] = + Globs.TheGraph->markDeletedSampleOccurence(SampleOccurenceIts[i]); + } + + valid = false; + } } -void Vertex::unmarkDeleted () -{ +void Vertex::unmarkDeleted() { #ifdef DEBUG - printDebug (2, "unmarking deletion of vertex with label %lu.", getLabel()) ; + printDebug(2, "unmarking deletion of vertex with label %lu.", getLabel()); #endif - if (!valid) { - // increment neighbour degrees - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - std::vector& potneighs = (*(Globs.TheGraph->SVALists[TargetValues[i]]))[SampleValues[i]] ; - for (std::vector::iterator svit = potneighs.begin() ; svit != potneighs.end() ; svit++) { - (*svit)->incNumEdges (SampleValues[i]->getEmbeddedValue()) ; - } - } - - // undelete into sample occurences in graph - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - SampleOccurenceIts[i] = Globs.TheGraph->unmarkDeletedSampleOccurence (SampleOccurenceIts[i]) ; - } - - valid = true ; - } + if (!valid) { + // increment neighbour degrees + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + std::vector &potneighs = + (*(Globs.TheGraph->SVALists[TargetValues[i]]))[SampleValues[i]]; + for (std::vector::iterator svit = potneighs.begin(); + svit != potneighs.end(); svit++) { + (*svit)->incNumEdges(SampleValues[i]->getEmbeddedValue()); + } + } + + // undelete into sample occurences in graph + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + SampleOccurenceIts[i] = + Globs.TheGraph->unmarkDeletedSampleOccurence(SampleOccurenceIts[i]); + } + + valid = true; + } } -void Vertex::updateShortestEdge () -{ +void Vertex::updateShortestEdge() { #ifdef DEBUG - printDebug (3, "updating shorted edge for vertex with label %lu", getLabel()) ; + printDebug(3, "updating shorted edge for vertex with label %lu", getLabel()); #endif - delete ShortestEdge ; + delete ShortestEdge; - if (getDegree() == 0) { - ShortestEdge = NULL ; - } - else { - EdgeIterator edgeit (this) ; - ShortestEdge = new Edge (**edgeit) ; - } + if (getDegree() == 0) { + ShortestEdge = NULL; + } else { + EdgeIterator edgeit(this); + ShortestEdge = new Edge(**edgeit); + } } -EmbValue Vertex::getEmbeddedValue () const -{ - EmbValue retval = 0 ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - retval = (retval + SampleValues[i]->getEmbeddedValue()) % Globs.TheCvrStgFile->getEmbValueModulus() ; - } - return retval ; +EmbValue Vertex::getEmbeddedValue() const { + EmbValue retval = 0; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + retval = (retval + SampleValues[i]->getEmbeddedValue()) % + Globs.TheCvrStgFile->getEmbValueModulus(); + } + return retval; } -#define BMINUS(A,B) ((A > B) ? (A - B) : (0)) -UWORD32 Vertex::getDegree () const -{ - UWORD32 degree = 0 ; +#define BMINUS(A, B) ((A > B) ? (A - B) : (0)) +UWORD32 Vertex::getDegree() const { + UWORD32 degree = 0; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - degree += SampleValues[i]->getNumEdges(TargetValues[i]) ; - } + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + degree += SampleValues[i]->getNumEdges(TargetValues[i]); + } - return BMINUS(degree, SelfDegree) ; + return BMINUS(degree, SelfDegree); } -void Vertex::print (unsigned short spc) const -{ - char* space = new char[spc + 1] ; - for (unsigned short i = 0 ; i < spc ; i++) { - space[i] = ' ' ; - } - space[spc] = '\0' ; - - std::cerr << space << "Vertex:" << std::endl ; - std::cerr << space << " Label: " << getLabel() << std::endl ; - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - std::cerr << space << " SamplePosition: " << getSamplePos(i) << std::endl ; - getSampleValue(i)->print (spc + 1) ; - std::cerr << space << " Target Value: " << (unsigned int) getTargetValue(i) << std::endl ; - } - std::cerr << space << " ShortestEdge:" << std::endl ; - if (ShortestEdge) { - ShortestEdge->print(spc + 2) ; - } - else { - std::cerr << space << " NULL" << std::endl ; - } - std::cerr << space << " SelfDegree: " << SelfDegree << std::endl ; - std::cerr << space << " getDegree(): " << getDegree() << std::endl ; +void Vertex::print(unsigned short spc) const { + char *space = new char[spc + 1]; + for (unsigned short i = 0; i < spc; i++) { + space[i] = ' '; + } + space[spc] = '\0'; + + std::cerr << space << "Vertex:" << std::endl; + std::cerr << space << " Label: " << getLabel() << std::endl; + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + std::cerr << space << " SamplePosition: " << getSamplePos(i) << std::endl; + getSampleValue(i)->print(spc + 1); + std::cerr << space << " Target Value: " << (unsigned int)getTargetValue(i) << std::endl; + } + std::cerr << space << " ShortestEdge:" << std::endl; + if (ShortestEdge) { + ShortestEdge->print(spc + 2); + } else { + std::cerr << space << " NULL" << std::endl; + } + std::cerr << space << " SelfDegree: " << SelfDegree << std::endl; + std::cerr << space << " getDegree(): " << getDegree() << std::endl; } -void Vertex::printEdges() const -{ - std::cerr << "edges of vertex with label " << getLabel() << std::endl ; - EdgeIterator edgeit (Globs.TheGraph->getVertex(getLabel())) ; - while (*edgeit != NULL) { - Edge* e = new Edge (**edgeit) ; - std::cerr << " label of other vertex: " << e->getOtherVertex(this)->getLabel() << std::endl ; - std::cerr << " weight: " << e->getWeight() << std::endl ; - delete e ; - ++edgeit ; - } +void Vertex::printEdges() const { + std::cerr << "edges of vertex with label " << getLabel() << std::endl; + EdgeIterator edgeit(Globs.TheGraph->getVertex(getLabel())); + while (*edgeit != NULL) { + Edge *e = new Edge(**edgeit); + std::cerr << " label of other vertex: " << e->getOtherVertex(this)->getLabel() + << std::endl; + std::cerr << " weight: " << e->getWeight() << std::endl; + delete e; + ++edgeit; + } } diff --git a/src/Vertex.h b/src/Vertex.h index 569320c..7614141 100644 --- a/src/Vertex.h +++ b/src/Vertex.h @@ -24,9 +24,9 @@ #include "CvrStgFile.h" #include "common.h" -class Edge ; -class SampleOccurence ; -class SampleValue ; +class Edge; +class SampleOccurence; +class SampleValue; /** * \class Vertex @@ -41,101 +41,100 @@ class SampleValue ; * This means that it must be set correctly before using any method of a Vertex object. **/ class Vertex { - public: - /** - * construct a new vertex object - * \param l the vertex label for this vertex - * \param sposs the array (with length g->getSamplesPerVertex()) of the positions of the samples - * \param svalues the array (with length g->getSamplesPerVertex()) of (unique (!)) pointers to the sample values - * \param t the target value for the whole vertex - the value that should be returned by getEmbeddedValue() after the embedding - **/ - Vertex (VertexLabel l, SamplePos* sposs, SampleValue** svalues, EmbValue t) ; - - ~Vertex (void) ; - - /** - * get the i-th sample position - * \param i an index of a sample in this vertex (must be < TheCvrStgFile->getNumSamplesPerVertex()) - * \return the position of the sample in the associated cvrstgfile - **/ - SamplePos getSamplePos (unsigned short i) const - { return SamplePositions[i] ; } ; - - /** - * get the i-th sample value - * \param i an index of a sample in this vertex (must be < TheCvrStgFile->getNumSamplesPerVertex()) - * \return the value of the sample in the associated cvrstgfile - **/ - SampleValue* getSampleValue (unsigned short i) const - { return SampleValues[i] ; } ; - - /** - * get the degree of this vertex - **/ - UWORD32 getDegree (void) const ; - - /** - * get the shortest edge of this vertex - **/ - Edge *getShortestEdge (void) const - { return ShortestEdge ; } ; - - /** - * find shortest edge of this vertex and save result to ShortestEdge - **/ - void updateShortestEdge (void) ; - - /** - * if this vertex is valid, mark it as deleted - **/ - void markDeleted (void) ; - - /** - * if this vertex is marked as deleted, undo this - **/ - void unmarkDeleted (void) ; - - VertexLabel getLabel (void) const - { return Label ; } ; - - void setLabel (VertexLabel l) - { Label = l ; } ; - - void setSampleOccurenceIt (unsigned short i, std::list::iterator it) - { SampleOccurenceIts[i] = it ; } - - EmbValue getEmbeddedValue (void) const ; - - EmbValue getTargetValue (unsigned short i) const - { return TargetValues[i] ; } ; - - void print (unsigned short spc = 0) const ; - void printEdges (void) const ; - - private: - /// the vertex label of this vertex - VertexLabel Label ; - - /// the sample positions of the samples described by this vertex in the CvrStgFile - SamplePos* SamplePositions ; - - /// the sample values at the SamplePositions - SampleValue** SampleValues ; - - /// the target values for the sample values (exactly one of them has to be reached (and the other left unchanged) to embed this vertex) - EmbValue* TargetValues ; - - /// point to entries in std::lists of sample occurences in the graph - std::list::iterator* SampleOccurenceIts ; - - /// the shortest edge of this vertex (as calculated by updateShortestEdge) - Edge *ShortestEdge ; - - /// true iff this vertex is not deleted - bool valid ; - - /// the number of loop edges (loop edges are not valid edges) - unsigned short SelfDegree ; -} ; + public: + /** + * construct a new vertex object + * \param l the vertex label for this vertex + * \param sposs the array (with length g->getSamplesPerVertex()) of the positions of the samples + * \param svalues the array (with length g->getSamplesPerVertex()) of (unique (!)) pointers to + *the sample values \param t the target value for the whole vertex - the value that should be + *returned by getEmbeddedValue() after the embedding + **/ + Vertex(VertexLabel l, SamplePos *sposs, SampleValue **svalues, EmbValue t); + + ~Vertex(void); + + /** + * get the i-th sample position + * \param i an index of a sample in this vertex (must be < + *TheCvrStgFile->getNumSamplesPerVertex()) \return the position of the sample in the associated + *cvrstgfile + **/ + SamplePos getSamplePos(unsigned short i) const { return SamplePositions[i]; }; + + /** + * get the i-th sample value + * \param i an index of a sample in this vertex (must be < + *TheCvrStgFile->getNumSamplesPerVertex()) \return the value of the sample in the associated + *cvrstgfile + **/ + SampleValue *getSampleValue(unsigned short i) const { return SampleValues[i]; }; + + /** + * get the degree of this vertex + **/ + UWORD32 getDegree(void) const; + + /** + * get the shortest edge of this vertex + **/ + Edge *getShortestEdge(void) const { return ShortestEdge; }; + + /** + * find shortest edge of this vertex and save result to ShortestEdge + **/ + void updateShortestEdge(void); + + /** + * if this vertex is valid, mark it as deleted + **/ + void markDeleted(void); + + /** + * if this vertex is marked as deleted, undo this + **/ + void unmarkDeleted(void); + + VertexLabel getLabel(void) const { return Label; }; + + void setLabel(VertexLabel l) { Label = l; }; + + void setSampleOccurenceIt(unsigned short i, std::list::iterator it) { + SampleOccurenceIts[i] = it; + } + + EmbValue getEmbeddedValue(void) const; + + EmbValue getTargetValue(unsigned short i) const { return TargetValues[i]; }; + + void print(unsigned short spc = 0) const; + void printEdges(void) const; + + private: + /// the vertex label of this vertex + VertexLabel Label; + + /// the sample positions of the samples described by this vertex in the CvrStgFile + SamplePos *SamplePositions; + + /// the sample values at the SamplePositions + SampleValue **SampleValues; + + /// the target values for the sample values (exactly one of them has to be reached (and the + /// other left unchanged) to embed this vertex) + EmbValue *TargetValues; + + /// point to entries in std::lists of sample occurences in the graph + std::list::iterator *SampleOccurenceIts; + + /// the shortest edge of this vertex (as calculated by updateShortestEdge) + Edge *ShortestEdge; + + /// true iff this vertex is not deleted + bool valid; + + /// the number of loop edges (loop edges are not valid edges) + unsigned short SelfDegree; +}; #endif // ndef SH_VERTEX_H diff --git a/src/WKSConstructionHeuristic.cc b/src/WKSConstructionHeuristic.cc index bc551cd..aeb079f 100644 --- a/src/WKSConstructionHeuristic.cc +++ b/src/WKSConstructionHeuristic.cc @@ -24,201 +24,207 @@ #include "Matching.h" #include "common.h" -WKSConstructionHeuristic::WKSConstructionHeuristic (Graph* g, Matching* m, float goal) - : MatchingAlgorithm (g, m, goal) -{ - unsigned long nvertices = g->getNumVertices() ; - - // fill the VerticesDeg1 and VerticesDegG priority queues - VerticesDeg1 = std::priority_queue, LongerShortestEdge> () ; - VerticesDegG = std::priority_queue, LongerShortestEdge> () ; - - for (VertexLabel l = 0 ; l < nvertices ; l++) { - Vertex *v = g->getVertex(l) ; - v->updateShortestEdge() ; - UWORD32 degree = v->getDegree() ; - if (degree != 0) { - myassert (v->getShortestEdge() != NULL) ; - if (degree == 1) { - VerticesDeg1.push (v) ; - } - else { - VerticesDegG.push (v) ; - } - } - } +WKSConstructionHeuristic::WKSConstructionHeuristic(Graph *g, Matching *m, float goal) + : MatchingAlgorithm(g, m, goal) { + unsigned long nvertices = g->getNumVertices(); + + // fill the VerticesDeg1 and VerticesDegG priority queues + VerticesDeg1 = std::priority_queue, LongerShortestEdge>(); + VerticesDegG = std::priority_queue, LongerShortestEdge>(); + + for (VertexLabel l = 0; l < nvertices; l++) { + Vertex *v = g->getVertex(l); + v->updateShortestEdge(); + UWORD32 degree = v->getDegree(); + if (degree != 0) { + myassert(v->getShortestEdge() != NULL); + if (degree == 1) { + VerticesDeg1.push(v); + } else { + VerticesDegG.push(v); + } + } + } } -void WKSConstructionHeuristic::run () -{ - unsigned long numDegG = 0 ; - unsigned long numDeg1 = 0 ; +void WKSConstructionHeuristic::run() { + unsigned long numDegG = 0; + unsigned long numDeg1 = 0; - while ((TheMatching->getCardinality() < CardinalityGoal) && !(VerticesDegG.empty() && VerticesDeg1.empty())) { - Vertex *v = NULL ; + while ((TheMatching->getCardinality() < CardinalityGoal) && + !(VerticesDegG.empty() && VerticesDeg1.empty())) { + Vertex *v = NULL; - // get a vertex from one of the priority queues - if (!VerticesDeg1.empty()) { - v = findVertexDeg1() ; - if (v != NULL) { + // get a vertex from one of the priority queues + if (!VerticesDeg1.empty()) { + v = findVertexDeg1(); + if (v != NULL) { #ifdef DEBUG - printDebug (5, "WKSConstructionHeuristic: vertex %lu has been chosen from VerticesDeg1.", v->getLabel()) ; + printDebug(5, + "WKSConstructionHeuristic: vertex %lu has been chosen from " + "VerticesDeg1.", + v->getLabel()); #endif - numDeg1++ ; - } - } - else { - v = findVertexDegG() ; - if (v != NULL) { + numDeg1++; + } + } else { + v = findVertexDegG(); + if (v != NULL) { #ifdef DEBUG - printDebug (5, "WKSConstructionHeuristic: vertex %lu has been chosen from VerticesDegG.", v->getLabel()) ; + printDebug(5, + "WKSConstructionHeuristic: vertex %lu has been chosen from " + "VerticesDegG.", + v->getLabel()); #endif - numDegG++ ; - } - } + numDegG++; + } + } - if (v != NULL) { // insert v's shortest edge into matching - Edge* e = v->getShortestEdge() ; - Vertex* vother = e->getOtherVertex(v) ; + if (v != NULL) { // insert v's shortest edge into matching + Edge *e = v->getShortestEdge(); + Vertex *vother = e->getOtherVertex(v); #ifdef DEBUG - printDebug (5, "WKSConstructionHeuristic: inserting edge %lu - %lu into matching", v->getLabel(), vother->getLabel()) ; + printDebug(5, "WKSConstructionHeuristic: inserting edge %lu - %lu into matching", + v->getLabel(), vother->getLabel()); #endif - TheMatching->addEdge(*e) ; - v->markDeleted() ; - vother->markDeleted() ; - checkNeighboursDeg1 (v) ; - checkNeighboursDeg1 (vother) ; - } - } - - TheGraph->unmarkDeletedAllVertices() ; + TheMatching->addEdge(*e); + v->markDeleted(); + vother->markDeleted(); + checkNeighboursDeg1(v); + checkNeighboursDeg1(vother); + } + } + + TheGraph->unmarkDeletedAllVertices(); } -void WKSConstructionHeuristic::checkNeighboursDeg1 (Vertex *v) -{ - // for all sample values in v... - for (unsigned short i = 0 ; i < Globs.TheCvrStgFile->getSamplesPerVertex() ; i++) { - SampleValue* srcsv = v->getSampleValue(i) ; - const std::vector& tneighbours = (*(TheGraph->SVALists[v->getTargetValue(i)]))[srcsv] ; - - // ...get all target neighbour sample values... - for (std::vector::const_iterator tnit = tneighbours.begin() ; tnit != tneighbours.end() ; tnit++) { - const std::list& soccs = TheGraph->SampleOccurences[(*tnit)->getLabel()] ; - - // ...and for each of them look at every sample occurence of it,... - for (std::list::const_iterator soccit = soccs.begin() ; soccit != soccs.end() ; soccit++) { - // ...determine wether it is in an edge with v and ... - if (srcsv->getEmbeddedValue() == soccit->getVertex()->getTargetValue(soccit->getIndex())) { - // ...if the corresponding vertex has degree 1: - if (soccit->getVertex()->getDegree() == 1) { - soccit->getVertex()->updateShortestEdge() ; - VerticesDeg1.push(soccit->getVertex()) ; // move it to the Deg1 priority queue - } - } - } - } - } +void WKSConstructionHeuristic::checkNeighboursDeg1(Vertex *v) { + // for all sample values in v... + for (unsigned short i = 0; i < Globs.TheCvrStgFile->getSamplesPerVertex(); i++) { + SampleValue *srcsv = v->getSampleValue(i); + const std::vector &tneighbours = + (*(TheGraph->SVALists[v->getTargetValue(i)]))[srcsv]; + + // ...get all target neighbour sample values... + for (std::vector::const_iterator tnit = tneighbours.begin(); + tnit != tneighbours.end(); tnit++) { + const std::list &soccs = + TheGraph->SampleOccurences[(*tnit)->getLabel()]; + + // ...and for each of them look at every sample occurence of it,... + for (std::list::const_iterator soccit = soccs.begin(); + soccit != soccs.end(); soccit++) { + // ...determine wether it is in an edge with v and ... + if (srcsv->getEmbeddedValue() == + soccit->getVertex()->getTargetValue(soccit->getIndex())) { + // ...if the corresponding vertex has degree 1: + if (soccit->getVertex()->getDegree() == 1) { + soccit->getVertex()->updateShortestEdge(); + VerticesDeg1.push( + soccit->getVertex()); // move it to the Deg1 priority queue + } + } + } + } + } } -Vertex* WKSConstructionHeuristic::findVertexDegG () -{ - Vertex *v = NULL ; - bool usethisvertex = false ; - - // get the vertex that is nearest to top (with updated len of shortest edge) and has degree > 1 - do { - myassert (!VerticesDegG.empty()) ; - v = VerticesDegG.top() ; - VerticesDegG.pop() ; - - if ((TheMatching->isExposed(v)) && (v->getDegree() > 1)) { // implicitly delete vertices that have been moved to VerticesDeg1 or have already been matched - UWORD32 weight_before = v->getShortestEdge()->getWeight() ; - - v->updateShortestEdge() ; - - if (v->getShortestEdge()->getWeight() == weight_before) { - usethisvertex = true ; - } - else { - myassert (v->getShortestEdge()->getWeight() > weight_before) ; // weight can only rise - VerticesDegG.push (v) ; // push v into a position that is further away from top - } - } - } while (!(usethisvertex || VerticesDegG.empty())) ; - - return (usethisvertex ? v : NULL) ; +Vertex *WKSConstructionHeuristic::findVertexDegG() { + Vertex *v = NULL; + bool usethisvertex = false; + + // get the vertex that is nearest to top (with updated len of shortest edge) + // and has degree > 1 + do { + myassert(!VerticesDegG.empty()); + v = VerticesDegG.top(); + VerticesDegG.pop(); + + if ((TheMatching->isExposed(v)) && + (v->getDegree() > 1)) { // implicitly delete vertices that have been moved to + // VerticesDeg1 or have already been matched + UWORD32 weight_before = v->getShortestEdge()->getWeight(); + + v->updateShortestEdge(); + + if (v->getShortestEdge()->getWeight() == weight_before) { + usethisvertex = true; + } else { + myassert(v->getShortestEdge()->getWeight() > weight_before); // weight can only rise + VerticesDegG.push(v); // push v into a position that is further away from top + } + } + } while (!(usethisvertex || VerticesDegG.empty())); + + return (usethisvertex ? v : NULL); } -Vertex *WKSConstructionHeuristic::findVertexDeg1 () -{ - Vertex *v = NULL ; - bool usethisvertex = false ; +Vertex *WKSConstructionHeuristic::findVertexDeg1() { + Vertex *v = NULL; + bool usethisvertex = false; - // get the vertex that is nearest to top and still has degree 1 - do { - myassert (!VerticesDeg1.empty()) ; - v = VerticesDeg1.top() ; - VerticesDeg1.pop() ; + // get the vertex that is nearest to top and still has degree 1 + do { + myassert(!VerticesDeg1.empty()); + v = VerticesDeg1.top(); + VerticesDeg1.pop(); - if ((TheMatching->isExposed(v)) && (v->getDegree() == 1)) { // implicitly delete vertices that have degree zero or have already been matched - usethisvertex = true ; - } - } while (!(usethisvertex || VerticesDeg1.empty())) ; + if ((TheMatching->isExposed(v)) && + (v->getDegree() == 1)) { // implicitly delete vertices that have degree + // zero or have already been matched + usethisvertex = true; + } + } while (!(usethisvertex || VerticesDeg1.empty())); - return (usethisvertex ? v : NULL) ; + return (usethisvertex ? v : NULL); } -bool WKSConstructionHeuristic::LongerShortestEdge::operator() (const Vertex* v1, const Vertex* v2) -{ - bool retval = false ; - UWORD32 deg1 = v1->getDegree() ; - UWORD32 deg2 = v2->getDegree() ; - if (deg1 == 0 && deg2 == 0) { - retval = (v1->getLabel() > v2->getLabel()) ; - } - else if (deg1 == 0) { - retval = true ; - } - else if (deg2 == 0) { - retval = false ; - } - else { - retval = v1->getShortestEdge()->getWeight() > v2->getShortestEdge()->getWeight(); - } - return retval ; +bool WKSConstructionHeuristic::LongerShortestEdge::operator()(const Vertex *v1, const Vertex *v2) { + bool retval = false; + UWORD32 deg1 = v1->getDegree(); + UWORD32 deg2 = v2->getDegree(); + if (deg1 == 0 && deg2 == 0) { + retval = (v1->getLabel() > v2->getLabel()); + } else if (deg1 == 0) { + retval = true; + } else if (deg2 == 0) { + retval = false; + } else { + retval = v1->getShortestEdge()->getWeight() > v2->getShortestEdge()->getWeight(); + } + return retval; } #ifdef DEBUG -void WKSConstructionHeuristic::print (unsigned short spc) -{ - char* space = new char[spc + 1] ; - for (unsigned short i = 0 ; i < spc ; i++) { - space[i] = ' ' ; - } - space[spc] = '\0' ; - - std::cerr << space << "VerticesDeg1 (top->down): " ; - printPQ (VerticesDeg1) ; - std::cerr << std::endl ; - - std::cerr << space << "VerticesDegG (top->down): " ; - printPQ (VerticesDegG) ; - std::cerr << std::endl ; +void WKSConstructionHeuristic::print(unsigned short spc) { + char *space = new char[spc + 1]; + for (unsigned short i = 0; i < spc; i++) { + space[i] = ' '; + } + space[spc] = '\0'; + + std::cerr << space << "VerticesDeg1 (top->down): "; + printPQ(VerticesDeg1); + std::cerr << std::endl; + + std::cerr << space << "VerticesDegG (top->down): "; + printPQ(VerticesDegG); + std::cerr << std::endl; } -void WKSConstructionHeuristic::printPQ (std::priority_queue, LongerShortestEdge>& pq) -{ - std::vector backup ; - while (!pq.empty()) { - Vertex *v = pq.top() ; - pq.pop() ; - std::cerr << v->getLabel() << ", " ; - backup.push_back(v) ; - } - - for (std::vector::const_iterator it = backup.begin() ; it != backup.end() ; it++) { - pq.push (*it) ; - } +void WKSConstructionHeuristic::printPQ( + std::priority_queue, LongerShortestEdge> &pq) { + std::vector backup; + while (!pq.empty()) { + Vertex *v = pq.top(); + pq.pop(); + std::cerr << v->getLabel() << ", "; + backup.push_back(v); + } + + for (std::vector::const_iterator it = backup.begin(); it != backup.end(); it++) { + pq.push(*it); + } } #endif diff --git a/src/WKSConstructionHeuristic.h b/src/WKSConstructionHeuristic.h index c376bbd..5dc8a3e 100644 --- a/src/WKSConstructionHeuristic.h +++ b/src/WKSConstructionHeuristic.h @@ -25,12 +25,12 @@ #include #include -class Edge ; -class Graph ; -class Matching ; +class Edge; +class Graph; +class Matching; #include "MatchingAlgorithm.h" -class ProgressOutput ; -class Vertex ; +class ProgressOutput; +class Vertex; #include "common.h" /** @@ -46,60 +46,62 @@ class Vertex ; * algorithm to choose shorter edges on average. **/ class WKSConstructionHeuristic : public MatchingAlgorithm { - public: - /** - * \param g the underlying graph - * \param m the inital matching (should be empty) - **/ - WKSConstructionHeuristic (Graph* g, Matching* m, float goal = 100.0) ; + public: + /** + * \param g the underlying graph + * \param m the inital matching (should be empty) + **/ + WKSConstructionHeuristic(Graph *g, Matching *m, float goal = 100.0); - virtual ~WKSConstructionHeuristic (void) {} ; + virtual ~WKSConstructionHeuristic(void){}; - const char* getName (void) const - { return "Weighted Karp&Sipser Construction Heuristic" ; } ; + const char *getName(void) const { return "Weighted Karp&Sipser Construction Heuristic"; }; - void run (void) ; + void run(void); - /** - * \class LongerShortestEdge - * \brief a comparison operator - * - * lse(v1, v2) is true if the length of the shortest edge of v1 - * is greater than the length of the shortest edge of v2. If a vertex - * has Degree 0, the length of its shortest edge is defined to be +Infinity. - * If both v1 and v2 have degree 0, then the vertex with the greater label - * is defined to have the "longer shortest edge". - **/ - class LongerShortestEdge : public std::binary_function { - public: - bool operator() (const Vertex *v1, const Vertex *v2) ; - } ; + /** + * \class LongerShortestEdge + * \brief a comparison operator + * + * lse(v1, v2) is true if the length of the shortest edge of v1 + * is greater than the length of the shortest edge of v2. If a vertex + * has Degree 0, the length of its shortest edge is defined to be +Infinity. + * If both v1 and v2 have degree 0, then the vertex with the greater label + * is defined to have the "longer shortest edge". + **/ + class LongerShortestEdge : public std::binary_function { + public: + bool operator()(const Vertex *v1, const Vertex *v2); + }; #ifdef DEBUG - void print (unsigned short spc = 0) ; - void printPQ (std::priority_queue, LongerShortestEdge>& pq) ; + void print(unsigned short spc = 0); + void printPQ(std::priority_queue, LongerShortestEdge> &pq); #endif - private: - /** - * get the Vertex from VerticesDeg1 that is nearest to top (with updated degrees and shortest edges) - **/ - Vertex *findVertexDeg1 (void) ; + private: + /** + * get the Vertex from VerticesDeg1 that is nearest to top (with updated degrees and shortest + *edges) + **/ + Vertex *findVertexDeg1(void); - /** - * get the Vertex from VerticesDegG that is nearest to top (with updated degrees and shortest edges) - **/ - Vertex *findVertexDegG (void) ; + /** + * get the Vertex from VerticesDegG that is nearest to top (with updated degrees and shortest + *edges) + **/ + Vertex *findVertexDegG(void); - /** - * copy all Neighbours of v that have degree 1 to VerticesDeg1 - **/ - void checkNeighboursDeg1 (Vertex *v) ; + /** + * copy all Neighbours of v that have degree 1 to VerticesDeg1 + **/ + void checkNeighboursDeg1(Vertex *v); - /// contains all vertices of degree 1 - every vertex in this queue has a correct shortest edge if it still has degree 1 - std::priority_queue, LongerShortestEdge> VerticesDeg1 ; - /// contains all vertices with degree greater than 1 - std::priority_queue, LongerShortestEdge> VerticesDegG ; -} ; + /// contains all vertices of degree 1 - every vertex in this queue has a correct shortest edge + /// if it still has degree 1 + std::priority_queue, LongerShortestEdge> VerticesDeg1; + /// contains all vertices with degree greater than 1 + std::priority_queue, LongerShortestEdge> VerticesDegG; +}; #endif // ndef SH_WKSCONSTRUCTIONHEURISTIC_H diff --git a/src/WavChunk.cc b/src/WavChunk.cc index 8c85e10..8b7f9d6 100644 --- a/src/WavChunk.cc +++ b/src/WavChunk.cc @@ -21,14 +21,10 @@ #include "WavChunk.h" #include "WavChunkHeader.h" -WavChunk::~WavChunk () -{ - if (ChunkHeader != NULL) { - delete ChunkHeader ; - } +WavChunk::~WavChunk() { + if (ChunkHeader != NULL) { + delete ChunkHeader; + } } -void WavChunk::write (BinaryIO *io) -{ - ChunkHeader->write (io) ; -} +void WavChunk::write(BinaryIO *io) { ChunkHeader->write(io); } diff --git a/src/WavChunk.h b/src/WavChunk.h index 4b24b61..8d7b9c4 100644 --- a/src/WavChunk.h +++ b/src/WavChunk.h @@ -21,21 +21,20 @@ #ifndef SH_WAVCHUNK_H #define SH_WAVCHUNK_H -class BinaryIO ; -class WavChunkHeader ; +class BinaryIO; +class WavChunkHeader; class WavChunk { - public: - WavChunk (void) {} ; - WavChunk (WavChunkHeader *chh) : - ChunkHeader(chh) {} ; - virtual ~WavChunk (void) ; + public: + WavChunk(void){}; + WavChunk(WavChunkHeader *chh) : ChunkHeader(chh){}; + virtual ~WavChunk(void); - virtual void read (BinaryIO *io) = 0 ; - virtual void write (BinaryIO *io) ; + virtual void read(BinaryIO *io) = 0; + virtual void write(BinaryIO *io); - protected: - WavChunkHeader *ChunkHeader ; -} ; + protected: + WavChunkHeader *ChunkHeader; +}; #endif // ndef SH_WAVCHUNK_H diff --git a/src/WavChunkHeader.cc b/src/WavChunkHeader.cc index 3688a85..09ecdcc 100644 --- a/src/WavChunkHeader.cc +++ b/src/WavChunkHeader.cc @@ -18,34 +18,28 @@ * */ -#include "BinaryIO.h" #include "WavChunkHeader.h" +#include "BinaryIO.h" -WavChunkHeader::WavChunkHeader (const char *id, UWORD32 len) -{ - for (unsigned int i = 0 ; i < 4 ; i++) { - ChunkId[i] = id[i] ; - } - ChunkLength = len ; +WavChunkHeader::WavChunkHeader(const char *id, UWORD32 len) { + for (unsigned int i = 0; i < 4; i++) { + ChunkId[i] = id[i]; + } + ChunkLength = len; } -WavChunkHeader::WavChunkHeader (BinaryIO *io) -{ - read (io) ; -} +WavChunkHeader::WavChunkHeader(BinaryIO *io) { read(io); } -void WavChunkHeader::read (BinaryIO *io) -{ - for (unsigned int i = 0 ; i < 4 ; i++) { - ChunkId[i] = io->read8() ; - } - ChunkLength = io->read32_le() ; +void WavChunkHeader::read(BinaryIO *io) { + for (unsigned int i = 0; i < 4; i++) { + ChunkId[i] = io->read8(); + } + ChunkLength = io->read32_le(); } -void WavChunkHeader::write (BinaryIO *io) const -{ - for (unsigned int i = 0 ; i < 4 ; i++) { - io->write8 (ChunkId[i]) ; - } - io->write32_le (ChunkLength) ; +void WavChunkHeader::write(BinaryIO *io) const { + for (unsigned int i = 0; i < 4; i++) { + io->write8(ChunkId[i]); + } + io->write32_le(ChunkLength); } diff --git a/src/WavChunkHeader.h b/src/WavChunkHeader.h index 94f3312..64e84e0 100644 --- a/src/WavChunkHeader.h +++ b/src/WavChunkHeader.h @@ -23,23 +23,23 @@ #include "common.h" -class BinaryIO ; +class BinaryIO; class WavChunkHeader { - public: - WavChunkHeader (void) {} ; - WavChunkHeader (const char *id, UWORD32 len) ; - WavChunkHeader (BinaryIO *io) ; + public: + WavChunkHeader(void){}; + WavChunkHeader(const char *id, UWORD32 len); + WavChunkHeader(BinaryIO *io); - void read (BinaryIO *io) ; - void write (BinaryIO *io) const ; + void read(BinaryIO *io); + void write(BinaryIO *io) const; - UWORD32 getChunkLength (void) const { return ChunkLength ; } ; - const char *getChunkId (void) const { return ChunkId ; } ; + UWORD32 getChunkLength(void) const { return ChunkLength; }; + const char *getChunkId(void) const { return ChunkId; }; - private: - char ChunkId[4] ; - UWORD32 ChunkLength ; -} ; + private: + char ChunkId[4]; + UWORD32 ChunkLength; +}; #endif // ndef SH_WAVCHUNKHEADER_H diff --git a/src/WavChunkUnused.cc b/src/WavChunkUnused.cc index d919db2..fabeac9 100644 --- a/src/WavChunkUnused.cc +++ b/src/WavChunkUnused.cc @@ -18,22 +18,20 @@ * */ +#include "WavChunkUnused.h" #include "BinaryIO.h" #include "WavChunkHeader.h" -#include "WavChunkUnused.h" -void WavChunkUnused::read (BinaryIO *io) -{ - Data = std::vector (ChunkHeader->getChunkLength()) ; - for (unsigned int i = 0 ; i < ChunkHeader->getChunkLength() ; i++) { - Data[i] = io->read8() ; - } +void WavChunkUnused::read(BinaryIO *io) { + Data = std::vector(ChunkHeader->getChunkLength()); + for (unsigned int i = 0; i < ChunkHeader->getChunkLength(); i++) { + Data[i] = io->read8(); + } } -void WavChunkUnused::write (BinaryIO *io) -{ - WavChunk::write (io) ; - for (std::vector::const_iterator i = Data.begin() ; i != Data.end() ; i++) { - io->write8 (*i) ; - } +void WavChunkUnused::write(BinaryIO *io) { + WavChunk::write(io); + for (std::vector::const_iterator i = Data.begin(); i != Data.end(); i++) { + io->write8(*i); + } } diff --git a/src/WavChunkUnused.h b/src/WavChunkUnused.h index 7da5d49..5219e8c 100644 --- a/src/WavChunkUnused.h +++ b/src/WavChunkUnused.h @@ -21,26 +21,23 @@ #ifndef SH_WAVCHUNKUNUSED_H #define SH_WAVCHUNKUNUSED_H -#include "common.h" #include "WavChunk.h" +#include "common.h" -class BinaryIO ; -class WavChunkHeader ; +class BinaryIO; +class WavChunkHeader; class WavChunkUnused : public WavChunk { - public: - WavChunkUnused (void) : - WavChunk() {} ; - WavChunkUnused (WavChunkHeader *chh) : - WavChunk(chh) {} ; - WavChunkUnused (WavChunkHeader *chh, BinaryIO *io) : - WavChunk(chh) { read(io) ; } ; + public: + WavChunkUnused(void) : WavChunk(){}; + WavChunkUnused(WavChunkHeader *chh) : WavChunk(chh){}; + WavChunkUnused(WavChunkHeader *chh, BinaryIO *io) : WavChunk(chh) { read(io); }; - void read (BinaryIO *io) ; - void write (BinaryIO *io) ; + void read(BinaryIO *io); + void write(BinaryIO *io); - private: - std::vector Data ; -} ; + private: + std::vector Data; +}; #endif // ndef SH_WAVCHUNKUNUSED_H diff --git a/src/WavFile.cc b/src/WavFile.cc index 8fcc584..3ccd4db 100644 --- a/src/WavFile.cc +++ b/src/WavFile.cc @@ -18,389 +18,380 @@ * */ +#include #include #include #include -#include #include "CvrStgFile.h" #include "DFSAPHeuristic.h" -#include "SampleValueAdjacencyList.h" #include "SMDConstructionHeuristic.h" -#include "WavFormatChunk.h" +#include "SampleValueAdjacencyList.h" #include "WavChunkHeader.h" #include "WavChunkUnused.h" #include "WavFile.h" +#include "WavFormatChunk.h" #include "WavPCMSampleValue.h" #include "common.h" #include "error.h" #include "msg.h" -WavFile::WavFile (BinaryIO *io) - : CvrStgFile() -{ - setSamplesPerVertex (SamplesPerVertex) ; - setEmbValueModulus (EmbValueModulus) ; - read (io) ; +WavFile::WavFile(BinaryIO *io) : CvrStgFile() { + setSamplesPerVertex(SamplesPerVertex); + setEmbValueModulus(EmbValueModulus); + read(io); } -WavFile::~WavFile () -{ - delete riffchhdr ; - delete FormatChunk ; - delete datachhdr ; - for (std::vector::iterator i = UnusedBeforeData.begin() ; i != UnusedBeforeData.end() ; i++) { - delete (*i) ; - } +WavFile::~WavFile() { + delete riffchhdr; + delete FormatChunk; + delete datachhdr; + for (std::vector::iterator i = UnusedBeforeData.begin(); + i != UnusedBeforeData.end(); i++) { + delete *i; + } } -void WavFile::read (BinaryIO *io) -{ - CvrStgFile::read (io) ; +void WavFile::read(BinaryIO *io) { + CvrStgFile::read(io); - readheaders () ; - readdata () ; + readheaders(); + readdata(); } -void WavFile::write () -{ - CvrStgFile::write () ; +void WavFile::write() { + CvrStgFile::write(); - writeheaders () ; - writedata () ; + writeheaders(); + writedata(); } -std::list WavFile::getProperties () const -{ - std::list retval ; +std::list WavFile::getProperties() const { + std::list retval; - // format - std::string formatstring = "wave audio" ; - if (FormatChunk->getFormatTag() == WavFormatChunk::FormatPCM) { - formatstring += ", PCM encoding" ; - } - retval.push_back (CvrStgFile::Property (_("format"), formatstring)) ; + // format + std::string formatstring = "wave audio"; + if (FormatChunk->getFormatTag() == WavFormatChunk::FormatPCM) { + formatstring += ", PCM encoding"; + } + retval.push_back(CvrStgFile::Property(_("format"), formatstring)); - return retval ; + return retval; } -std::vector WavFile::getMatchingAlgorithms (Graph* g, Matching* m) const -{ - std::vector retval ; - retval.push_back (new SMDConstructionHeuristic (g, m)) ; - retval.push_back (new DFSAPHeuristic (g, m)) ; - return retval ; +std::vector WavFile::getMatchingAlgorithms(Graph *g, Matching *m) const { + std::vector retval; + retval.push_back(new SMDConstructionHeuristic(g, m)); + retval.push_back(new DFSAPHeuristic(g, m)); + return retval; } -unsigned long WavFile::getNumSamples() const -{ - unsigned long retval = 0 ; - if (FormatChunk->getBitsPerSample() <= 8) { - retval = data_small.size() ; - } - else { - retval = data_large.size() ; - } - return retval ; +unsigned long WavFile::getNumSamples() const { + unsigned long retval = 0; + if (FormatChunk->getBitsPerSample() <= 8) { + retval = data_small.size(); + } else { + retval = data_large.size(); + } + return retval; } -void WavFile::replaceSample (const SamplePos pos, const SampleValue* s) -{ - const WavPCMSampleValue* sample = dynamic_cast (s) ; - myassert (sample != NULL) ; - if (FormatChunk->getBitsPerSample() <= 8) { - data_small[pos] = (unsigned char) sample->getValue() ; - } - else { - data_large[pos] = sample->getValue() ; - } +void WavFile::replaceSample(const SamplePos pos, const SampleValue *s) { + const WavPCMSampleValue *sample = dynamic_cast(s); + myassert(sample != NULL); + if (FormatChunk->getBitsPerSample() <= 8) { + data_small[pos] = (unsigned char)sample->getValue(); + } else { + data_large[pos] = sample->getValue(); + } } -SampleValue *WavFile::getSampleValue (SamplePos pos) const -{ - int value = 0 ; - if (FormatChunk->getBitsPerSample() <= 8) { - value = (int) data_small[pos] ; - } - else { - value = data_large[pos] ; - } - return ((SampleValue *) new WavPCMSampleValue (value)) ; +SampleValue *WavFile::getSampleValue(SamplePos pos) const { + int value = 0; + if (FormatChunk->getBitsPerSample() <= 8) { + value = (int)data_small[pos]; + } else { + value = data_large[pos]; + } + return ((SampleValue *)new WavPCMSampleValue(value)); } -std::vector WavFile::calcSVAdjacencyLists (const std::vector& svs) const -{ - EmbValue m = getEmbValueModulus() ; - std::vector lists (svs.size()) ; - for (EmbValue i = 0 ; i < m ; i++) { - lists[i] = new SampleValueAdjacencyList (svs.size()) ; - } - - std::vector svs_sorted (svs.size()) ; - for (unsigned long i = 0 ; i < svs.size() ; i++) { - svs_sorted[i] = (WavPCMSampleValue*) svs[i] ; - } - - WavPCMSmaller smaller ; - sort (svs_sorted.begin(), svs_sorted.end(), smaller) ; - - // fill the lists - int r = Globs.TheCvrStgFile->getRadius() ; - unsigned long dstart = 0 ; - for (unsigned long si = 0 ; si < svs_sorted.size() ; si++) { - while ((dstart < svs_sorted.size()) && (svs_sorted[dstart]->getValue() < svs_sorted[si]->getValue() - r)) { - dstart++ ; - } - // dstart is the index of the first sample in svs_sorted that is >= (svs_sorted[si]->getValue() - r) - unsigned long di = dstart ; - while ((di < svs_sorted.size()) && (svs_sorted[di]->getValue() <= svs_sorted[si]->getValue() + r)) { - if (si != di) { - (*(lists[svs_sorted[di]->getEmbeddedValue()]))[svs_sorted[si]].push_back (svs_sorted[di]) ; - } - di++ ; - } - } - - // sort rows - for (EmbValue i = 0 ; i < m ; i++) { - lists[i]->sort() ; - } - - return lists ; +std::vector +WavFile::calcSVAdjacencyLists(const std::vector &svs) const { + EmbValue m = getEmbValueModulus(); + std::vector lists(svs.size()); + for (EmbValue i = 0; i < m; i++) { + lists[i] = new SampleValueAdjacencyList(svs.size()); + } + + std::vector svs_sorted(svs.size()); + for (unsigned long i = 0; i < svs.size(); i++) { + svs_sorted[i] = (WavPCMSampleValue *)svs[i]; + } + + WavPCMSmaller smaller; + sort(svs_sorted.begin(), svs_sorted.end(), smaller); + + // fill the lists + int r = Globs.TheCvrStgFile->getRadius(); + unsigned long dstart = 0; + for (unsigned long si = 0; si < svs_sorted.size(); si++) { + while ((dstart < svs_sorted.size()) && + (svs_sorted[dstart]->getValue() < svs_sorted[si]->getValue() - r)) { + dstart++; + } + // dstart is the index of the first sample in svs_sorted that is >= + // (svs_sorted[si]->getValue() - r) + unsigned long di = dstart; + while ((di < svs_sorted.size()) && + (svs_sorted[di]->getValue() <= svs_sorted[si]->getValue() + r)) { + if (si != di) { + (*(lists[svs_sorted[di]->getEmbeddedValue()]))[svs_sorted[si]].push_back( + svs_sorted[di]); + } + di++; + } + } + + // sort rows + for (EmbValue i = 0; i < m; i++) { + lists[i]->sort(); + } + + return lists; } -unsigned short WavFile::getBitsPerSample() const -{ - return FormatChunk->getBitsPerSample() ; -} +unsigned short WavFile::getBitsPerSample() const { return FormatChunk->getBitsPerSample(); } -unsigned short WavFile::getBytesPerSample() -{ - unsigned short retval = 0 ; - if (FormatChunk->getBitsPerSample() % 8 == 0) { - retval = FormatChunk->getBitsPerSample() / 8 ; - } - else { - retval = (FormatChunk->getBitsPerSample() / 8) + 1 ; - } - return retval ; +unsigned short WavFile::getBytesPerSample() { + unsigned short retval = 0; + if (FormatChunk->getBitsPerSample() % 8 == 0) { + retval = FormatChunk->getBitsPerSample() / 8; + } else { + retval = (FormatChunk->getBitsPerSample() / 8) + 1; + } + return retval; } -unsigned short WavFile::getFirstBitPosinSample() -{ - unsigned short retval = 0 ; - if (FormatChunk->getBitsPerSample() % 8 == 0) { - retval = 0 ; - } - else { - retval = 8 - (FormatChunk->getBitsPerSample() % 8) ; - } - return retval ; +unsigned short WavFile::getFirstBitPosinSample() { + unsigned short retval = 0; + if (FormatChunk->getBitsPerSample() % 8 == 0) { + retval = 0; + } else { + retval = 8 - (FormatChunk->getBitsPerSample() % 8); + } + return retval; } /* reads the wav file data from disk */ -void WavFile::readdata (void) -{ - try { - data_small.clear() ; - data_large.clear() ; - unsigned short bitspersample = FormatChunk->getBitsPerSample() ; - unsigned short bytespersample = getBytesPerSample() ; - unsigned short firstbitpos = getFirstBitPosinSample() ; - - UWORD32 mask = 0 ; - for (unsigned short i = 0 ; i < bitspersample ; i++) { - mask <<= 1 ; - mask |= 1 ; - } - unsigned long readpos = 0 ; - while (readpos < datachhdr->getChunkLength()) { - if (bitspersample <= 8) { - data_small.push_back ((getBinIO()->read8()) >> firstbitpos) ; - } - else { - // decode two's complement - UWORD32 value = (UWORD32) getBinIO()->read_le (bytespersample) ; - value = value >> firstbitpos ; - - int sign = 0 ; - if (((value & (1 << (bitspersample - 1))) >> (bitspersample - 1)) == 0) { - sign = 1 ; - } - else { - sign = -1 ; - value = ~value ; - value++ ; - value &= mask ; - } - - data_large.push_back (sign * ((int) value)) ; - } - readpos += bytespersample ; - } - - UnusedAfterData.clear() ; - while (!getBinIO()->eof()) { - UnusedAfterData.push_back (getBinIO()->read8()) ; - } - } - catch (BinaryInputError e) { - switch (e.getType()) { - case BinaryInputError::FILE_ERR: { - throw SteghideError (_("an error occurred while reading the audio data from the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryInputError::FILE_EOF: { - throw SteghideError (_("premature end of file \"%s\" while reading audio data."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryInputError::STDIN_ERR: { - throw SteghideError (_("an error occurred while reading the audio data from standard input.")) ; - break ; } - - case BinaryInputError::STDIN_EOF: { - throw SteghideError (_("premature end of data from standard input while reading audio data.")) ; - break ; } - } - } +void WavFile::readdata(void) { + try { + data_small.clear(); + data_large.clear(); + unsigned short bitspersample = FormatChunk->getBitsPerSample(); + unsigned short bytespersample = getBytesPerSample(); + unsigned short firstbitpos = getFirstBitPosinSample(); + + UWORD32 mask = 0; + for (unsigned short i = 0; i < bitspersample; i++) { + mask <<= 1; + mask |= 1; + } + unsigned long readpos = 0; + while (readpos < datachhdr->getChunkLength()) { + if (bitspersample <= 8) { + data_small.push_back((getBinIO()->read8()) >> firstbitpos); + } else { + // decode two's complement + UWORD32 value = (UWORD32)getBinIO()->read_le(bytespersample); + value = value >> firstbitpos; + + int sign = 0; + if (((value & (1 << (bitspersample - 1))) >> (bitspersample - 1)) == 0) { + sign = 1; + } else { + sign = -1; + value = ~value; + value++; + value &= mask; + } + + data_large.push_back(sign * ((int)value)); + } + readpos += bytespersample; + } + + UnusedAfterData.clear(); + while (!getBinIO()->eof()) { + UnusedAfterData.push_back(getBinIO()->read8()); + } + } catch (BinaryInputError e) { + switch (e.getType()) { + case BinaryInputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while reading the audio data from the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::FILE_EOF: { + throw SteghideError(_("premature end of file \"%s\" while reading audio data."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::STDIN_ERR: { + throw SteghideError( + _("an error occurred while reading the audio data from standard input.")); + break; + } + + case BinaryInputError::STDIN_EOF: { + throw SteghideError( + _("premature end of data from standard input while reading audio data.")); + break; + } + } + } } -void WavFile::writedata (void) -{ - try { - unsigned short bitspersample = FormatChunk->getBitsPerSample() ; - unsigned short bytespersample = getBytesPerSample() ; - unsigned short firstbitpos = getFirstBitPosinSample() ; - - unsigned long writepos = 0 ; - while (writepos < datachhdr->getChunkLength()) { - if (bitspersample <= 8) { - getBinIO()->write8 (data_small[writepos] << firstbitpos) ; - } - else { - unsigned long value = 0 ; - if (data_large[writepos / bytespersample] >= 0) { - value = (unsigned long) data_large[writepos / bytespersample] ; - } - else { - value = (unsigned long) -data_large[writepos / bytespersample] ; // value is now |sample| - value = ~value ; - value++ ; - } - value <<= firstbitpos ; - getBinIO()->write_le (value, bytespersample) ; - } - writepos += bytespersample ; - } - - for (std::vector::const_iterator it = UnusedAfterData.begin() ; it != UnusedAfterData.end() ; it++) { - getBinIO()->write8(*it) ; - } - } - catch (BinaryOutputError e) { - switch (e.getType()) { - case BinaryOutputError::FILE_ERR: { - throw SteghideError (_("an error occurred while writing the audio data to the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; } - - case BinaryOutputError::STDOUT_ERR: { - throw SteghideError (_("an error occurred while writing the audio data to standard output.")) ; - break ; } - } - } +void WavFile::writedata(void) { + try { + unsigned short bitspersample = FormatChunk->getBitsPerSample(); + unsigned short bytespersample = getBytesPerSample(); + unsigned short firstbitpos = getFirstBitPosinSample(); + + unsigned long writepos = 0; + while (writepos < datachhdr->getChunkLength()) { + if (bitspersample <= 8) { + getBinIO()->write8(data_small[writepos] << firstbitpos); + } else { + unsigned long value = 0; + if (data_large[writepos / bytespersample] >= 0) { + value = (unsigned long)data_large[writepos / bytespersample]; + } else { + value = (unsigned long)-data_large[writepos / + bytespersample]; // value is now |sample| + value = ~value; + value++; + } + value <<= firstbitpos; + getBinIO()->write_le(value, bytespersample); + } + writepos += bytespersample; + } + + for (std::vector::const_iterator it = UnusedAfterData.begin(); + it != UnusedAfterData.end(); it++) { + getBinIO()->write8(*it); + } + } catch (BinaryOutputError e) { + switch (e.getType()) { + case BinaryOutputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while writing the audio data to the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryOutputError::STDOUT_ERR: { + throw SteghideError( + _("an error occurred while writing the audio data to standard output.")); + break; + } + } + } } /* reads the headers of a wav file from disk */ -void WavFile::readheaders () -{ - try { - riffchhdr = new WavChunkHeader ("RIFF", getBinIO()->read32_le()) ; - - for (unsigned int i = 0 ; i < 4 ; i++) { - id_wave[i] = getBinIO()->read8() ; - } - if (strncmp (id_wave, "WAVE", 4) != 0) { - throw UnSupFileFormat (getBinIO()) ; - } - - FormatChunk = new WavFormatChunk (new WavChunkHeader (getBinIO()), getBinIO()) ; - if (FormatChunk->getBitsPerSample() <= 8) { - setRadius (Radius_small) ; - } - else { - setRadius (Radius_large) ; - } - - UnusedBeforeData.clear() ; - WavChunkHeader *chhdr = new WavChunkHeader (getBinIO()) ; - while (strncmp (chhdr->getChunkId(), "data", 4) != 0) { - UnusedBeforeData.push_back (new WavChunkUnused (chhdr, getBinIO())) ; - chhdr = new WavChunkHeader (getBinIO()) ; - } - - datachhdr = chhdr ; - } - catch (BinaryInputError e) { - switch (e.getType()) { - case BinaryInputError::FILE_ERR: - { - throw SteghideError (_("an error occurred while reading the wav headers from the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; - } - - case BinaryInputError::FILE_EOF: - { - throw SteghideError (_("premature end of file \"%s\" while reading wav headers."), getBinIO()->getName().c_str()) ; - break ; - } - - case BinaryInputError::STDIN_ERR: - { - throw SteghideError (_("an error occurred while reading the wav headers from standard input.")) ; - break ; - } - - case BinaryInputError::STDIN_EOF: - { - throw SteghideError (_("premature end of data from standard input while reading wav headers.")) ; - break ; - } - } - } - - return ; +void WavFile::readheaders() { + try { + riffchhdr = new WavChunkHeader("RIFF", getBinIO()->read32_le()); + + for (unsigned int i = 0; i < 4; i++) { + id_wave[i] = getBinIO()->read8(); + } + if (strncmp(id_wave, "WAVE", 4) != 0) { + throw UnSupFileFormat(getBinIO()); + } + + FormatChunk = new WavFormatChunk(new WavChunkHeader(getBinIO()), getBinIO()); + if (FormatChunk->getBitsPerSample() <= 8) { + setRadius(Radius_small); + } else { + setRadius(Radius_large); + } + + UnusedBeforeData.clear(); + WavChunkHeader *chhdr = new WavChunkHeader(getBinIO()); + while (strncmp(chhdr->getChunkId(), "data", 4) != 0) { + UnusedBeforeData.push_back(new WavChunkUnused(chhdr, getBinIO())); + chhdr = new WavChunkHeader(getBinIO()); + } + + datachhdr = chhdr; + } catch (BinaryInputError e) { + switch (e.getType()) { + case BinaryInputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while reading the wav headers from the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::FILE_EOF: { + throw SteghideError(_("premature end of file \"%s\" while reading wav headers."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryInputError::STDIN_ERR: { + throw SteghideError( + _("an error occurred while reading the wav headers from standard input.")); + break; + } + + case BinaryInputError::STDIN_EOF: { + throw SteghideError( + _("premature end of data from standard input while reading wav headers.")); + break; + } + } + } + + return; } /* writes the headers of a wav file to disk */ -void WavFile::writeheaders () -{ - try { - riffchhdr->write (getBinIO()) ; - for (int i = 0 ; i < 4 ; i++) { - getBinIO()->write8 (id_wave[i]) ; - } - - FormatChunk->write (getBinIO()) ; - - for (std::vector::const_iterator i = UnusedBeforeData.begin() ; i != UnusedBeforeData.end() ; i++) { - (*i)->write (getBinIO()) ; - } - - datachhdr->write (getBinIO()) ; - } - catch (BinaryOutputError e) { - switch (e.getType()) { - case BinaryOutputError::FILE_ERR: - { - throw SteghideError (_("an error occurred while writing the wav headers to the file \"%s\"."), getBinIO()->getName().c_str()) ; - break ; - } - - case BinaryOutputError::STDOUT_ERR: - { - throw SteghideError (_("an error occurred while writing the wav headers to standard output.")) ; - break ; - } - } - } +void WavFile::writeheaders() { + try { + riffchhdr->write(getBinIO()); + for (int i = 0; i < 4; i++) { + getBinIO()->write8(id_wave[i]); + } + + FormatChunk->write(getBinIO()); + + for (std::vector::const_iterator i = UnusedBeforeData.begin(); + i != UnusedBeforeData.end(); i++) { + (*i)->write(getBinIO()); + } + + datachhdr->write(getBinIO()); + } catch (BinaryOutputError e) { + switch (e.getType()) { + case BinaryOutputError::FILE_ERR: { + throw SteghideError( + _("an error occurred while writing the wav headers to the file \"%s\"."), + getBinIO()->getName().c_str()); + break; + } + + case BinaryOutputError::STDOUT_ERR: { + throw SteghideError( + _("an error occurred while writing the wav headers to standard output.")); + break; + } + } + } } diff --git a/src/WavFile.h b/src/WavFile.h index ecd35a1..d80d033 100644 --- a/src/WavFile.h +++ b/src/WavFile.h @@ -25,64 +25,65 @@ #include "CvrStgFile.h" -class BinaryIO ; -class WavChunkHeader ; -class WavChunkUnused ; -class WavFormatChunk ; +class BinaryIO; +class WavChunkHeader; +class WavChunkUnused; +class WavFormatChunk; class WavFile : public CvrStgFile { - public: - WavFile (void) ; - WavFile (BinaryIO *io) ; - ~WavFile (void) ; - - void read (BinaryIO *io) ; - void write (void) ; - - std::list getProperties (void) const ; - - unsigned long getNumSamples (void) const ; - void replaceSample (const SamplePos pos, const SampleValue* s) ; - SampleValue* getSampleValue (SamplePos pos) const ; - - std::vector calcSVAdjacencyLists (const std::vector& svs) const ; - std::vector getMatchingAlgorithms (Graph* g, Matching* m) const ; - - unsigned short getBitsPerSample (void) const ; - - private: - static const signed short FormatPCM = 1 ; - - static const unsigned short SamplesPerVertex = 2 ; - static const UWORD32 Radius_small = 1 ; - static const UWORD32 Radius_large = 20 ; - static const EmbValue EmbValueModulus = 2 ; - - WavChunkHeader *riffchhdr ; - char id_wave[4] ; - - WavFormatChunk *FormatChunk ; - - WavChunkHeader *datachhdr ; - /// this std::vector contains the wav data if BitsPerSample <= 8 - std::vector data_small ; - /// this std::vector contains the wav data if BitsPerSample >8 - std::vector data_large ; // it is assumed that an int can hold 32 bits - - std::vector UnusedBeforeData ; - std::vector UnusedAfterData ; - - void readheaders (void) ; - void readdata (void) ; - void writeheaders (void) ; - void writedata (void) ; - void calcpos (SamplePos n, unsigned long *bytepos, unsigned short *firstbitpos) const ; - /** - * get the position of the first bit (of the first byte) containing the actual sample data - * \return the bit position (where 0 is the lsb and 7 the msb) - **/ - unsigned short getFirstBitPosinSample (void) ; - unsigned short getBytesPerSample (void) ; -} ; + public: + WavFile(void); + WavFile(BinaryIO *io); + ~WavFile(void); + + void read(BinaryIO *io); + void write(void); + + std::list getProperties(void) const; + + unsigned long getNumSamples(void) const; + void replaceSample(const SamplePos pos, const SampleValue *s); + SampleValue *getSampleValue(SamplePos pos) const; + + std::vector + calcSVAdjacencyLists(const std::vector &svs) const; + std::vector getMatchingAlgorithms(Graph *g, Matching *m) const; + + unsigned short getBitsPerSample(void) const; + + private: + static const signed short FormatPCM = 1; + + static const unsigned short SamplesPerVertex = 2; + static const UWORD32 Radius_small = 1; + static const UWORD32 Radius_large = 20; + static const EmbValue EmbValueModulus = 2; + + WavChunkHeader *riffchhdr; + char id_wave[4]; + + WavFormatChunk *FormatChunk; + + WavChunkHeader *datachhdr; + /// this std::vector contains the wav data if BitsPerSample <= 8 + std::vector data_small; + /// this std::vector contains the wav data if BitsPerSample >8 + std::vector data_large; // it is assumed that an int can hold 32 bits + + std::vector UnusedBeforeData; + std::vector UnusedAfterData; + + void readheaders(void); + void readdata(void); + void writeheaders(void); + void writedata(void); + void calcpos(SamplePos n, unsigned long *bytepos, unsigned short *firstbitpos) const; + /** + * get the position of the first bit (of the first byte) containing the actual sample data + * \return the bit position (where 0 is the lsb and 7 the msb) + **/ + unsigned short getFirstBitPosinSample(void); + unsigned short getBytesPerSample(void); +}; #endif // ndef SH_WAVFILE_H diff --git a/src/WavFormatChunk.cc b/src/WavFormatChunk.cc index 66d18de..608f57c 100644 --- a/src/WavFormatChunk.cc +++ b/src/WavFormatChunk.cc @@ -18,61 +18,62 @@ * */ -#include "error.h" +#include "WavFormatChunk.h" #include "BinaryIO.h" #include "WavChunkHeader.h" -#include "WavFormatChunk.h" +#include "error.h" -void WavFormatChunk::read (BinaryIO *io) -{ - FormatTag = io->read16_le() ; - if (FormatTag != FormatPCM) { - if (io->is_std()) { - throw NotImplementedError (_("the wav file from standard input has a format that is not supported (FormatTag: 0x%X)."), FormatTag) ; - } - else { - throw NotImplementedError (_("the wav file \"%s\" has a format that is not supported (FormatTag: 0x%X)."), io->getName().c_str(), FormatTag) ; - } - } - Channels = io->read16_le() ; - SamplesPerSec = io->read32_le() ; - AvgBytesPerSec = io->read32_le() ; - BlockAlign = io->read16_le() ; - BitsPerSample = io->read16_le() ; - if (ChunkHeader->getChunkLength() == 16) { - AdditionalSize = 0 ; - } - else { - AdditionalSize = io->read16_le() ; - if (AdditionalSize != 0) { - if (io->is_std()) { - throw SteghideError (_("the wav file from standard input does not have pcm format (header too long).")) ; - } - else { - throw SteghideError (_("the wav file \"%s\" does not have pcm format (header too long)."), io->getName().c_str()) ; - } - } - if (ChunkHeader->getChunkLength() != 18) { - if (io->is_std()) { - throw SteghideError (_("the wav file from standard input is corrupted.")) ; - } - else { - throw SteghideError (_("the wav file \"%s\" is corrupted."), io->getName().c_str()) ; - } - } - } +void WavFormatChunk::read(BinaryIO *io) { + FormatTag = io->read16_le(); + if (FormatTag != FormatPCM) { + if (io->is_std()) { + throw NotImplementedError(_("the wav file from standard input has a format that is not " + "supported (FormatTag: 0x%X)."), + FormatTag); + } else { + throw NotImplementedError(_("the wav file \"%s\" has a format that is " + "not supported (FormatTag: 0x%X)."), + io->getName().c_str(), FormatTag); + } + } + Channels = io->read16_le(); + SamplesPerSec = io->read32_le(); + AvgBytesPerSec = io->read32_le(); + BlockAlign = io->read16_le(); + BitsPerSample = io->read16_le(); + if (ChunkHeader->getChunkLength() == 16) { + AdditionalSize = 0; + } else { + AdditionalSize = io->read16_le(); + if (AdditionalSize != 0) { + if (io->is_std()) { + throw SteghideError(_("the wav file from standard input does not have " + "pcm format (header too long).")); + } else { + throw SteghideError(_("the wav file \"%s\" does not have pcm format " + "(header too long)."), + io->getName().c_str()); + } + } + if (ChunkHeader->getChunkLength() != 18) { + if (io->is_std()) { + throw SteghideError(_("the wav file from standard input is corrupted.")); + } else { + throw SteghideError(_("the wav file \"%s\" is corrupted."), io->getName().c_str()); + } + } + } } -void WavFormatChunk::write (BinaryIO *io) -{ - ChunkHeader->write (io) ; - io->write16_le (FormatTag) ; - io->write16_le (Channels) ; - io->write32_le (SamplesPerSec) ; - io->write32_le (AvgBytesPerSec) ; - io->write16_le (BlockAlign) ; - io->write16_le (BitsPerSample) ; - if (ChunkHeader->getChunkLength() == 18) { - io->write16_le (AdditionalSize) ; - } +void WavFormatChunk::write(BinaryIO *io) { + ChunkHeader->write(io); + io->write16_le(FormatTag); + io->write16_le(Channels); + io->write32_le(SamplesPerSec); + io->write32_le(AvgBytesPerSec); + io->write16_le(BlockAlign); + io->write16_le(BitsPerSample); + if (ChunkHeader->getChunkLength() == 18) { + io->write16_le(AdditionalSize); + } } diff --git a/src/WavFormatChunk.h b/src/WavFormatChunk.h index a238943..cbd8a86 100644 --- a/src/WavFormatChunk.h +++ b/src/WavFormatChunk.h @@ -21,39 +21,34 @@ #ifndef SH_WAVFORMATCHUNK_H #define SH_WAVFORMATCHUNK_H -#include "common.h" #include "WavChunk.h" +#include "common.h" -class BinaryIO ; +class BinaryIO; class WavFormatChunk : public WavChunk { - public: - WavFormatChunk (void) : - WavChunk() {} ; - WavFormatChunk (WavChunkHeader *chh) : - WavChunk(chh) {} ; - WavFormatChunk (WavChunkHeader *chh, BinaryIO *io) : - WavChunk(chh) { read(io) ; } ; - - void read (BinaryIO *io) ; - void write (BinaryIO *io) ; - - UWORD16 getFormatTag (void) const - { return FormatTag ; } ; - - UWORD16 getBitsPerSample (void) const - { return BitsPerSample ; } ; - - static const UWORD16 FormatPCM = 0x0001 ; - - private: - UWORD16 FormatTag ; - UWORD16 Channels ; - UWORD32 SamplesPerSec ; - UWORD32 AvgBytesPerSec ; - UWORD16 BlockAlign ; - UWORD16 BitsPerSample ; - UWORD16 AdditionalSize ; -} ; + public: + WavFormatChunk(void) : WavChunk(){}; + WavFormatChunk(WavChunkHeader *chh) : WavChunk(chh){}; + WavFormatChunk(WavChunkHeader *chh, BinaryIO *io) : WavChunk(chh) { read(io); }; + + void read(BinaryIO *io); + void write(BinaryIO *io); + + UWORD16 getFormatTag(void) const { return FormatTag; }; + + UWORD16 getBitsPerSample(void) const { return BitsPerSample; }; + + static const UWORD16 FormatPCM = 0x0001; + + private: + UWORD16 FormatTag; + UWORD16 Channels; + UWORD32 SamplesPerSec; + UWORD32 AvgBytesPerSec; + UWORD16 BlockAlign; + UWORD16 BitsPerSample; + UWORD16 AdditionalSize; +}; #endif // ndef SH_WAVCHUNKFORMAT_H diff --git a/src/WavPCMSampleValue.cc b/src/WavPCMSampleValue.cc index c7821ed..fd5db8a 100644 --- a/src/WavPCMSampleValue.cc +++ b/src/WavPCMSampleValue.cc @@ -21,102 +21,94 @@ #include #include -#include "common.h" #include "WavFile.h" #include "WavPCMSampleValue.h" +#include "common.h" -WavPCMSampleValue::WavPCMSampleValue (int v) - : SampleValue(), Value(v) -{ - const WavFile* wavfile = dynamic_cast (Globs.TheCvrStgFile) ; - myassert (wavfile != NULL) ; - unsigned short samplesize = wavfile->getBitsPerSample() ; +WavPCMSampleValue::WavPCMSampleValue(int v) : SampleValue(), Value(v) { + const WavFile *wavfile = dynamic_cast(Globs.TheCvrStgFile); + myassert(wavfile != NULL); + unsigned short samplesize = wavfile->getBitsPerSample(); - int maxvalue = 1 ; - int minvalue = 1 ; - if ((samplesize >= 1) && (samplesize <= 8)) { - // maxvalue is 2^samplesize - for (unsigned short i = 0 ; i < samplesize ; i++) { - maxvalue *= 2 ; - } + int maxvalue = 1; + int minvalue = 1; + if ((samplesize >= 1) && (samplesize <= 8)) { + // maxvalue is 2^samplesize + for (unsigned short i = 0; i < samplesize; i++) { + maxvalue *= 2; + } - minvalue = 0 ; - } - else { - // maxvalue is (2^(samplesize - 1)) - 1 - for (unsigned short i = 0 ; i < (samplesize - 1) ; i++) { - maxvalue *= 2 ; - } - maxvalue-- ; + minvalue = 0; + } else { + // maxvalue is (2^(samplesize - 1)) - 1 + for (unsigned short i = 0; i < (samplesize - 1); i++) { + maxvalue *= 2; + } + maxvalue--; - // minvalue is -(2^(SampleSize - 1)) - for (unsigned short i = 0 ; i < (samplesize - 1) ; i++) { - minvalue *= 2 ; - } - minvalue = -minvalue ; - } + // minvalue is -(2^(SampleSize - 1)) + for (unsigned short i = 0; i < (samplesize - 1); i++) { + minvalue *= 2; + } + minvalue = -minvalue; + } - MaxValue = maxvalue ; - MinValue = minvalue ; - if (MinValue > Value) { - std::cerr << "MinValue: " << MinValue << ", Value: " << Value << std::endl ; - } - myassert (MinValue <= Value) ; - myassert (Value <= MaxValue) ; + MaxValue = maxvalue; + MinValue = minvalue; + if (MinValue > Value) { + std::cerr << "MinValue: " << MinValue << ", Value: " << Value << std::endl; + } + myassert(MinValue <= Value); + myassert(Value <= MaxValue); - Key = (UWORD32) Value ; - EValue = calcEValue (Value) ; + Key = (UWORD32)Value; + EValue = calcEValue(Value); } -SampleValue *WavPCMSampleValue::getNearestTargetSampleValue (EmbValue t) const -{ - int val_up = Value, val_down = Value, newval = 0 ; - bool found = false ; +SampleValue *WavPCMSampleValue::getNearestTargetSampleValue(EmbValue t) const { + int val_up = Value, val_down = Value, newval = 0; + bool found = false; - do { - if (val_up < MaxValue) { - val_up++ ; - } - if (val_down > MinValue) { - val_down-- ; - } + do { + if (val_up < MaxValue) { + val_up++; + } + if (val_down > MinValue) { + val_down--; + } - if (calcEValue(val_up) == t && calcEValue(val_down) == t) { - if (RndSrc.getBool()) { - newval = val_up ; - } - else { - newval = val_down ; - } - found = true ; - } - else if (calcEValue(val_up) == t) { - newval = val_up ; - found = true ; - } - else if (calcEValue(val_down) == t) { - newval = val_down ; - found = true ; - } - } while (!found) ; + if (calcEValue(val_up) == t && calcEValue(val_down) == t) { + if (RndSrc.getBool()) { + newval = val_up; + } else { + newval = val_down; + } + found = true; + } else if (calcEValue(val_up) == t) { + newval = val_up; + found = true; + } else if (calcEValue(val_down) == t) { + newval = val_down; + found = true; + } + } while (!found); - return ((SampleValue *) new WavPCMSampleValue (newval)) ; + return ((SampleValue *)new WavPCMSampleValue(newval)); } -UWORD32 WavPCMSampleValue::calcDistance (const SampleValue *s) const -{ - const WavPCMSampleValue *sample = (const WavPCMSampleValue*) s ; - /* If s is not a WavPCMSampleValue then we get into real trouble here. - But calcDistance is called very often, a dynamic_cast costs a lot of time and - it does not make sense to pass anything but a WavPCMSampleValue as s anyway. */ +UWORD32 WavPCMSampleValue::calcDistance(const SampleValue *s) const { + const WavPCMSampleValue *sample = (const WavPCMSampleValue *)s; + /* If s is not a WavPCMSampleValue then we get into real trouble here. + But calcDistance is called very often, a dynamic_cast costs a lot of time and + it does not make sense to pass anything but a WavPCMSampleValue as s anyway. + */ - int d = Value - sample->Value ; - return ((d >= 0) ? ((UWORD32) d) : ((UWORD32) -d)) ; + int d = Value - sample->Value; + return ((d >= 0) ? ((UWORD32)d) : ((UWORD32)-d)); } -std::string WavPCMSampleValue::getName () const -{ - char buf[128] ; - sprintf (buf, "%d", Value) ; - return std::string (buf) ; +std::string WavPCMSampleValue::getName() const { + char buf[128]; + sprintf(buf, "%d", Value); + return std::string(buf); } diff --git a/src/WavPCMSampleValue.h b/src/WavPCMSampleValue.h index 444827d..1142467 100644 --- a/src/WavPCMSampleValue.h +++ b/src/WavPCMSampleValue.h @@ -25,31 +25,31 @@ #include "SampleValue.h" -class CvrStgFile ; +class CvrStgFile; class WavPCMSampleValue : public SampleValue { - public: - WavPCMSampleValue (int v) ; + public: + WavPCMSampleValue(int v); - SampleValue* getNearestTargetSampleValue (EmbValue t) const ; - UWORD32 calcDistance (const SampleValue *s) const ; - std::string getName (void) const ; + SampleValue *getNearestTargetSampleValue(EmbValue t) const; + UWORD32 calcDistance(const SampleValue *s) const; + std::string getName(void) const; - int getValue (void) const - { return Value ; } ; + int getValue(void) const { return Value; }; - private: - int Value ; - int MaxValue ; - int MinValue ; + private: + int Value; + int MaxValue; + int MinValue; - EmbValue calcEValue (int v) const - { return (v & 1) ; } -} ; + EmbValue calcEValue(int v) const { return (v & 1); } +}; -class WavPCMSmaller : public std::binary_function { - public: - bool operator() (const WavPCMSampleValue *v, const WavPCMSampleValue *w) { return v->getValue() < w->getValue() ; } ; -} ; +class WavPCMSmaller : public std::binary_function { + public: + bool operator()(const WavPCMSampleValue *v, const WavPCMSampleValue *w) { + return v->getValue() < w->getValue(); + }; +}; #endif // ndef SH_WAVSAMPLE_H diff --git a/src/common.h b/src/common.h index 2b8f5ec..081325a 100644 --- a/src/common.h +++ b/src/common.h @@ -34,40 +34,40 @@ // // generic type definitions #ifdef HAVE_CONFIG_H -typedef TYPE_UWORD32 UWORD32 ; -typedef TYPE_UWORD16 UWORD16 ; -typedef TYPE_BYTE BYTE ; -typedef TYPE_SWORD32 SWORD32 ; -typedef TYPE_SWORD16 SWORD16 ; -typedef TYPE_SBYTE SBYTE ; +typedef TYPE_UWORD32 UWORD32; +typedef TYPE_UWORD16 UWORD16; +typedef TYPE_BYTE BYTE; +typedef TYPE_SWORD32 SWORD32; +typedef TYPE_SWORD16 SWORD16; +typedef TYPE_SBYTE SBYTE; #else // use types that are at least the correct size -typedef unsigned int UWORD32 ; -typedef unsigned short UWORD16 ; -typedef unsigned char BYTE ; -typedef int SWORD32 ; -typedef short SWORD16 ; -typedef char SBYTE ; +typedef unsigned int UWORD32; +typedef unsigned short UWORD16; +typedef unsigned char BYTE; +typedef int SWORD32; +typedef short SWORD16; +typedef char SBYTE; #endif -#define UWORD32_MAX 0xFFFFFFFFUL -#define UWORD16_MAX 0xFFFF -#define BYTE_MAX 0xFF -#define SWORD32_MIN -2147483647 - 1 // to avoid a gcc warning (caused by an overflow) -#define SWORD32_MAX 2147483647 -#define SWORD16_MIN -32768 -#define SWORD16_MAX 32767 -#define SBYTE_MIN -128 -#define SBYTE_MAX 127 +#define UWORD32_MAX 0xFFFFFFFFUL +#define UWORD16_MAX 0xFFFF +#define BYTE_MAX 0xFF +#define SWORD32_MIN -2147483647 - 1 // to avoid a gcc warning (caused by an overflow) +#define SWORD32_MAX 2147483647 +#define SWORD16_MIN -32768 +#define SWORD16_MAX 32767 +#define SBYTE_MIN -128 +#define SBYTE_MAX 127 // // specialised type definitions -typedef bool BIT ; -typedef BYTE EmbValue ; -typedef UWORD32 SamplePos ; -typedef UWORD32 VertexLabel ; -typedef UWORD32 SampleValueLabel ; -typedef UWORD32 SampleKey ; +typedef bool BIT; +typedef BYTE EmbValue; +typedef UWORD32 SamplePos; +typedef UWORD32 VertexLabel; +typedef UWORD32 SampleValueLabel; +typedef UWORD32 SampleKey; #define SAMPLEKEY_MAX UWORD32_MAX #define VERTEXLABEL_MAX UWORD32_MAX @@ -79,30 +79,32 @@ typedef UWORD32 SampleKey ; // // global variables #include "Globals.h" -extern Globals Globs ; +extern Globals Globs; // // every class should (be able to) do assertions // (myassert(expr) is more verbose than the standard C assert) #include "AssertionFailed.h" -#define myassert(expr) if (!(expr)) throw AssertionFailed (__FILE__, __LINE__) +#define myassert(expr) \ + if (!(expr)) \ + throw AssertionFailed(__FILE__, __LINE__) // // every class can have debugging output #include // for verbose testing output #if DEBUG #define RUNDEBUGLEVEL(LEVEL) ((LEVEL) <= Args.DebugLevel.getValue()) -extern void printDebug (unsigned short level, const char *msgfmt, ...) ; +extern void printDebug(unsigned short level, const char *msgfmt, ...); #endif // // every class has access to the command line arguments #include "Arguments.h" -extern Arguments Args ; +extern Arguments Args; // // every class has access to random data #include "RandomSource.h" -extern RandomSource RndSrc ; +extern RandomSource RndSrc; #endif // ndef SH_COMMON_H diff --git a/src/error.cc b/src/error.cc index e89f6a8..8b7bd11 100644 --- a/src/error.cc +++ b/src/error.cc @@ -15,16 +15,16 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * + * * 2020: * - Changed steghide help to stegseek help * */ +#include +#include #include #include -#include -#include #include "BinaryIO.h" #include "common.h" @@ -33,134 +33,106 @@ // // class ArgError // -ArgError::ArgError (const char* msgfmt, ...) - : SteghideError() -{ - va_list ap ; - va_start (ap, msgfmt) , - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +ArgError::ArgError(const char *msgfmt, ...) : SteghideError() { + va_list ap; + va_start(ap, msgfmt), setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void ArgError::printMessage () const -{ - SteghideError::printMessage() ; - std::cerr << "stegseek: " << _("type \"stegseek --help\" for help.") << std::endl ; +void ArgError::printMessage() const { + SteghideError::printMessage(); + std::cerr << "stegseek: " << _("type \"stegseek --help\" for help.") << std::endl; } // // class BinaryInputError // -BinaryInputError::BinaryInputError (std::string fn, FILE* s) - : SteghideError() -{ - if (feof (s)) { - if (fn == "") { - setMessage(_("premature end of data from standard input.")) ; - setType (STDIN_EOF) ; - } - else { - setMessage(compose (_("premature end of file \"%s\"."), fn.c_str())) ; - setType (FILE_EOF) ; - } - } - else { - if (fn == "") { - setMessage(_("an error occurred while reading data from standard input.")) ; - setType (STDIN_ERR) ; - } - else { - setMessage(compose (_("an error occurred while reading data from the file \"%s\"."), fn.c_str())) ; - setType (FILE_ERR) ; - } - } +BinaryInputError::BinaryInputError(std::string fn, FILE *s) : SteghideError() { + if (feof(s)) { + if (fn == "") { + setMessage(_("premature end of data from standard input.")); + setType(STDIN_EOF); + } else { + setMessage(compose(_("premature end of file \"%s\"."), fn.c_str())); + setType(FILE_EOF); + } + } else { + if (fn == "") { + setMessage(_("an error occurred while reading data from standard input.")); + setType(STDIN_ERR); + } else { + setMessage(compose(_("an error occurred while reading data from the file \"%s\"."), + fn.c_str())); + setType(FILE_ERR); + } + } } -BinaryInputError::TYPE BinaryInputError::getType (void) -{ - return type ; -} +BinaryInputError::TYPE BinaryInputError::getType(void) { return type; } -void BinaryInputError::setType (BinaryInputError::TYPE t) -{ - type = t ; -} +void BinaryInputError::setType(BinaryInputError::TYPE t) { type = t; } // // class BinaryOutputError // -BinaryOutputError::BinaryOutputError (std::string fn) - : SteghideError() -{ - if (fn == "") { - setMessage(_("an error occurred while writing data to standard output.")) ; - setType(STDOUT_ERR) ; - } - else { - setMessage(compose (_("an error occurred while writing data to the file \"%s\"."), fn.c_str())) ; - setType(FILE_ERR) ; - } +BinaryOutputError::BinaryOutputError(std::string fn) : SteghideError() { + if (fn == "") { + setMessage(_("an error occurred while writing data to standard output.")); + setType(STDOUT_ERR); + } else { + setMessage( + compose(_("an error occurred while writing data to the file \"%s\"."), fn.c_str())); + setType(FILE_ERR); + } } -BinaryOutputError::TYPE BinaryOutputError::getType (void) -{ - return type ; -} +BinaryOutputError::TYPE BinaryOutputError::getType(void) { return type; } -void BinaryOutputError::setType (BinaryOutputError::TYPE t) -{ - type = t ; -} +void BinaryOutputError::setType(BinaryOutputError::TYPE t) { type = t; } // // class UnSupFileFormat // -UnSupFileFormat::UnSupFileFormat (BinaryIO *io) - : SteghideError() -{ - if (io->is_std()) { - setMessage(_("the file format of the data from standard input is not supported.")) ; - } - else { - setMessage(compose (_("the file format of the file \"%s\" is not supported."), io->getName().c_str())) ; - } +UnSupFileFormat::UnSupFileFormat(BinaryIO *io) : SteghideError() { + if (io->is_std()) { + setMessage(_("the file format of the data from standard input is not supported.")); + } else { + setMessage(compose(_("the file format of the file \"%s\" is not supported."), + io->getName().c_str())); + } } // // class NotImplementedError // -NotImplementedError::NotImplementedError (const char *msgfmt, ...) - : SteghideError() -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +NotImplementedError::NotImplementedError(const char *msgfmt, ...) : SteghideError() { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void NotImplementedError::printMessage () const -{ - SteghideError::printMessage() ; - printf (_("This feature is not (yet) available. Please let steghide's author (shetzl@chello.at) know\n" - "that you want to use this functionality to increase the chance that this will\n" - "be implemented in the near future.\n")) ; +void NotImplementedError::printMessage() const { + SteghideError::printMessage(); + printf(_("This feature is not (yet) available. Please let steghide's author " + "(shetzl@chello.at) know\n" + "that you want to use this functionality to increase the chance " + "that this will\n" + "be implemented in the near future.\n")); } // // class CorruptDataError // -CorruptDataError::CorruptDataError (const char* msgfmt, ...) - : SteghideError() -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +CorruptDataError::CorruptDataError(const char *msgfmt, ...) : SteghideError() { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void CorruptDataError::printMessage () const -{ - SteghideError::printMessage() ; - printf (_("Other possible reasons for this error are that the passphrase is wrong\n" - "or that there is no embedded data.\n")) ; +void CorruptDataError::printMessage() const { + SteghideError::printMessage(); + printf(_("Other possible reasons for this error are that the passphrase is wrong\n" + "or that there is no embedded data.\n")); } diff --git a/src/error.h b/src/error.h index 8130393..b9374c2 100644 --- a/src/error.h +++ b/src/error.h @@ -26,56 +26,56 @@ #include "SteghideError.h" -class BinaryIO ; +class BinaryIO; class ArgError : public SteghideError { - public: - ArgError (const char *msgfmt, ...) ; + public: + ArgError(const char *msgfmt, ...); - void printMessage (void) const ; -} ; + void printMessage(void) const; +}; class BinaryInputError : public SteghideError { - public: - enum TYPE { FILE_ERR, FILE_EOF, STDIN_ERR, STDIN_EOF } ; + public: + enum TYPE { FILE_ERR, FILE_EOF, STDIN_ERR, STDIN_EOF }; - BinaryInputError (std::string fn, FILE* s) ; + BinaryInputError(std::string fn, FILE *s); - TYPE getType (void) ; + TYPE getType(void); - protected: - void setType (TYPE t) ; + protected: + void setType(TYPE t); - private: - TYPE type ; -} ; + private: + TYPE type; +}; class BinaryOutputError : public SteghideError { - public: - enum TYPE { FILE_ERR, STDOUT_ERR } ; + public: + enum TYPE { FILE_ERR, STDOUT_ERR }; - BinaryOutputError (std::string fn) ; + BinaryOutputError(std::string fn); - TYPE getType (void) ; + TYPE getType(void); - protected: - void setType (TYPE t) ; + protected: + void setType(TYPE t); - private: - TYPE type ; -} ; + private: + TYPE type; +}; class UnSupFileFormat : public SteghideError { - public: - UnSupFileFormat (BinaryIO *io) ; -} ; + public: + UnSupFileFormat(BinaryIO *io); +}; class NotImplementedError : public SteghideError { - public: - NotImplementedError (const char* msgfmt, ...) ; + public: + NotImplementedError(const char *msgfmt, ...); - void printMessage (void) const ; -} ; + void printMessage(void) const; +}; /** * \class CorruptDataError @@ -84,10 +84,10 @@ class NotImplementedError : public SteghideError { * A possible cause of this exception being thrown is a wrong password. **/ class CorruptDataError : public SteghideError { - public: - CorruptDataError (const char* msgfmt, ...) ; + public: + CorruptDataError(const char *msgfmt, ...); - void printMessage (void) const ; -} ; + void printMessage(void) const; +}; #endif diff --git a/src/main.cc b/src/main.cc index 8f4ea43..e2bdf6b 100644 --- a/src/main.cc +++ b/src/main.cc @@ -18,24 +18,21 @@ * */ -#include "common.h" #include "Session.h" #include "SteghideError.h" +#include "common.h" +int main(int argc, char *argv[]) { + try { + Args = Arguments(argc, argv); + Args.parse(); -int main (int argc, char *argv[]) -{ - try { - Args = Arguments (argc, argv) ; - Args.parse() ; - - Session s ; - s.run() ; - } - catch (const SteghideError& e) { - e.printMessage() ; - exit(EXIT_FAILURE) ; - } + Session s; + s.run(); + } catch (const SteghideError &e) { + e.printMessage(); + exit(EXIT_FAILURE); + } - exit(EXIT_SUCCESS) ; + exit(EXIT_SUCCESS); } diff --git a/src/msg.cc b/src/msg.cc index 6ae9358..d5e7807 100644 --- a/src/msg.cc +++ b/src/msg.cc @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * + * * 2020: * - Changed userfacing steghide mentions to stegseek * @@ -26,200 +26,172 @@ #include #include +#include "Terminal.h" #include "common.h" #include "msg.h" -#include "Terminal.h" // // class MessageBase // -MessageBase::MessageBase () -{ - setMessage (std::string(_("__no_message_defined__"))) ; - setNewline (true) ; +MessageBase::MessageBase() { + setMessage(std::string(_("__no_message_defined__"))); + setNewline(true); } -MessageBase::MessageBase (std::string msg) -{ - setMessage (msg) ; - setNewline (true) ; +MessageBase::MessageBase(std::string msg) { + setMessage(msg); + setNewline(true); } -MessageBase::MessageBase (const char *msgfmt, ...) -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (msgfmt, ap) ; - va_end (ap) ; - setNewline (true) ; +MessageBase::MessageBase(const char *msgfmt, ...) { + va_list ap; + va_start(ap, msgfmt); + setMessage(msgfmt, ap); + va_end(ap); + setNewline(true); } -void MessageBase::setMessage (const char *msgfmt, ...) -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +void MessageBase::setMessage(const char *msgfmt, ...) { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -std::string MessageBase::compose (const char *msgfmt, ...) const -{ - va_list ap ; - va_start (ap, msgfmt) ; - std::string retval = vcompose (msgfmt, ap) ; - va_end (ap) ; - return retval ; +std::string MessageBase::compose(const char *msgfmt, ...) const { + va_list ap; + va_start(ap, msgfmt); + std::string retval = vcompose(msgfmt, ap); + va_end(ap); + return retval; } -std::string MessageBase::vcompose (const char *msgfmt, va_list ap) const -{ - char *str = new char[MsgMaxSize] ; - vsnprintf (str, MsgMaxSize, msgfmt, ap) ; - std::string retval (str) ; - delete[] str ; - return retval ; +std::string MessageBase::vcompose(const char *msgfmt, va_list ap) const { + char *str = new char[MsgMaxSize]; + vsnprintf(str, MsgMaxSize, msgfmt, ap); + std::string retval(str); + delete[] str; + return retval; } // // class Message // -Message::Message (const char *msgfmt, ...) - : MessageBase() -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +Message::Message(const char *msgfmt, ...) : MessageBase() { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void Message::printMessage () const -{ - if (Args.Verbosity.getValue() == NORMAL || - Args.Verbosity.getValue() == VERBOSE) { - std::cerr << getMessage() << getNewline() ; - } +void Message::printMessage() const { + if (Args.Verbosity.getValue() == NORMAL || Args.Verbosity.getValue() == VERBOSE) { + std::cerr << getMessage() << getNewline(); + } } // // class VerboseMessage // -VerboseMessage::VerboseMessage (const char *msgfmt, ...) - : MessageBase() -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; - setNewline (true) ; +VerboseMessage::VerboseMessage(const char *msgfmt, ...) : MessageBase() { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); + setNewline(true); } -void VerboseMessage::printMessage () const -{ - if (Args.Verbosity.getValue() == VERBOSE) { - std::cerr << getMessage() << getNewline() ; - } +void VerboseMessage::printMessage() const { + if (Args.Verbosity.getValue() == VERBOSE) { + std::cerr << getMessage() << getNewline(); + } } // // class Warning // -Warning::Warning (const char *msgfmt, ...) - : MessageBase() -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +Warning::Warning(const char *msgfmt, ...) : MessageBase() { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void Warning::printMessage () const -{ - if (Args.Verbosity.getValue() != QUIET) { - std::cerr << "stegseek: " << _("warning:") << " " << getMessage() << getNewline() ; - } +void Warning::printMessage() const { + if (Args.Verbosity.getValue() != QUIET) { + std::cerr << "stegseek: " << _("warning:") << " " << getMessage() << getNewline(); + } } // // class CriticalWarning // -CriticalWarning::CriticalWarning (const char *msgfmt, ...) - : MessageBase() -{ - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; +CriticalWarning::CriticalWarning(const char *msgfmt, ...) : MessageBase() { + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void CriticalWarning::printMessage () const -{ - std::cerr << "stegseek: " << _("warning:") << " " << getMessage() << getNewline() ; +void CriticalWarning::printMessage() const { + std::cerr << "stegseek: " << _("warning:") << " " << getMessage() << getNewline(); } // // class Question // -Question::Question (void) - : MessageBase() -{ - yeschar = std::string (_("y")) ; - nochar = std::string (_("n")) ; +Question::Question(void) : MessageBase() { + yeschar = std::string(_("y")); + nochar = std::string(_("n")); } -Question::Question (std::string msg) - : MessageBase (msg) -{ - yeschar = std::string (_("y")) ; - nochar = std::string (_("n")) ; +Question::Question(std::string msg) : MessageBase(msg) { + yeschar = std::string(_("y")); + nochar = std::string(_("n")); } -Question::Question (const char *msgfmt, ...) - : MessageBase() -{ - yeschar = std::string (_("y")) ; - nochar = std::string (_("n")) ; +Question::Question(const char *msgfmt, ...) : MessageBase() { + yeschar = std::string(_("y")); + nochar = std::string(_("n")); - va_list ap ; - va_start (ap, msgfmt) ; - setMessage (vcompose (msgfmt, ap)) ; - va_end (ap) ; + va_list ap; + va_start(ap, msgfmt); + setMessage(vcompose(msgfmt, ap)); + va_end(ap); } -void Question::printMessage () const -{ +void Question::printMessage() const { #ifndef HAVE_TERMIOS_H - Warning w (_("unknown terminal. you might need to press after answering.")) ; - w.printMessage() ; + Warning w(_("unknown terminal. you might need to press after answering.")); + w.printMessage(); #endif - std::cerr << getMessage() << " (" << yeschar << "/" << nochar << ") " ; + std::cerr << getMessage() << " (" << yeschar << "/" << nochar << ") "; } -bool Question::getAnswer () -{ - Terminal term ; - term.SingleKeyOn() ; - char input[2] ; - input[0] = std::cin.get() ; - input[1] = '\0' ; - bool retval = (std::string (input) == yeschar) ; - term.reset() ; - std::cerr << std::endl ; +bool Question::getAnswer() { + Terminal term; + term.SingleKeyOn(); + char input[2]; + input[0] = std::cin.get(); + input[1] = '\0'; + bool retval = (std::string(input) == yeschar); + term.reset(); + std::cerr << std::endl; - return retval ; + return retval; } // // debugging output // #ifdef DEBUG -void printDebug (unsigned short level, const char *msgfmt, ...) -{ - if (RUNDEBUGLEVEL(level)) { - va_list ap ; - va_start (ap, msgfmt) ; - vfprintf (stderr, msgfmt, ap) ; - va_end (ap) ; - fprintf (stderr, "\n") ; - } +void printDebug(unsigned short level, const char *msgfmt, ...) { + if (RUNDEBUGLEVEL(level)) { + va_list ap; + va_start(ap, msgfmt); + vfprintf(stderr, msgfmt, ap); + va_end(ap); + fprintf(stderr, "\n"); + } } #endif diff --git a/src/msg.h b/src/msg.h index 1ac9f23..b261255 100644 --- a/src/msg.h +++ b/src/msg.h @@ -25,98 +25,95 @@ #include class MessageBase { - public: - MessageBase (void) ; - MessageBase (std::string msg) ; - MessageBase (const char* msgfmt, ...) ; - virtual ~MessageBase() {} ; + public: + MessageBase(void); + MessageBase(std::string msg); + MessageBase(const char *msgfmt, ...); + virtual ~MessageBase(){}; - const std::string& getMessage (void) const - { return Message ; } ; + const std::string &getMessage(void) const { return Message; }; - void setMessage (std::string msg) - { Message = msg ; } ; + void setMessage(std::string msg) { Message = msg; }; - /** - * toggle newline printing on/off - * \param prnl wether to print a newline character after the message - **/ - void setNewline (bool prnl) - { Newline = prnl ; } ; + /** + * toggle newline printing on/off + * \param prnl wether to print a newline character after the message + **/ + void setNewline(bool prnl) { Newline = prnl; }; - /** - * return either "\n" or "" depending on wether this message should be followed by a newline or not - **/ - const std::string getNewline (void) const - { return (Newline ? "\n" : "") ; } ; + /** + * return either "\n" or "" depending on wether this message should be followed by a newline or + *not + **/ + const std::string getNewline(void) const { return (Newline ? "\n" : ""); }; - void setMessage (const char *msgfmt, ...) ; - virtual void printMessage (void) const = 0 ; + void setMessage(const char *msgfmt, ...); + virtual void printMessage(void) const = 0; - protected: - static const unsigned int MsgMaxSize = 512 ; + protected: + static const unsigned int MsgMaxSize = 512; - std::string compose (const char *msgfmt, ...) const ; - std::string vcompose (const char *msgfmt, va_list ap) const ; + std::string compose(const char *msgfmt, ...) const; + std::string vcompose(const char *msgfmt, va_list ap) const; - private: - std::string Message ; - bool Newline ; -} ; + private: + std::string Message; + bool Newline; +}; class Message : public MessageBase { - public: - Message (void) : MessageBase() {} ; - Message (std::string msg) : MessageBase (msg) {} ; - Message (const char *msgfmt, ...) ; + public: + Message(void) : MessageBase(){}; + Message(std::string msg) : MessageBase(msg){}; + Message(const char *msgfmt, ...); - void printMessage (void) const ; -} ; + void printMessage(void) const; +}; class VerboseMessage : public MessageBase { - public: - VerboseMessage (void) : MessageBase() {} ; - VerboseMessage (std::string msg) : MessageBase (msg) {} ; - VerboseMessage (const char *msgfmt, ...) ; + public: + VerboseMessage(void) : MessageBase(){}; + VerboseMessage(std::string msg) : MessageBase(msg){}; + VerboseMessage(const char *msgfmt, ...); - void printMessage (void) const ; -} ; + void printMessage(void) const; +}; class Warning : public MessageBase { - public: - Warning (void) : MessageBase() {} ; - Warning (std::string msg) : MessageBase (msg) {} ; - Warning (const char *msgfmt, ...) ; + public: + Warning(void) : MessageBase(){}; + Warning(std::string msg) : MessageBase(msg){}; + Warning(const char *msgfmt, ...); - void printMessage (void) const ; -} ; + void printMessage(void) const; +}; class CriticalWarning : public MessageBase { - public: - CriticalWarning (void) : MessageBase() {} ; - CriticalWarning (std::string msg) : MessageBase (msg) {} ; - CriticalWarning (const char *msgfmt, ...) ; + public: + CriticalWarning(void) : MessageBase(){}; + CriticalWarning(std::string msg) : MessageBase(msg){}; + CriticalWarning(const char *msgfmt, ...); - void printMessage (void) const ; -} ; + void printMessage(void) const; +}; class Question : public MessageBase { - public: - Question (void) ; - Question (std::string msg) ; - Question (const char *msgfmt, ...) ; + public: + Question(void); + Question(std::string msg); + Question(const char *msgfmt, ...); - void printMessage (void) const ; + void printMessage(void) const; - /** - * wait for the user to answer the question (should be printed before) - * \return true iff the user answers with yes, i.e. presses the yeschar-key - **/ - bool getAnswer (void) ; + /** + * wait for the user to answer the question (should be printed before) + * \return true iff the user answers with yes, i.e. presses the yeschar-key + **/ + bool getAnswer(void); - private: - std::string yeschar ; - std::string nochar ; -} ; + private: + std::string yeschar; + std::string nochar; +}; -#endif /* ndef SH_MSG_H */ +#endif /* ndef SH_MSG_H */ diff --git a/tests/steghide/AUtilsTest.cc b/tests/steghide/AUtilsTest.cc index bccb12f..5cb2d51 100644 --- a/tests/steghide/AUtilsTest.cc +++ b/tests/steghide/AUtilsTest.cc @@ -23,25 +23,21 @@ #include "AUtilsTest.h" #include "TestCategoryCaller.h" -AUtilsTest::AUtilsTest (TestSuite* s) - : UnitTest ("AUtils", s) -{ - ADDTESTCATEGORY (AUtilsTest, testLog2) ; +AUtilsTest::AUtilsTest(TestSuite *s) : UnitTest("AUtils", s) { + ADDTESTCATEGORY(AUtilsTest, testLog2); } -void AUtilsTest::testLog2 () -{ - addTestResult (genericTestLog2 (2, 1.0)) ; - addTestResult (genericTestLog2 (8, 3.0)) ; - addTestResult (genericTestLog2 (5, 2.321928)) ; - addTestResult (genericTestLog2 (21, 4.392317)) ; +void AUtilsTest::testLog2() { + addTestResult(genericTestLog2(2, 1.0)); + addTestResult(genericTestLog2(8, 3.0)); + addTestResult(genericTestLog2(5, 2.321928)); + addTestResult(genericTestLog2(21, 4.392317)); } -bool AUtilsTest::genericTestLog2 (int n, double res) -{ - // to avoid failing because of numeric problems - double tmp = log2 (n) ; - double lb = res - 0.000001 ; - double ub = res + 0.000001 ; - return (lb < tmp && tmp < ub) ; +bool AUtilsTest::genericTestLog2(int n, double res) { + // to avoid failing because of numeric problems + double tmp = log2(n); + double lb = res - 0.000001; + double ub = res + 0.000001; + return (lb < tmp && tmp < ub); } diff --git a/tests/steghide/AUtilsTest.h b/tests/steghide/AUtilsTest.h index 421a12b..5bfb1f8 100644 --- a/tests/steghide/AUtilsTest.h +++ b/tests/steghide/AUtilsTest.h @@ -23,17 +23,17 @@ #include "AUtils.h" -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class AUtilsTest : public UnitTest { - public: - AUtilsTest (TestSuite* s) ; + public: + AUtilsTest(TestSuite *s); - void testLog2 (void) ; + void testLog2(void); - private: - bool genericTestLog2 (int n, double res) ; -} ; + private: + bool genericTestLog2(int n, double res); +}; #endif // ndef SH_AUTILSTEST_H diff --git a/tests/steghide/AuFileTest.cc b/tests/steghide/AuFileTest.cc index 34e0218..56436b8 100644 --- a/tests/steghide/AuFileTest.cc +++ b/tests/steghide/AuFileTest.cc @@ -20,112 +20,127 @@ #include "AuSampleValues.h" -#include "utcommon.h" #include "AuFileTest.h" +#include "utcommon.h" -AuFileTest::AuFileTest (TestSuite* s) - : CvrStgFileTest("AuFile", s) -{ - ADDTESTCATEGORY (AuFileTest, testReadWrite) ; - ADDTESTCATEGORY (AuFileTest, testReadEmbedExtract) ; - ADDTESTCATEGORY (AuFileTest, testReadEmbedWriteReadExtract) ; - ADDTESTCATEGORY (AuFileTest, testPosition) ; - ADDTESTCATEGORY (AuFileTest, testReadExtractCompare) ; - ADDTESTCATEGORY (AuFileTest, testEmbeddedValue) ; +AuFileTest::AuFileTest(TestSuite *s) : CvrStgFileTest("AuFile", s) { + ADDTESTCATEGORY(AuFileTest, testReadWrite); + ADDTESTCATEGORY(AuFileTest, testReadEmbedExtract); + ADDTESTCATEGORY(AuFileTest, testReadEmbedWriteReadExtract); + ADDTESTCATEGORY(AuFileTest, testPosition); + ADDTESTCATEGORY(AuFileTest, testReadExtractCompare); + ADDTESTCATEGORY(AuFileTest, testEmbeddedValue); } -void AuFileTest::setup () -{ - UnitTest::setup() ; - - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "mulaw_std.au") ; - bs1 = new BitString (std::string ("a test passphrase")) ; - gl1 = Globs ; +void AuFileTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "pcm8_std.au") ; - bs2 = new BitString (std::string ("another test passphrase")) ; - gl2 = Globs ; + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "mulaw_std.au"); + bs1 = new BitString(std::string("a test passphrase")); + gl1 = Globs; - Globs.reset() ; - f3 = CvrStgFile::readFile (std::string(DATADIR) + "pcm16_std.au") ; - bs3 = new BitString (std::string ("inventing test passphrases is boring")) ; - gl3 = Globs ; + Globs.reset(); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "pcm8_std.au"); + bs2 = new BitString(std::string("another test passphrase")); + gl2 = Globs; + Globs.reset(); + f3 = CvrStgFile::readFile(std::string(DATADIR) + "pcm16_std.au"); + bs3 = new BitString(std::string("inventing test passphrases is boring")); + gl3 = Globs; } -void AuFileTest::cleanup () -{ - UnitTest::cleanup() ; +void AuFileTest::cleanup() { + UnitTest::cleanup(); - delete bs1 ; delete bs2 ; delete bs3 ; - delete f1 ; delete f2 ; delete f3 ; + delete bs1; + delete bs2; + delete bs3; + delete f1; + delete f2; + delete f3; } -void AuFileTest::testReadWrite() -{ - Globs = gl1 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "mulaw_std.au")) ; - Globs = gl2 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "pcm8_std.au")) ; - Globs = gl3 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "pcm16_std.au")) ; +void AuFileTest::testReadWrite() { + Globs = gl1; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "mulaw_std.au")); + Globs = gl2; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "pcm8_std.au")); + Globs = gl3; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "pcm16_std.au")); } -void AuFileTest::testReadEmbedExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "mulaw_std.au", *bs1)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "pcm8_std.au", *bs2)) ; - Globs = gl3 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "pcm16_std.au", *bs3)) ; +void AuFileTest::testReadEmbedExtract() { + Globs = gl1; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "mulaw_std.au", *bs1)); + Globs = gl2; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "pcm8_std.au", *bs2)); + Globs = gl3; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "pcm16_std.au", *bs3)); } -void AuFileTest::testReadEmbedWriteReadExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "mulaw_std.au", *bs2)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "pcm8_std.au", *bs3)) ; - Globs = gl3 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "pcm16_std.au", *bs1)) ; +void AuFileTest::testReadEmbedWriteReadExtract() { + Globs = gl1; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "mulaw_std.au", *bs2)); + Globs = gl2; + addTestResult(genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "pcm8_std.au", *bs3)); + Globs = gl3; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "pcm16_std.au", *bs1)); } -void AuFileTest::testPosition() -{ - Globs = gl1 ; - addTestResult (genericTestPosition (f1, 0, new AuMuLawSampleValue (224))) ; - addTestResult (genericTestPosition (f1, 10, new AuMuLawSampleValue (148))) ; - - Globs = gl2 ; - addTestResult (genericTestPosition (f2, 0, new AuPCM8SampleValue (-7))) ; - addTestResult (genericTestPosition (f2, 1, new AuPCM8SampleValue (-8))) ; - addTestResult (genericTestPosition (f2, 17, new AuPCM8SampleValue (4))) ; - addTestResult (genericTestPosition (f2, 81, new AuPCM8SampleValue (-2))) ; - - Globs = gl3 ; - addTestResult (genericTestPosition (f3, 0, new AuPCM16SampleValue (80))) ; - addTestResult (genericTestPosition (f3, 2, new AuPCM16SampleValue (-76))) ; - addTestResult (genericTestPosition (f3, 9, new AuPCM16SampleValue (4403))) ; - addTestResult (genericTestPosition (f3, 15, new AuPCM16SampleValue (4191))) ; +void AuFileTest::testPosition() { + Globs = gl1; + addTestResult(genericTestPosition(f1, 0, new AuMuLawSampleValue(224))); + addTestResult(genericTestPosition(f1, 10, new AuMuLawSampleValue(148))); + + Globs = gl2; + addTestResult(genericTestPosition(f2, 0, new AuPCM8SampleValue(-7))); + addTestResult(genericTestPosition(f2, 1, new AuPCM8SampleValue(-8))); + addTestResult(genericTestPosition(f2, 17, new AuPCM8SampleValue(4))); + addTestResult(genericTestPosition(f2, 81, new AuPCM8SampleValue(-2))); + + Globs = gl3; + addTestResult(genericTestPosition(f3, 0, new AuPCM16SampleValue(80))); + addTestResult(genericTestPosition(f3, 2, new AuPCM16SampleValue(-76))); + addTestResult(genericTestPosition(f3, 9, new AuPCM16SampleValue(4403))); + addTestResult(genericTestPosition(f3, 15, new AuPCM16SampleValue(4191))); } -void AuFileTest::testReadExtractCompare () -{ - { - Globs = gl1 ; - BitString shouldbe ; - shouldbe.append(false).append(true).append(true).append(false).append(false).append(false).append(false).append(true) ; - addTestResult (genericTestReadExtractCompare (std::string(DATADIR) + "mulaw_std.au", shouldbe)) ; - } - - { - Globs = gl2 ; - // TODO - } - - { - Globs = gl3 ; - // TODO - } +void AuFileTest::testReadExtractCompare() { + { + Globs = gl1; + BitString shouldbe; + shouldbe.append(false) + .append(true) + .append(true) + .append(false) + .append(false) + .append(false) + .append(false) + .append(true); + addTestResult( + genericTestReadExtractCompare(std::string(DATADIR) + "mulaw_std.au", shouldbe)); + } + + { + Globs = gl2; + // TODO + } + + { + Globs = gl3; + // TODO + } } -void AuFileTest::testEmbeddedValue () -{ - Globs = gl1 ; addTestResult (genericTestEmbeddedValue (f1)) ; - Globs = gl2 ; addTestResult (genericTestEmbeddedValue (f2)) ; - Globs = gl3 ; addTestResult (genericTestEmbeddedValue (f3)) ; +void AuFileTest::testEmbeddedValue() { + Globs = gl1; + addTestResult(genericTestEmbeddedValue(f1)); + Globs = gl2; + addTestResult(genericTestEmbeddedValue(f2)); + Globs = gl3; + addTestResult(genericTestEmbeddedValue(f3)); } diff --git a/tests/steghide/AuFileTest.h b/tests/steghide/AuFileTest.h index 3e37a70..ef35d22 100644 --- a/tests/steghide/AuFileTest.h +++ b/tests/steghide/AuFileTest.h @@ -26,23 +26,23 @@ #include "CvrStgFileTest.h" class AuFileTest : public CvrStgFileTest { - public: - AuFileTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testReadWrite (void) ; - void testReadEmbedExtract (void) ; - void testReadEmbedWriteReadExtract (void) ; - void testPosition (void) ; - void testReadExtractCompare (void) ; - void testEmbeddedValue (void) ; - - private: - BitString *bs1, *bs2, *bs3 ; - CvrStgFile *f1, *f2, *f3 ; - Globals gl1, gl2, gl3 ; -} ; + public: + AuFileTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testReadWrite(void); + void testReadEmbedExtract(void); + void testReadEmbedWriteReadExtract(void); + void testPosition(void); + void testReadExtractCompare(void); + void testEmbeddedValue(void); + + private: + BitString *bs1, *bs2, *bs3; + CvrStgFile *f1, *f2, *f3; + Globals gl1, gl2, gl3; +}; #endif // ndef SH_AUFILETEST_H diff --git a/tests/steghide/AudioSampleValueTest.cc b/tests/steghide/AudioSampleValueTest.cc index 4a7d803..1f5f867 100644 --- a/tests/steghide/AudioSampleValueTest.cc +++ b/tests/steghide/AudioSampleValueTest.cc @@ -25,62 +25,62 @@ #include "AudioSampleValueTest.h" #include "utcommon.h" -AudioSampleValueTest::AudioSampleValueTest (TestSuite* s) - : SampleValueTest ("AudioSampleValue", s) -{ - ADDTESTCATEGORY (AudioSampleValueTest, testDistance) ; - ADDTESTCATEGORY (AudioSampleValueTest, testIsNeighbour) ; +AudioSampleValueTest::AudioSampleValueTest(TestSuite *s) : SampleValueTest("AudioSampleValue", s) { + ADDTESTCATEGORY(AudioSampleValueTest, testDistance); + ADDTESTCATEGORY(AudioSampleValueTest, testIsNeighbour); } -void AudioSampleValueTest::setup () -{ - UnitTest::setup() ; +void AudioSampleValueTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f_AuMuLaw = CvrStgFile::readFile (std::string(DATADIR) + "mulaw_std.au") ; - sv_AuMuLaw_0 = new AuMuLawSampleValue (0) ; - sv_AuMuLaw_1 = new AuMuLawSampleValue (1) ; - sv_AuMuLaw_45 = new AuMuLawSampleValue (45) ; - gl_AuMuLaw = Globs ; + Globs.reset(); + f_AuMuLaw = CvrStgFile::readFile(std::string(DATADIR) + "mulaw_std.au"); + sv_AuMuLaw_0 = new AuMuLawSampleValue(0); + sv_AuMuLaw_1 = new AuMuLawSampleValue(1); + sv_AuMuLaw_45 = new AuMuLawSampleValue(45); + gl_AuMuLaw = Globs; - Globs.reset() ; - f_AuPCM16 = CvrStgFile::readFile (std::string(DATADIR) + "pcm16_std.au") ; - sv_AuPCM16_m32768 = new AuPCM16SampleValue (-32768) ; - sv_AuPCM16_32767 = new AuPCM16SampleValue (32767) ; - sv_AuPCM16_0 = new AuPCM16SampleValue (0) ; - sv_AuPCM16_15 = new AuPCM16SampleValue (15) ; - gl_AuPCM16 = Globs ; + Globs.reset(); + f_AuPCM16 = CvrStgFile::readFile(std::string(DATADIR) + "pcm16_std.au"); + sv_AuPCM16_m32768 = new AuPCM16SampleValue(-32768); + sv_AuPCM16_32767 = new AuPCM16SampleValue(32767); + sv_AuPCM16_0 = new AuPCM16SampleValue(0); + sv_AuPCM16_15 = new AuPCM16SampleValue(15); + gl_AuPCM16 = Globs; } -void AudioSampleValueTest::cleanup () -{ - UnitTest::cleanup() ; +void AudioSampleValueTest::cleanup() { + UnitTest::cleanup(); - delete f_AuMuLaw ; delete f_AuPCM16 ; - delete sv_AuMuLaw_0 ; delete sv_AuMuLaw_1 ; delete sv_AuMuLaw_45 ; - delete sv_AuPCM16_m32768 ; delete sv_AuPCM16_32767 ; delete sv_AuPCM16_0 ; delete sv_AuPCM16_15 ; + delete f_AuMuLaw; + delete f_AuPCM16; + delete sv_AuMuLaw_0; + delete sv_AuMuLaw_1; + delete sv_AuMuLaw_45; + delete sv_AuPCM16_m32768; + delete sv_AuPCM16_32767; + delete sv_AuPCM16_0; + delete sv_AuPCM16_15; } -void AudioSampleValueTest::testDistance () -{ - Globs = gl_AuMuLaw ; - addTestResult (genericTestDistance (sv_AuMuLaw_0, sv_AuMuLaw_1, 1)) ; - addTestResult (genericTestDistance (sv_AuMuLaw_1, sv_AuMuLaw_45, 44)) ; +void AudioSampleValueTest::testDistance() { + Globs = gl_AuMuLaw; + addTestResult(genericTestDistance(sv_AuMuLaw_0, sv_AuMuLaw_1, 1)); + addTestResult(genericTestDistance(sv_AuMuLaw_1, sv_AuMuLaw_45, 44)); - Globs = gl_AuPCM16 ; - addTestResult (genericTestDistance (sv_AuPCM16_0, sv_AuPCM16_15, 15)) ; - addTestResult (genericTestDistance (sv_AuPCM16_15, sv_AuPCM16_32767, 32752)) ; - addTestResult (genericTestDistance (sv_AuPCM16_m32768, sv_AuPCM16_32767, 65535)) ; + Globs = gl_AuPCM16; + addTestResult(genericTestDistance(sv_AuPCM16_0, sv_AuPCM16_15, 15)); + addTestResult(genericTestDistance(sv_AuPCM16_15, sv_AuPCM16_32767, 32752)); + addTestResult(genericTestDistance(sv_AuPCM16_m32768, sv_AuPCM16_32767, 65535)); } -void AudioSampleValueTest::testIsNeighbour () -{ - Globs = gl_AuMuLaw ; - addTestResult (genericTestIsNeighbour (sv_AuMuLaw_0, sv_AuMuLaw_1, true)) ; - addTestResult (genericTestIsNeighbour (sv_AuMuLaw_0, sv_AuMuLaw_45, false)) ; +void AudioSampleValueTest::testIsNeighbour() { + Globs = gl_AuMuLaw; + addTestResult(genericTestIsNeighbour(sv_AuMuLaw_0, sv_AuMuLaw_1, true)); + addTestResult(genericTestIsNeighbour(sv_AuMuLaw_0, sv_AuMuLaw_45, false)); - Globs = gl_AuPCM16 ; - addTestResult (genericTestIsNeighbour (sv_AuPCM16_0, sv_AuPCM16_15, true)) ; - addTestResult (genericTestIsNeighbour (sv_AuPCM16_m32768, sv_AuPCM16_0, false)) ; - addTestResult (genericTestIsNeighbour (sv_AuPCM16_m32768, sv_AuPCM16_32767, false)) ; + Globs = gl_AuPCM16; + addTestResult(genericTestIsNeighbour(sv_AuPCM16_0, sv_AuPCM16_15, true)); + addTestResult(genericTestIsNeighbour(sv_AuPCM16_m32768, sv_AuPCM16_0, false)); + addTestResult(genericTestIsNeighbour(sv_AuPCM16_m32768, sv_AuPCM16_32767, false)); } diff --git a/tests/steghide/AudioSampleValueTest.h b/tests/steghide/AudioSampleValueTest.h index 32c21f3..67d46fa 100644 --- a/tests/steghide/AudioSampleValueTest.h +++ b/tests/steghide/AudioSampleValueTest.h @@ -23,22 +23,23 @@ #include "SampleValueTest.h" -class CvrStgFile ; +class CvrStgFile; class AudioSampleValueTest : public SampleValueTest { - public: - AudioSampleValueTest (TestSuite* s) ; + public: + AudioSampleValueTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testDistance (void) ; - void testIsNeighbour (void) ; + void testDistance(void); + void testIsNeighbour(void); - private: - CvrStgFile *f_AuMuLaw, *f_AuPCM16 ; - SampleValue *sv_AuMuLaw_0, *sv_AuMuLaw_1, *sv_AuMuLaw_45, *sv_AuPCM16_m32768, *sv_AuPCM16_32767, *sv_AuPCM16_0, *sv_AuPCM16_15 ; - Globals gl_AuMuLaw, gl_AuPCM16 ; -} ; + private: + CvrStgFile *f_AuMuLaw, *f_AuPCM16; + SampleValue *sv_AuMuLaw_0, *sv_AuMuLaw_1, *sv_AuMuLaw_45, *sv_AuPCM16_m32768, *sv_AuPCM16_32767, + *sv_AuPCM16_0, *sv_AuPCM16_15; + Globals gl_AuMuLaw, gl_AuPCM16; +}; #endif // ndef SH_AUDIOSAMPLEVALUETEST_H diff --git a/tests/steghide/BFSAPHeuristicTest.cc b/tests/steghide/BFSAPHeuristicTest.cc index 334c9e1..ad2c4fd 100644 --- a/tests/steghide/BFSAPHeuristicTest.cc +++ b/tests/steghide/BFSAPHeuristicTest.cc @@ -29,121 +29,134 @@ #include "Matching.h" #include "Selector.h" -#include "DummyFile.h" #include "BFSAPHeuristicTest.h" +#include "DummyFile.h" -#define CREATEEDGE(G,V1,V2) (new Edge ((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) +#define CREATEEDGE(G, V1, V2) (new Edge((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) -BFSAPHeuristicTest::BFSAPHeuristicTest (TestSuite* s) - : UnitTest ("BFSAPHeuristic", s) -{ - ADDTESTCATEGORY (BFSAPHeuristicTest, testAlgorithm) ; +BFSAPHeuristicTest::BFSAPHeuristicTest(TestSuite *s) : UnitTest("BFSAPHeuristic", s) { + ADDTESTCATEGORY(BFSAPHeuristicTest, testAlgorithm); } -void BFSAPHeuristicTest::setup () -{ - UnitTest::setup() ; +void BFSAPHeuristicTest::setup() { + UnitTest::setup(); - // a trivial case to start with - { - Globs.reset() ; - std::vector > adjlist (2) ; - adjlist[0].push_back(1) ; - DummyFile::createGraph (adjlist, &bs1, &f1, &s1) ; - g1 = new Graph (f1, *bs1, *s1) ; - m1 = new Matching (g1) ; - aph1 = new BFSAPHeuristic (g1, m1) ; - gl1 = Globs ; - } + // a trivial case to start with + { + Globs.reset(); + std::vector> adjlist(2); + adjlist[0].push_back(1); + DummyFile::createGraph(adjlist, &bs1, &f1, &s1); + g1 = new Graph(f1, *bs1, *s1); + m1 = new Matching(g1); + aph1 = new BFSAPHeuristic(g1, m1); + gl1 = Globs; + } - { - Globs.reset() ; - std::vector > adjlist (4) ; - adjlist[0].push_back(1) ; - adjlist[1].push_back(2) ; - adjlist[2].push_back(3) ; - DummyFile::createGraph (adjlist, &bs2, &f2, &s2) ; - g2 = new Graph (f2, *bs2, *s2) ; - m2 = new Matching (g2) ; - m2->addEdge (CREATEEDGE (g2, 1, 2)) ; - aph2 = new BFSAPHeuristic (g2, m2) ; - gl2 = Globs ; - } + { + Globs.reset(); + std::vector> adjlist(4); + adjlist[0].push_back(1); + adjlist[1].push_back(2); + adjlist[2].push_back(3); + DummyFile::createGraph(adjlist, &bs2, &f2, &s2); + g2 = new Graph(f2, *bs2, *s2); + m2 = new Matching(g2); + m2->addEdge(CREATEEDGE(g2, 1, 2)); + aph2 = new BFSAPHeuristic(g2, m2); + gl2 = Globs; + } - // example: aph should be found in graph with blossom (walk through blossom in good direction) - { - Globs.reset() ; - std::vector > adjlist (4) ; - adjlist[0].push_back(1) ; adjlist[0].push_back(2) ; - adjlist[1].push_back(2) ; - adjlist[2].push_back(3) ; - DummyFile::createGraph (adjlist, &bs3, &f3, &s3) ; - g3 = new Graph (f3, *bs3, *s3) ; - m3 = new Matching (g3) ; - m3->addEdge (CREATEEDGE (g3, 1, 2)) ; - aph3 = new BFSAPHeuristic (g3, m3) ; - gl3 = Globs ; - } + // example: aph should be found in graph with blossom (walk through blossom in + // good direction) + { + Globs.reset(); + std::vector> adjlist(4); + adjlist[0].push_back(1); + adjlist[0].push_back(2); + adjlist[1].push_back(2); + adjlist[2].push_back(3); + DummyFile::createGraph(adjlist, &bs3, &f3, &s3); + g3 = new Graph(f3, *bs3, *s3); + m3 = new Matching(g3); + m3->addEdge(CREATEEDGE(g3, 1, 2)); + aph3 = new BFSAPHeuristic(g3, m3); + gl3 = Globs; + } - // counterexample: walk through blossom in bad direction - { - Globs.reset() ; - std::vector > adjlist (4) ; - adjlist[0].push_back(1) ; adjlist[0].push_back(2) ; - adjlist[1].push_back(2) ; adjlist[1].push_back(3) ; - DummyFile::createGraph (adjlist, &bs4, &f4, &s4) ; - g4 = new Graph (f4, *bs4, *s4) ; - m4 = new Matching (g4) ; - m4->addEdge (CREATEEDGE (g4, 1, 2)) ; - aph4 = new BFSAPHeuristic (g4, m4) ; - gl4 = Globs ; - } + // counterexample: walk through blossom in bad direction + { + Globs.reset(); + std::vector> adjlist(4); + adjlist[0].push_back(1); + adjlist[0].push_back(2); + adjlist[1].push_back(2); + adjlist[1].push_back(3); + DummyFile::createGraph(adjlist, &bs4, &f4, &s4); + g4 = new Graph(f4, *bs4, *s4); + m4 = new Matching(g4); + m4->addEdge(CREATEEDGE(g4, 1, 2)); + aph4 = new BFSAPHeuristic(g4, m4); + gl4 = Globs; + } } -void BFSAPHeuristicTest::cleanup () -{ - UnitTest::cleanup() ; +void BFSAPHeuristicTest::cleanup() { + UnitTest::cleanup(); - delete aph1 ; delete m1 ; delete g1 ; delete s1 ; delete bs1 ; delete f1 ; - delete aph2 ; delete m2 ; delete g2 ; delete s2 ; delete bs2 ; delete f2 ; - delete aph3 ; delete m3 ; delete g3 ; delete s3 ; delete bs3 ; delete f3 ; - delete aph4 ; delete m4 ; delete g4 ; delete s4 ; delete bs4 ; delete f4 ; + delete aph1; + delete m1; + delete g1; + delete s1; + delete bs1; + delete f1; + delete aph2; + delete m2; + delete g2; + delete s2; + delete bs2; + delete f2; + delete aph3; + delete m3; + delete g3; + delete s3; + delete bs3; + delete f3; + delete aph4; + delete m4; + delete g4; + delete s4; + delete bs4; + delete f4; } -void BFSAPHeuristicTest::testAlgorithm () -{ - { - Globs = gl1 ; - aph1->run() ; - addTestResult ( m1->isMatched((VertexLabel) 0) && - m1->isMatched((VertexLabel) 1)) ; - } +void BFSAPHeuristicTest::testAlgorithm() { + { + Globs = gl1; + aph1->run(); + addTestResult(m1->isMatched((VertexLabel)0) && m1->isMatched((VertexLabel)1)); + } - { - Globs = gl2 ; - Edge* e01 = CREATEEDGE (g2, 0, 1) ; - Edge* e23 = CREATEEDGE (g2, 2, 3) ; - aph2->run() ; - addTestResult ( m2->getCardinality() == 2 && - m2->includesEdge(e01) && - m2->includesEdge(e23)) ; - } + { + Globs = gl2; + Edge *e01 = CREATEEDGE(g2, 0, 1); + Edge *e23 = CREATEEDGE(g2, 2, 3); + aph2->run(); + addTestResult(m2->getCardinality() == 2 && m2->includesEdge(e01) && m2->includesEdge(e23)); + } - { - Globs = gl3 ; - Edge* e01 = CREATEEDGE (g3, 0, 1) ; - Edge* e23 = CREATEEDGE (g3, 2, 3) ; - aph3->run() ; - addTestResult ( m3->getCardinality() == 2 && - m3->includesEdge(e01) && - m3->includesEdge(e23)) ; - } + { + Globs = gl3; + Edge *e01 = CREATEEDGE(g3, 0, 1); + Edge *e23 = CREATEEDGE(g3, 2, 3); + aph3->run(); + addTestResult(m3->getCardinality() == 2 && m3->includesEdge(e01) && m3->includesEdge(e23)); + } - { - Globs = gl4 ; - Edge* e12 = CREATEEDGE (g4, 1, 2) ; - aph4->run() ; - addTestResult ( m4->getCardinality() == 1 && - m4->includesEdge(e12)) ; - } + { + Globs = gl4; + Edge *e12 = CREATEEDGE(g4, 1, 2); + aph4->run(); + addTestResult(m4->getCardinality() == 1 && m4->includesEdge(e12)); + } } diff --git a/tests/steghide/BFSAPHeuristicTest.h b/tests/steghide/BFSAPHeuristicTest.h index fd20585..411c6ec 100644 --- a/tests/steghide/BFSAPHeuristicTest.h +++ b/tests/steghide/BFSAPHeuristicTest.h @@ -21,32 +21,32 @@ #ifndef SH_BFSAPHEURISTICTEST_H #define SH_BFSAPHEURISTICTEST_H -class BFSAPHeuristic ; -class BitString ; -class CvrStgFile ; -class Matching ; -class Selector ; +class BFSAPHeuristic; +class BitString; +class CvrStgFile; +class Matching; +class Selector; -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class BFSAPHeuristicTest : public UnitTest { - public: - BFSAPHeuristicTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testAlgorithm (void) ; - - private: - BitString *bs1, *bs2, *bs3, *bs4, *bs5 ; - CvrStgFile *f1, *f2, *f3, *f4, *f5 ; - Selector *s1, *s2, *s3, *s4, *s5 ; - Graph *g1, *g2, *g3, *g4, *g5 ; - Matching *m1, *m2, *m3, *m4, *m5 ; - BFSAPHeuristic *aph1, *aph2, *aph3, *aph4, *aph5 ; - Globals gl1, gl2, gl3, gl4, gl5 ; -} ; + public: + BFSAPHeuristicTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testAlgorithm(void); + + private: + BitString *bs1, *bs2, *bs3, *bs4, *bs5; + CvrStgFile *f1, *f2, *f3, *f4, *f5; + Selector *s1, *s2, *s3, *s4, *s5; + Graph *g1, *g2, *g3, *g4, *g5; + Matching *m1, *m2, *m3, *m4, *m5; + BFSAPHeuristic *aph1, *aph2, *aph3, *aph4, *aph5; + Globals gl1, gl2, gl3, gl4, gl5; +}; #endif // ndef SH_BFSAPHEURISTICTEST_H diff --git a/tests/steghide/BitStringTest.cc b/tests/steghide/BitStringTest.cc index 1769305..abcfe97 100644 --- a/tests/steghide/BitStringTest.cc +++ b/tests/steghide/BitStringTest.cc @@ -23,357 +23,442 @@ #include "BitStringTest.h" #include "TestCategoryCaller.h" -BitStringTest::BitStringTest (TestSuite* s) - : UnitTest ("BitString", s) -{ - ADDTESTCATEGORY (BitStringTest, testBitInputOutput) ; - ADDTESTCATEGORY (BitStringTest, testLength) ; - ADDTESTCATEGORY (BitStringTest, testDatatypeInput) ; - ADDTESTCATEGORY (BitStringTest, testDatatypeOutput) ; - ADDTESTCATEGORY (BitStringTest, testEquality) ; - ADDTESTCATEGORY (BitStringTest, testCutting) ; - ADDTESTCATEGORY (BitStringTest, testCompression) ; - ADDTESTCATEGORY (BitStringTest, testArity) ; +BitStringTest::BitStringTest(TestSuite *s) : UnitTest("BitString", s) { + ADDTESTCATEGORY(BitStringTest, testBitInputOutput); + ADDTESTCATEGORY(BitStringTest, testLength); + ADDTESTCATEGORY(BitStringTest, testDatatypeInput); + ADDTESTCATEGORY(BitStringTest, testDatatypeOutput); + ADDTESTCATEGORY(BitStringTest, testEquality); + ADDTESTCATEGORY(BitStringTest, testCutting); + ADDTESTCATEGORY(BitStringTest, testCompression); + ADDTESTCATEGORY(BitStringTest, testArity); } -void BitStringTest::setup () -{ - bs_0 = new BitString() ; - bs_0->append(false) ; - - bs_1 = new BitString() ; - bs_1->append(true) ; - - bs_10 = new BitString() ; - bs_10->append(true) ; - bs_10->append(false) ; - - bs_001 = new BitString() ; - bs_001->append (false) ; - bs_001->append (false) ; - bs_001->append (true) ; - - bs_100 = new BitString() ; - bs_100->append(true) ; - bs_100->append(false) ; - bs_100->append(false) ; - - bs_1010 = new BitString() ; - bs_1010->append(true) ; - bs_1010->append(false) ; - bs_1010->append(true) ; - bs_1010->append(false) ; - - bs_1110 = new BitString() ; - bs_1110->append(true) ; - bs_1110->append(true) ; - bs_1110->append(true) ; - bs_1110->append(false) ; - - bs_01011 = new BitString() ; - bs_01011->append(false) ; - bs_01011->append(true) ; - bs_01011->append(false) ; - bs_01011->append(true) ; - bs_01011->append(true) ; - - bs_10010 = new BitString() ; - bs_10010->append(true) ; - bs_10010->append(false) ; - bs_10010->append(false) ; - bs_10010->append(true) ; - bs_10010->append(false) ; - - bs_10101110 = new BitString() ; - bs_10101110->append(true) ; - bs_10101110->append(false) ; - bs_10101110->append(true) ; - bs_10101110->append(false) ; - bs_10101110->append(true) ; - bs_10101110->append(true) ; - bs_10101110->append(true) ; - bs_10101110->append(false) ; - - bs_101011101 = new BitString() ; - bs_101011101->append(true) ; - bs_101011101->append(false) ; - bs_101011101->append(true) ; - bs_101011101->append(false) ; - bs_101011101->append(true) ; - bs_101011101->append(true) ; - bs_101011101->append(true) ; - bs_101011101->append(false) ; - bs_101011101->append(true) ; +void BitStringTest::setup() { + bs_0 = new BitString(); + bs_0->append(false); + + bs_1 = new BitString(); + bs_1->append(true); + + bs_10 = new BitString(); + bs_10->append(true); + bs_10->append(false); + + bs_001 = new BitString(); + bs_001->append(false); + bs_001->append(false); + bs_001->append(true); + + bs_100 = new BitString(); + bs_100->append(true); + bs_100->append(false); + bs_100->append(false); + + bs_1010 = new BitString(); + bs_1010->append(true); + bs_1010->append(false); + bs_1010->append(true); + bs_1010->append(false); + + bs_1110 = new BitString(); + bs_1110->append(true); + bs_1110->append(true); + bs_1110->append(true); + bs_1110->append(false); + + bs_01011 = new BitString(); + bs_01011->append(false); + bs_01011->append(true); + bs_01011->append(false); + bs_01011->append(true); + bs_01011->append(true); + + bs_10010 = new BitString(); + bs_10010->append(true); + bs_10010->append(false); + bs_10010->append(false); + bs_10010->append(true); + bs_10010->append(false); + + bs_10101110 = new BitString(); + bs_10101110->append(true); + bs_10101110->append(false); + bs_10101110->append(true); + bs_10101110->append(false); + bs_10101110->append(true); + bs_10101110->append(true); + bs_10101110->append(true); + bs_10101110->append(false); + + bs_101011101 = new BitString(); + bs_101011101->append(true); + bs_101011101->append(false); + bs_101011101->append(true); + bs_101011101->append(false); + bs_101011101->append(true); + bs_101011101->append(true); + bs_101011101->append(true); + bs_101011101->append(false); + bs_101011101->append(true); } -void BitStringTest::cleanup () -{ - delete bs_0 ; - delete bs_1 ; - delete bs_10 ; - delete bs_001 ; - delete bs_100 ; - delete bs_1010 ; - delete bs_1110 ; - delete bs_01011 ; - delete bs_10010 ; - delete bs_10101110 ; - delete bs_101011101 ; +void BitStringTest::cleanup() { + delete bs_0; + delete bs_1; + delete bs_10; + delete bs_001; + delete bs_100; + delete bs_1010; + delete bs_1110; + delete bs_01011; + delete bs_10010; + delete bs_10101110; + delete bs_101011101; } -void BitStringTest::testBitInputOutput() -{ - addTestResult((*bs_0)[0] == false) ; - addTestResult((*bs_1)[0] == true) ; - addTestResult( (*bs_10010)[0] == true && - (*bs_10010)[1] == false && - (*bs_10010)[2] == false && - (*bs_10010)[3] == true && - (*bs_10010)[4] == false) ; - addTestResult( (*bs_10101110)[0] == true && - (*bs_10101110)[1] == false && - (*bs_10101110)[2] == true && - (*bs_10101110)[3] == false && - (*bs_10101110)[4] == true && - (*bs_10101110)[5] == true && - (*bs_10101110)[6] == true && - (*bs_10101110)[7] == false) ; - addTestResult( (*bs_101011101)[0] == true && - (*bs_101011101)[1] == false && - (*bs_101011101)[2] == true && - (*bs_101011101)[3] == false && - (*bs_101011101)[4] == true && - (*bs_101011101)[5] == true && - (*bs_101011101)[6] == true && - (*bs_101011101)[7] == false && - (*bs_101011101)[8] == true) ; - { - BitString bs1 = *bs_10010 ; - BitString bs2 = *bs_01011 ; - bs1.setBit(0, 0) ; - bs1.setBit(1, 1) ; - bs2.setBit(4, 0) ; - addTestResult (bs1 == bs2) ; - } +void BitStringTest::testBitInputOutput() { + addTestResult((*bs_0)[0] == false); + addTestResult((*bs_1)[0] == true); + addTestResult((*bs_10010)[0] == true && (*bs_10010)[1] == false && (*bs_10010)[2] == false && + (*bs_10010)[3] == true && (*bs_10010)[4] == false); + addTestResult((*bs_10101110)[0] == true && (*bs_10101110)[1] == false && + (*bs_10101110)[2] == true && (*bs_10101110)[3] == false && + (*bs_10101110)[4] == true && (*bs_10101110)[5] == true && + (*bs_10101110)[6] == true && (*bs_10101110)[7] == false); + addTestResult( + (*bs_101011101)[0] == true && (*bs_101011101)[1] == false && (*bs_101011101)[2] == true && + (*bs_101011101)[3] == false && (*bs_101011101)[4] == true && (*bs_101011101)[5] == true && + (*bs_101011101)[6] == true && (*bs_101011101)[7] == false && (*bs_101011101)[8] == true); + { + BitString bs1 = *bs_10010; + BitString bs2 = *bs_01011; + bs1.setBit(0, 0); + bs1.setBit(1, 1); + bs2.setBit(4, 0); + addTestResult(bs1 == bs2); + } } -void BitStringTest::testLength() -{ - addTestResult(bs_0->getLength() == 1) ; - addTestResult(bs_1->getLength() == 1) ; - addTestResult(bs_10010->getLength() == 5) ; - addTestResult(bs_10101110->getLength() == 8) ; - addTestResult(bs_101011101->getLength() == 9) ; +void BitStringTest::testLength() { + addTestResult(bs_0->getLength() == 1); + addTestResult(bs_1->getLength() == 1); + addTestResult(bs_10010->getLength() == 5); + addTestResult(bs_10101110->getLength() == 8); + addTestResult(bs_101011101->getLength() == 9); } -void BitStringTest::testDatatypeInput() -{ - { - UWORD16 v = 0xFF81 ; - BitString bs ; - bs.append (v, 10) ; - addTestResult (bs.getLength() == 10 && - bs.Data[0] == 0x81 && - bs.Data[1] == 0x03) ; - } - - { - std::string str ("test") ; - BitString bs (str) ; - addTestResult (bs.getLength() == 32 && - bs.Data[0] == 't' && - bs.Data[1] == 'e' && - bs.Data[2] == 's' && - bs.Data[3] == 't') ; - } - - { - std::vector vec ; - vec.push_back (123) ; - vec.push_back (45) ; - vec.push_back (6) ; - BitString bs (vec) ; - addTestResult (bs.getLength() == 24 && - bs.Data[0] == 123 && - bs.Data[1] == 45 && - bs.Data[2] == 6) ; - } - - { - BitString bs1 ; - bs1.append(true).append(false).append(true).append(false) ; - BitString bs2 ; - bs2.append(false).append(true).append(true).append(false).append(bs1) ; - addTestResult (bs2.getLength() == 8 && bs2.Data[0] == 0x56) ; - } - - { - BitString bs1 ; - bs1.append(false).append(true).append(true).append(true).append(true).append(true) ; - bs1.cutBits (1, 5) ; - BitString bs2 ; - bs2.append(true).append(false).append(true).append(true).append(false).append(true).append(false).append(true) ; - bs2.append(true).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bs2.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bs2.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bs1.append (bs2) ; - - BitString bsref ; - bsref.append(false).append(true).append(false).append(true).append(true).append(false).append(true).append(false) ; - bsref.append(true).append(true).append(false).append(false).append(false).append(false).append(false).append(false) ; - bsref.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bsref.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bsref.append(false) ; - - if (bs1 != bsref) { - std::cerr << "bs1:" << std::endl ; - bs1.print(1) ; - std::cerr << "bsref:" << std::endl ; - bsref.print(1) ; - } - addTestResult (bs1 == bsref) ; - } +void BitStringTest::testDatatypeInput() { + { + UWORD16 v = 0xFF81; + BitString bs; + bs.append(v, 10); + addTestResult(bs.getLength() == 10 && bs.Data[0] == 0x81 && bs.Data[1] == 0x03); + } + + { + std::string str("test"); + BitString bs(str); + addTestResult(bs.getLength() == 32 && bs.Data[0] == 't' && bs.Data[1] == 'e' && + bs.Data[2] == 's' && bs.Data[3] == 't'); + } + + { + std::vector vec; + vec.push_back(123); + vec.push_back(45); + vec.push_back(6); + BitString bs(vec); + addTestResult(bs.getLength() == 24 && bs.Data[0] == 123 && bs.Data[1] == 45 && + bs.Data[2] == 6); + } + + { + BitString bs1; + bs1.append(true).append(false).append(true).append(false); + BitString bs2; + bs2.append(false).append(true).append(true).append(false).append(bs1); + addTestResult(bs2.getLength() == 8 && bs2.Data[0] == 0x56); + } + + { + BitString bs1; + bs1.append(false).append(true).append(true).append(true).append(true).append(true); + bs1.cutBits(1, 5); + BitString bs2; + bs2.append(true) + .append(false) + .append(true) + .append(true) + .append(false) + .append(true) + .append(false) + .append(true); + bs2.append(true) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bs2.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bs2.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bs1.append(bs2); + + BitString bsref; + bsref.append(false) + .append(true) + .append(false) + .append(true) + .append(true) + .append(false) + .append(true) + .append(false); + bsref.append(true) + .append(true) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bsref.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bsref.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bsref.append(false); + + if (bs1 != bsref) { + std::cerr << "bs1:" << std::endl; + bs1.print(1); + std::cerr << "bsref:" << std::endl; + bsref.print(1); + } + addTestResult(bs1 == bsref); + } } -void BitStringTest::testDatatypeOutput() -{ - addTestResult (bs_10010->getValue(1, 2) == 0) ; - - { - std::vector vec ; - vec.push_back(0x88) ; - vec.push_back(0x07) ; - BitString bs (vec) ; - addTestResult (bs.getValue(4, 8) == 0x78) ; - } - - { - BitString bs = bs_10101110->getBits(2, 4) ; - addTestResult (bs.getLength() == 4 && - bs[0] == true && - bs[1] == false && - bs[2] == true && - bs[3] == true) ; - } - - { - std::vector vec = bs_10101110->getBytes() ; - addTestResult (vec.size() == 1 && vec[0] == 0x75) ; - } +void BitStringTest::testDatatypeOutput() { + addTestResult(bs_10010->getValue(1, 2) == 0); + + { + std::vector vec; + vec.push_back(0x88); + vec.push_back(0x07); + BitString bs(vec); + addTestResult(bs.getValue(4, 8) == 0x78); + } + + { + BitString bs = bs_10101110->getBits(2, 4); + addTestResult(bs.getLength() == 4 && bs[0] == true && bs[1] == false && bs[2] == true && + bs[3] == true); + } + + { + std::vector vec = bs_10101110->getBytes(); + addTestResult(vec.size() == 1 && vec[0] == 0x75); + } } -void BitStringTest::testEquality() -{ - addTestResult (*bs_0 == *bs_0) ; - addTestResult (!(*bs_0 == *bs_1)) ; - - { - BitString bs (std::string("a test")) ; - addTestResult (bs == bs) ; - } - - { - BitString bs1 ; - bs1.append ((BYTE) 0xAB) ; - BitString bs2 ; - bs2.append(true).append(true).append(false).append(true) ; - bs2.append(false).append(true).append(false).append(true) ; - addTestResult (bs1 == bs2) ; - } +void BitStringTest::testEquality() { + addTestResult(*bs_0 == *bs_0); + addTestResult(!(*bs_0 == *bs_1)); + + { + BitString bs(std::string("a test")); + addTestResult(bs == bs); + } + + { + BitString bs1; + bs1.append((BYTE)0xAB); + BitString bs2; + bs2.append(true).append(true).append(false).append(true); + bs2.append(false).append(true).append(false).append(true); + addTestResult(bs1 == bs2); + } } -void BitStringTest::testCutting () -{ - { - BitString bs1 = *bs_10010 ; - BitString bs2 = *bs_100 ; - addTestResult (bs1.truncate(0, 3) == bs2) ; - } - - { - BitString bs1 = *bs_10101110 ; - BitString bs2 ; - bs2.append(true).append(false).append(true).append(true) ; - addTestResult (bs1.truncate(2, 6) == bs2) ; - } - - { - BitString bs1 = *bs_10010 ; - BitString bs2 = *bs_001 ; - BitString bs3 = *bs_10 ; - - BitString middle = bs1.cutBits(1, 3) ; - addTestResult (middle == bs2 && bs1 == bs3) ; - } - - { - BitString bs1 = *bs_10101110 ; - BitString bs2 = *bs_1110 ; - BitString bs3 = *bs_1010 ; - - BitString cutted = bs1.cutBits(4, 4) ; - addTestResult (cutted == bs2 && bs1 == bs3) ; - } - - { - BitString bs1 ; - bs1.append(false) ; - BitString bs2 ; - bs2.append(true).append(false).append(true).append(true).append(false).append(true).append(false).append(true) ; - bs2.append(true).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bs2.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bs2.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bs1.append (bs2) ; - BitString bs3 = bs1.cutBits (0, 32) ; - - BitString bsref ; - bsref.append(false).append(true).append(false).append(true).append(true).append(false).append(true).append(false) ; - bsref.append(true).append(true).append(false).append(false).append(false).append(false).append(false).append(false) ; - bsref.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - bsref.append(false).append(false).append(false).append(false).append(false).append(false).append(false).append(false) ; - - addTestResult (bs3 == bsref && bs1 == *bs_0) ; - } +void BitStringTest::testCutting() { + { + BitString bs1 = *bs_10010; + BitString bs2 = *bs_100; + addTestResult(bs1.truncate(0, 3) == bs2); + } + + { + BitString bs1 = *bs_10101110; + BitString bs2; + bs2.append(true).append(false).append(true).append(true); + addTestResult(bs1.truncate(2, 6) == bs2); + } + + { + BitString bs1 = *bs_10010; + BitString bs2 = *bs_001; + BitString bs3 = *bs_10; + + BitString middle = bs1.cutBits(1, 3); + addTestResult(middle == bs2 && bs1 == bs3); + } + + { + BitString bs1 = *bs_10101110; + BitString bs2 = *bs_1110; + BitString bs3 = *bs_1010; + + BitString cutted = bs1.cutBits(4, 4); + addTestResult(cutted == bs2 && bs1 == bs3); + } + + { + BitString bs1; + bs1.append(false); + BitString bs2; + bs2.append(true) + .append(false) + .append(true) + .append(true) + .append(false) + .append(true) + .append(false) + .append(true); + bs2.append(true) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bs2.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bs2.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bs1.append(bs2); + BitString bs3 = bs1.cutBits(0, 32); + + BitString bsref; + bsref.append(false) + .append(true) + .append(false) + .append(true) + .append(true) + .append(false) + .append(true) + .append(false); + bsref.append(true) + .append(true) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bsref.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + bsref.append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false) + .append(false); + + addTestResult(bs3 == bsref && bs1 == *bs_0); + } } -void BitStringTest::testCompression () -{ - { - BitString bs1 (std::string("a test of tests of some recurrence")) ; - BitString bs2 = bs1 ; - bs1.compress (9) ; - bs1.uncompress (bs2.getLength()) ; - addTestResult (bs1 == bs2) ; - } - - { - BitString bs1 (std::string("afafafafafafafaf")) ; - BitString bs2 = bs1 ; - bs1.compress(9) ; - addTestResult (bs1 != bs2) ; - } +void BitStringTest::testCompression() { + { + BitString bs1(std::string("a test of tests of some recurrence")); + BitString bs2 = bs1; + bs1.compress(9); + bs1.uncompress(bs2.getLength()); + addTestResult(bs1 == bs2); + } + + { + BitString bs1(std::string("afafafafafafafaf")); + BitString bs2 = bs1; + bs1.compress(9); + addTestResult(bs1 != bs2); + } } -void BitStringTest::testArity () -{ - bs_0->setArity(2) ; addTestResult (bs_0->getNAry(0) == 0) ; - bs_1->setArity(2) ; addTestResult (bs_1->getNAry(0) == 1) ; - bs_10010->setArity(4) ; addTestResult (bs_10010->getNAry(1) != 3) ; - bs_101011101->setArity(8) ; addTestResult (bs_101011101->getNAry(2) == 5) ; - - { - BitString bs1 ; - bs1.setArity(2) ; bs1.appendNAry (0) ; - bs1.setArity(8) ; bs1.appendNAry (6) ; - bs1.appendNAry (1) ; - bs1.setArity(4) ; bs1.appendNAry (3) ; - - BitString bs2 ; - bs2.append(false) ; - bs2.append(false).append(true).append(true) ; - bs2.append(true).append(false).append(false) ; - bs2.append(true).append(true) ; - - addTestResult (bs1 == bs2) ; - } +void BitStringTest::testArity() { + bs_0->setArity(2); + addTestResult(bs_0->getNAry(0) == 0); + bs_1->setArity(2); + addTestResult(bs_1->getNAry(0) == 1); + bs_10010->setArity(4); + addTestResult(bs_10010->getNAry(1) != 3); + bs_101011101->setArity(8); + addTestResult(bs_101011101->getNAry(2) == 5); + + { + BitString bs1; + bs1.setArity(2); + bs1.appendNAry(0); + bs1.setArity(8); + bs1.appendNAry(6); + bs1.appendNAry(1); + bs1.setArity(4); + bs1.appendNAry(3); + + BitString bs2; + bs2.append(false); + bs2.append(false).append(true).append(true); + bs2.append(true).append(false).append(false); + bs2.append(true).append(true); + + addTestResult(bs1 == bs2); + } } diff --git a/tests/steghide/BitStringTest.h b/tests/steghide/BitStringTest.h index 6e5d034..5809553 100644 --- a/tests/steghide/BitStringTest.h +++ b/tests/steghide/BitStringTest.h @@ -27,27 +27,28 @@ #undef private #undef protected -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class BitStringTest : public UnitTest { - public: - BitStringTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testBitInputOutput (void) ; - void testLength (void) ; - void testDatatypeInput (void) ; - void testDatatypeOutput (void) ; - void testEquality (void) ; - void testCutting (void) ; - void testCompression (void) ; - void testArity (void) ; - - private: - BitString *bs_0, *bs_1, *bs_10, *bs_001, *bs_100, *bs_1010, *bs_1110, *bs_01011, *bs_10010, *bs_10101110, *bs_101011101 ; -} ; + public: + BitStringTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testBitInputOutput(void); + void testLength(void); + void testDatatypeInput(void); + void testDatatypeOutput(void); + void testEquality(void); + void testCutting(void); + void testCompression(void); + void testArity(void); + + private: + BitString *bs_0, *bs_1, *bs_10, *bs_001, *bs_100, *bs_1010, *bs_1110, *bs_01011, *bs_10010, + *bs_10101110, *bs_101011101; +}; #endif // ndef SH_BITSTRINGTEST_H diff --git a/tests/steghide/BmpFileTest.cc b/tests/steghide/BmpFileTest.cc index d3ffaaf..4205455 100644 --- a/tests/steghide/BmpFileTest.cc +++ b/tests/steghide/BmpFileTest.cc @@ -22,46 +22,48 @@ #include "Graph.h" -#include "utcommon.h" #include "BmpFileTest.h" +#include "utcommon.h" -BmpFileTest::BmpFileTest (TestSuite* s) - : CvrStgFileTest("BmpFile", s) -{ - ADDTESTCATEGORY (BmpFileTest, testSVALCalculation) ; +BmpFileTest::BmpFileTest(TestSuite *s) : CvrStgFileTest("BmpFile", s) { + ADDTESTCATEGORY(BmpFileTest, testSVALCalculation); } -void BmpFileTest::setup () -{ - UnitTest::setup() ; +void BmpFileTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "win3x24_std.bmp") ; - bs1 = new BitString (std::string ("this BitString will be embedded")) ; - s1 = new Selector (bs1->getLength() * f1->getSamplesPerVertex(), std::string ("a passphrase")) ; - g1 = new Graph (f1, *bs1, *s1) ; - gl1 = Globs ; + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "win3x24_std.bmp"); + bs1 = new BitString(std::string("this BitString will be embedded")); + s1 = new Selector(bs1->getLength() * f1->getSamplesPerVertex(), std::string("a passphrase")); + g1 = new Graph(f1, *bs1, *s1); + gl1 = Globs; - Globs.reset() ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "os21x24_std.bmp") ; - bs2 = new BitString (std::string ("this BitString will be embedded too")) ; - s2 = new Selector (bs2->getLength() * f2->getSamplesPerVertex(), std::string ("another passphrase")) ; - g2 = new Graph (f2, *bs2, *s2) ; - gl2 = Globs ; + Globs.reset(); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "os21x24_std.bmp"); + bs2 = new BitString(std::string("this BitString will be embedded too")); + s2 = new Selector(bs2->getLength() * f2->getSamplesPerVertex(), + std::string("another passphrase")); + g2 = new Graph(f2, *bs2, *s2); + gl2 = Globs; } -void BmpFileTest::cleanup () -{ - UnitTest::cleanup() ; +void BmpFileTest::cleanup() { + UnitTest::cleanup(); - delete g1 ; delete g2 ; - delete s1 ; delete s2 ; - delete bs1 ; delete bs2 ; - delete f1 ; delete f2 ; + delete g1; + delete g2; + delete s1; + delete s2; + delete bs1; + delete bs2; + delete f1; + delete f2; } -void BmpFileTest::testSVALCalculation () -{ - Globs = gl1 ; addTestResult (genericTestSVALCalculation (f1, g1)) ; - Globs = gl2 ; addTestResult (genericTestSVALCalculation (f2, g2)) ; +void BmpFileTest::testSVALCalculation() { + Globs = gl1; + addTestResult(genericTestSVALCalculation(f1, g1)); + Globs = gl2; + addTestResult(genericTestSVALCalculation(f2, g2)); } diff --git a/tests/steghide/BmpFileTest.h b/tests/steghide/BmpFileTest.h index 6fad2a7..9c51ea0 100644 --- a/tests/steghide/BmpFileTest.h +++ b/tests/steghide/BmpFileTest.h @@ -27,20 +27,20 @@ #include "CvrStgFileTest.h" class BmpFileTest : public CvrStgFileTest { - public: - BmpFileTest (TestSuite* s) ; + public: + BmpFileTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testSVALCalculation (void) ; + void testSVALCalculation(void); - private: - CvrStgFile *f1, *f2 ; - Graph *g1, *g2 ; - Selector *s1, *s2 ; - BitString *bs1, *bs2 ; - Globals gl1, gl2 ; -} ; + private: + CvrStgFile *f1, *f2; + Graph *g1, *g2; + Selector *s1, *s2; + BitString *bs1, *bs2; + Globals gl1, gl2; +}; #endif // ndef SH_BMPFILETEST_H diff --git a/tests/steghide/BmpOS2FileTest.cc b/tests/steghide/BmpOS2FileTest.cc index 7e590eb..d343646 100644 --- a/tests/steghide/BmpOS2FileTest.cc +++ b/tests/steghide/BmpOS2FileTest.cc @@ -23,104 +23,120 @@ #include "BmpPaletteSampleValue.h" #include "BmpRGBSampleValue.h" -#include "utcommon.h" #include "BmpOS2FileTest.h" +#include "utcommon.h" -BmpOS2FileTest::BmpOS2FileTest (TestSuite* s) - : CvrStgFileTest("BmpOS2File", s) -{ - ADDTESTCATEGORY (BmpOS2FileTest, testReadWrite) ; - ADDTESTCATEGORY (BmpOS2FileTest, testReadEmbedExtract) ; - ADDTESTCATEGORY (BmpOS2FileTest, testReadEmbedWriteReadExtract) ; - ADDTESTCATEGORY (BmpOS2FileTest, testPosition) ; - ADDTESTCATEGORY (BmpOS2FileTest, testEmbeddedValue) ; +BmpOS2FileTest::BmpOS2FileTest(TestSuite *s) : CvrStgFileTest("BmpOS2File", s) { + ADDTESTCATEGORY(BmpOS2FileTest, testReadWrite); + ADDTESTCATEGORY(BmpOS2FileTest, testReadEmbedExtract); + ADDTESTCATEGORY(BmpOS2FileTest, testReadEmbedWriteReadExtract); + ADDTESTCATEGORY(BmpOS2FileTest, testPosition); + ADDTESTCATEGORY(BmpOS2FileTest, testEmbeddedValue); } -void BmpOS2FileTest::setup () -{ - UnitTest::setup() ; - - Globs.reset() ; - bs1 = new BitString (std::string ("a test")) ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "os21x1_std.bmp") ; - gl1 = Globs ; - - Globs.reset() ; - bs2 = new BitString (std::string ("another test - this time a little longer")) ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "os21x4_std.bmp") ; - gl2 = Globs ; - - Globs.reset() ; - bs3 = new BitString (std::string ("yet another test")) ; - f3 = CvrStgFile::readFile (std::string(DATADIR) + "os21x8_std.bmp") ; - gl3 = Globs ; - - Globs.reset() ; - bs4 = new BitString (std::string ("last test")) ; - f4 = CvrStgFile::readFile (std::string(DATADIR) + "os21x24_std.bmp") ; - gl4 = Globs ; -} +void BmpOS2FileTest::setup() { + UnitTest::setup(); + + Globs.reset(); + bs1 = new BitString(std::string("a test")); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "os21x1_std.bmp"); + gl1 = Globs; -void BmpOS2FileTest::cleanup () -{ - UnitTest::cleanup() ; + Globs.reset(); + bs2 = new BitString(std::string("another test - this time a little longer")); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "os21x4_std.bmp"); + gl2 = Globs; + + Globs.reset(); + bs3 = new BitString(std::string("yet another test")); + f3 = CvrStgFile::readFile(std::string(DATADIR) + "os21x8_std.bmp"); + gl3 = Globs; + + Globs.reset(); + bs4 = new BitString(std::string("last test")); + f4 = CvrStgFile::readFile(std::string(DATADIR) + "os21x24_std.bmp"); + gl4 = Globs; +} - delete bs1 ; delete bs2 ; delete bs3 ; delete bs4 ; - delete f1 ; delete f2 ; delete f3 ; delete f4 ; +void BmpOS2FileTest::cleanup() { + UnitTest::cleanup(); + + delete bs1; + delete bs2; + delete bs3; + delete bs4; + delete f1; + delete f2; + delete f3; + delete f4; } -void BmpOS2FileTest::testReadWrite (void) -{ - Globs = gl1 ; addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x1_std.bmp")) ; - Globs = gl2 ; addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x4_std.bmp")) ; - Globs = gl3 ; addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x8_std.bmp")) ; - Globs = gl4 ; addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x24_std.bmp")) ; +void BmpOS2FileTest::testReadWrite(void) { + Globs = gl1; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x1_std.bmp")); + Globs = gl2; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x4_std.bmp")); + Globs = gl3; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x8_std.bmp")); + Globs = gl4; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "os21x24_std.bmp")); } -void BmpOS2FileTest::testReadEmbedExtract (void) -{ - Globs = gl1 ; addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x1_std.bmp", *bs1)) ; - Globs = gl2 ; addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x4_std.bmp", *bs2)) ; - Globs = gl3 ; addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x8_std.bmp", *bs3)) ; - Globs = gl4 ; addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x24_std.bmp", *bs4)) ; +void BmpOS2FileTest::testReadEmbedExtract(void) { + Globs = gl1; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x1_std.bmp", *bs1)); + Globs = gl2; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x4_std.bmp", *bs2)); + Globs = gl3; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x8_std.bmp", *bs3)); + Globs = gl4; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "os21x24_std.bmp", *bs4)); } -void BmpOS2FileTest::testReadEmbedWriteReadExtract (void) -{ - Globs = gl1 ; addTestResult(genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x1_std.bmp", *bs2)) ; - Globs = gl2 ; addTestResult(genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x4_std.bmp", *bs3)) ; - Globs = gl3 ; addTestResult(genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x8_std.bmp", *bs4)) ; - Globs = gl4 ; addTestResult(genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x24_std.bmp", *bs1)) ; +void BmpOS2FileTest::testReadEmbedWriteReadExtract(void) { + Globs = gl1; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x1_std.bmp", *bs2)); + Globs = gl2; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x4_std.bmp", *bs3)); + Globs = gl3; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x8_std.bmp", *bs4)); + Globs = gl4; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "os21x24_std.bmp", *bs1)); } -void BmpOS2FileTest::testPosition() -{ - Globs = gl1 ; - addTestResult (genericTestPosition (f1, 0, new BmpPaletteSampleValue (1))) ; - addTestResult (genericTestPosition (f1, 1, new BmpPaletteSampleValue (1))) ; - addTestResult (genericTestPosition (f1, 2, new BmpPaletteSampleValue (1))) ; - addTestResult (genericTestPosition (f1, 50, new BmpPaletteSampleValue (0))) ; - addTestResult (genericTestPosition (f1, 2300, new BmpPaletteSampleValue (0))) ; - addTestResult (genericTestPosition (f1, 2303, new BmpPaletteSampleValue (1))) ; - - Globs = gl2 ; - addTestResult (genericTestPosition (f2, 0, new BmpPaletteSampleValue (7))) ; - addTestResult (genericTestPosition (f2, 10, new BmpPaletteSampleValue (5))) ; - addTestResult (genericTestPosition (f2, 95, new BmpPaletteSampleValue (1))) ; - addTestResult (genericTestPosition (f2, 96, new BmpPaletteSampleValue (8))) ; - - // TODO +void BmpOS2FileTest::testPosition() { + Globs = gl1; + addTestResult(genericTestPosition(f1, 0, new BmpPaletteSampleValue(1))); + addTestResult(genericTestPosition(f1, 1, new BmpPaletteSampleValue(1))); + addTestResult(genericTestPosition(f1, 2, new BmpPaletteSampleValue(1))); + addTestResult(genericTestPosition(f1, 50, new BmpPaletteSampleValue(0))); + addTestResult(genericTestPosition(f1, 2300, new BmpPaletteSampleValue(0))); + addTestResult(genericTestPosition(f1, 2303, new BmpPaletteSampleValue(1))); + + Globs = gl2; + addTestResult(genericTestPosition(f2, 0, new BmpPaletteSampleValue(7))); + addTestResult(genericTestPosition(f2, 10, new BmpPaletteSampleValue(5))); + addTestResult(genericTestPosition(f2, 95, new BmpPaletteSampleValue(1))); + addTestResult(genericTestPosition(f2, 96, new BmpPaletteSampleValue(8))); + + // TODO } -void BmpOS2FileTest::testReadExtractCompare () -{ - // TODO +void BmpOS2FileTest::testReadExtractCompare() { + // TODO } -void BmpOS2FileTest::testEmbeddedValue () -{ - Globs = gl1 ; addTestResult (genericTestEmbeddedValue (f1)) ; - Globs = gl2 ; addTestResult (genericTestEmbeddedValue (f2)) ; - Globs = gl3 ; addTestResult (genericTestEmbeddedValue (f3)) ; - Globs = gl4 ; addTestResult (genericTestEmbeddedValue (f4)) ; +void BmpOS2FileTest::testEmbeddedValue() { + Globs = gl1; + addTestResult(genericTestEmbeddedValue(f1)); + Globs = gl2; + addTestResult(genericTestEmbeddedValue(f2)); + Globs = gl3; + addTestResult(genericTestEmbeddedValue(f3)); + Globs = gl4; + addTestResult(genericTestEmbeddedValue(f4)); } diff --git a/tests/steghide/BmpOS2FileTest.h b/tests/steghide/BmpOS2FileTest.h index fd69fae..bdf11ae 100644 --- a/tests/steghide/BmpOS2FileTest.h +++ b/tests/steghide/BmpOS2FileTest.h @@ -26,23 +26,23 @@ #include "CvrStgFileTest.h" class BmpOS2FileTest : public CvrStgFileTest { - public: - BmpOS2FileTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testReadWrite (void) ; - void testReadEmbedExtract (void) ; - void testReadEmbedWriteReadExtract (void) ; - void testPosition (void) ; - void testReadExtractCompare (void) ; - void testEmbeddedValue (void) ; - - private: - BitString *bs1, *bs2, *bs3, *bs4 ; - CvrStgFile *f1, *f2, *f3, *f4 ; - Globals gl1, gl2, gl3, gl4 ; -} ; + public: + BmpOS2FileTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testReadWrite(void); + void testReadEmbedExtract(void); + void testReadEmbedWriteReadExtract(void); + void testPosition(void); + void testReadExtractCompare(void); + void testEmbeddedValue(void); + + private: + BitString *bs1, *bs2, *bs3, *bs4; + CvrStgFile *f1, *f2, *f3, *f4; + Globals gl1, gl2, gl3, gl4; +}; #endif // ndef SH_BMPOS2FILETEST_H diff --git a/tests/steghide/BmpPaletteSampleValueTest.cc b/tests/steghide/BmpPaletteSampleValueTest.cc index cd60c27..640c0ae 100644 --- a/tests/steghide/BmpPaletteSampleValueTest.cc +++ b/tests/steghide/BmpPaletteSampleValueTest.cc @@ -24,73 +24,75 @@ #include "BmpPaletteSampleValue.h" #include "CvrStgFile.h" -BmpPaletteSampleValueTest::BmpPaletteSampleValueTest (TestSuite* s) - : SampleValueTest ("BmpPaletteSampleValue", s) -{ - ADDTESTCATEGORY (BmpPaletteSampleValueTest, testDistance) ; - ADDTESTCATEGORY (BmpPaletteSampleValueTest, testIsNeighbour) ; +BmpPaletteSampleValueTest::BmpPaletteSampleValueTest(TestSuite *s) + : SampleValueTest("BmpPaletteSampleValue", s) { + ADDTESTCATEGORY(BmpPaletteSampleValueTest, testDistance); + ADDTESTCATEGORY(BmpPaletteSampleValueTest, testIsNeighbour); } -void BmpPaletteSampleValueTest::setup () -{ - UnitTest::setup() ; +void BmpPaletteSampleValueTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "os21x4_std.bmp") ; - sv1_0 = new BmpPaletteSampleValue (0) ; - sv1_3 = new BmpPaletteSampleValue (3) ; - sv1_7 = new BmpPaletteSampleValue (7) ; - sv1_15 = new BmpPaletteSampleValue (15) ; - gl1 = Globs ; + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "os21x4_std.bmp"); + sv1_0 = new BmpPaletteSampleValue(0); + sv1_3 = new BmpPaletteSampleValue(3); + sv1_7 = new BmpPaletteSampleValue(7); + sv1_15 = new BmpPaletteSampleValue(15); + gl1 = Globs; - Globs.reset() ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "win3x8_std.bmp") ; - sv2_3_49_96_5 = new BmpPaletteSampleValue (3) ; - sv2_10_11_99_203 = new BmpPaletteSampleValue (10) ; - sv2_48_18_106_194 = new BmpPaletteSampleValue (48) ; - sv2_68_73_104_15 = new BmpPaletteSampleValue (68) ; - sv2_171_61_97_25 = new BmpPaletteSampleValue (171) ; - gl2 = Globs ; + Globs.reset(); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "win3x8_std.bmp"); + sv2_3_49_96_5 = new BmpPaletteSampleValue(3); + sv2_10_11_99_203 = new BmpPaletteSampleValue(10); + sv2_48_18_106_194 = new BmpPaletteSampleValue(48); + sv2_68_73_104_15 = new BmpPaletteSampleValue(68); + sv2_171_61_97_25 = new BmpPaletteSampleValue(171); + gl2 = Globs; } -void BmpPaletteSampleValueTest::cleanup () -{ - UnitTest::cleanup() ; +void BmpPaletteSampleValueTest::cleanup() { + UnitTest::cleanup(); - delete sv1_0 ; delete sv1_3 ; delete sv1_7 ; delete sv1_15 ; - delete f1 ; + delete sv1_0; + delete sv1_3; + delete sv1_7; + delete sv1_15; + delete f1; - delete sv2_3_49_96_5 ; delete sv2_10_11_99_203 ; delete sv2_48_18_106_194 ; delete sv2_68_73_104_15 ; delete sv2_171_61_97_25 ; - delete f2 ; + delete sv2_3_49_96_5; + delete sv2_10_11_99_203; + delete sv2_48_18_106_194; + delete sv2_68_73_104_15; + delete sv2_171_61_97_25; + delete f2; } -void BmpPaletteSampleValueTest::testDistance () -{ - Globs = gl1 ; - addTestResult (genericTestDistance (sv1_0, sv1_0, 0)) ; - addTestResult (genericTestDistance (sv1_0, sv1_3, 32768)) ; - addTestResult (genericTestDistance (sv1_0, sv1_15, 195075)) ; - addTestResult (genericTestDistance (sv1_3, sv1_7, 16384)) ; +void BmpPaletteSampleValueTest::testDistance() { + Globs = gl1; + addTestResult(genericTestDistance(sv1_0, sv1_0, 0)); + addTestResult(genericTestDistance(sv1_0, sv1_3, 32768)); + addTestResult(genericTestDistance(sv1_0, sv1_15, 195075)); + addTestResult(genericTestDistance(sv1_3, sv1_7, 16384)); - Globs = gl2 ; - addTestResult (genericTestDistance (sv2_3_49_96_5, sv2_10_11_99_203, 40657)) ; - addTestResult (genericTestDistance (sv2_3_49_96_5, sv2_48_18_106_194, 36782)) ; - addTestResult (genericTestDistance (sv2_3_49_96_5, sv2_68_73_104_15, 740)) ; - addTestResult (genericTestDistance (sv2_48_18_106_194, sv2_68_73_104_15, 35070)) ; - addTestResult (genericTestDistance (sv2_171_61_97_25, sv2_10_11_99_203, 34188)) ; + Globs = gl2; + addTestResult(genericTestDistance(sv2_3_49_96_5, sv2_10_11_99_203, 40657)); + addTestResult(genericTestDistance(sv2_3_49_96_5, sv2_48_18_106_194, 36782)); + addTestResult(genericTestDistance(sv2_3_49_96_5, sv2_68_73_104_15, 740)); + addTestResult(genericTestDistance(sv2_48_18_106_194, sv2_68_73_104_15, 35070)); + addTestResult(genericTestDistance(sv2_171_61_97_25, sv2_10_11_99_203, 34188)); } -void BmpPaletteSampleValueTest::testIsNeighbour () -{ - Globs = gl1 ; - addTestResult (genericTestIsNeighbour (sv1_3, sv1_3, true)) ; - addTestResult (genericTestIsNeighbour (sv1_15, sv1_0, false)) ; - addTestResult (genericTestIsNeighbour (sv1_7, sv1_15, false)) ; - addTestResult (genericTestIsNeighbour (sv1_3, sv1_7, false)) ; +void BmpPaletteSampleValueTest::testIsNeighbour() { + Globs = gl1; + addTestResult(genericTestIsNeighbour(sv1_3, sv1_3, true)); + addTestResult(genericTestIsNeighbour(sv1_15, sv1_0, false)); + addTestResult(genericTestIsNeighbour(sv1_7, sv1_15, false)); + addTestResult(genericTestIsNeighbour(sv1_3, sv1_7, false)); - Globs = gl2 ; - addTestResult (genericTestIsNeighbour (sv2_10_11_99_203, sv2_3_49_96_5, false)) ; - addTestResult (genericTestIsNeighbour (sv2_68_73_104_15, sv2_171_61_97_25, true)) ; - addTestResult (genericTestIsNeighbour (sv2_68_73_104_15, sv2_48_18_106_194, false)) ; - addTestResult (genericTestIsNeighbour (sv2_171_61_97_25, sv2_10_11_99_203, false)) ; + Globs = gl2; + addTestResult(genericTestIsNeighbour(sv2_10_11_99_203, sv2_3_49_96_5, false)); + addTestResult(genericTestIsNeighbour(sv2_68_73_104_15, sv2_171_61_97_25, true)); + addTestResult(genericTestIsNeighbour(sv2_68_73_104_15, sv2_48_18_106_194, false)); + addTestResult(genericTestIsNeighbour(sv2_171_61_97_25, sv2_10_11_99_203, false)); } diff --git a/tests/steghide/BmpPaletteSampleValueTest.h b/tests/steghide/BmpPaletteSampleValueTest.h index b1e2c77..e1651fc 100644 --- a/tests/steghide/BmpPaletteSampleValueTest.h +++ b/tests/steghide/BmpPaletteSampleValueTest.h @@ -23,23 +23,24 @@ #include "SampleValueTest.h" -class CvrStgFile ; +class CvrStgFile; class BmpPaletteSampleValueTest : public SampleValueTest { - public: - BmpPaletteSampleValueTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testDistance (void) ; - void testIsNeighbour (void) ; - - private: - CvrStgFile *f1, *f2 ; - Globals gl1, gl2 ; - SampleValue *sv1_0, *sv1_3, *sv1_7, *sv1_15 ; - SampleValue *sv2_3_49_96_5, *sv2_10_11_99_203, *sv2_48_18_106_194, *sv2_68_73_104_15, *sv2_171_61_97_25 ; -} ; + public: + BmpPaletteSampleValueTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testDistance(void); + void testIsNeighbour(void); + + private: + CvrStgFile *f1, *f2; + Globals gl1, gl2; + SampleValue *sv1_0, *sv1_3, *sv1_7, *sv1_15; + SampleValue *sv2_3_49_96_5, *sv2_10_11_99_203, *sv2_48_18_106_194, *sv2_68_73_104_15, + *sv2_171_61_97_25; +}; #endif // ndef SH_BMPPALETTESAMPLEVALUETEST_H diff --git a/tests/steghide/BmpRGBSampleValueTest.cc b/tests/steghide/BmpRGBSampleValueTest.cc index d53f1d9..a22a69c 100644 --- a/tests/steghide/BmpRGBSampleValueTest.cc +++ b/tests/steghide/BmpRGBSampleValueTest.cc @@ -24,66 +24,62 @@ #include "BmpRGBSampleValue.h" #include "CvrStgFile.h" -BmpRGBSampleValueTest::BmpRGBSampleValueTest (TestSuite* s) - : SampleValueTest ("BmpRGBSampleValue", s) -{ - ADDTESTCATEGORY (BmpRGBSampleValueTest, testDistance) ; - ADDTESTCATEGORY (BmpRGBSampleValueTest, testIsNeighbour) ; +BmpRGBSampleValueTest::BmpRGBSampleValueTest(TestSuite *s) + : SampleValueTest("BmpRGBSampleValue", s) { + ADDTESTCATEGORY(BmpRGBSampleValueTest, testDistance); + ADDTESTCATEGORY(BmpRGBSampleValueTest, testIsNeighbour); } -void BmpRGBSampleValueTest::setup () -{ - UnitTest::setup() ; +void BmpRGBSampleValueTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f_win = CvrStgFile::readFile (std::string(DATADIR) + "win3x24_std.bmp") ; - sv_0_0_0 = new BmpRGBSampleValue (0, 0, 0) ; - sv_1_1_1 = new BmpRGBSampleValue (1, 1, 1) ; - sv_0_3_4 = new BmpRGBSampleValue (0, 3, 4) ; - sv_10_10_10 = new BmpRGBSampleValue (10, 10, 10) ; - sv_12_13_14 = new BmpRGBSampleValue (12, 13, 14) ; - sv_128_128_128 = new BmpRGBSampleValue (128, 128, 128) ; - sv_210_0_120 = new BmpRGBSampleValue (210, 0, 120) ; - sv_255_255_255 = new BmpRGBSampleValue (255, 255, 255) ; - gl_win = Globs ; + Globs.reset(); + f_win = CvrStgFile::readFile(std::string(DATADIR) + "win3x24_std.bmp"); + sv_0_0_0 = new BmpRGBSampleValue(0, 0, 0); + sv_1_1_1 = new BmpRGBSampleValue(1, 1, 1); + sv_0_3_4 = new BmpRGBSampleValue(0, 3, 4); + sv_10_10_10 = new BmpRGBSampleValue(10, 10, 10); + sv_12_13_14 = new BmpRGBSampleValue(12, 13, 14); + sv_128_128_128 = new BmpRGBSampleValue(128, 128, 128); + sv_210_0_120 = new BmpRGBSampleValue(210, 0, 120); + sv_255_255_255 = new BmpRGBSampleValue(255, 255, 255); + gl_win = Globs; - Globs.reset() ; - f_os2 = CvrStgFile::readFile (std::string(DATADIR) + "os21x24_std.bmp") ; - gl_os2 = Globs ; + Globs.reset(); + f_os2 = CvrStgFile::readFile(std::string(DATADIR) + "os21x24_std.bmp"); + gl_os2 = Globs; } -void BmpRGBSampleValueTest::cleanup () -{ - UnitTest::cleanup() ; +void BmpRGBSampleValueTest::cleanup() { + UnitTest::cleanup(); - delete f_win ; delete f_os2 ; - delete sv_0_0_0 ; - delete sv_1_1_1 ; - delete sv_0_3_4 ; - delete sv_12_13_14 ; - delete sv_128_128_128 ; - delete sv_210_0_120 ; - delete sv_255_255_255 ; + delete f_win; + delete f_os2; + delete sv_0_0_0; + delete sv_1_1_1; + delete sv_0_3_4; + delete sv_12_13_14; + delete sv_128_128_128; + delete sv_210_0_120; + delete sv_255_255_255; } -void BmpRGBSampleValueTest::testDistance () -{ - Globs = gl_win ; - addTestResult (genericTestDistance (sv_0_0_0, sv_0_0_0, 0)) ; - addTestResult (genericTestDistance (sv_0_0_0, sv_0_3_4, 25)) ; - addTestResult (genericTestDistance (sv_0_3_4, sv_12_13_14, 344)) ; - addTestResult (genericTestDistance (sv_1_1_1, sv_128_128_128, 48387)) ; - addTestResult (genericTestDistance (sv_210_0_120, sv_12_13_14, 50609)) ; - addTestResult (genericTestDistance (sv_0_0_0, sv_255_255_255, 195075)) ; +void BmpRGBSampleValueTest::testDistance() { + Globs = gl_win; + addTestResult(genericTestDistance(sv_0_0_0, sv_0_0_0, 0)); + addTestResult(genericTestDistance(sv_0_0_0, sv_0_3_4, 25)); + addTestResult(genericTestDistance(sv_0_3_4, sv_12_13_14, 344)); + addTestResult(genericTestDistance(sv_1_1_1, sv_128_128_128, 48387)); + addTestResult(genericTestDistance(sv_210_0_120, sv_12_13_14, 50609)); + addTestResult(genericTestDistance(sv_0_0_0, sv_255_255_255, 195075)); } -void BmpRGBSampleValueTest::testIsNeighbour () -{ - Globs = gl_win ; - addTestResult (genericTestIsNeighbour (sv_0_0_0, sv_0_3_4, true)) ; - addTestResult (genericTestIsNeighbour (sv_0_3_4, sv_12_13_14, false)) ; - addTestResult (genericTestIsNeighbour (sv_1_1_1, sv_0_3_4, true)) ; - addTestResult (genericTestIsNeighbour (sv_10_10_10, sv_0_3_4, false)) ; - addTestResult (genericTestIsNeighbour (sv_128_128_128, sv_255_255_255, false)) ; - addTestResult (genericTestIsNeighbour (sv_10_10_10, sv_12_13_14, true)) ; +void BmpRGBSampleValueTest::testIsNeighbour() { + Globs = gl_win; + addTestResult(genericTestIsNeighbour(sv_0_0_0, sv_0_3_4, true)); + addTestResult(genericTestIsNeighbour(sv_0_3_4, sv_12_13_14, false)); + addTestResult(genericTestIsNeighbour(sv_1_1_1, sv_0_3_4, true)); + addTestResult(genericTestIsNeighbour(sv_10_10_10, sv_0_3_4, false)); + addTestResult(genericTestIsNeighbour(sv_128_128_128, sv_255_255_255, false)); + addTestResult(genericTestIsNeighbour(sv_10_10_10, sv_12_13_14, true)); } diff --git a/tests/steghide/BmpRGBSampleValueTest.h b/tests/steghide/BmpRGBSampleValueTest.h index eee4df7..fc9c813 100644 --- a/tests/steghide/BmpRGBSampleValueTest.h +++ b/tests/steghide/BmpRGBSampleValueTest.h @@ -23,22 +23,23 @@ #include "SampleValueTest.h" -class CvrStgFile ; +class CvrStgFile; class BmpRGBSampleValueTest : public SampleValueTest { - public: - BmpRGBSampleValueTest (TestSuite* s) ; + public: + BmpRGBSampleValueTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testDistance (void) ; - void testIsNeighbour (void) ; + void testDistance(void); + void testIsNeighbour(void); - private: - CvrStgFile *f_win, *f_os2 ; - SampleValue *sv_0_0_0, *sv_1_1_1, *sv_0_3_4, *sv_10_10_10, *sv_12_13_14, *sv_128_128_128, *sv_210_0_120, *sv_255_255_255 ; - Globals gl_win, gl_os2 ; -} ; + private: + CvrStgFile *f_win, *f_os2; + SampleValue *sv_0_0_0, *sv_1_1_1, *sv_0_3_4, *sv_10_10_10, *sv_12_13_14, *sv_128_128_128, + *sv_210_0_120, *sv_255_255_255; + Globals gl_win, gl_os2; +}; #endif // ndef SH_BMPRGBSAMPLEVALUETEST_H diff --git a/tests/steghide/BmpWinFileTest.cc b/tests/steghide/BmpWinFileTest.cc index a8eb024..13cbc05 100644 --- a/tests/steghide/BmpWinFileTest.cc +++ b/tests/steghide/BmpWinFileTest.cc @@ -20,119 +20,136 @@ #include -#include "utcommon.h" #include "BmpWinFileTest.h" +#include "utcommon.h" #include "BmpPaletteSampleValue.h" #include "BmpRGBSampleValue.h" -BmpWinFileTest::BmpWinFileTest (TestSuite* s) - : CvrStgFileTest("BmpWinFile", s) -{ - ADDTESTCATEGORY (BmpWinFileTest, testReadWrite) ; - ADDTESTCATEGORY (BmpWinFileTest, testReadEmbedExtract) ; - ADDTESTCATEGORY (BmpWinFileTest, testReadEmbedWriteReadExtract) ; - ADDTESTCATEGORY (BmpWinFileTest, testPosition) ; - ADDTESTCATEGORY (BmpWinFileTest, testEmbeddedValue) ; +BmpWinFileTest::BmpWinFileTest(TestSuite *s) : CvrStgFileTest("BmpWinFile", s) { + ADDTESTCATEGORY(BmpWinFileTest, testReadWrite); + ADDTESTCATEGORY(BmpWinFileTest, testReadEmbedExtract); + ADDTESTCATEGORY(BmpWinFileTest, testReadEmbedWriteReadExtract); + ADDTESTCATEGORY(BmpWinFileTest, testPosition); + ADDTESTCATEGORY(BmpWinFileTest, testEmbeddedValue); } -void BmpWinFileTest::setup () -{ - UnitTest::setup() ; - - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "win3x1_std.bmp") ; - bs1 = new BitString (std::string ("this is a test")) ; - gl1 = Globs ; - - Globs.reset() ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "win3x4_std.bmp") ; - bs2 = new BitString (std::string ("this is another test - this time a little longer")) ; - gl2 = Globs ; - - Globs.reset() ; - f3 = CvrStgFile::readFile (std::string(DATADIR) + "win3x8_std.bmp") ; - bs3 = new BitString (std::string ("yet another test which is even longer than the previous test bitstring")) ; - gl3 = Globs ; - - Globs.reset() ; - f4 = CvrStgFile::readFile (std::string(DATADIR) + "win3x24_std.bmp") ; - bs4 = new BitString (std::string ("the last test")) ; - gl4 = Globs ; +void BmpWinFileTest::setup() { + UnitTest::setup(); + + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "win3x1_std.bmp"); + bs1 = new BitString(std::string("this is a test")); + gl1 = Globs; + + Globs.reset(); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "win3x4_std.bmp"); + bs2 = new BitString(std::string("this is another test - this time a little longer")); + gl2 = Globs; + + Globs.reset(); + f3 = CvrStgFile::readFile(std::string(DATADIR) + "win3x8_std.bmp"); + bs3 = new BitString(std::string("yet another test which is even longer than " + "the previous test bitstring")); + gl3 = Globs; + + Globs.reset(); + f4 = CvrStgFile::readFile(std::string(DATADIR) + "win3x24_std.bmp"); + bs4 = new BitString(std::string("the last test")); + gl4 = Globs; } -void BmpWinFileTest::cleanup () -{ - UnitTest::cleanup() ; - - delete bs1 ; delete bs2 ; delete bs3 ; delete bs4 ; - delete f1 ; delete f2 ; delete f3 ; delete f4 ; +void BmpWinFileTest::cleanup() { + UnitTest::cleanup(); + + delete bs1; + delete bs2; + delete bs3; + delete bs4; + delete f1; + delete f2; + delete f3; + delete f4; } -void BmpWinFileTest::testReadWrite() -{ - Globs = gl1 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "win3x1_std.bmp")) ; - Globs = gl2 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "win3x4_std.bmp")) ; - Globs = gl3 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "win3x8_std.bmp")) ; - Globs = gl4 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "win3x24_std.bmp")) ; +void BmpWinFileTest::testReadWrite() { + Globs = gl1; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "win3x1_std.bmp")); + Globs = gl2; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "win3x4_std.bmp")); + Globs = gl3; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "win3x8_std.bmp")); + Globs = gl4; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "win3x24_std.bmp")); } -void BmpWinFileTest::testReadEmbedExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "win3x1_std.bmp", *bs1)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "win3x4_std.bmp", *bs2)) ; - Globs = gl3 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "win3x8_std.bmp", *bs3)) ; - Globs = gl4 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "win3x24_std.bmp", *bs4)) ; +void BmpWinFileTest::testReadEmbedExtract() { + Globs = gl1; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "win3x1_std.bmp", *bs1)); + Globs = gl2; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "win3x4_std.bmp", *bs2)); + Globs = gl3; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "win3x8_std.bmp", *bs3)); + Globs = gl4; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "win3x24_std.bmp", *bs4)); } -void BmpWinFileTest::testReadEmbedWriteReadExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "win3x1_std.bmp", *bs2)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "win3x4_std.bmp", *bs3)) ; - Globs = gl3 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "win3x8_std.bmp", *bs4)) ; - Globs = gl4 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "win3x24_std.bmp", *bs1)) ; +void BmpWinFileTest::testReadEmbedWriteReadExtract() { + Globs = gl1; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "win3x1_std.bmp", *bs2)); + Globs = gl2; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "win3x4_std.bmp", *bs3)); + Globs = gl3; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "win3x8_std.bmp", *bs4)); + Globs = gl4; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "win3x24_std.bmp", *bs1)); } -void BmpWinFileTest::testPosition() -{ - Globs = gl1 ; - addTestResult (genericTestPosition (f1, 0, new BmpPaletteSampleValue (0))) ; - addTestResult (genericTestPosition (f1, 1, new BmpPaletteSampleValue (1))) ; - addTestResult (genericTestPosition (f1, 143, new BmpPaletteSampleValue (1))) ; - addTestResult (genericTestPosition (f1, 144, new BmpPaletteSampleValue (0))) ; - addTestResult (genericTestPosition (f1, 2303, new BmpPaletteSampleValue (1))) ; - addTestResult (genericTestPosition (f1, 2302, new BmpPaletteSampleValue (0))) ; - - Globs = gl2 ; - addTestResult (genericTestPosition (f2, 0, new BmpPaletteSampleValue (9))) ; - addTestResult (genericTestPosition (f2, 20, new BmpPaletteSampleValue (4))) ; - addTestResult (genericTestPosition (f2, 47, new BmpPaletteSampleValue (13))) ; - addTestResult (genericTestPosition (f2, 48, new BmpPaletteSampleValue (9))) ; - addTestResult (genericTestPosition (f2, 2303, new BmpPaletteSampleValue (3))) ; - - Globs = gl3 ; - addTestResult (genericTestPosition (f3, 0, new BmpPaletteSampleValue (202))) ; - addTestResult (genericTestPosition (f3, 4, new BmpPaletteSampleValue (38))) ; - addTestResult (genericTestPosition (f3, 47, new BmpPaletteSampleValue (81))) ; - addTestResult (genericTestPosition (f3, 48, new BmpPaletteSampleValue (66))) ; - addTestResult (genericTestPosition (f3, 2302, new BmpPaletteSampleValue (105))) ; - - Globs = gl4 ; - addTestResult (genericTestPosition (f4, 0, new BmpRGBSampleValue (121, 110, 119))) ; - addTestResult (genericTestPosition (f4, 1, new BmpRGBSampleValue (113, 109, 130))) ; - addTestResult (genericTestPosition (f4, 12, new BmpRGBSampleValue (92, 113, 115))) ; - addTestResult (genericTestPosition (f4, 2303, new BmpRGBSampleValue (75, 107, 158))) ; +void BmpWinFileTest::testPosition() { + Globs = gl1; + addTestResult(genericTestPosition(f1, 0, new BmpPaletteSampleValue(0))); + addTestResult(genericTestPosition(f1, 1, new BmpPaletteSampleValue(1))); + addTestResult(genericTestPosition(f1, 143, new BmpPaletteSampleValue(1))); + addTestResult(genericTestPosition(f1, 144, new BmpPaletteSampleValue(0))); + addTestResult(genericTestPosition(f1, 2303, new BmpPaletteSampleValue(1))); + addTestResult(genericTestPosition(f1, 2302, new BmpPaletteSampleValue(0))); + + Globs = gl2; + addTestResult(genericTestPosition(f2, 0, new BmpPaletteSampleValue(9))); + addTestResult(genericTestPosition(f2, 20, new BmpPaletteSampleValue(4))); + addTestResult(genericTestPosition(f2, 47, new BmpPaletteSampleValue(13))); + addTestResult(genericTestPosition(f2, 48, new BmpPaletteSampleValue(9))); + addTestResult(genericTestPosition(f2, 2303, new BmpPaletteSampleValue(3))); + + Globs = gl3; + addTestResult(genericTestPosition(f3, 0, new BmpPaletteSampleValue(202))); + addTestResult(genericTestPosition(f3, 4, new BmpPaletteSampleValue(38))); + addTestResult(genericTestPosition(f3, 47, new BmpPaletteSampleValue(81))); + addTestResult(genericTestPosition(f3, 48, new BmpPaletteSampleValue(66))); + addTestResult(genericTestPosition(f3, 2302, new BmpPaletteSampleValue(105))); + + Globs = gl4; + addTestResult(genericTestPosition(f4, 0, new BmpRGBSampleValue(121, 110, 119))); + addTestResult(genericTestPosition(f4, 1, new BmpRGBSampleValue(113, 109, 130))); + addTestResult(genericTestPosition(f4, 12, new BmpRGBSampleValue(92, 113, 115))); + addTestResult(genericTestPosition(f4, 2303, new BmpRGBSampleValue(75, 107, 158))); } -void BmpWinFileTest::testReadExtractCompare() -{ - // TODO +void BmpWinFileTest::testReadExtractCompare() { + // TODO } -void BmpWinFileTest::testEmbeddedValue () -{ - Globs = gl1 ; addTestResult (genericTestEmbeddedValue (f1)) ; - Globs = gl2 ; addTestResult (genericTestEmbeddedValue (f2)) ; - Globs = gl3 ; addTestResult (genericTestEmbeddedValue (f3)) ; - Globs = gl4 ; addTestResult (genericTestEmbeddedValue (f4)) ; +void BmpWinFileTest::testEmbeddedValue() { + Globs = gl1; + addTestResult(genericTestEmbeddedValue(f1)); + Globs = gl2; + addTestResult(genericTestEmbeddedValue(f2)); + Globs = gl3; + addTestResult(genericTestEmbeddedValue(f3)); + Globs = gl4; + addTestResult(genericTestEmbeddedValue(f4)); } diff --git a/tests/steghide/BmpWinFileTest.h b/tests/steghide/BmpWinFileTest.h index ead894a..90fd621 100644 --- a/tests/steghide/BmpWinFileTest.h +++ b/tests/steghide/BmpWinFileTest.h @@ -29,23 +29,23 @@ #include "CvrStgFileTest.h" class BmpWinFileTest : public CvrStgFileTest { - public: - BmpWinFileTest (TestSuite* s) ; + public: + BmpWinFileTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testReadWrite (void) ; - void testReadEmbedExtract (void) ; - void testReadEmbedWriteReadExtract (void) ; - void testPosition (void) ; - void testReadExtractCompare (void) ; - void testEmbeddedValue (void) ; + void testReadWrite(void); + void testReadEmbedExtract(void); + void testReadEmbedWriteReadExtract(void); + void testPosition(void); + void testReadExtractCompare(void); + void testEmbeddedValue(void); - private: - BitString *bs1, *bs2, *bs3, *bs4 ; - CvrStgFile *f1, *f2, *f3, *f4 ; - Globals gl1, gl2, gl3, gl4 ; -} ; + private: + BitString *bs1, *bs2, *bs3, *bs4; + CvrStgFile *f1, *f2, *f3, *f4; + Globals gl1, gl2, gl3, gl4; +}; #endif // ndef SH_BMPWINFILETEST_H diff --git a/tests/steghide/CvrStgFileTest.cc b/tests/steghide/CvrStgFileTest.cc index ac9bb41..3e1fa9f 100644 --- a/tests/steghide/CvrStgFileTest.cc +++ b/tests/steghide/CvrStgFileTest.cc @@ -31,177 +31,169 @@ #include "utcommon.h" // TODO - do tests with new_wfn == false in *FileTests ! -bool CvrStgFileTest::genericTestReadWrite (const std::string& rfn, bool new_wfn) const -{ - bool retval = false ; - if (new_wfn) { - CvrStgFile *file = CvrStgFile::readFile (rfn) ; - std::string wfn ("test_rw.out") ; - file->transform (wfn) ; - file->write() ; - delete file ; - - retval = areEqual (rfn, wfn) ; - removeFile (wfn) ; - } - else { - CvrStgFile *file = CvrStgFile::readFile (rfn) ; - copyFile (rfn, "test_rw.bak") ; // make backup copy - file->write() ; - delete file ; - - retval = areEqual (rfn, "test_rw.bak") ; - - moveFile ("test_rw.bak", rfn) ; // overwrite written file with backup copy - } - - return retval ; +bool CvrStgFileTest::genericTestReadWrite(const std::string &rfn, bool new_wfn) const { + bool retval = false; + if (new_wfn) { + CvrStgFile *file = CvrStgFile::readFile(rfn); + std::string wfn("test_rw.out"); + file->transform(wfn); + file->write(); + delete file; + + retval = areEqual(rfn, wfn); + removeFile(wfn); + } else { + CvrStgFile *file = CvrStgFile::readFile(rfn); + copyFile(rfn, "test_rw.bak"); // make backup copy + file->write(); + delete file; + + retval = areEqual(rfn, "test_rw.bak"); + + moveFile("test_rw.bak", rfn); // overwrite written file with backup copy + } + + return retval; } -bool CvrStgFileTest::genericTestReadExtractCompare (const std::string& fn, BitString& emb) const -{ - CvrStgFile *file = CvrStgFile::readFile (fn) ; - emb.setArity (file->getEmbValueModulus()) ; - bool ok = true ; - for (unsigned long i = 0 ; i < emb.getLength() ; i++) { - ok = (emb.getNAry(i) == file->getEmbeddedValue(i)) && ok ; - } - delete file ; - - return ok ; +bool CvrStgFileTest::genericTestReadExtractCompare(const std::string &fn, BitString &emb) const { + CvrStgFile *file = CvrStgFile::readFile(fn); + emb.setArity(file->getEmbValueModulus()); + bool ok = true; + for (unsigned long i = 0; i < emb.getLength(); i++) { + ok = (emb.getNAry(i) == file->getEmbeddedValue(i)) && ok; + } + delete file; + + return ok; } -bool CvrStgFileTest::genericTestReadEmbedExtract (const std::string& fn, BitString& emb) const -{ - CvrStgFile *file = CvrStgFile::readFile (fn) ; - emb.setArity (file->getEmbValueModulus()) ; - - // embed data (at the beginning of the file) - for (unsigned long i = 0 ; i < emb.getNAryLength() ; i++) { - SampleValue *oldsample = file->getSampleValue (i) ; - EmbValue target = emb.getNAry(i) ; - if (oldsample->getEmbeddedValue() != target) { - SampleValue* newsample = oldsample->getNearestTargetSampleValue (target) ; - file->replaceSample (i, newsample) ; - delete newsample ; - } - delete oldsample ; - } - - // extract and compare - bool retval = true ; - for (unsigned long i = 0 ; i < emb.getNAryLength() ; i++) { - if (file->getEmbeddedValue(i) != emb.getNAry(i)) { - retval = false ; - } - } - - delete file ; - return retval ; +bool CvrStgFileTest::genericTestReadEmbedExtract(const std::string &fn, BitString &emb) const { + CvrStgFile *file = CvrStgFile::readFile(fn); + emb.setArity(file->getEmbValueModulus()); + + // embed data (at the beginning of the file) + for (unsigned long i = 0; i < emb.getNAryLength(); i++) { + SampleValue *oldsample = file->getSampleValue(i); + EmbValue target = emb.getNAry(i); + if (oldsample->getEmbeddedValue() != target) { + SampleValue *newsample = oldsample->getNearestTargetSampleValue(target); + file->replaceSample(i, newsample); + delete newsample; + } + delete oldsample; + } + + // extract and compare + bool retval = true; + for (unsigned long i = 0; i < emb.getNAryLength(); i++) { + if (file->getEmbeddedValue(i) != emb.getNAry(i)) { + retval = false; + } + } + + delete file; + return retval; } -bool CvrStgFileTest::genericTestReadEmbedWriteReadExtract (const std::string& cvrfn, BitString& emb) const -{ - std::string stgfn ("test_rewrx.out") ; - - // read - CvrStgFile *file = CvrStgFile::readFile (cvrfn) ; - emb.setArity (file->getEmbValueModulus()) ; - - // embed - for (unsigned long i = 0 ; i < emb.getLength() ; i++) { - SampleValue *oldsample = file->getSampleValue (i) ; - EmbValue target = emb.getNAry(i) ; - if (oldsample->getEmbeddedValue() != target) { - SampleValue* newsample = oldsample->getNearestTargetSampleValue (target) ; - file->replaceSample (i, newsample) ; - delete newsample ; - } - delete oldsample ; - } - - // write - file->transform (stgfn) ; - file->write() ; - delete file ; - - // read - file = CvrStgFile::readFile (stgfn) ; - - // extract and compare - bool retval = true ; - for (unsigned long i = 0 ; i < emb.getNAryLength() ; i++) { - if (file->getEmbeddedValue(i) != emb.getNAry(i)) { - retval = false ; - } - } - - delete file ; - removeFile (stgfn) ; - return retval ; +bool CvrStgFileTest::genericTestReadEmbedWriteReadExtract(const std::string &cvrfn, + BitString &emb) const { + std::string stgfn("test_rewrx.out"); + + // read + CvrStgFile *file = CvrStgFile::readFile(cvrfn); + emb.setArity(file->getEmbValueModulus()); + + // embed + for (unsigned long i = 0; i < emb.getLength(); i++) { + SampleValue *oldsample = file->getSampleValue(i); + EmbValue target = emb.getNAry(i); + if (oldsample->getEmbeddedValue() != target) { + SampleValue *newsample = oldsample->getNearestTargetSampleValue(target); + file->replaceSample(i, newsample); + delete newsample; + } + delete oldsample; + } + + // write + file->transform(stgfn); + file->write(); + delete file; + + // read + file = CvrStgFile::readFile(stgfn); + + // extract and compare + bool retval = true; + for (unsigned long i = 0; i < emb.getNAryLength(); i++) { + if (file->getEmbeddedValue(i) != emb.getNAry(i)) { + retval = false; + } + } + + delete file; + removeFile(stgfn); + return retval; } -bool CvrStgFileTest::genericTestPosition (const CvrStgFile* f, const SamplePos pos, SampleValue* sv_r) const -{ - SampleValue* sv_o = f->getSampleValue (pos) ; - bool retval = (*sv_o == *sv_r) ; - if (ArgVerbose && !retval) { - std::cerr << std::endl << "---- FAILED: genericTestPosition ----" << std::endl ; - std::cerr << "file->getSampleValue (" << pos << ") has key: " << std::hex << sv_o->getKey() << std::dec << std::endl ; - std::cerr << "should be: " << std::hex << sv_r->getKey() << std::dec << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - delete sv_o ; - delete sv_r ; - return retval ; +bool CvrStgFileTest::genericTestPosition(const CvrStgFile *f, const SamplePos pos, + SampleValue *sv_r) const { + SampleValue *sv_o = f->getSampleValue(pos); + bool retval = (*sv_o == *sv_r); + if (ArgVerbose && !retval) { + std::cerr << std::endl << "---- FAILED: genericTestPosition ----" << std::endl; + std::cerr << "file->getSampleValue (" << pos << ") has key: " << std::hex << sv_o->getKey() + << std::dec << std::endl; + std::cerr << "should be: " << std::hex << sv_r->getKey() << std::dec << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + delete sv_o; + delete sv_r; + return retval; } -bool CvrStgFileTest::genericTestSVALCalculation (const CvrStgFile* f, const Graph* g) const -{ - const std::vector& svs = g->SampleValues ; - std::vector svals_generic = f->CvrStgFile::calcSVAdjacencyLists (svs) ; - std::vector svals_specialized = f->calcSVAdjacencyLists (svs) ; - bool ok = true ; - for (EmbValue i = 0 ; i < f->getEmbValueModulus() ; i++) { - ok = (*(svals_generic[i]) == *(svals_specialized[i])) && ok ; - } - return ok ; +bool CvrStgFileTest::genericTestSVALCalculation(const CvrStgFile *f, const Graph *g) const { + const std::vector &svs = g->SampleValues; + std::vector svals_generic = + f->CvrStgFile::calcSVAdjacencyLists(svs); + std::vector svals_specialized = f->calcSVAdjacencyLists(svs); + bool ok = true; + for (EmbValue i = 0; i < f->getEmbValueModulus(); i++) { + ok = (*(svals_generic[i]) == *(svals_specialized[i])) && ok; + } + return ok; } -bool CvrStgFileTest::genericTestEmbeddedValue (const CvrStgFile* f) const -{ - bool retval = true ; - for (SamplePos pos = 0 ; pos < f->getNumSamples() ; pos++) { - SampleValue* sv = f->getSampleValue(pos) ; - retval = (sv->getEmbeddedValue() == f->getEmbeddedValue(pos)) && retval ; - delete sv ; - } - return retval ; +bool CvrStgFileTest::genericTestEmbeddedValue(const CvrStgFile *f) const { + bool retval = true; + for (SamplePos pos = 0; pos < f->getNumSamples(); pos++) { + SampleValue *sv = f->getSampleValue(pos); + retval = (sv->getEmbeddedValue() == f->getEmbeddedValue(pos)) && retval; + delete sv; + } + return retval; } -bool CvrStgFileTest::areEqual (const std::string& fn1, const std::string& fn2) const -{ - char command[256] ; - sprintf (command, "%s %s %s", COMPARE, fn1.c_str(), fn2.c_str()) ; - return (system(command) ? false : true) ; +bool CvrStgFileTest::areEqual(const std::string &fn1, const std::string &fn2) const { + char command[256]; + sprintf(command, "%s %s %s", COMPARE, fn1.c_str(), fn2.c_str()); + return (system(command) ? false : true); } -void CvrStgFileTest::removeFile (const std::string& fn) const -{ - char command[256] ; - sprintf (command, "%s %s", REMOVE, fn.c_str()) ; - system (command) ; +void CvrStgFileTest::removeFile(const std::string &fn) const { + char command[256]; + sprintf(command, "%s %s", REMOVE, fn.c_str()); + system(command); } -void CvrStgFileTest::copyFile (const std::string& src, const std::string& dest) const -{ - char command[256] ; - sprintf (command, "%s %s %s", COPY, src.c_str(), dest.c_str()) ; - system (command) ; +void CvrStgFileTest::copyFile(const std::string &src, const std::string &dest) const { + char command[256]; + sprintf(command, "%s %s %s", COPY, src.c_str(), dest.c_str()); + system(command); } -void CvrStgFileTest::moveFile (const std::string& src, const std::string& dest) const -{ - copyFile (src, dest) ; - removeFile (src) ; +void CvrStgFileTest::moveFile(const std::string &src, const std::string &dest) const { + copyFile(src, dest); + removeFile(src); } diff --git a/tests/steghide/CvrStgFileTest.h b/tests/steghide/CvrStgFileTest.h index 8ec8291..c8b86cf 100644 --- a/tests/steghide/CvrStgFileTest.h +++ b/tests/steghide/CvrStgFileTest.h @@ -24,40 +24,41 @@ #include "BitString.h" #include "CvrStgFile.h" -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class CvrStgFileTest : public UnitTest { - public: - CvrStgFileTest (std::string n, TestSuite* s) : UnitTest(n,s) {} ; - - protected: - /** - * read the file rfn and write it again, return true iff write op created what was read by read op - * \param rfn the file name of the file to read - * \param new_wfn wether to write the data to another file or to rfn (a backup copy is done) - **/ - bool genericTestReadWrite (const std::string& rfn, bool new_wfn = true) const ; - bool genericTestReadEmbedExtract (const std::string& fn, BitString& emb) const ; - - /** - * read fn and extract the first emb.getLength() bits, return true iff these equal emb - **/ - bool genericTestReadExtractCompare (const std::string& fn, BitString& emb) const ; - bool genericTestReadEmbedWriteReadExtract (const std::string& cvrfn, BitString& emb) const ; - bool genericTestPosition (const CvrStgFile* f, const SamplePos pos, SampleValue* sv_r) const ; - bool genericTestSVALCalculation (const CvrStgFile* f, const Graph* g) const ; - - /** - * for all sample positions, test if f->getEmbeddedValue(p) and f->getSampleValue(p)->getEmbeddedValue() return the same result - **/ - bool genericTestEmbeddedValue (const CvrStgFile* f) const ; - - private: - bool areEqual (const std::string& fn1, const std::string& fn2) const ; - void removeFile (const std::string& fn) const ; - void copyFile (const std::string& src, const std::string& dest) const ; - void moveFile (const std::string& src, const std::string& dest) const ; -} ; + public: + CvrStgFileTest(std::string n, TestSuite *s) : UnitTest(n, s){}; + + protected: + /** + * read the file rfn and write it again, return true iff write op created what was read by read + *op \param rfn the file name of the file to read \param new_wfn wether to write the data to + *another file or to rfn (a backup copy is done) + **/ + bool genericTestReadWrite(const std::string &rfn, bool new_wfn = true) const; + bool genericTestReadEmbedExtract(const std::string &fn, BitString &emb) const; + + /** + * read fn and extract the first emb.getLength() bits, return true iff these equal emb + **/ + bool genericTestReadExtractCompare(const std::string &fn, BitString &emb) const; + bool genericTestReadEmbedWriteReadExtract(const std::string &cvrfn, BitString &emb) const; + bool genericTestPosition(const CvrStgFile *f, const SamplePos pos, SampleValue *sv_r) const; + bool genericTestSVALCalculation(const CvrStgFile *f, const Graph *g) const; + + /** + * for all sample positions, test if f->getEmbeddedValue(p) and + *f->getSampleValue(p)->getEmbeddedValue() return the same result + **/ + bool genericTestEmbeddedValue(const CvrStgFile *f) const; + + private: + bool areEqual(const std::string &fn1, const std::string &fn2) const; + void removeFile(const std::string &fn) const; + void copyFile(const std::string &src, const std::string &dest) const; + void moveFile(const std::string &src, const std::string &dest) const; +}; #endif // ndef SH_CVRSTGFILETEST_H diff --git a/tests/steghide/DFSAPHeuristicTest.cc b/tests/steghide/DFSAPHeuristicTest.cc index 3356193..ffcdb72 100644 --- a/tests/steghide/DFSAPHeuristicTest.cc +++ b/tests/steghide/DFSAPHeuristicTest.cc @@ -29,184 +29,207 @@ #include "Matching.h" #include "Selector.h" -#include "DummyFile.h" #include "DFSAPHeuristicTest.h" +#include "DummyFile.h" -#define CREATEEDGE(G,V1,V2) (new Edge ((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) +#define CREATEEDGE(G, V1, V2) (new Edge((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) -DFSAPHeuristicTest::DFSAPHeuristicTest (TestSuite* s) - : UnitTest ("DFSAPHeuristic", s) -{ - ADDTESTCATEGORY (DFSAPHeuristicTest, testAlgorithm) ; +DFSAPHeuristicTest::DFSAPHeuristicTest(TestSuite *s) : UnitTest("DFSAPHeuristic", s) { + ADDTESTCATEGORY(DFSAPHeuristicTest, testAlgorithm); } -void DFSAPHeuristicTest::setup () -{ - UnitTest::setup() ; - - // a trivial case to start with - { - Globs.reset() ; - std::vector > adjlist (2) ; - adjlist[0].push_back(1) ; - DummyFile::createGraph (adjlist, &bs1, &f1, &s1) ; - g1 = new Graph (f1, *bs1, *s1) ; - m1 = new Matching (g1) ; - aph1 = new DFSAPHeuristic (g1, m1, 100.0) ; - gl1 = Globs ; - } - - { - Globs.reset() ; - std::vector > adjlist (4) ; - adjlist[0].push_back(1) ; - adjlist[1].push_back(2) ; - adjlist[2].push_back(3) ; - DummyFile::createGraph (adjlist, &bs2, &f2, &s2) ; - g2 = new Graph (f2, *bs2, *s2) ; - m2 = new Matching (g2) ; - m2->addEdge (CREATEEDGE (g2, 1, 2)) ; - aph2 = new DFSAPHeuristic (g2, m2, 100.0) ; - gl2 = Globs ; - } - - // this is the example from Moehring's and Mueller-Hannemann's paper (Figure 2) - { - Globs.reset() ; - std::vector > adjlist (8) ; - adjlist[0].push_back(1) ; - adjlist[1].push_back(2) ; - adjlist[2].push_back(3) ; adjlist[2].push_back(6) ; - adjlist[3].push_back(4) ; - adjlist[4].push_back(5) ; - adjlist[5].push_back(6) ; adjlist[5].push_back(7) ; - DummyFile::createGraph (adjlist, &bs3, &f3, &s3) ; - g3 = new Graph (f3, *bs3, *s3) ; - m3 = new Matching (g3) ; - m3->addEdge (CREATEEDGE (g3, 1, 2)) ; - m3->addEdge (CREATEEDGE (g3, 3, 4)) ; - m3->addEdge (CREATEEDGE (g3, 5, 6)) ; - aph3 = new DFSAPHeuristic (g3, m3, 100.0) ; - gl3 = Globs ; - } - - // this is the counterexample from Moehring's and Mueller-Hannemann's paper (Figure 3) - { - Globs.reset() ; - std::vector > adjlist (8) ; - adjlist[0].push_back(1) ; adjlist[0].push_back(6) ; - adjlist[1].push_back(2) ; adjlist[1].push_back(7) ; - adjlist[2].push_back(3) ; adjlist[2].push_back(6) ; - adjlist[3].push_back(4) ; - adjlist[4].push_back(5) ; - adjlist[5].push_back(6) ; - DummyFile::createGraph (adjlist, &bs4, &f4, &s4) ; - g4 = new Graph (f4, *bs4, *s4) ; - m4 = new Matching (g4) ; - m4->addEdge (CREATEEDGE (g4, 1, 2)) ; - m4->addEdge (CREATEEDGE (g4, 3, 4)) ; - m4->addEdge (CREATEEDGE (g4, 5, 6)) ; - aph4 = new DFSAPHeuristic (g4, m4, 100.0) ; - gl4 = Globs ; - } - - // another counterexample where the existing augmenting path will not be found no matter which start vertex is chosen - { - Globs.reset() ; - std::vector > adjlist (14) ; - adjlist[0].push_back(2) ; adjlist[0].push_back(4) ; - adjlist[1].push_back(3) ; adjlist[1].push_back(5) ; - adjlist[2].push_back(3) ; adjlist[2].push_back(12) ; - adjlist[3].push_back(13) ; - adjlist[4].push_back(6) ; adjlist[4].push_back(12) ; - adjlist[5].push_back(7) ; adjlist[5].push_back(13) ; - adjlist[6].push_back(8) ; - adjlist[7].push_back(9) ; - adjlist[8].push_back(10) ; - adjlist[9].push_back(11) ; - adjlist[10].push_back(12) ; - adjlist[11].push_back(13) ; - DummyFile::createGraph (adjlist, &bs5, &f5, &s5) ; - g5 = new Graph (f5, *bs5, *s5) ; - m5 = new Matching (g5) ; - m5->addEdge (CREATEEDGE (g5, 2, 12)) ; - m5->addEdge (CREATEEDGE (g5, 3, 13)) ; - m5->addEdge (CREATEEDGE (g5, 4, 6)) ; - m5->addEdge (CREATEEDGE (g5, 5, 7)) ; - m5->addEdge (CREATEEDGE (g5, 8, 10)) ; - m5->addEdge (CREATEEDGE (g5, 9, 11)) ; - aph5 = new DFSAPHeuristic (g5, m5, 100.0) ; - gl5 = Globs ; - } +void DFSAPHeuristicTest::setup() { + UnitTest::setup(); + + // a trivial case to start with + { + Globs.reset(); + std::vector> adjlist(2); + adjlist[0].push_back(1); + DummyFile::createGraph(adjlist, &bs1, &f1, &s1); + g1 = new Graph(f1, *bs1, *s1); + m1 = new Matching(g1); + aph1 = new DFSAPHeuristic(g1, m1, 100.0); + gl1 = Globs; + } + + { + Globs.reset(); + std::vector> adjlist(4); + adjlist[0].push_back(1); + adjlist[1].push_back(2); + adjlist[2].push_back(3); + DummyFile::createGraph(adjlist, &bs2, &f2, &s2); + g2 = new Graph(f2, *bs2, *s2); + m2 = new Matching(g2); + m2->addEdge(CREATEEDGE(g2, 1, 2)); + aph2 = new DFSAPHeuristic(g2, m2, 100.0); + gl2 = Globs; + } + + // this is the example from Moehring's and Mueller-Hannemann's paper (Figure + // 2) + { + Globs.reset(); + std::vector> adjlist(8); + adjlist[0].push_back(1); + adjlist[1].push_back(2); + adjlist[2].push_back(3); + adjlist[2].push_back(6); + adjlist[3].push_back(4); + adjlist[4].push_back(5); + adjlist[5].push_back(6); + adjlist[5].push_back(7); + DummyFile::createGraph(adjlist, &bs3, &f3, &s3); + g3 = new Graph(f3, *bs3, *s3); + m3 = new Matching(g3); + m3->addEdge(CREATEEDGE(g3, 1, 2)); + m3->addEdge(CREATEEDGE(g3, 3, 4)); + m3->addEdge(CREATEEDGE(g3, 5, 6)); + aph3 = new DFSAPHeuristic(g3, m3, 100.0); + gl3 = Globs; + } + + // this is the counterexample from Moehring's and Mueller-Hannemann's paper + // (Figure 3) + { + Globs.reset(); + std::vector> adjlist(8); + adjlist[0].push_back(1); + adjlist[0].push_back(6); + adjlist[1].push_back(2); + adjlist[1].push_back(7); + adjlist[2].push_back(3); + adjlist[2].push_back(6); + adjlist[3].push_back(4); + adjlist[4].push_back(5); + adjlist[5].push_back(6); + DummyFile::createGraph(adjlist, &bs4, &f4, &s4); + g4 = new Graph(f4, *bs4, *s4); + m4 = new Matching(g4); + m4->addEdge(CREATEEDGE(g4, 1, 2)); + m4->addEdge(CREATEEDGE(g4, 3, 4)); + m4->addEdge(CREATEEDGE(g4, 5, 6)); + aph4 = new DFSAPHeuristic(g4, m4, 100.0); + gl4 = Globs; + } + + // another counterexample where the existing augmenting path will not be found + // no matter which start vertex is chosen + { + Globs.reset(); + std::vector> adjlist(14); + adjlist[0].push_back(2); + adjlist[0].push_back(4); + adjlist[1].push_back(3); + adjlist[1].push_back(5); + adjlist[2].push_back(3); + adjlist[2].push_back(12); + adjlist[3].push_back(13); + adjlist[4].push_back(6); + adjlist[4].push_back(12); + adjlist[5].push_back(7); + adjlist[5].push_back(13); + adjlist[6].push_back(8); + adjlist[7].push_back(9); + adjlist[8].push_back(10); + adjlist[9].push_back(11); + adjlist[10].push_back(12); + adjlist[11].push_back(13); + DummyFile::createGraph(adjlist, &bs5, &f5, &s5); + g5 = new Graph(f5, *bs5, *s5); + m5 = new Matching(g5); + m5->addEdge(CREATEEDGE(g5, 2, 12)); + m5->addEdge(CREATEEDGE(g5, 3, 13)); + m5->addEdge(CREATEEDGE(g5, 4, 6)); + m5->addEdge(CREATEEDGE(g5, 5, 7)); + m5->addEdge(CREATEEDGE(g5, 8, 10)); + m5->addEdge(CREATEEDGE(g5, 9, 11)); + aph5 = new DFSAPHeuristic(g5, m5, 100.0); + gl5 = Globs; + } } -void DFSAPHeuristicTest::cleanup () -{ - UnitTest::cleanup() ; - - delete aph1 ; delete m1 ; delete g1 ; delete s1 ; delete bs1 ; delete f1 ; - delete aph2 ; delete m2 ; delete g2 ; delete s2 ; delete bs2 ; delete f2 ; - delete aph3 ; delete m3 ; delete g3 ; delete s3 ; delete bs3 ; delete f3 ; - delete aph4 ; delete m4 ; delete g4 ; delete s4 ; delete bs4 ; delete f4 ; - delete aph5 ; delete m5 ; delete g5 ; delete s5 ; delete bs5 ; delete f5 ; +void DFSAPHeuristicTest::cleanup() { + UnitTest::cleanup(); + + delete aph1; + delete m1; + delete g1; + delete s1; + delete bs1; + delete f1; + delete aph2; + delete m2; + delete g2; + delete s2; + delete bs2; + delete f2; + delete aph3; + delete m3; + delete g3; + delete s3; + delete bs3; + delete f3; + delete aph4; + delete m4; + delete g4; + delete s4; + delete bs4; + delete f4; + delete aph5; + delete m5; + delete g5; + delete s5; + delete bs5; + delete f5; } -void DFSAPHeuristicTest::testAlgorithm () -{ - { - Globs = gl1 ; - aph1->run() ; - addTestResult ( m1->isMatched((VertexLabel) 0) && - m1->isMatched((VertexLabel) 1)) ; - } - - { - Globs = gl2 ; - Edge* e01 = CREATEEDGE (g2, 0, 1) ; - Edge* e23 = CREATEEDGE (g2, 2, 3) ; - aph2->run() ; - addTestResult ( m2->getCardinality() == 2 && - m2->includesEdge(e01) && - m2->includesEdge(e23)) ; - } - - { - Globs = gl3 ; - Edge* e01 = CREATEEDGE (g3, 0, 1) ; - Edge* e26 = CREATEEDGE (g3, 2, 6) ; - Edge* e34 = CREATEEDGE (g3, 3, 4) ; - Edge* e57 = CREATEEDGE (g3, 5, 7) ; - aph3->run() ; - addTestResult ( m3->getCardinality() == 4 && - m3->includesEdge(e01) && - m3->includesEdge(e26) && - m3->includesEdge(e34) && - m3->includesEdge(e57)) ; - } - - { - Globs = gl4 ; - const Edge** path = new const Edge*[g4->getNumVertices()] ; - unsigned long len = aph4->searchAugmentingPath (g4->getVertex(0), path) ; - addTestResult (len == 0) ; - delete[] path ; - } - - { - Globs = gl5 ; - Edge* e2_12 = CREATEEDGE (g5, 2, 12) ; - Edge* e3_13 = CREATEEDGE (g5, 3, 13) ; - Edge* e4_6 = CREATEEDGE (g5, 4, 6) ; - Edge* e5_7 = CREATEEDGE (g5, 5, 7) ; - Edge* e8_10 = CREATEEDGE (g5, 8, 10) ; - Edge* e9_11 = CREATEEDGE (g5, 9, 11) ; - aph5->run() ; - addTestResult ( m5->getCardinality() == 6 && - m5->includesEdge(e2_12) && - m5->includesEdge(e3_13) && - m5->includesEdge(e4_6) && - m5->includesEdge(e5_7) && - m5->includesEdge(e8_10) && - m5->includesEdge(e9_11)) ; - } +void DFSAPHeuristicTest::testAlgorithm() { + { + Globs = gl1; + aph1->run(); + addTestResult(m1->isMatched((VertexLabel)0) && m1->isMatched((VertexLabel)1)); + } + + { + Globs = gl2; + Edge *e01 = CREATEEDGE(g2, 0, 1); + Edge *e23 = CREATEEDGE(g2, 2, 3); + aph2->run(); + addTestResult(m2->getCardinality() == 2 && m2->includesEdge(e01) && m2->includesEdge(e23)); + } + + { + Globs = gl3; + Edge *e01 = CREATEEDGE(g3, 0, 1); + Edge *e26 = CREATEEDGE(g3, 2, 6); + Edge *e34 = CREATEEDGE(g3, 3, 4); + Edge *e57 = CREATEEDGE(g3, 5, 7); + aph3->run(); + addTestResult(m3->getCardinality() == 4 && m3->includesEdge(e01) && m3->includesEdge(e26) && + m3->includesEdge(e34) && m3->includesEdge(e57)); + } + + { + Globs = gl4; + const Edge **path = new const Edge *[g4->getNumVertices()]; + unsigned long len = aph4->searchAugmentingPath(g4->getVertex(0), path); + addTestResult(len == 0); + delete[] path; + } + + { + Globs = gl5; + Edge *e2_12 = CREATEEDGE(g5, 2, 12); + Edge *e3_13 = CREATEEDGE(g5, 3, 13); + Edge *e4_6 = CREATEEDGE(g5, 4, 6); + Edge *e5_7 = CREATEEDGE(g5, 5, 7); + Edge *e8_10 = CREATEEDGE(g5, 8, 10); + Edge *e9_11 = CREATEEDGE(g5, 9, 11); + aph5->run(); + addTestResult(m5->getCardinality() == 6 && m5->includesEdge(e2_12) && + m5->includesEdge(e3_13) && m5->includesEdge(e4_6) && m5->includesEdge(e5_7) && + m5->includesEdge(e8_10) && m5->includesEdge(e9_11)); + } } diff --git a/tests/steghide/DFSAPHeuristicTest.h b/tests/steghide/DFSAPHeuristicTest.h index 83544f6..8da0481 100644 --- a/tests/steghide/DFSAPHeuristicTest.h +++ b/tests/steghide/DFSAPHeuristicTest.h @@ -21,32 +21,32 @@ #ifndef SH_DFSAPHEURISTICTEST_H #define SH_DFSAPHEURISTICTEST_H -class DFSAPHeuristic ; -class BitString ; -class CvrStgFile ; -class Matching ; -class Selector ; +class DFSAPHeuristic; +class BitString; +class CvrStgFile; +class Matching; +class Selector; -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class DFSAPHeuristicTest : public UnitTest { - public: - DFSAPHeuristicTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testAlgorithm (void) ; - - private: - BitString *bs1, *bs2, *bs3, *bs4, *bs5 ; - CvrStgFile *f1, *f2, *f3, *f4, *f5 ; - Selector *s1, *s2, *s3, *s4, *s5 ; - Graph *g1, *g2, *g3, *g4, *g5 ; - Matching *m1, *m2, *m3, *m4, *m5 ; - DFSAPHeuristic *aph1, *aph2, *aph3, *aph4, *aph5 ; - Globals gl1, gl2, gl3, gl4, gl5 ; -} ; + public: + DFSAPHeuristicTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testAlgorithm(void); + + private: + BitString *bs1, *bs2, *bs3, *bs4, *bs5; + CvrStgFile *f1, *f2, *f3, *f4, *f5; + Selector *s1, *s2, *s3, *s4, *s5; + Graph *g1, *g2, *g3, *g4, *g5; + Matching *m1, *m2, *m3, *m4, *m5; + DFSAPHeuristic *aph1, *aph2, *aph3, *aph4, *aph5; + Globals gl1, gl2, gl3, gl4, gl5; +}; #endif // ndef SH_DFSAPHEURISTICTEST_H diff --git a/tests/steghide/DummyFile.cc b/tests/steghide/DummyFile.cc index 40d6502..97db328 100644 --- a/tests/steghide/DummyFile.cc +++ b/tests/steghide/DummyFile.cc @@ -24,73 +24,69 @@ #include "DummyFile.h" #include "DummySampleValue.h" -DummyFile::DummyFile (UWORD16 s, std::vector >* svam) - : SampleValueAdjacencyMatrix(svam) -{ - Samples.resize (s) ; - for (UWORD16 i = 0 ; i < s ; i++) { - Samples[i] = i ; - } - setSamplesPerVertex (SamplesPerVertex) ; - setEmbValueModulus (EmbValueModulus) ; - setRadius (0) ; // undefined, neighbourhood relatin decided by svam +DummyFile::DummyFile(UWORD16 s, std::vector> *svam) + : SampleValueAdjacencyMatrix(svam) { + Samples.resize(s); + for (UWORD16 i = 0; i < s; i++) { + Samples[i] = i; + } + setSamplesPerVertex(SamplesPerVertex); + setEmbValueModulus(EmbValueModulus); + setRadius(0); // undefined, neighbourhood relatin decided by svam } -std::list DummyFile::getProperties () const -{ - std::list retval ; - retval.push_back (CvrStgFile::Property (_("format"), "dummy")) ; - return retval ; +std::list DummyFile::getProperties() const { + std::list retval; + retval.push_back(CvrStgFile::Property(_("format"), "dummy")); + return retval; } -unsigned long DummyFile::getNumSamples () const -{ - return Samples.size() ; -} +unsigned long DummyFile::getNumSamples() const { return Samples.size(); } -SampleValue* DummyFile::getSampleValue (const SamplePos pos) const -{ - return (SampleValue*) (new DummySampleValue (Samples[pos])) ; +SampleValue *DummyFile::getSampleValue(const SamplePos pos) const { + return (SampleValue *)(new DummySampleValue(Samples[pos])); } -void DummyFile::replaceSample (const SamplePos pos, const SampleValue* s) -{ - myassert (pos < Samples.size()) ; - DummySampleValue *sample = (DummySampleValue*) s ; - Samples[pos] = sample->getValue() ; +void DummyFile::replaceSample(const SamplePos pos, const SampleValue *s) { + myassert(pos < Samples.size()); + DummySampleValue *sample = (DummySampleValue *)s; + Samples[pos] = sample->getValue(); } -void DummyFile::createGraph (std::vector >& adjlist, BitString** bs, CvrStgFile** f, Selector** s) -{ - unsigned int numvertices = adjlist.size() ; +void DummyFile::createGraph(std::vector> &adjlist, BitString **bs, + CvrStgFile **f, Selector **s) { + unsigned int numvertices = adjlist.size(); - // eliminate duplicated edges from adjlist (only allow v_i -> ...,v_j,... with j > i) - for (UWORD16 srcv = 0 ; srcv < numvertices ; srcv++) { - for (std::list::iterator destv = adjlist[srcv].begin() ; destv != adjlist[srcv].end() ; destv++) { - if (srcv > (*destv)) { - adjlist[srcv].erase (destv) ; - } - } - } + // eliminate duplicated edges from adjlist (only allow v_i -> ...,v_j,... with + // j > i) + for (UWORD16 srcv = 0; srcv < numvertices; srcv++) { + for (std::list::iterator destv = adjlist[srcv].begin(); + destv != adjlist[srcv].end(); destv++) { + if (srcv > (*destv)) { + adjlist[srcv].erase(destv); + } + } + } - // allocate memory for SampleValue Adjacency-Matrix - std::vector >* svam = new std::vector > (2 * numvertices) ; - for (UWORD16 srcv = 0 ; srcv < numvertices ; srcv++) { - (*svam)[2*srcv] = std::vector (2 * numvertices) ; - (*svam)[2*srcv + 1] = std::vector (2 * numvertices) ; - } + // allocate memory for SampleValue Adjacency-Matrix + std::vector> *svam = new std::vector>(2 * numvertices); + for (UWORD16 srcv = 0; srcv < numvertices; srcv++) { + (*svam)[2 * srcv] = std::vector(2 * numvertices); + (*svam)[2 * srcv + 1] = std::vector(2 * numvertices); + } - // fill SampleValue Adjacency-Matrix - for (UWORD16 srcv = 0 ; srcv < numvertices ; srcv++) { - UWORD16 srcsv = 2 * srcv ; - for (std::list::const_iterator destv = adjlist[srcv].begin() ; destv != adjlist[srcv].end() ; destv++) { - UWORD16 destsv = 2 * (*destv) + 1 ; - (*svam)[srcsv][destsv] = true ; - (*svam)[destsv][srcsv] = true ; - } - } + // fill SampleValue Adjacency-Matrix + for (UWORD16 srcv = 0; srcv < numvertices; srcv++) { + UWORD16 srcsv = 2 * srcv; + for (std::list::const_iterator destv = adjlist[srcv].begin(); + destv != adjlist[srcv].end(); destv++) { + UWORD16 destsv = 2 * (*destv) + 1; + (*svam)[srcsv][destsv] = true; + (*svam)[destsv][srcsv] = true; + } + } - (*f) = (CvrStgFile*) new DummyFile (2 * numvertices, svam) ; - (*bs) = new BitString ((unsigned long) numvertices) ; // zeros only - (*s) = new Selector (2 * numvertices) ; // identity permutation + (*f) = (CvrStgFile *)new DummyFile(2 * numvertices, svam); + (*bs) = new BitString((unsigned long)numvertices); // zeros only + (*s) = new Selector(2 * numvertices); // identity permutation } diff --git a/tests/steghide/DummyFile.h b/tests/steghide/DummyFile.h index 1765eda..f1560ea 100644 --- a/tests/steghide/DummyFile.h +++ b/tests/steghide/DummyFile.h @@ -21,12 +21,12 @@ #ifndef SH_DUMMYFILE_H #define SH_DUMMYFILE_H -#include #include +#include -class BitString ; +class BitString; #include "CvrStgFile.h" -class Selector ; +class Selector; #include "common.h" /** @@ -34,50 +34,53 @@ class Selector ; * \brief a dummy CvrStgFile implementation to facilitate testing and debugging **/ class DummyFile : public CvrStgFile { - public: - /** - * construct a DummyFile object containing the sample values 0,1,...,s-1 - * \param s the size of the DummyFile (i.e. the number of samples it should contain) - * \param svam the SampleValueAdjacencyMatrix for the Samples in this file - **/ - DummyFile (UWORD16 s, std::vector >* svam) ; + public: + /** + * construct a DummyFile object containing the sample values 0,1,...,s-1 + * \param s the size of the DummyFile (i.e. the number of samples it should contain) + * \param svam the SampleValueAdjacencyMatrix for the Samples in this file + **/ + DummyFile(UWORD16 s, std::vector> *svam); - std::list getProperties (void) const ; + std::list getProperties(void) const; - unsigned long getNumSamples (void) const ; + unsigned long getNumSamples(void) const; - void replaceSample (const SamplePos pos, const SampleValue* s) ; + void replaceSample(const SamplePos pos, const SampleValue *s); - SampleValue* getSampleValue (const SamplePos pos) const ; + SampleValue *getSampleValue(const SamplePos pos) const; - std::vector >* getSampleValueAdjacencyMatrix() const - { return SampleValueAdjacencyMatrix ; } ; + std::vector> *getSampleValueAdjacencyMatrix() const { + return SampleValueAdjacencyMatrix; + }; - /** - * create a BitString, a DummyFile and a Selector that together will produce a graph like described by the adjacency list - * \param adjlist an adjacency list describing the "target graph" - * \param bs will be filled with the BitString - * \param f will be filled with the DummyFile - * \param s will be filled with the Selector - * - * Constructing a Graph object with "Graph (*f, **bs, **s)" will result in a graph of the form of adjlist. - * - * The constructed graph has the following form: - * SamplesPerVertex == 2, EmbValueModulus = 2 - * every vertex has a sample value with bit == 0 at index 0 and one with bit == 1 at index 1, - * if two vertices are adjacent, one end of the edge is at index 0 of the vertex with - * the lower vertex label and the other end of the edge is at index 1 of the vertex with - * the higher vertex label. - * The distance between vertex with label i and vertex with label j is : 2*|j - i| + 1 - **/ - static void createGraph (std::vector >& adjlist, BitString** bs, CvrStgFile** f, Selector** s) ; + /** + * create a BitString, a DummyFile and a Selector that together will produce a graph like + *described by the adjacency list \param adjlist an adjacency list describing the "target graph" + * \param bs will be filled with the BitString + * \param f will be filled with the DummyFile + * \param s will be filled with the Selector + * + * Constructing a Graph object with "Graph (*f, **bs, **s)" will result in a graph of the form + *of adjlist. + * + * The constructed graph has the following form: + * SamplesPerVertex == 2, EmbValueModulus = 2 + * every vertex has a sample value with bit == 0 at index 0 and one with bit == 1 at index 1, + * if two vertices are adjacent, one end of the edge is at index 0 of the vertex with + * the lower vertex label and the other end of the edge is at index 1 of the vertex with + * the higher vertex label. + * The distance between vertex with label i and vertex with label j is : 2*|j - i| + 1 + **/ + static void createGraph(std::vector> &adjlist, BitString **bs, + CvrStgFile **f, Selector **s); - private: - static const unsigned short SamplesPerVertex = 2 ; - static const EmbValue EmbValueModulus = 2 ; + private: + static const unsigned short SamplesPerVertex = 2; + static const EmbValue EmbValueModulus = 2; - std::vector Samples ; - std::vector >* SampleValueAdjacencyMatrix ; -} ; + std::vector Samples; + std::vector> *SampleValueAdjacencyMatrix; +}; #endif // ndef SH_DUMMYFILE_H diff --git a/tests/steghide/DummySampleValue.cc b/tests/steghide/DummySampleValue.cc index 7ec9c04..6785b26 100644 --- a/tests/steghide/DummySampleValue.cc +++ b/tests/steghide/DummySampleValue.cc @@ -23,44 +23,37 @@ #include "DummyFile.h" #include "DummySampleValue.h" -UWORD32 DummySampleValue::calcDistance (const SampleValue* s) const -{ - DummySampleValue *sample = (DummySampleValue*) s ; - return ((sample->Value > Value) ? (sample->Value - Value) : (Value - sample->Value)) ; +UWORD32 DummySampleValue::calcDistance(const SampleValue *s) const { + DummySampleValue *sample = (DummySampleValue *)s; + return ((sample->Value > Value) ? (sample->Value - Value) : (Value - sample->Value)); } -bool DummySampleValue::isNeighbour (const SampleValue* s) const -{ - DummyFile *f = (DummyFile*) Globs.TheCvrStgFile ; - DummySampleValue *sample = (DummySampleValue*) s ; - std::vector >* svam = f->getSampleValueAdjacencyMatrix() ; - return (*svam)[Value][sample->getValue()] ; +bool DummySampleValue::isNeighbour(const SampleValue *s) const { + DummyFile *f = (DummyFile *)Globs.TheCvrStgFile; + DummySampleValue *sample = (DummySampleValue *)s; + std::vector> *svam = f->getSampleValueAdjacencyMatrix(); + return (*svam)[Value][sample->getValue()]; } -SampleValue* DummySampleValue::getNearestTargetSampleValue (EmbValue t) const -{ - UWORD16 n_value = 0 ; - if (Value == 0) { - n_value = 1 ; - } - else if (Value == UWORD16_MAX) { - n_value = UWORD16_MAX - 1 ; - } - else { - if (RndSrc.getBool()) { - n_value = Value - 1 ; - } - else { - n_value = Value + 1 ; - } - } - myassert (n_value % 2 == t) ; - return ((SampleValue *) new DummySampleValue (n_value)) ; +SampleValue *DummySampleValue::getNearestTargetSampleValue(EmbValue t) const { + UWORD16 n_value = 0; + if (Value == 0) { + n_value = 1; + } else if (Value == UWORD16_MAX) { + n_value = UWORD16_MAX - 1; + } else { + if (RndSrc.getBool()) { + n_value = Value - 1; + } else { + n_value = Value + 1; + } + } + myassert(n_value % 2 == t); + return ((SampleValue *)new DummySampleValue(n_value)); } -std::string DummySampleValue::getName (void) const -{ - char buf[128] ; - sprintf (buf, "%d", Value) ; - return std::string (buf) ; +std::string DummySampleValue::getName(void) const { + char buf[128]; + sprintf(buf, "%d", Value); + return std::string(buf); } diff --git a/tests/steghide/DummySampleValue.h b/tests/steghide/DummySampleValue.h index e503f6c..eadcfc3 100644 --- a/tests/steghide/DummySampleValue.h +++ b/tests/steghide/DummySampleValue.h @@ -25,30 +25,30 @@ #include "common.h" class DummySampleValue : public SampleValue { - public: - DummySampleValue (UWORD16 v) - : SampleValue(), Value(v) - { EValue = (v % 2) ; Key = v ; } ; + public: + DummySampleValue(UWORD16 v) : SampleValue(), Value(v) { + EValue = (v % 2); + Key = v; + }; - UWORD16 getValue (void) const - { return Value ; } ; + UWORD16 getValue(void) const { return Value; }; - /** - * calculate the distance as | Value - s->Value | - **/ - UWORD32 calcDistance (const SampleValue* s) const ; + /** + * calculate the distance as | Value - s->Value | + **/ + UWORD32 calcDistance(const SampleValue *s) const; - /** - * return from the contents of the SampleValueAdjacencyMatrix in the DummyFile - **/ - bool isNeighbour (const SampleValue* s) const ; + /** + * return from the contents of the SampleValueAdjacencyMatrix in the DummyFile + **/ + bool isNeighbour(const SampleValue *s) const; - SampleValue* getNearestTargetSampleValue (EmbValue t) const ; + SampleValue *getNearestTargetSampleValue(EmbValue t) const; - std::string getName (void) const ; + std::string getName(void) const; - private: - UWORD16 Value ; -} ; + private: + UWORD16 Value; +}; #endif // ndef SH_DUMMYSAMPLEVALUE_H diff --git a/tests/steghide/EdgeIteratorTest.cc b/tests/steghide/EdgeIteratorTest.cc index 723de3d..d4b8595 100644 --- a/tests/steghide/EdgeIteratorTest.cc +++ b/tests/steghide/EdgeIteratorTest.cc @@ -26,131 +26,145 @@ #include "TestCategoryCaller.h" #include "utcommon.h" -#define CREATEEDGE(G,V1,V2) ((V1 < V2) ? \ - (new Edge ((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) : \ - (new Edge ((G)->getVertex(V2), 0, (G)->getVertex(V1), 1))) +#define CREATEEDGE(G, V1, V2) \ + ((V1 < V2) ? (new Edge((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) \ + : (new Edge((G)->getVertex(V2), 0, (G)->getVertex(V1), 1))) -EdgeIteratorTest::EdgeIteratorTest (TestSuite* s) - : UnitTest ("EdgeIterator", s) -{ - ADDTESTCATEGORY (EdgeIteratorTest, testReferenceIteration) ; - ADDTESTCATEGORY (EdgeIteratorTest, testIterationLength) ; -} - -void EdgeIteratorTest::setup () -{ - // reference tests - { - Globs.reset() ; - std::vector > adjlist1 (10) ; - adjlist1[0].push_back(1) ; adjlist1[0].push_back(4) ; - adjlist1[1].push_back(3) ; adjlist1[1].push_back(7) ; - adjlist1[2].push_back(3) ; adjlist1[2].push_back(5) ; adjlist1[2].push_back(6) ; - adjlist1[3].push_back(6) ; - adjlist1[4].push_back(6) ; adjlist1[4].push_back(7) ; adjlist1[4].push_back(9) ; - adjlist1[5].push_back(6) ; - adjlist1[7].push_back(8) ; - DummyFile::createGraph (adjlist1, &bs1, &f1, &s1) ; - g1 = new Graph (f1, *bs1, *s1) ; - gl1 = Globs ; - } - - // real files - { - Globs.reset() ; - f10 = CvrStgFile::readFile (std::string(DATADIR) + "win3x8_std.bmp") ; - bs10 = new BitString (std::string ("secret message")) ; - s10 = new Selector (bs10->getLength() * f10->getSamplesPerVertex(), std::string ("secret passphrase")) ; - g10 = new Graph (f10, *bs10, *s10) ; - gl10 = Globs ; - - Globs.reset() ; - f11 = CvrStgFile::readFile (std::string(DATADIR) + "pcm16_std.wav") ; - bs11 = new BitString (std::string ("16 bits per sample")) ; - s11 = new Selector (bs11->getLength() * f11->getSamplesPerVertex(), std::string ("a passphrase")) ; - g11 = new Graph (f11, *bs11, *s11) ; - gl11 = Globs ; - - Globs.reset() ; - f12 = CvrStgFile::readFile (std::string(DATADIR) + "mulaw_std.au") ; - bs12 = new BitString (std::string ("mu law sample data in an au file")) ; - s12 = new Selector (bs12->getLength() * f12->getSamplesPerVertex(), std::string ("another passphrase")) ; - g12 = new Graph (f12, *bs12, *s12) ; - gl12 = Globs ; - } +EdgeIteratorTest::EdgeIteratorTest(TestSuite *s) : UnitTest("EdgeIterator", s) { + ADDTESTCATEGORY(EdgeIteratorTest, testReferenceIteration); + ADDTESTCATEGORY(EdgeIteratorTest, testIterationLength); } -void EdgeIteratorTest::cleanup () -{ +void EdgeIteratorTest::setup() { + // reference tests + { + Globs.reset(); + std::vector> adjlist1(10); + adjlist1[0].push_back(1); + adjlist1[0].push_back(4); + adjlist1[1].push_back(3); + adjlist1[1].push_back(7); + adjlist1[2].push_back(3); + adjlist1[2].push_back(5); + adjlist1[2].push_back(6); + adjlist1[3].push_back(6); + adjlist1[4].push_back(6); + adjlist1[4].push_back(7); + adjlist1[4].push_back(9); + adjlist1[5].push_back(6); + adjlist1[7].push_back(8); + DummyFile::createGraph(adjlist1, &bs1, &f1, &s1); + g1 = new Graph(f1, *bs1, *s1); + gl1 = Globs; + } + + // real files + { + Globs.reset(); + f10 = CvrStgFile::readFile(std::string(DATADIR) + "win3x8_std.bmp"); + bs10 = new BitString(std::string("secret message")); + s10 = new Selector(bs10->getLength() * f10->getSamplesPerVertex(), + std::string("secret passphrase")); + g10 = new Graph(f10, *bs10, *s10); + gl10 = Globs; + + Globs.reset(); + f11 = CvrStgFile::readFile(std::string(DATADIR) + "pcm16_std.wav"); + bs11 = new BitString(std::string("16 bits per sample")); + s11 = new Selector(bs11->getLength() * f11->getSamplesPerVertex(), + std::string("a passphrase")); + g11 = new Graph(f11, *bs11, *s11); + gl11 = Globs; + + Globs.reset(); + f12 = CvrStgFile::readFile(std::string(DATADIR) + "mulaw_std.au"); + bs12 = new BitString(std::string("mu law sample data in an au file")); + s12 = new Selector(bs12->getLength() * f12->getSamplesPerVertex(), + std::string("another passphrase")); + g12 = new Graph(f12, *bs12, *s12); + gl12 = Globs; + } } -void EdgeIteratorTest::testReferenceIteration () -{ - { - Globs = gl1 ; - - std::vector edges ; - edges.push_back (CREATEEDGE (g1, 0, 1)) ; - edges.push_back (CREATEEDGE (g1, 0, 4)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(0), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 1, 0)) ; - edges.push_back (CREATEEDGE (g1, 1, 3)) ; - edges.push_back (CREATEEDGE (g1, 1, 7)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(1), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 2, 3)) ; - edges.push_back (CREATEEDGE (g1, 2, 5)) ; - edges.push_back (CREATEEDGE (g1, 2, 6)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(2), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 3, 2)) ; - edges.push_back (CREATEEDGE (g1, 3, 1)) ; - edges.push_back (CREATEEDGE (g1, 3, 6)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(3), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 4, 6)) ; - edges.push_back (CREATEEDGE (g1, 4, 7)) ; - edges.push_back (CREATEEDGE (g1, 4, 0)) ; - edges.push_back (CREATEEDGE (g1, 4, 9)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(4), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 5, 6)) ; - edges.push_back (CREATEEDGE (g1, 5, 2)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(5), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 6, 5)) ; - edges.push_back (CREATEEDGE (g1, 6, 4)) ; - edges.push_back (CREATEEDGE (g1, 6, 3)) ; - edges.push_back (CREATEEDGE (g1, 6, 2)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(6), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 7, 8)) ; - edges.push_back (CREATEEDGE (g1, 7, 4)) ; - edges.push_back (CREATEEDGE (g1, 7, 1)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(7), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 8, 7)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(8), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - - edges.clear() ; - edges.push_back (CREATEEDGE (g1, 9, 4)) ; - addTestResult (genericTestVertexIteration (g1->getVertex(9), EdgeIterator::SAMPLEOCCURENCE, edges)) ; - } +void EdgeIteratorTest::cleanup() {} + +void EdgeIteratorTest::testReferenceIteration() { + { + Globs = gl1; + + std::vector edges; + edges.push_back(CREATEEDGE(g1, 0, 1)); + edges.push_back(CREATEEDGE(g1, 0, 4)); + addTestResult( + genericTestVertexIteration(g1->getVertex(0), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 1, 0)); + edges.push_back(CREATEEDGE(g1, 1, 3)); + edges.push_back(CREATEEDGE(g1, 1, 7)); + addTestResult( + genericTestVertexIteration(g1->getVertex(1), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 2, 3)); + edges.push_back(CREATEEDGE(g1, 2, 5)); + edges.push_back(CREATEEDGE(g1, 2, 6)); + addTestResult( + genericTestVertexIteration(g1->getVertex(2), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 3, 2)); + edges.push_back(CREATEEDGE(g1, 3, 1)); + edges.push_back(CREATEEDGE(g1, 3, 6)); + addTestResult( + genericTestVertexIteration(g1->getVertex(3), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 4, 6)); + edges.push_back(CREATEEDGE(g1, 4, 7)); + edges.push_back(CREATEEDGE(g1, 4, 0)); + edges.push_back(CREATEEDGE(g1, 4, 9)); + addTestResult( + genericTestVertexIteration(g1->getVertex(4), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 5, 6)); + edges.push_back(CREATEEDGE(g1, 5, 2)); + addTestResult( + genericTestVertexIteration(g1->getVertex(5), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 6, 5)); + edges.push_back(CREATEEDGE(g1, 6, 4)); + edges.push_back(CREATEEDGE(g1, 6, 3)); + edges.push_back(CREATEEDGE(g1, 6, 2)); + addTestResult( + genericTestVertexIteration(g1->getVertex(6), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 7, 8)); + edges.push_back(CREATEEDGE(g1, 7, 4)); + edges.push_back(CREATEEDGE(g1, 7, 1)); + addTestResult( + genericTestVertexIteration(g1->getVertex(7), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 8, 7)); + addTestResult( + genericTestVertexIteration(g1->getVertex(8), EdgeIterator::SAMPLEOCCURENCE, edges)); + + edges.clear(); + edges.push_back(CREATEEDGE(g1, 9, 4)); + addTestResult( + genericTestVertexIteration(g1->getVertex(9), EdgeIterator::SAMPLEOCCURENCE, edges)); + } } -void EdgeIteratorTest::testIterationLength () -{ - Globs = gl10 ; addTestResult (genericTestIterationLength (g10)) ; - Globs = gl11 ; addTestResult (genericTestIterationLength (g11)) ; +void EdgeIteratorTest::testIterationLength() { + Globs = gl10; + addTestResult(genericTestIterationLength(g10)); + Globs = gl11; + addTestResult(genericTestIterationLength(g11)); } #if 0 @@ -161,84 +175,87 @@ bool EdgeIteratorTest::genericTestGraphIteration (Graph* g, EdgeIterator::ITERAT } #endif -bool EdgeIteratorTest::genericTestVertexIteration (Vertex* srcvertex, EdgeIterator::ITERATIONMODE m, const std::vector& edges) -{ - EdgeIterator edgeit (srcvertex, m) ; - std::vector::const_iterator refit = edges.begin() ; - - bool ok = true ; - while (!edgeit.isFinished() && refit != edges.end()) { - if (**refit != **edgeit) { - if (ArgVerbose) { - if (ok) { - std::cerr << std::endl << "---- FAILED: genericTestVertexIteration ----" << std::endl ; - } - std::cerr << "expected edge:" << std::endl ; - (*refit)->print(1) ; - std::cerr << "found edge:" << std::endl ; - Edge* e = new Edge(**edgeit) ; - e->print(1) ; - delete e ; - } - ok = false ; - } - - ++refit ; - ++edgeit ; - } - - bool lenok = (edgeit.isFinished() && (refit == edges.end())) ; - - if (!lenok && ArgVerbose) { - if (ok) { - std::cerr << std::endl << "---- FAILED: genericTestVertexIteration ----" << std::endl ; - } - std::cerr << "length problem:" << std::endl ; - std::cerr << "edgeit is" << ((edgeit.isFinished()) ? "" : " not") << " finished" << std::endl ; - std::cerr << "refit is" << ((refit == edges.end()) ? "" : " not") << " finished" << std::endl ; - - std::cerr << "rest of reference iteration:" << std::endl ; - for ( ; refit != edges.end() ; refit++) { - (*refit)->print(1) ; - } - if (ok) { - std::cerr << "-------------------------------------" << std::endl ; - } - } - - if (!ok && ArgVerbose) { - std::cerr << "-------------------------------------" << std::endl ; - } - - return (lenok && ok) ; +bool EdgeIteratorTest::genericTestVertexIteration(Vertex *srcvertex, EdgeIterator::ITERATIONMODE m, + const std::vector &edges) { + EdgeIterator edgeit(srcvertex, m); + std::vector::const_iterator refit = edges.begin(); + + bool ok = true; + while (!edgeit.isFinished() && refit != edges.end()) { + if (**refit != **edgeit) { + if (ArgVerbose) { + if (ok) { + std::cerr << std::endl + << "---- FAILED: genericTestVertexIteration ----" << std::endl; + } + std::cerr << "expected edge:" << std::endl; + (*refit)->print(1); + std::cerr << "found edge:" << std::endl; + Edge *e = new Edge(**edgeit); + e->print(1); + delete e; + } + ok = false; + } + + ++refit; + ++edgeit; + } + + bool lenok = (edgeit.isFinished() && (refit == edges.end())); + + if (!lenok && ArgVerbose) { + if (ok) { + std::cerr << std::endl << "---- FAILED: genericTestVertexIteration ----" << std::endl; + } + std::cerr << "length problem:" << std::endl; + std::cerr << "edgeit is" << ((edgeit.isFinished()) ? "" : " not") << " finished" + << std::endl; + std::cerr << "refit is" << ((refit == edges.end()) ? "" : " not") << " finished" + << std::endl; + + std::cerr << "rest of reference iteration:" << std::endl; + for (; refit != edges.end(); refit++) { + (*refit)->print(1); + } + if (ok) { + std::cerr << "-------------------------------------" << std::endl; + } + } + + if (!ok && ArgVerbose) { + std::cerr << "-------------------------------------" << std::endl; + } + + return (lenok && ok); } -bool EdgeIteratorTest::genericTestIterationLength (Graph* g) -{ - bool ok = true ; - for (VertexLabel l = 0 ; l < g->getNumVertices() ; l++) { - Vertex* srcvertex = g->getVertex(l) ; - - EdgeIterator edgeit (srcvertex) ; - unsigned long n = 0 ; - while (!edgeit.isFinished()) { - ++edgeit ; - n++ ; - } - - if (n != srcvertex->getDegree() && ArgVerbose) { - if (ok) { - std::cerr << std::endl << "---- FAILED: genericTestIterationLength ----" << std::endl ; - } - std::cerr << "for vertex " << l << ": getDegree(): " << srcvertex->getDegree() << ", edgeit goes through: " << n << std::endl ; - } - ok = (n == srcvertex->getDegree()) && ok ; - - } - - if (!ok && ArgVerbose) { - std::cerr << "-------------------------------------" << std::endl ; - } - - return ok ; +bool EdgeIteratorTest::genericTestIterationLength(Graph *g) { + bool ok = true; + for (VertexLabel l = 0; l < g->getNumVertices(); l++) { + Vertex *srcvertex = g->getVertex(l); + + EdgeIterator edgeit(srcvertex); + unsigned long n = 0; + while (!edgeit.isFinished()) { + ++edgeit; + n++; + } + + if (n != srcvertex->getDegree() && ArgVerbose) { + if (ok) { + std::cerr << std::endl + << "---- FAILED: genericTestIterationLength ----" << std::endl; + } + std::cerr << "for vertex " << l << ": getDegree(): " << srcvertex->getDegree() + << ", edgeit goes through: " << n << std::endl; + } + ok = (n == srcvertex->getDegree()) && ok; + } + + if (!ok && ArgVerbose) { + std::cerr << "-------------------------------------" << std::endl; + } + + return ok; } diff --git a/tests/steghide/EdgeIteratorTest.h b/tests/steghide/EdgeIteratorTest.h index f8220d4..1a86f03 100644 --- a/tests/steghide/EdgeIteratorTest.h +++ b/tests/steghide/EdgeIteratorTest.h @@ -31,43 +31,45 @@ #include "EdgeIterator.h" #include "Selector.h" -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class EdgeIteratorTest : public UnitTest { - public: - EdgeIteratorTest (TestSuite* s) ; + public: + EdgeIteratorTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testReferenceIteration (void) ; - void testIterationLength (void) ; + void testReferenceIteration(void); + void testIterationLength(void); - private: - BitString *bs1, *bs2 ; - CvrStgFile *f1, *f2 ; - Selector *s1, *s2 ; - Graph *g1, *g2 ; - Globals gl1, gl2 ; + private: + BitString *bs1, *bs2; + CvrStgFile *f1, *f2; + Selector *s1, *s2; + Graph *g1, *g2; + Globals gl1, gl2; - BitString *bs10, *bs11, *bs12 ; - CvrStgFile *f10, *f11, *f12 ; - Selector *s10, *s11, *s12 ; - Graph *g10, *g11, *g12 ; - Globals gl10, gl11, gl12 ; + BitString *bs10, *bs11, *bs12; + CvrStgFile *f10, *f11, *f12; + Selector *s10, *s11, *s12; + Graph *g10, *g11, *g12; + Globals gl10, gl11, gl12; - bool genericTestGraphIteration (Graph* g, EdgeIterator::ITERATIONMODE m) ; + bool genericTestGraphIteration(Graph *g, EdgeIterator::ITERATIONMODE m); - /** - * check if an edge iterator for srcvertex with m iterates exactly through edges - **/ - bool genericTestVertexIteration (Vertex* srcvertex, EdgeIterator::ITERATIONMODE m, const std::vector& edges) ; + /** + * check if an edge iterator for srcvertex with m iterates exactly through edges + **/ + bool genericTestVertexIteration(Vertex *srcvertex, EdgeIterator::ITERATIONMODE m, + const std::vector &edges); - /** - * for all vertices in the graph test if getDegree() returns exactly the number of edges EdgeIterator iterates through - **/ - bool genericTestIterationLength (Graph* g) ; -} ; + /** + * for all vertices in the graph test if getDegree() returns exactly the number of edges + *EdgeIterator iterates through + **/ + bool genericTestIterationLength(Graph *g); +}; #endif // ndef SH_EDGEITERATORTEST_H diff --git a/tests/steghide/EmbDataTest.cc b/tests/steghide/EmbDataTest.cc index 127f391..20b2697 100644 --- a/tests/steghide/EmbDataTest.cc +++ b/tests/steghide/EmbDataTest.cc @@ -26,96 +26,90 @@ #include "TestCategoryCaller.h" #include "utcommon.h" -EmbDataTest::EmbDataTest (TestSuite* s) - : UnitTest ("EmbData", s) -{ - ADDTESTCATEGORY (EmbDataTest, testEmbedding) ; - ADDTESTCATEGORY (EmbDataTest, testExtracting) ; +EmbDataTest::EmbDataTest(TestSuite *s) : UnitTest("EmbData", s) { + ADDTESTCATEGORY(EmbDataTest, testEmbedding); + ADDTESTCATEGORY(EmbDataTest, testExtracting); } -void EmbDataTest::testEmbedding () -{ - { - std::vector data (1) ; - EmbData emb (EmbData::EMBED, "passphrase not used", "test.txt") ; - emb.setEncAlgo (EncryptionAlgorithm (EncryptionAlgorithm::NONE)) ; - emb.setEncMode (EncryptionMode (EncryptionMode::ECB)) ; - emb.setCompression (0) ; - emb.setChecksum (false) ; - emb.setData (data) ; +void EmbDataTest::testEmbedding() { + { + std::vector data(1); + EmbData emb(EmbData::EMBED, "passphrase not used", "test.txt"); + emb.setEncAlgo(EncryptionAlgorithm(EncryptionAlgorithm::NONE)); + emb.setEncMode(EncryptionMode(EncryptionMode::ECB)); + emb.setCompression(0); + emb.setChecksum(false); + emb.setData(data); - BitString shouldbe ; - shouldbe.append (EmbData::Magic, EmbData::NBitsMagic) ; // magic - shouldbe.append (false) ; // version - shouldbe.append ((BYTE) 0, 5) ; // encalgo - shouldbe.append ((BYTE) 0, 3) ; // encmode - shouldbe.append ((UWORD32) 82, 32) ; // nplainbits - shouldbe.append (false) ; // compression - shouldbe.append (false) ; // checksum - shouldbe.append (std::string("test.txt")) ; // filename - shouldbe.append ((BYTE) 0, 8) ; // end of filename - shouldbe.append ((BYTE) 0, 8) ; // data + BitString shouldbe; + shouldbe.append(EmbData::Magic, EmbData::NBitsMagic); // magic + shouldbe.append(false); // version + shouldbe.append((BYTE)0, 5); // encalgo + shouldbe.append((BYTE)0, 3); // encmode + shouldbe.append((UWORD32)82, 32); // nplainbits + shouldbe.append(false); // compression + shouldbe.append(false); // checksum + shouldbe.append(std::string("test.txt")); // filename + shouldbe.append((BYTE)0, 8); // end of filename + shouldbe.append((BYTE)0, 8); // data - addTestResult (genericTestEmbedding (emb, shouldbe)) ; - } + addTestResult(genericTestEmbedding(emb, shouldbe)); + } } -void EmbDataTest::testExtracting () -{ - { - BitString bs ; - bs.append (EmbData::Magic, EmbData::NBitsMagic) ; // magic - bs.append (false) ; // version - bs.append ((BYTE) 0, 5) ; // encalgo - bs.append ((BYTE) 1, 3) ; // encmode - bs.append ((UWORD32) 82, 32) ; // nplainbits - bs.append (false) ; // compression - bs.append (false) ; // checksum - bs.append (std::string("testfile")) ; // filename - bs.append ((BYTE) 0, 8) ; // end of filename - bs.append ((BYTE) 0xff, 8) ; // data +void EmbDataTest::testExtracting() { + { + BitString bs; + bs.append(EmbData::Magic, EmbData::NBitsMagic); // magic + bs.append(false); // version + bs.append((BYTE)0, 5); // encalgo + bs.append((BYTE)1, 3); // encmode + bs.append((UWORD32)82, 32); // nplainbits + bs.append(false); // compression + bs.append(false); // checksum + bs.append(std::string("testfile")); // filename + bs.append((BYTE)0, 8); // end of filename + bs.append((BYTE)0xff, 8); // data - EmbData emb (EmbData::EXTRACT, "passphrase not used") ; - bool ok = feed_to (bs, emb) ; + EmbData emb(EmbData::EXTRACT, "passphrase not used"); + bool ok = feed_to(bs, emb); - ok = (emb.getEncAlgo() == EncryptionAlgorithm(EncryptionAlgorithm::NONE)) && ok ; - ok = (emb.getEncMode() == EncryptionMode(EncryptionMode::CBC)) && ok ; - ok = (emb.getCompression() == 0) && ok ; - ok = (emb.getChecksum() == false) && ok ; - ok = (emb.getFileName() == "testfile") && ok ; - ok = (emb.getData().size() == 1 && emb.getData()[0] == 0xff) && ok ; + ok = (emb.getEncAlgo() == EncryptionAlgorithm(EncryptionAlgorithm::NONE)) && ok; + ok = (emb.getEncMode() == EncryptionMode(EncryptionMode::CBC)) && ok; + ok = (emb.getCompression() == 0) && ok; + ok = (emb.getChecksum() == false) && ok; + ok = (emb.getFileName() == "testfile") && ok; + ok = (emb.getData().size() == 1 && emb.getData()[0] == 0xff) && ok; - addTestResult (ok) ; - } + addTestResult(ok); + } } -bool EmbDataTest::genericTestEmbedding (EmbData e, BitString shouldbe) -{ - BitString res = e.getBitString() ; - bool retval = (res == shouldbe) ; - if (ArgVerbose && !retval) { - std::cerr << std::endl << "---- FAILED: genericTestEmbedding ----" << std::endl ; - std::cerr << "result:" << std::endl ; - res.print() ; - std::cerr << "should be:" << std::endl ; - shouldbe.print() ; - std::cerr << "-------------------------------------" << std::endl ; - } - return retval ; +bool EmbDataTest::genericTestEmbedding(EmbData e, BitString shouldbe) { + BitString res = e.getBitString(); + bool retval = (res == shouldbe); + if (ArgVerbose && !retval) { + std::cerr << std::endl << "---- FAILED: genericTestEmbedding ----" << std::endl; + std::cerr << "result:" << std::endl; + res.print(); + std::cerr << "should be:" << std::endl; + shouldbe.print(); + std::cerr << "-------------------------------------" << std::endl; + } + return retval; } -bool EmbDataTest::feed_to (const BitString& bs, EmbData& emb) -{ - UWORD32 idx = 0 ; - while (!emb.finished()) { - UWORD32 bitsrequested = emb.getNumBitsRequested() ; - if (idx + bitsrequested > bs.getLength()) { - return false ; - } +bool EmbDataTest::feed_to(const BitString &bs, EmbData &emb) { + UWORD32 idx = 0; + while (!emb.finished()) { + UWORD32 bitsrequested = emb.getNumBitsRequested(); + if (idx + bitsrequested > bs.getLength()) { + return false; + } - emb.addBits (bs.getBits (idx, bitsrequested)) ; - idx += bitsrequested ; - } + emb.addBits(bs.getBits(idx, bitsrequested)); + idx += bitsrequested; + } - return (idx == bs.getLength()) ; + return (idx == bs.getLength()); } diff --git a/tests/steghide/EmbDataTest.h b/tests/steghide/EmbDataTest.h index 6c16f35..d1e4c93 100644 --- a/tests/steghide/EmbDataTest.h +++ b/tests/steghide/EmbDataTest.h @@ -21,28 +21,28 @@ #ifndef SH_EMBDATATEST_H #define SH_EMBDATATEST_H -class BitString ; +class BitString; #define private public #include "EmbData.h" #undef private -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class EmbDataTest : public UnitTest { - public: - EmbDataTest (TestSuite* s) ; + public: + EmbDataTest(TestSuite *s); - void testEmbedding (void) ; - void testExtracting (void) ; + void testEmbedding(void); + void testExtracting(void); - private: - bool genericTestEmbedding (EmbData emb, BitString shouldbe) ; - /** - * pass the BitString bs to emb using getNumBitsNeeded and addBits - * \return true iff emb took exactly the (number of) bits from bs - **/ - bool feed_to (const BitString& bs, EmbData& emb) ; -} ; + private: + bool genericTestEmbedding(EmbData emb, BitString shouldbe); + /** + * pass the BitString bs to emb using getNumBitsNeeded and addBits + * \return true iff emb took exactly the (number of) bits from bs + **/ + bool feed_to(const BitString &bs, EmbData &emb); +}; #endif // ndef SH_EMBDATATEST_H diff --git a/tests/steghide/GraphTest.cc b/tests/steghide/GraphTest.cc index 52525dc..8835ca8 100644 --- a/tests/steghide/GraphTest.cc +++ b/tests/steghide/GraphTest.cc @@ -27,241 +27,346 @@ #undef protected #include "Selector.h" -#include "utcommon.h" #include "GraphTest.h" +#include "utcommon.h" -GraphTest::GraphTest (TestSuite* s) - : UnitTest ("Graph", s) -{ - ADDTESTCATEGORY (GraphTest, testSampleValues) ; - ADDTESTCATEGORY (GraphTest, testVertices) ; - ADDTESTCATEGORY (GraphTest, testSampleOccurences) ; - ADDTESTCATEGORY (GraphTest, testSampleValueAdjacencyLists) ; +GraphTest::GraphTest(TestSuite *s) : UnitTest("Graph", s) { + ADDTESTCATEGORY(GraphTest, testSampleValues); + ADDTESTCATEGORY(GraphTest, testVertices); + ADDTESTCATEGORY(GraphTest, testSampleOccurences); + ADDTESTCATEGORY(GraphTest, testSampleValueAdjacencyLists); } -void GraphTest::setup () -{ - UnitTest::setup() ; +void GraphTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "win3x1_std.bmp") ; - bs1 = new BitString (std::string ("this BitString will be embedded")) ; - s1 = new Selector (bs1->getLength() * f1->getSamplesPerVertex(), std::string ("a passphrase")) ; - g1 = new Graph (f1, *bs1, *s1) ; - gl1 = Globs ; + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "win3x1_std.bmp"); + bs1 = new BitString(std::string("this BitString will be embedded")); + s1 = new Selector(bs1->getLength() * f1->getSamplesPerVertex(), std::string("a passphrase")); + g1 = new Graph(f1, *bs1, *s1); + gl1 = Globs; - Globs.reset() ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "win3x4_std.bmp") ; - bs2 = new BitString (std::string ("this is a test")) ; - s2 = new Selector (bs2->getLength() * f2->getSamplesPerVertex(), std::string ("another passphrase")) ; - g2 = new Graph (f2, *bs2, *s2) ; - gl2 = Globs ; + Globs.reset(); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "win3x4_std.bmp"); + bs2 = new BitString(std::string("this is a test")); + s2 = new Selector(bs2->getLength() * f2->getSamplesPerVertex(), + std::string("another passphrase")); + g2 = new Graph(f2, *bs2, *s2); + gl2 = Globs; - Globs.reset() ; - f3 = CvrStgFile::readFile (std::string(DATADIR) + "win3x8_std.bmp") ; - bs3 = new BitString (std::string ("this is another test")) ; - s3 = new Selector (bs3->getLength() * f3->getSamplesPerVertex(), std::string ("yet another passphrase")) ; - g3 = new Graph (f3, *bs3, *s3) ; - gl3 = Globs ; + Globs.reset(); + f3 = CvrStgFile::readFile(std::string(DATADIR) + "win3x8_std.bmp"); + bs3 = new BitString(std::string("this is another test")); + s3 = new Selector(bs3->getLength() * f3->getSamplesPerVertex(), + std::string("yet another passphrase")); + g3 = new Graph(f3, *bs3, *s3); + gl3 = Globs; - Globs.reset() ; - f4 = CvrStgFile::readFile (std::string(DATADIR) + "win3x24_std.bmp") ; - bs4 = new BitString (std::string ("this time embedding in RGB pixel data")) ; - s4 = new Selector (bs4->getLength() * f4->getSamplesPerVertex(), std::string ("a true-color passphrase ;-)")) ; - g4 = new Graph (f4, *bs4, *s4) ; - gl4 = Globs ; + Globs.reset(); + f4 = CvrStgFile::readFile(std::string(DATADIR) + "win3x24_std.bmp"); + bs4 = new BitString(std::string("this time embedding in RGB pixel data")); + s4 = new Selector(bs4->getLength() * f4->getSamplesPerVertex(), + std::string("a true-color passphrase ;-)")); + g4 = new Graph(f4, *bs4, *s4); + gl4 = Globs; - Globs.reset() ; - f5 = CvrStgFile::readFile (std::string(DATADIR) + "os21x1_std.bmp") ; - bs5 = new BitString (std::string ("this BitString will be embedded")) ; - s5 = new Selector (bs5->getLength() * f5->getSamplesPerVertex(), std::string ("a passphrase")) ; - g5 = new Graph (f5, *bs5, *s5) ; - gl5 = Globs ; + Globs.reset(); + f5 = CvrStgFile::readFile(std::string(DATADIR) + "os21x1_std.bmp"); + bs5 = new BitString(std::string("this BitString will be embedded")); + s5 = new Selector(bs5->getLength() * f5->getSamplesPerVertex(), std::string("a passphrase")); + g5 = new Graph(f5, *bs5, *s5); + gl5 = Globs; - Globs.reset() ; - f6 = CvrStgFile::readFile (std::string(DATADIR) + "os21x4_std.bmp") ; - bs6 = new BitString (std::string ("this is a test")) ; - s6 = new Selector (bs6->getLength() * f6->getSamplesPerVertex(), std::string ("another passphrase")) ; - g6 = new Graph (f6, *bs6, *s6) ; - gl6 = Globs ; + Globs.reset(); + f6 = CvrStgFile::readFile(std::string(DATADIR) + "os21x4_std.bmp"); + bs6 = new BitString(std::string("this is a test")); + s6 = new Selector(bs6->getLength() * f6->getSamplesPerVertex(), + std::string("another passphrase")); + g6 = new Graph(f6, *bs6, *s6); + gl6 = Globs; - Globs.reset() ; - f7 = CvrStgFile::readFile (std::string(DATADIR) + "os21x8_std.bmp") ; - bs7 = new BitString (std::string ("this is another test")) ; - s7 = new Selector (bs7->getLength() * f7->getSamplesPerVertex(), std::string ("yet another passphrase")) ; - g7 = new Graph (f7, *bs7, *s7) ; - gl7 = Globs ; + Globs.reset(); + f7 = CvrStgFile::readFile(std::string(DATADIR) + "os21x8_std.bmp"); + bs7 = new BitString(std::string("this is another test")); + s7 = new Selector(bs7->getLength() * f7->getSamplesPerVertex(), + std::string("yet another passphrase")); + g7 = new Graph(f7, *bs7, *s7); + gl7 = Globs; - Globs.reset() ; - f8 = CvrStgFile::readFile (std::string(DATADIR) + "os21x24_std.bmp") ; - bs8 = new BitString (std::string ("this time embedding in RGB pixel data")) ; - s8 = new Selector (bs8->getLength() * f8->getSamplesPerVertex(), std::string ("a true-color passphrase ;-)")) ; - g8 = new Graph (f8, *bs8, *s8) ; - gl8 = Globs ; + Globs.reset(); + f8 = CvrStgFile::readFile(std::string(DATADIR) + "os21x24_std.bmp"); + bs8 = new BitString(std::string("this time embedding in RGB pixel data")); + s8 = new Selector(bs8->getLength() * f8->getSamplesPerVertex(), + std::string("a true-color passphrase ;-)")); + g8 = new Graph(f8, *bs8, *s8); + gl8 = Globs; - Globs.reset() ; - f9 = CvrStgFile::readFile (std::string(DATADIR) + "mulaw_std.au") ; - bs9 = new BitString (std::string ("u-law or mu-law that's the question")) ; - s9 = new Selector (bs9->getLength() * f9->getSamplesPerVertex(), std::string ("muuuuuuuu")) ; - g9 = new Graph (f9, *bs9, *s9) ; - gl9 = Globs ; + Globs.reset(); + f9 = CvrStgFile::readFile(std::string(DATADIR) + "mulaw_std.au"); + bs9 = new BitString(std::string("u-law or mu-law that's the question")); + s9 = new Selector(bs9->getLength() * f9->getSamplesPerVertex(), std::string("muuuuuuuu")); + g9 = new Graph(f9, *bs9, *s9); + gl9 = Globs; - Globs.reset() ; - f10 = CvrStgFile::readFile (std::string(DATADIR) + "pcm8_std.au") ; - bs10 = new BitString (std::string ("also au files can have pcm encoded data")) ; - s10 = new Selector (bs10->getLength() * f10->getSamplesPerVertex(), std::string ("pulse code modulation")) ; - g10 = new Graph (f10, *bs10, *s10) ; - gl10 = Globs ; + Globs.reset(); + f10 = CvrStgFile::readFile(std::string(DATADIR) + "pcm8_std.au"); + bs10 = new BitString(std::string("also au files can have pcm encoded data")); + s10 = new Selector(bs10->getLength() * f10->getSamplesPerVertex(), + std::string("pulse code modulation")); + g10 = new Graph(f10, *bs10, *s10); + gl10 = Globs; - Globs.reset() ; - f11 = CvrStgFile::readFile (std::string(DATADIR) + "pcm16_std.au") ; - bs11 = new BitString (std::string ("even with 16 bits per sample")) ; - s11 = new Selector (bs11->getLength() * f11->getSamplesPerVertex(), std::string ("pcm16")) ; - g11 = new Graph (f11, *bs11, *s11) ; - gl11 = Globs ; + Globs.reset(); + f11 = CvrStgFile::readFile(std::string(DATADIR) + "pcm16_std.au"); + bs11 = new BitString(std::string("even with 16 bits per sample")); + s11 = new Selector(bs11->getLength() * f11->getSamplesPerVertex(), std::string("pcm16")); + g11 = new Graph(f11, *bs11, *s11); + gl11 = Globs; - Globs.reset() ; - f12 = CvrStgFile::readFile (std::string(DATADIR) + "pcm8_std.wav") ; - bs12 = new BitString (std::string ("8 bit pcm data in a riff wav file")) ; - s12 = new Selector (bs12->getLength() * f12->getSamplesPerVertex(), std::string ("afaf")) ; - g12 = new Graph (f12, *bs12, *s12) ; - gl12 = Globs ; + Globs.reset(); + f12 = CvrStgFile::readFile(std::string(DATADIR) + "pcm8_std.wav"); + bs12 = new BitString(std::string("8 bit pcm data in a riff wav file")); + s12 = new Selector(bs12->getLength() * f12->getSamplesPerVertex(), std::string("afaf")); + g12 = new Graph(f12, *bs12, *s12); + gl12 = Globs; - Globs.reset() ; - f13 = CvrStgFile::readFile (std::string(DATADIR) + "pcm16_std.wav") ; - bs13 = new BitString (std::string ("16 bits per sample")) ; - s13 = new Selector (bs13->getLength() * f13->getSamplesPerVertex(), std::string ("passphrase")) ; - g13 = new Graph (f13, *bs13, *s13) ; - gl13 = Globs ; + Globs.reset(); + f13 = CvrStgFile::readFile(std::string(DATADIR) + "pcm16_std.wav"); + bs13 = new BitString(std::string("16 bits per sample")); + s13 = new Selector(bs13->getLength() * f13->getSamplesPerVertex(), std::string("passphrase")); + g13 = new Graph(f13, *bs13, *s13); + gl13 = Globs; - Globs.reset() ; - f14 = CvrStgFile::readFile (std::string(DATADIR) + "std.jpg") ; - bs14 = new BitString (std::string ("standard jpeg produced by the GIMP")) ; - s14 = new Selector (bs14->getLength() * f14->getSamplesPerVertex(), std::string ("passphrase")) ; - g14 = new Graph (f14, *bs14, *s14) ; - gl14 = Globs ; + Globs.reset(); + f14 = CvrStgFile::readFile(std::string(DATADIR) + "std.jpg"); + bs14 = new BitString(std::string("standard jpeg produced by the GIMP")); + s14 = new Selector(bs14->getLength() * f14->getSamplesPerVertex(), std::string("passphrase")); + g14 = new Graph(f14, *bs14, *s14); + gl14 = Globs; - Globs.reset() ; - f15 = CvrStgFile::readFile (std::string(DATADIR) + "prog.jpg") ; - bs15 = new BitString (std::string ("progressive encoding")) ; - s15 = new Selector (bs15->getLength() * f15->getSamplesPerVertex(), std::string ("passphrase")) ; - g15 = new Graph (f15, *bs15, *s15) ; - gl15 = Globs ; + Globs.reset(); + f15 = CvrStgFile::readFile(std::string(DATADIR) + "prog.jpg"); + bs15 = new BitString(std::string("progressive encoding")); + s15 = new Selector(bs15->getLength() * f15->getSamplesPerVertex(), std::string("passphrase")); + g15 = new Graph(f15, *bs15, *s15); + gl15 = Globs; - Globs.reset() ; - f_f = CvrStgFile::readFile (std::string(DATADIR) + "win3x24_std.bmp") ; - bs_f = new BitString (std::string ("this time embedding in RGB pixel data")) ; - s_f = new Selector (bs_f->getLength() * f_f->getSamplesPerVertex(), std::string ("a true-color passphrase ;-)")) ; - g_f = new Graph (f_f, *bs_f, *s_f) ; - gl_f = Globs ; + Globs.reset(); + f_f = CvrStgFile::readFile(std::string(DATADIR) + "win3x24_std.bmp"); + bs_f = new BitString(std::string("this time embedding in RGB pixel data")); + s_f = new Selector(bs_f->getLength() * f_f->getSamplesPerVertex(), + std::string("a true-color passphrase ;-)")); + g_f = new Graph(f_f, *bs_f, *s_f); + gl_f = Globs; } -void GraphTest::cleanup () -{ - UnitTest::cleanup() ; +void GraphTest::cleanup() { + UnitTest::cleanup(); - delete f1 ; delete bs1 ; delete s1 ; delete g1 ; - delete f2 ; delete bs2 ; delete s2 ; delete g2 ; - delete f3 ; delete bs3 ; delete s3 ; delete g3 ; - delete f4 ; delete bs4 ; delete s4 ; delete g4 ; - delete f5 ; delete bs5 ; delete s5 ; delete g5 ; - delete f6 ; delete bs6 ; delete s6 ; delete g6 ; - delete f7 ; delete bs7 ; delete s7 ; delete g7 ; - delete f8 ; delete bs8 ; delete s8 ; delete g8 ; - delete f9 ; delete bs9 ; delete s9 ; delete g9 ; - delete f10 ; delete bs10 ; delete s10 ; delete g10 ; - delete f11 ; delete bs11 ; delete s11 ; delete g11 ; - delete f12 ; delete bs12 ; delete s12 ; delete g12 ; - delete f13 ; delete bs13 ; delete s13 ; delete g13 ; - delete f14 ; delete bs14 ; delete s14 ; delete g14 ; - delete f15 ; delete bs15 ; delete s15 ; delete g15 ; - // *_f are not delted because inconsistencies might crash the destructors + delete f1; + delete bs1; + delete s1; + delete g1; + delete f2; + delete bs2; + delete s2; + delete g2; + delete f3; + delete bs3; + delete s3; + delete g3; + delete f4; + delete bs4; + delete s4; + delete g4; + delete f5; + delete bs5; + delete s5; + delete g5; + delete f6; + delete bs6; + delete s6; + delete g6; + delete f7; + delete bs7; + delete s7; + delete g7; + delete f8; + delete bs8; + delete s8; + delete g8; + delete f9; + delete bs9; + delete s9; + delete g9; + delete f10; + delete bs10; + delete s10; + delete g10; + delete f11; + delete bs11; + delete s11; + delete g11; + delete f12; + delete bs12; + delete s12; + delete g12; + delete f13; + delete bs13; + delete s13; + delete g13; + delete f14; + delete bs14; + delete s14; + delete g14; + delete f15; + delete bs15; + delete s15; + delete g15; + // *_f are not delted because inconsistencies might crash the destructors } -void GraphTest::testVertices() -{ - Globs = gl1 ; addTestResult (g1->check_Vertices(ArgVerbose)) ; - Globs = gl2 ; addTestResult (g2->check_Vertices(ArgVerbose)) ; - Globs = gl3 ; addTestResult (g3->check_Vertices(ArgVerbose)) ; - Globs = gl4 ; addTestResult (g4->check_Vertices(ArgVerbose)) ; - Globs = gl5 ; addTestResult (g5->check_Vertices(ArgVerbose)) ; - Globs = gl6 ; addTestResult (g6->check_Vertices(ArgVerbose)) ; - Globs = gl7 ; addTestResult (g7->check_Vertices(ArgVerbose)) ; - Globs = gl8 ; addTestResult (g8->check_Vertices(ArgVerbose)) ; - Globs = gl9 ; addTestResult (g9->check_Vertices(ArgVerbose)) ; - Globs = gl10 ; addTestResult (g10->check_Vertices(ArgVerbose)) ; - Globs = gl11 ; addTestResult (g11->check_Vertices(ArgVerbose)) ; - Globs = gl12 ; addTestResult (g12->check_Vertices(ArgVerbose)) ; - Globs = gl13 ; addTestResult (g13->check_Vertices(ArgVerbose)) ; - Globs = gl14 ; addTestResult (g14->check_Vertices(ArgVerbose)) ; - Globs = gl15 ; addTestResult (g15->check_Vertices(ArgVerbose)) ; +void GraphTest::testVertices() { + Globs = gl1; + addTestResult(g1->check_Vertices(ArgVerbose)); + Globs = gl2; + addTestResult(g2->check_Vertices(ArgVerbose)); + Globs = gl3; + addTestResult(g3->check_Vertices(ArgVerbose)); + Globs = gl4; + addTestResult(g4->check_Vertices(ArgVerbose)); + Globs = gl5; + addTestResult(g5->check_Vertices(ArgVerbose)); + Globs = gl6; + addTestResult(g6->check_Vertices(ArgVerbose)); + Globs = gl7; + addTestResult(g7->check_Vertices(ArgVerbose)); + Globs = gl8; + addTestResult(g8->check_Vertices(ArgVerbose)); + Globs = gl9; + addTestResult(g9->check_Vertices(ArgVerbose)); + Globs = gl10; + addTestResult(g10->check_Vertices(ArgVerbose)); + Globs = gl11; + addTestResult(g11->check_Vertices(ArgVerbose)); + Globs = gl12; + addTestResult(g12->check_Vertices(ArgVerbose)); + Globs = gl13; + addTestResult(g13->check_Vertices(ArgVerbose)); + Globs = gl14; + addTestResult(g14->check_Vertices(ArgVerbose)); + Globs = gl15; + addTestResult(g15->check_Vertices(ArgVerbose)); - // violate label consistency - Globs = gl_f ; - Vertex* tmp = g_f->Vertices[10] ; - g_f->Vertices[10] = g_f->Vertices[11] ; - g_f->Vertices[11] = tmp ; - addTestResult (!g_f->check_Vertices()) ; + // violate label consistency + Globs = gl_f; + Vertex *tmp = g_f->Vertices[10]; + g_f->Vertices[10] = g_f->Vertices[11]; + g_f->Vertices[11] = tmp; + addTestResult(!g_f->check_Vertices()); } -void GraphTest::testSampleValues() -{ - Globs = gl1 ; addTestResult (g1->check_SampleValues(ArgVerbose)) ; - Globs = gl2 ; addTestResult (g2->check_SampleValues(ArgVerbose)) ; - Globs = gl3 ; addTestResult (g3->check_SampleValues(ArgVerbose)) ; - Globs = gl4 ; addTestResult (g4->check_SampleValues(ArgVerbose)) ; - Globs = gl5 ; addTestResult (g5->check_SampleValues(ArgVerbose)) ; - Globs = gl6 ; addTestResult (g6->check_SampleValues(ArgVerbose)) ; - Globs = gl7 ; addTestResult (g7->check_SampleValues(ArgVerbose)) ; - Globs = gl8 ; addTestResult (g8->check_SampleValues(ArgVerbose)) ; - Globs = gl9 ; addTestResult (g9->check_SampleValues(ArgVerbose)) ; - Globs = gl10 ; addTestResult (g10->check_SampleValues(ArgVerbose)) ; - Globs = gl11 ; addTestResult (g11->check_SampleValues(ArgVerbose)) ; - Globs = gl12 ; addTestResult (g12->check_SampleValues(ArgVerbose)) ; - Globs = gl13 ; addTestResult (g13->check_SampleValues(ArgVerbose)) ; - Globs = gl14 ; addTestResult (g14->check_SampleValues(ArgVerbose)) ; - Globs = gl15 ; addTestResult (g15->check_SampleValues(ArgVerbose)) ; +void GraphTest::testSampleValues() { + Globs = gl1; + addTestResult(g1->check_SampleValues(ArgVerbose)); + Globs = gl2; + addTestResult(g2->check_SampleValues(ArgVerbose)); + Globs = gl3; + addTestResult(g3->check_SampleValues(ArgVerbose)); + Globs = gl4; + addTestResult(g4->check_SampleValues(ArgVerbose)); + Globs = gl5; + addTestResult(g5->check_SampleValues(ArgVerbose)); + Globs = gl6; + addTestResult(g6->check_SampleValues(ArgVerbose)); + Globs = gl7; + addTestResult(g7->check_SampleValues(ArgVerbose)); + Globs = gl8; + addTestResult(g8->check_SampleValues(ArgVerbose)); + Globs = gl9; + addTestResult(g9->check_SampleValues(ArgVerbose)); + Globs = gl10; + addTestResult(g10->check_SampleValues(ArgVerbose)); + Globs = gl11; + addTestResult(g11->check_SampleValues(ArgVerbose)); + Globs = gl12; + addTestResult(g12->check_SampleValues(ArgVerbose)); + Globs = gl13; + addTestResult(g13->check_SampleValues(ArgVerbose)); + Globs = gl14; + addTestResult(g14->check_SampleValues(ArgVerbose)); + Globs = gl15; + addTestResult(g15->check_SampleValues(ArgVerbose)); - // violate uniqueness - Globs = gl_f ; - g_f->SampleValues[0] = g_f->SampleValues[1] ; - addTestResult (!g_f->check_SampleValues()) ; + // violate uniqueness + Globs = gl_f; + g_f->SampleValues[0] = g_f->SampleValues[1]; + addTestResult(!g_f->check_SampleValues()); } -void GraphTest::testSampleOccurences() -{ - Globs = gl1 ; addTestResult (g1->check_SampleOccurences(ArgVerbose)) ; - Globs = gl2 ; addTestResult (g2->check_SampleOccurences(ArgVerbose)) ; - Globs = gl3 ; addTestResult (g3->check_SampleOccurences(ArgVerbose)) ; - Globs = gl4 ; addTestResult (g4->check_SampleOccurences(ArgVerbose)) ; - Globs = gl5 ; addTestResult (g5->check_SampleOccurences(ArgVerbose)) ; - Globs = gl6 ; addTestResult (g6->check_SampleOccurences(ArgVerbose)) ; - Globs = gl7 ; addTestResult (g7->check_SampleOccurences(ArgVerbose)) ; - Globs = gl8 ; addTestResult (g8->check_SampleOccurences(ArgVerbose)) ; - Globs = gl9 ; addTestResult (g9->check_SampleOccurences(ArgVerbose)) ; - Globs = gl10 ; addTestResult (g10->check_SampleOccurences(ArgVerbose)) ; - Globs = gl11 ; addTestResult (g11->check_SampleOccurences(ArgVerbose)) ; - Globs = gl12 ; addTestResult (g12->check_SampleOccurences(ArgVerbose)) ; - Globs = gl13 ; addTestResult (g13->check_SampleOccurences(ArgVerbose)) ; - Globs = gl14 ; addTestResult (g14->check_SampleOccurences(ArgVerbose)) ; - Globs = gl15 ; addTestResult (g15->check_SampleOccurences(ArgVerbose)) ; +void GraphTest::testSampleOccurences() { + Globs = gl1; + addTestResult(g1->check_SampleOccurences(ArgVerbose)); + Globs = gl2; + addTestResult(g2->check_SampleOccurences(ArgVerbose)); + Globs = gl3; + addTestResult(g3->check_SampleOccurences(ArgVerbose)); + Globs = gl4; + addTestResult(g4->check_SampleOccurences(ArgVerbose)); + Globs = gl5; + addTestResult(g5->check_SampleOccurences(ArgVerbose)); + Globs = gl6; + addTestResult(g6->check_SampleOccurences(ArgVerbose)); + Globs = gl7; + addTestResult(g7->check_SampleOccurences(ArgVerbose)); + Globs = gl8; + addTestResult(g8->check_SampleOccurences(ArgVerbose)); + Globs = gl9; + addTestResult(g9->check_SampleOccurences(ArgVerbose)); + Globs = gl10; + addTestResult(g10->check_SampleOccurences(ArgVerbose)); + Globs = gl11; + addTestResult(g11->check_SampleOccurences(ArgVerbose)); + Globs = gl12; + addTestResult(g12->check_SampleOccurences(ArgVerbose)); + Globs = gl13; + addTestResult(g13->check_SampleOccurences(ArgVerbose)); + Globs = gl14; + addTestResult(g14->check_SampleOccurences(ArgVerbose)); + Globs = gl15; + addTestResult(g15->check_SampleOccurences(ArgVerbose)); } -void GraphTest::testSampleValueAdjacencyLists () -{ - Globs = gl1 ; addTestResult (g1->check_SVALists(ArgVerbose)) ; - Globs = gl2 ; addTestResult (g2->check_SVALists(ArgVerbose)) ; - Globs = gl3 ; addTestResult (g3->check_SVALists(ArgVerbose)) ; - Globs = gl4 ; addTestResult (g4->check_SVALists(ArgVerbose)) ; - Globs = gl5 ; addTestResult (g5->check_SVALists(ArgVerbose)) ; - Globs = gl6 ; addTestResult (g6->check_SVALists(ArgVerbose)) ; - Globs = gl7 ; addTestResult (g7->check_SVALists(ArgVerbose)) ; - Globs = gl8 ; addTestResult (g8->check_SVALists(ArgVerbose)) ; - Globs = gl9 ; addTestResult (g9->check_SVALists(ArgVerbose)) ; - Globs = gl10 ; addTestResult (g10->check_SVALists(ArgVerbose)) ; - Globs = gl11 ; addTestResult (g11->check_SVALists(ArgVerbose)) ; - Globs = gl12 ; addTestResult (g12->check_SVALists(ArgVerbose)) ; - Globs = gl13 ; addTestResult (g13->check_SVALists(ArgVerbose)) ; - Globs = gl14 ; addTestResult (g14->check_SVALists(ArgVerbose)) ; - Globs = gl15 ; addTestResult (g15->check_SVALists(ArgVerbose)) ; +void GraphTest::testSampleValueAdjacencyLists() { + Globs = gl1; + addTestResult(g1->check_SVALists(ArgVerbose)); + Globs = gl2; + addTestResult(g2->check_SVALists(ArgVerbose)); + Globs = gl3; + addTestResult(g3->check_SVALists(ArgVerbose)); + Globs = gl4; + addTestResult(g4->check_SVALists(ArgVerbose)); + Globs = gl5; + addTestResult(g5->check_SVALists(ArgVerbose)); + Globs = gl6; + addTestResult(g6->check_SVALists(ArgVerbose)); + Globs = gl7; + addTestResult(g7->check_SVALists(ArgVerbose)); + Globs = gl8; + addTestResult(g8->check_SVALists(ArgVerbose)); + Globs = gl9; + addTestResult(g9->check_SVALists(ArgVerbose)); + Globs = gl10; + addTestResult(g10->check_SVALists(ArgVerbose)); + Globs = gl11; + addTestResult(g11->check_SVALists(ArgVerbose)); + Globs = gl12; + addTestResult(g12->check_SVALists(ArgVerbose)); + Globs = gl13; + addTestResult(g13->check_SVALists(ArgVerbose)); + Globs = gl14; + addTestResult(g14->check_SVALists(ArgVerbose)); + Globs = gl15; + addTestResult(g15->check_SVALists(ArgVerbose)); } diff --git a/tests/steghide/GraphTest.h b/tests/steghide/GraphTest.h index 1ffb881..f607840 100644 --- a/tests/steghide/GraphTest.h +++ b/tests/steghide/GraphTest.h @@ -23,30 +23,32 @@ #include "UnitTest.h" -class TestSuite ; -class CvrStgFile ; -class BitString ; -class Selector ; -class Graph ; +class TestSuite; +class CvrStgFile; +class BitString; +class Selector; +class Graph; class GraphTest : public UnitTest { - public: - GraphTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testVertices (void) ; - void testSampleValues (void) ; - void testSampleOccurences (void) ; - void testSampleValueAdjacencyLists (void) ; - - private: - CvrStgFile *f1, *f2, *f3, *f4, *f5, *f6, *f7, *f8, *f9, *f10, *f11, *f12, *f13, *f14, *f15, *f_f ; - BitString *bs1, *bs2, *bs3, *bs4, *bs5, *bs6, *bs7, *bs8, *bs9, *bs10, *bs11, *bs12, *bs13, *bs14, *bs15, *bs_f ; - Selector *s1, *s2, *s3, *s4, *s5, *s6, *s7, *s8, *s9, *s10, *s11, *s12, *s13, *s14, *s15, *s_f ; - Graph *g1, *g2, *g3, *g4, *g5, *g6, *g7, *g8, *g9, *g10, *g11, *g12, *g13, *g14, *g15, *g_f ; - Globals gl1, gl2, gl3, gl4, gl5, gl6, gl7, gl8, gl9, gl10, gl11, gl12, gl13, gl14, gl15, gl_f ; -} ; + public: + GraphTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testVertices(void); + void testSampleValues(void); + void testSampleOccurences(void); + void testSampleValueAdjacencyLists(void); + + private: + CvrStgFile *f1, *f2, *f3, *f4, *f5, *f6, *f7, *f8, *f9, *f10, *f11, *f12, *f13, *f14, *f15, + *f_f; + BitString *bs1, *bs2, *bs3, *bs4, *bs5, *bs6, *bs7, *bs8, *bs9, *bs10, *bs11, *bs12, *bs13, + *bs14, *bs15, *bs_f; + Selector *s1, *s2, *s3, *s4, *s5, *s6, *s7, *s8, *s9, *s10, *s11, *s12, *s13, *s14, *s15, *s_f; + Graph *g1, *g2, *g3, *g4, *g5, *g6, *g7, *g8, *g9, *g10, *g11, *g12, *g13, *g14, *g15, *g_f; + Globals gl1, gl2, gl3, gl4, gl5, gl6, gl7, gl8, gl9, gl10, gl11, gl12, gl13, gl14, gl15, gl_f; +}; #endif // ndef SH_GRAPHTEST_H diff --git a/tests/steghide/JpegFileTest.cc b/tests/steghide/JpegFileTest.cc index eb750ab..6dd6bcd 100644 --- a/tests/steghide/JpegFileTest.cc +++ b/tests/steghide/JpegFileTest.cc @@ -18,64 +18,60 @@ * */ - -#include "utcommon.h" #include "JpegFileTest.h" +#include "utcommon.h" -JpegFileTest::JpegFileTest (TestSuite* s) - : CvrStgFileTest("JpegFile", s) -{ - ADDTESTCATEGORY (JpegFileTest, testReadEmbedExtract) ; - ADDTESTCATEGORY (JpegFileTest, testReadEmbedWriteReadExtract) ; +JpegFileTest::JpegFileTest(TestSuite *s) : CvrStgFileTest("JpegFile", s) { + ADDTESTCATEGORY(JpegFileTest, testReadEmbedExtract); + ADDTESTCATEGORY(JpegFileTest, testReadEmbedWriteReadExtract); } -void JpegFileTest::setup () -{ - UnitTest::setup() ; +void JpegFileTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "std.jpg") ; - bs1 = new BitString (std::string ("a test passphrase")) ; - gl1 = Globs ; + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "std.jpg"); + bs1 = new BitString(std::string("a test passphrase")); + gl1 = Globs; - Globs.reset() ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "prog.jpg") ; - bs2 = new BitString (std::string ("another test passphrase")) ; - gl2 = Globs ; + Globs.reset(); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "prog.jpg"); + bs2 = new BitString(std::string("another test passphrase")); + gl2 = Globs; } -void JpegFileTest::cleanup () -{ - UnitTest::cleanup() ; +void JpegFileTest::cleanup() { + UnitTest::cleanup(); - delete bs1 ; delete bs2 ; - delete f1 ; delete f2 ; + delete bs1; + delete bs2; + delete f1; + delete f2; } -void JpegFileTest::testReadEmbedExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "std.jpg", *bs1)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "prog.jpg", *bs2)) ; +void JpegFileTest::testReadEmbedExtract() { + Globs = gl1; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "std.jpg", *bs1)); + Globs = gl2; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "prog.jpg", *bs2)); } -void JpegFileTest::testReadEmbedWriteReadExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "std.jpg", *bs2)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "prog.jpg", *bs1)) ; +void JpegFileTest::testReadEmbedWriteReadExtract() { + Globs = gl1; + addTestResult(genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "std.jpg", *bs2)); + Globs = gl2; + addTestResult(genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "prog.jpg", *bs1)); } -void JpegFileTest::testPosition() -{ - // TODO +void JpegFileTest::testPosition() { + // TODO } -void JpegFileTest::testReadExtractCompare () -{ - // TODO +void JpegFileTest::testReadExtractCompare() { + // TODO } -void JpegFileTest::testEmbeddedValue () -{ +void JpegFileTest::testEmbeddedValue() { #if 0 Globs = gl1 ; addTestResult (genericTestEmbeddedValue (f1)) ; Globs = gl2 ; addTestResult (genericTestEmbeddedValue (f2)) ; diff --git a/tests/steghide/JpegFileTest.h b/tests/steghide/JpegFileTest.h index c80f0bc..a37c648 100644 --- a/tests/steghide/JpegFileTest.h +++ b/tests/steghide/JpegFileTest.h @@ -26,22 +26,22 @@ #include "CvrStgFileTest.h" class JpegFileTest : public CvrStgFileTest { - public: - JpegFileTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testReadEmbedExtract (void) ; - void testReadEmbedWriteReadExtract (void) ; - void testPosition (void) ; - void testReadExtractCompare (void) ; - void testEmbeddedValue (void) ; - - private: - BitString *bs1, *bs2 ; - CvrStgFile *f1, *f2 ; - Globals gl1, gl2 ; -} ; + public: + JpegFileTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testReadEmbedExtract(void); + void testReadEmbedWriteReadExtract(void); + void testPosition(void); + void testReadExtractCompare(void); + void testEmbeddedValue(void); + + private: + BitString *bs1, *bs2; + CvrStgFile *f1, *f2; + Globals gl1, gl2; +}; #endif // ndef SH_JPEGFILETEST_H diff --git a/tests/steghide/JpegSampleValueTest.cc b/tests/steghide/JpegSampleValueTest.cc index cd4a239..45c9281 100644 --- a/tests/steghide/JpegSampleValueTest.cc +++ b/tests/steghide/JpegSampleValueTest.cc @@ -21,45 +21,41 @@ #include "JpegSampleValueTest.h" #include "utcommon.h" -#include "JpegSampleValue.h" #include "CvrStgFile.h" +#include "JpegSampleValue.h" -JpegSampleValueTest::JpegSampleValueTest (TestSuite* s) - : SampleValueTest ("JpegSampleValue", s) -{ - ADDTESTCATEGORY (JpegSampleValueTest, testDistance) ; - ADDTESTCATEGORY (JpegSampleValueTest, testIsNeighbour) ; +JpegSampleValueTest::JpegSampleValueTest(TestSuite *s) : SampleValueTest("JpegSampleValue", s) { + ADDTESTCATEGORY(JpegSampleValueTest, testDistance); + ADDTESTCATEGORY(JpegSampleValueTest, testIsNeighbour); } -void JpegSampleValueTest::setup () -{ - UnitTest::setup() ; +void JpegSampleValueTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "std.jpg") ; - sv_m1 = new JpegSampleValue (-1) ; - sv_0 = new JpegSampleValue (0) ; - sv_1 = new JpegSampleValue (1) ; - gl1 = Globs ; + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "std.jpg"); + sv_m1 = new JpegSampleValue(-1); + sv_0 = new JpegSampleValue(0); + sv_1 = new JpegSampleValue(1); + gl1 = Globs; } -void JpegSampleValueTest::cleanup () -{ - UnitTest::cleanup() ; - delete f1 ; - delete sv_m1 ; delete sv_0 ; delete sv_1 ; +void JpegSampleValueTest::cleanup() { + UnitTest::cleanup(); + delete f1; + delete sv_m1; + delete sv_0; + delete sv_1; } -void JpegSampleValueTest::testDistance () -{ - Globs = gl1 ; - addTestResult (genericTestDistance (sv_0, sv_1, 1)) ; - addTestResult (genericTestDistance (sv_m1, sv_1, 2)) ; +void JpegSampleValueTest::testDistance() { + Globs = gl1; + addTestResult(genericTestDistance(sv_0, sv_1, 1)); + addTestResult(genericTestDistance(sv_m1, sv_1, 2)); } -void JpegSampleValueTest::testIsNeighbour () -{ - Globs = gl1 ; - addTestResult (genericTestIsNeighbour (sv_m1, sv_0, true)) ; - addTestResult (genericTestIsNeighbour (sv_1, sv_m1, false)) ; +void JpegSampleValueTest::testIsNeighbour() { + Globs = gl1; + addTestResult(genericTestIsNeighbour(sv_m1, sv_0, true)); + addTestResult(genericTestIsNeighbour(sv_1, sv_m1, false)); } diff --git a/tests/steghide/JpegSampleValueTest.h b/tests/steghide/JpegSampleValueTest.h index 5c683f6..cb65285 100644 --- a/tests/steghide/JpegSampleValueTest.h +++ b/tests/steghide/JpegSampleValueTest.h @@ -23,23 +23,23 @@ #include "SampleValueTest.h" -class JpegSampleValue ; -class CvrStgFile ; +class JpegSampleValue; +class CvrStgFile; class JpegSampleValueTest : public SampleValueTest { - public: - JpegSampleValueTest (TestSuite* s) ; + public: + JpegSampleValueTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testDistance (void) ; - void testIsNeighbour (void) ; + void testDistance(void); + void testIsNeighbour(void); - private: - CvrStgFile *f1 ; - JpegSampleValue *sv_m1, *sv_0, *sv_1 ; - Globals gl1 ; -} ; + private: + CvrStgFile *f1; + JpegSampleValue *sv_m1, *sv_0, *sv_1; + Globals gl1; +}; #endif // ndef SH_JPEGSAMPLEVALUETEST_H diff --git a/tests/steghide/MCryptPPTest.cc b/tests/steghide/MCryptPPTest.cc index ca5f292..0d6ecf6 100644 --- a/tests/steghide/MCryptPPTest.cc +++ b/tests/steghide/MCryptPPTest.cc @@ -20,28 +20,19 @@ #include "MCryptPPTest.h" -MCryptPPTest::MCryptPPTest (TestSuite* s) - : UnitTest ("MCryptPP", s) -{ - ADDTESTCATEGORY (MCryptPPTest, testEncryption) ; - ADDTESTCATEGORY (MCryptPPTest, testDecryption) ; +MCryptPPTest::MCryptPPTest(TestSuite *s) : UnitTest("MCryptPP", s) { + ADDTESTCATEGORY(MCryptPPTest, testEncryption); + ADDTESTCATEGORY(MCryptPPTest, testDecryption); } // TODO - implement this unit test -void MCryptPPTest::testEncryption (void) -{ -} +void MCryptPPTest::testEncryption(void) {} -void MCryptPPTest::testDecryption (void) -{ -} +void MCryptPPTest::testDecryption(void) {} -bool MCryptPPTest::genericTestEncryption () -{ - // evaluate test vector +bool MCryptPPTest::genericTestEncryption() { + // evaluate test vector } -bool MCryptPPTest::genericTestDecryption () -{ -} +bool MCryptPPTest::genericTestDecryption() {} diff --git a/tests/steghide/MCryptPPTest.h b/tests/steghide/MCryptPPTest.h index d3bc05e..fc2eaea 100644 --- a/tests/steghide/MCryptPPTest.h +++ b/tests/steghide/MCryptPPTest.h @@ -24,19 +24,19 @@ #include "BitString.h" #include "MCryptPP.h" -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class MCryptPPTest : public UnitTest { - public: - MCryptPPTest (TestSuite* s) ; + public: + MCryptPPTest(TestSuite *s); - void testEncryption (void) ; - void testDecryption (void) ; + void testEncryption(void); + void testDecryption(void); - private: - bool genericTestEncryption () ; - bool genericTestDecryption () ; -} ; + private: + bool genericTestEncryption(); + bool genericTestDecryption(); +}; #endif // ndef SH_MCRYPTPPTEST_H diff --git a/tests/steghide/MHashKeyGenTest.cc b/tests/steghide/MHashKeyGenTest.cc index e63b3a3..e2205a2 100644 --- a/tests/steghide/MHashKeyGenTest.cc +++ b/tests/steghide/MHashKeyGenTest.cc @@ -24,7 +24,4 @@ #include "BitString.h" -MHashKeyGenTest::MHashKeyGenTest (TestSuite* s) - : UnitTest ("MHashKeyGen", s) -{ -} +MHashKeyGenTest::MHashKeyGenTest(TestSuite *s) : UnitTest("MHashKeyGen", s) {} diff --git a/tests/steghide/MHashKeyGenTest.h b/tests/steghide/MHashKeyGenTest.h index f0744ca..8856058 100644 --- a/tests/steghide/MHashKeyGenTest.h +++ b/tests/steghide/MHashKeyGenTest.h @@ -24,18 +24,18 @@ #include "BitString.h" #include "MHashKeyGen.h" -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class MHashKeyGenTest : public UnitTest { - public: - MHashKeyGenTest (TestSuite* s) ; + public: + MHashKeyGenTest(TestSuite *s); - private: + private: #if 0 // TODO - implement this unit test bool genericTestReference () ; #endif -} ; +}; #endif // ndef SH_MHASHKEYGENTEST_H diff --git a/tests/steghide/MHashPPTest.cc b/tests/steghide/MHashPPTest.cc index 1246993..898c1b9 100644 --- a/tests/steghide/MHashPPTest.cc +++ b/tests/steghide/MHashPPTest.cc @@ -24,71 +24,82 @@ #include "BitString.h" -MHashPPTest::MHashPPTest (TestSuite* s) - : UnitTest ("MHashPP", s) -{ - ADDTESTCATEGORY (MHashPPTest, testMD5) ; - ADDTESTCATEGORY (MHashPPTest, testCRC32) ; +MHashPPTest::MHashPPTest(TestSuite *s) : UnitTest("MHashPP", s) { + ADDTESTCATEGORY(MHashPPTest, testMD5); + ADDTESTCATEGORY(MHashPPTest, testCRC32); } -void MHashPPTest::testMD5 (void) -{ - BYTE shouldbe1[] = { 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e } ; - addTestResult (genericTestMHashPP (MHASH_MD5, BitString (std::string("")), shouldbe1)) ; - - BYTE shouldbe2[] = { 0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61 } ; - addTestResult (genericTestMHashPP (MHASH_MD5, BitString (std::string("a")), shouldbe2)) ; - - BYTE shouldbe3[] = { 0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72 } ; - addTestResult (genericTestMHashPP (MHASH_MD5, BitString (std::string("abc")), shouldbe3)) ; - - BYTE shouldbe4[] = { 0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, 0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0 } ; - addTestResult (genericTestMHashPP (MHASH_MD5, BitString (std::string("message digest")), shouldbe4)) ; - - BYTE shouldbe5[] = { 0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b } ; - addTestResult (genericTestMHashPP (MHASH_MD5, BitString (std::string("abcdefghijklmnopqrstuvwxyz")), shouldbe5)) ; - - BYTE shouldbe6[] = { 0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, 0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f } ; - addTestResult (genericTestMHashPP (MHASH_MD5, BitString (std::string("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")), shouldbe6)) ; - - BYTE shouldbe7[] = { 0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, 0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a } ; - addTestResult (genericTestMHashPP (MHASH_MD5, BitString (std::string("12345678901234567890123456789012345678901234567890123456789012345678901234567890")), shouldbe7)) ; +void MHashPPTest::testMD5(void) { + BYTE shouldbe1[] = {0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, + 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e}; + addTestResult(genericTestMHashPP(MHASH_MD5, BitString(std::string("")), shouldbe1)); + + BYTE shouldbe2[] = {0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, + 0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61}; + addTestResult(genericTestMHashPP(MHASH_MD5, BitString(std::string("a")), shouldbe2)); + + BYTE shouldbe3[] = {0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, + 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72}; + addTestResult(genericTestMHashPP(MHASH_MD5, BitString(std::string("abc")), shouldbe3)); + + BYTE shouldbe4[] = {0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, + 0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0}; + addTestResult( + genericTestMHashPP(MHASH_MD5, BitString(std::string("message digest")), shouldbe4)); + + BYTE shouldbe5[] = {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, + 0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b}; + addTestResult(genericTestMHashPP( + MHASH_MD5, BitString(std::string("abcdefghijklmnopqrstuvwxyz")), shouldbe5)); + + BYTE shouldbe6[] = {0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, + 0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f}; + addTestResult(genericTestMHashPP( + MHASH_MD5, + BitString(std::string("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")), + shouldbe6)); + + BYTE shouldbe7[] = {0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, + 0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a}; + addTestResult(genericTestMHashPP( + MHASH_MD5, + BitString(std::string("12345678901234567890123456789012345678901234567890" + "123456789012345678901234567890")), + shouldbe7)); } -void MHashPPTest::testCRC32 (void) -{ - // the test vector used by libmhash - BYTE shouldbe2[] = { 0x7F, 0xBE, 0xB0, 0x2E } ; - addTestResult (genericTestMHashPP (MHASH_CRC32, BitString(std::string("checksum")), shouldbe2)) ; +void MHashPPTest::testCRC32(void) { + // the test vector used by libmhash + BYTE shouldbe2[] = {0x7F, 0xBE, 0xB0, 0x2E}; + addTestResult(genericTestMHashPP(MHASH_CRC32, BitString(std::string("checksum")), shouldbe2)); } -bool MHashPPTest::genericTestMHashPP (hashid a, BitString data, BYTE* shouldbe) -{ - bool retval = true ; - - MHashPP hash (a) ; - hash << data << MHashPP::endhash ; - const std::vector& result = hash.getHashBytes() ; - for (unsigned short i = 0 ; i < result.size() ; i++) { - if (result[i] != shouldbe[i]) { - retval = false ; - } - } - - if (!retval) { - std::cerr << std::endl << "---" << std::endl ; - std::cerr << "genericTestMHashPP failed" << std::endl ; - std::cerr << "shouldbe: " ; - for (unsigned short i = 0 ; i < result.size() ; i++) { - std::cerr << (unsigned short) shouldbe[i] ; - } - std::cerr << std::endl << "result: " ; - for (unsigned short i = 0 ; i < result.size() ; i++) { - std::cerr << (unsigned short) result[i] ; - } - std::cerr << std::dec << std::endl ; - std::cerr << "---" << std::endl << std::endl ; - } - - return retval ; +bool MHashPPTest::genericTestMHashPP(hashid a, BitString data, BYTE *shouldbe) { + bool retval = true; + + MHashPP hash(a); + hash << data << MHashPP::endhash; + const std::vector &result = hash.getHashBytes(); + for (unsigned short i = 0; i < result.size(); i++) { + if (result[i] != shouldbe[i]) { + retval = false; + } + } + + if (!retval) { + std::cerr << std::endl << "---" << std::endl; + std::cerr << "genericTestMHashPP failed" << std::endl; + std::cerr << "shouldbe: "; + for (unsigned short i = 0; i < result.size(); i++) { + std::cerr << (unsigned short)shouldbe[i]; + } + std::cerr << std::endl << "result: "; + for (unsigned short i = 0; i < result.size(); i++) { + std::cerr << (unsigned short)result[i]; + } + std::cerr << std::dec << std::endl; + std::cerr << "---" << std::endl << std::endl; + } + + return retval; } diff --git a/tests/steghide/MHashPPTest.h b/tests/steghide/MHashPPTest.h index 519f7e3..2643294 100644 --- a/tests/steghide/MHashPPTest.h +++ b/tests/steghide/MHashPPTest.h @@ -28,29 +28,29 @@ #undef protected #include "BitString.h" -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class MHashPPTest : public UnitTest { - public: - MHashPPTest (TestSuite* s) ; - - /** - * test output of MHashPP class with MD5 algorithm against the test vectors given in RFC 1321 - **/ - void testMD5 (void) ; - - void testCRC32 (void) ; - - private: - /** - * compute a hash using MHashPP and compare it to a reference value - * \param a the hash algorithm that should be used by MHashPP - * \param data the input of the hash algorithm - * \param shouldbe the reference value of the result of the hash algorithm - * \return true iff shouldbe is the result of the hash algorithm a applied to data by MHashPP - **/ - bool genericTestMHashPP (hashid a, BitString data, BYTE* shouldbe) ; -} ; + public: + MHashPPTest(TestSuite *s); + + /** + * test output of MHashPP class with MD5 algorithm against the test vectors given in RFC 1321 + **/ + void testMD5(void); + + void testCRC32(void); + + private: + /** + * compute a hash using MHashPP and compare it to a reference value + * \param a the hash algorithm that should be used by MHashPP + * \param data the input of the hash algorithm + * \param shouldbe the reference value of the result of the hash algorithm + * \return true iff shouldbe is the result of the hash algorithm a applied to data by MHashPP + **/ + bool genericTestMHashPP(hashid a, BitString data, BYTE *shouldbe); +}; #endif // ndef SH_MHASHPPTEST_H diff --git a/tests/steghide/MatchingTest.cc b/tests/steghide/MatchingTest.cc index acd2d12..30a4eba 100644 --- a/tests/steghide/MatchingTest.cc +++ b/tests/steghide/MatchingTest.cc @@ -26,204 +26,181 @@ #include "DummyFile.h" #include "MatchingTest.h" -#define CREATEEDGEPTR(G,V1,V2) (new Edge ((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) -#define CREATEEDGEOBJ(G,V1,V2) (Edge ((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) - -MatchingTest::MatchingTest (TestSuite* s) - : UnitTest ("Matching", s) -{ - ADDTESTCATEGORY (MatchingTest, testAddRemoveEdge) ; - ADDTESTCATEGORY (MatchingTest, testAugmentingPath) ; +#define CREATEEDGEPTR(G, V1, V2) (new Edge((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) +#define CREATEEDGEOBJ(G, V1, V2) (Edge((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) + +MatchingTest::MatchingTest(TestSuite *s) : UnitTest("Matching", s) { + ADDTESTCATEGORY(MatchingTest, testAddRemoveEdge); + ADDTESTCATEGORY(MatchingTest, testAugmentingPath); } -void MatchingTest::setup () -{ - UnitTest::setup() ; - - Globs.reset() ; - std::vector > adjlist1 (4) ; - adjlist1[0].push_back(1) ; adjlist1[0].push_back(2) ; - adjlist1[1].push_back(2) ; adjlist1[1].push_back(3) ; - DummyFile::createGraph (adjlist1, &bs1, &f1, &s1) ; - g1 = new Graph (f1, *bs1, *s1) ; - m1 = new Matching (g1) ; - gl1 = Globs ; - - Globs.reset() ; - std::vector > adjlist2 (10) ; - adjlist2[0].push_back(1) ; adjlist2[0].push_back(4) ; - adjlist2[1].push_back(2) ; adjlist2[1].push_back(3) ; adjlist2[1].push_back(7) ; - adjlist2[2].push_back(3) ; adjlist2[2].push_back(4) ; adjlist2[2].push_back(5) ; adjlist2[2].push_back(6) ; - adjlist2[3].push_back(6) ; - adjlist2[4].push_back(6) ; adjlist2[4].push_back(7) ; adjlist2[4].push_back(8) ; adjlist2[4].push_back(9) ; - adjlist2[5].push_back(6) ; - adjlist2[7].push_back(8) ; - DummyFile::createGraph (adjlist2, &bs2, &f2, &s2) ; - g2 = new Graph (f2, *bs2, *s2) ; - m2 = new Matching (g2) ; - gl2 = Globs ; +void MatchingTest::setup() { + UnitTest::setup(); + + Globs.reset(); + std::vector> adjlist1(4); + adjlist1[0].push_back(1); + adjlist1[0].push_back(2); + adjlist1[1].push_back(2); + adjlist1[1].push_back(3); + DummyFile::createGraph(adjlist1, &bs1, &f1, &s1); + g1 = new Graph(f1, *bs1, *s1); + m1 = new Matching(g1); + gl1 = Globs; + + Globs.reset(); + std::vector> adjlist2(10); + adjlist2[0].push_back(1); + adjlist2[0].push_back(4); + adjlist2[1].push_back(2); + adjlist2[1].push_back(3); + adjlist2[1].push_back(7); + adjlist2[2].push_back(3); + adjlist2[2].push_back(4); + adjlist2[2].push_back(5); + adjlist2[2].push_back(6); + adjlist2[3].push_back(6); + adjlist2[4].push_back(6); + adjlist2[4].push_back(7); + adjlist2[4].push_back(8); + adjlist2[4].push_back(9); + adjlist2[5].push_back(6); + adjlist2[7].push_back(8); + DummyFile::createGraph(adjlist2, &bs2, &f2, &s2); + g2 = new Graph(f2, *bs2, *s2); + m2 = new Matching(g2); + gl2 = Globs; } -void MatchingTest::cleanup () -{ - UnitTest::cleanup() ; - - delete m1 ; - delete g1 ; - delete s1 ; - delete bs1 ; - delete f1 ; - - delete m2 ; - delete g2 ; - delete s2 ; - delete bs2 ; - delete f2 ; +void MatchingTest::cleanup() { + UnitTest::cleanup(); + + delete m1; + delete g1; + delete s1; + delete bs1; + delete f1; + + delete m2; + delete g2; + delete s2; + delete bs2; + delete f2; } -void MatchingTest::testAddRemoveEdge () -{ - { // test Matching m1 - Globs = gl1 ; - - Edge e1 = CREATEEDGEOBJ (g1, 0, 2) ; - m1->addEdge (e1) ; - addTestResult ( m1->isMatched((VertexLabel) 0) && - m1->isExposed((VertexLabel) 1) && - m1->isMatched((VertexLabel) 2) && - m1->isExposed((VertexLabel) 3)) ; - - Edge e2 = CREATEEDGEOBJ (g1, 1, 3) ; - m1->addEdge (e2) ; - addTestResult ( m1->isMatched((VertexLabel) 0) && - m1->isMatched((VertexLabel) 1) && - m1->isMatched((VertexLabel) 2) && - m1->isMatched((VertexLabel) 3)) ; - - m1->removeEdge (e1) ; - addTestResult ( m1->isExposed((VertexLabel) 0) && - m1->isMatched((VertexLabel) 1) && - m1->isExposed((VertexLabel) 2) && - m1->isMatched((VertexLabel) 3)) ; - - m1->removeEdge (e2) ; - addTestResult ( m1->isExposed((VertexLabel) 0) && - m1->isExposed((VertexLabel) 1) && - m1->isExposed((VertexLabel) 2) && - m1->isExposed((VertexLabel) 3)) ; - - } - - { // test Matching m2 - Globs = gl2 ; - - Edge e1 = CREATEEDGEOBJ (g2, 1, 7) ; - m2->addEdge (e1) ; - addTestResult ( m2->getCardinality() == 1 && - m2->includesEdge(e1)) ; - - Edge e2 = CREATEEDGEOBJ (g2, 4, 8) ; - m2->addEdge (e2) ; - addTestResult ( m2->getCardinality() == 2 && - m2->includesEdge(e1) && - m2->includesEdge(e2)) ; - - Edge e3 = CREATEEDGEOBJ (g2, 2, 6) ; - m2->addEdge (e3) ; - addTestResult ( m2->getCardinality() == 3 && - m2->includesEdge(e1) && - m2->includesEdge(e2) && - m2->includesEdge(e3)) ; - - m2->removeEdge (e2) ; - addTestResult ( m2->getCardinality() == 2 && - m2->includesEdge(e1) && - m2->includesEdge(e3)) ; - - m2->removeEdge (e1) ; - addTestResult ( m2->getCardinality() == 1 && - m2->includesEdge(e3)) ; - - m2->removeEdge (e3) ; - addTestResult ( m2->getCardinality() == 0) ; - } +void MatchingTest::testAddRemoveEdge() { + { // test Matching m1 + Globs = gl1; + + Edge e1 = CREATEEDGEOBJ(g1, 0, 2); + m1->addEdge(e1); + addTestResult(m1->isMatched((VertexLabel)0) && m1->isExposed((VertexLabel)1) && + m1->isMatched((VertexLabel)2) && m1->isExposed((VertexLabel)3)); + + Edge e2 = CREATEEDGEOBJ(g1, 1, 3); + m1->addEdge(e2); + addTestResult(m1->isMatched((VertexLabel)0) && m1->isMatched((VertexLabel)1) && + m1->isMatched((VertexLabel)2) && m1->isMatched((VertexLabel)3)); + + m1->removeEdge(e1); + addTestResult(m1->isExposed((VertexLabel)0) && m1->isMatched((VertexLabel)1) && + m1->isExposed((VertexLabel)2) && m1->isMatched((VertexLabel)3)); + + m1->removeEdge(e2); + addTestResult(m1->isExposed((VertexLabel)0) && m1->isExposed((VertexLabel)1) && + m1->isExposed((VertexLabel)2) && m1->isExposed((VertexLabel)3)); + } + + { // test Matching m2 + Globs = gl2; + + Edge e1 = CREATEEDGEOBJ(g2, 1, 7); + m2->addEdge(e1); + addTestResult(m2->getCardinality() == 1 && m2->includesEdge(e1)); + + Edge e2 = CREATEEDGEOBJ(g2, 4, 8); + m2->addEdge(e2); + addTestResult(m2->getCardinality() == 2 && m2->includesEdge(e1) && m2->includesEdge(e2)); + + Edge e3 = CREATEEDGEOBJ(g2, 2, 6); + m2->addEdge(e3); + addTestResult(m2->getCardinality() == 3 && m2->includesEdge(e1) && m2->includesEdge(e2) && + m2->includesEdge(e3)); + + m2->removeEdge(e2); + addTestResult(m2->getCardinality() == 2 && m2->includesEdge(e1) && m2->includesEdge(e3)); + + m2->removeEdge(e1); + addTestResult(m2->getCardinality() == 1 && m2->includesEdge(e3)); + + m2->removeEdge(e3); + addTestResult(m2->getCardinality() == 0); + } } -void MatchingTest::testAugmentingPath () -{ - { // test Matching m1 - Globs = gl1 ; - - std::vector augpath1 ; - augpath1.push_back (CREATEEDGEPTR (g1, 0, 1)) ; - m1->augment (augpath1) ; - addTestResult ( m1->isMatched((VertexLabel) 0) && - m1->isMatched((VertexLabel) 1) && - m1->isExposed((VertexLabel) 2) && - m1->isExposed((VertexLabel) 3)) ; - - std::vector augpath2 ; - augpath2.push_back (CREATEEDGEPTR (g1, 1, 3)) ; - augpath2.push_back (CREATEEDGEPTR (g1, 0, 1)) ; - augpath2.push_back (CREATEEDGEPTR (g1, 0, 2)) ; - m1->augment (augpath2) ; - addTestResult ( m1->isMatched((VertexLabel) 0) && - m1->isMatched((VertexLabel) 1) && - m1->isMatched((VertexLabel) 2) && - m1->isMatched((VertexLabel) 3)) ; - } - - { // test Matching m2 - Globs = gl2 ; - - Edge* e12 = CREATEEDGEPTR (g2, 1, 2) ; - Edge* e17 = CREATEEDGEPTR (g2, 1, 7) ; - Edge* e23 = CREATEEDGEPTR (g2, 2, 3) ; - Edge* e36 = CREATEEDGEPTR (g2, 3, 6) ; - Edge* e47 = CREATEEDGEPTR (g2, 4, 7) ; - Edge* e49 = CREATEEDGEPTR (g2, 4, 9) ; - Edge* e56 = CREATEEDGEPTR (g2, 5, 6) ; - - std::vector augpath1 ; - augpath1.push_back (e12) ; - m2->augment (augpath1) ; - addTestResult ( m2->getCardinality() == 1 && - m2->includesEdge(*e12)) ; - - std::vector augpath2 ; - augpath2.push_back (e17) ; - augpath2.push_back (e12) ; - augpath2.push_back (e23) ; - m2->augment (augpath2) ; - addTestResult ( m2->getCardinality() == 2 && - m2->includesEdge(*e17) && - m2->includesEdge(*e23)) ; - - std::vector augpath3 ; - augpath3.push_back (e47) ; - augpath3.push_back (e17) ; - augpath3.push_back (e12) ; - augpath3.push_back (e23) ; - augpath3.push_back (e36) ; - m2->augment (augpath3) ; - addTestResult ( m2->getCardinality() == 3 && - m2->includesEdge(*e47) && - m2->includesEdge(*e12) && - m2->includesEdge(*e36)) ; - - std::vector augpath4 ; - augpath4.push_back (e49) ; - augpath4.push_back (e47) ; - augpath4.push_back (e17) ; - augpath4.push_back (e12) ; - augpath4.push_back (e23) ; - augpath4.push_back (e36) ; - augpath4.push_back (e56) ; - m2->augment (augpath4) ; - addTestResult ( m2->getCardinality() == 4 && - m2->includesEdge(*e49) && - m2->includesEdge(*e17) && - m2->includesEdge(*e23) && - m2->includesEdge(*e56)) ; - } +void MatchingTest::testAugmentingPath() { + { // test Matching m1 + Globs = gl1; + + std::vector augpath1; + augpath1.push_back(CREATEEDGEPTR(g1, 0, 1)); + m1->augment(augpath1); + addTestResult(m1->isMatched((VertexLabel)0) && m1->isMatched((VertexLabel)1) && + m1->isExposed((VertexLabel)2) && m1->isExposed((VertexLabel)3)); + + std::vector augpath2; + augpath2.push_back(CREATEEDGEPTR(g1, 1, 3)); + augpath2.push_back(CREATEEDGEPTR(g1, 0, 1)); + augpath2.push_back(CREATEEDGEPTR(g1, 0, 2)); + m1->augment(augpath2); + addTestResult(m1->isMatched((VertexLabel)0) && m1->isMatched((VertexLabel)1) && + m1->isMatched((VertexLabel)2) && m1->isMatched((VertexLabel)3)); + } + + { // test Matching m2 + Globs = gl2; + + Edge *e12 = CREATEEDGEPTR(g2, 1, 2); + Edge *e17 = CREATEEDGEPTR(g2, 1, 7); + Edge *e23 = CREATEEDGEPTR(g2, 2, 3); + Edge *e36 = CREATEEDGEPTR(g2, 3, 6); + Edge *e47 = CREATEEDGEPTR(g2, 4, 7); + Edge *e49 = CREATEEDGEPTR(g2, 4, 9); + Edge *e56 = CREATEEDGEPTR(g2, 5, 6); + + std::vector augpath1; + augpath1.push_back(e12); + m2->augment(augpath1); + addTestResult(m2->getCardinality() == 1 && m2->includesEdge(*e12)); + + std::vector augpath2; + augpath2.push_back(e17); + augpath2.push_back(e12); + augpath2.push_back(e23); + m2->augment(augpath2); + addTestResult(m2->getCardinality() == 2 && m2->includesEdge(*e17) && + m2->includesEdge(*e23)); + + std::vector augpath3; + augpath3.push_back(e47); + augpath3.push_back(e17); + augpath3.push_back(e12); + augpath3.push_back(e23); + augpath3.push_back(e36); + m2->augment(augpath3); + addTestResult(m2->getCardinality() == 3 && m2->includesEdge(*e47) && + m2->includesEdge(*e12) && m2->includesEdge(*e36)); + + std::vector augpath4; + augpath4.push_back(e49); + augpath4.push_back(e47); + augpath4.push_back(e17); + augpath4.push_back(e12); + augpath4.push_back(e23); + augpath4.push_back(e36); + augpath4.push_back(e56); + m2->augment(augpath4); + addTestResult(m2->getCardinality() == 4 && m2->includesEdge(*e49) && + m2->includesEdge(*e17) && m2->includesEdge(*e23) && m2->includesEdge(*e56)); + } } diff --git a/tests/steghide/MatchingTest.h b/tests/steghide/MatchingTest.h index 62736c5..14f91df 100644 --- a/tests/steghide/MatchingTest.h +++ b/tests/steghide/MatchingTest.h @@ -26,30 +26,30 @@ #include "Matching.h" #undef private #undef protected -class BitString ; -class CvrStgFile ; -class Selector ; +class BitString; +class CvrStgFile; +class Selector; -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class MatchingTest : public UnitTest { - public: - MatchingTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testAddRemoveEdge (void) ; - void testAugmentingPath (void) ; - - private: - BitString *bs1, *bs2 ; - CvrStgFile *f1, *f2 ; - Selector *s1, *s2 ; - Graph *g1, *g2 ; - Matching *m1, *m2 ; - Globals gl1, gl2 ; -} ; + public: + MatchingTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testAddRemoveEdge(void); + void testAugmentingPath(void); + + private: + BitString *bs1, *bs2; + CvrStgFile *f1, *f2; + Selector *s1, *s2; + Graph *g1, *g2; + Matching *m1, *m2; + Globals gl1, gl2; +}; #endif // ndef SH_MATCHINGTEST_H diff --git a/tests/steghide/SampleValueAdjacencyListTest.cc b/tests/steghide/SampleValueAdjacencyListTest.cc index 9d7d732..9ce6cca 100644 --- a/tests/steghide/SampleValueAdjacencyListTest.cc +++ b/tests/steghide/SampleValueAdjacencyListTest.cc @@ -26,80 +26,82 @@ #include "SampleValueAdjacencyListTest.h" #include "utcommon.h" -SampleValueAdjacencyListTest::SampleValueAdjacencyListTest (TestSuite* s) - : UnitTest ("SampleValueAdjacencyList", s), DummySVAL (100) -{ - ADDTESTCATEGORY (SampleValueAdjacencyListTest, testEquality) ; - ADDTESTCATEGORY (SampleValueAdjacencyListTest, testQuicksort) ; +SampleValueAdjacencyListTest::SampleValueAdjacencyListTest(TestSuite *s) + : UnitTest("SampleValueAdjacencyList", s), DummySVAL(100) { + ADDTESTCATEGORY(SampleValueAdjacencyListTest, testEquality); + ADDTESTCATEGORY(SampleValueAdjacencyListTest, testQuicksort); } -void SampleValueAdjacencyListTest::setup () -{ - SVEmpty = std::vector (100) ; -} +void SampleValueAdjacencyListTest::setup() { SVEmpty = std::vector(100); } -void SampleValueAdjacencyListTest::testEquality () -{ - CvrStgFile *f = CvrStgFile::readFile (std::string(DATADIR) + "mulaw_std.au") ; +void SampleValueAdjacencyListTest::testEquality() { + CvrStgFile *f = CvrStgFile::readFile(std::string(DATADIR) + "mulaw_std.au"); - SampleValueAdjacencyList sval1 (2) ; - SampleValueAdjacencyList sval2 (2) ; + SampleValueAdjacencyList sval1(2); + SampleValueAdjacencyList sval2(2); - sval1[(SampleValueLabel) 0].push_back (new AuMuLawSampleValue (10)) ; - sval1[(SampleValueLabel) 0].push_back (new AuMuLawSampleValue (15)) ; - sval1[(SampleValueLabel) 0].push_back (new AuMuLawSampleValue (17)) ; - sval1[(SampleValueLabel) 1].push_back (new AuMuLawSampleValue (100)) ; - sval2[(SampleValueLabel) 0].push_back (new AuMuLawSampleValue (10)) ; - sval2[(SampleValueLabel) 0].push_back (new AuMuLawSampleValue (15)) ; - sval2[(SampleValueLabel) 0].push_back (new AuMuLawSampleValue (17)) ; - sval2[(SampleValueLabel) 1].push_back (new AuMuLawSampleValue (100)) ; + sval1[(SampleValueLabel)0].push_back(new AuMuLawSampleValue(10)); + sval1[(SampleValueLabel)0].push_back(new AuMuLawSampleValue(15)); + sval1[(SampleValueLabel)0].push_back(new AuMuLawSampleValue(17)); + sval1[(SampleValueLabel)1].push_back(new AuMuLawSampleValue(100)); + sval2[(SampleValueLabel)0].push_back(new AuMuLawSampleValue(10)); + sval2[(SampleValueLabel)0].push_back(new AuMuLawSampleValue(15)); + sval2[(SampleValueLabel)0].push_back(new AuMuLawSampleValue(17)); + sval2[(SampleValueLabel)1].push_back(new AuMuLawSampleValue(100)); - addTestResult (sval1 == sval2) ; + addTestResult(sval1 == sval2); - sval2[(SampleValueLabel) 1].push_back (new AuMuLawSampleValue (110)) ; + sval2[(SampleValueLabel)1].push_back(new AuMuLawSampleValue(110)); - addTestResult (!(sval1 == sval2)) ; + addTestResult(!(sval1 == sval2)); - delete f ; + delete f; } -void SampleValueAdjacencyListTest::testQuicksort () -{ - { - UWORD32* d = new UWORD32[2] ; - d[0] = 3 ; - d[1] = 5 ; - DummySVAL.quicksort (SVEmpty, d, 0, 1) ; - addTestResult ((d[0] == 3) && (d[1] == 5)) ; - delete[] d ; - } - - { - UWORD32* d = new UWORD32[2] ; - d[0] = 5 ; - d[1] = 3 ; - DummySVAL.quicksort (SVEmpty, d, 0, 1) ; - addTestResult ((d[0] == 3) && (d[1] == 5)) ; - delete[] d ; - } - - { - UWORD32* d = new UWORD32[3] ; - d[0] = 2 ; - d[1] = 2 ; - d[2] = 2 ; - DummySVAL.quicksort (SVEmpty, d, 0, 2) ; - addTestResult ((d[0] == 2) && (d[1] == 2) && (d[2] == 2)) ; // asserting termination - delete[] d ; - } - - { - UWORD32* d = new UWORD32[10] ; - d[0] = 3 ; d[1] = 12 ; d[2] = 8 ; d[3] = 2 ; d[4] = 22 ; - d[5] = 7 ; d[6] = 8 ; d[7] = 4 ; d[8] = 6 ; d[9] = 17 ; - DummySVAL.quicksort (SVEmpty, d, 0, 9) ; - addTestResult ((d[0] == 2) && (d[1] == 3) && (d[2] == 4) && (d[3] == 6) && (d[4] == 7) && - (d[5] == 8) && (d[6] == 8) && (d[7] == 12) && (d[8] == 17) && (d[9] == 22)) ; - delete[] d ; - } +void SampleValueAdjacencyListTest::testQuicksort() { + { + UWORD32 *d = new UWORD32[2]; + d[0] = 3; + d[1] = 5; + DummySVAL.quicksort(SVEmpty, d, 0, 1); + addTestResult((d[0] == 3) && (d[1] == 5)); + delete[] d; + } + + { + UWORD32 *d = new UWORD32[2]; + d[0] = 5; + d[1] = 3; + DummySVAL.quicksort(SVEmpty, d, 0, 1); + addTestResult((d[0] == 3) && (d[1] == 5)); + delete[] d; + } + + { + UWORD32 *d = new UWORD32[3]; + d[0] = 2; + d[1] = 2; + d[2] = 2; + DummySVAL.quicksort(SVEmpty, d, 0, 2); + addTestResult((d[0] == 2) && (d[1] == 2) && (d[2] == 2)); // asserting termination + delete[] d; + } + + { + UWORD32 *d = new UWORD32[10]; + d[0] = 3; + d[1] = 12; + d[2] = 8; + d[3] = 2; + d[4] = 22; + d[5] = 7; + d[6] = 8; + d[7] = 4; + d[8] = 6; + d[9] = 17; + DummySVAL.quicksort(SVEmpty, d, 0, 9); + addTestResult((d[0] == 2) && (d[1] == 3) && (d[2] == 4) && (d[3] == 6) && (d[4] == 7) && + (d[5] == 8) && (d[6] == 8) && (d[7] == 12) && (d[8] == 17) && (d[9] == 22)); + delete[] d; + } } diff --git a/tests/steghide/SampleValueAdjacencyListTest.h b/tests/steghide/SampleValueAdjacencyListTest.h index c42cb94..8c8789f 100644 --- a/tests/steghide/SampleValueAdjacencyListTest.h +++ b/tests/steghide/SampleValueAdjacencyListTest.h @@ -27,21 +27,21 @@ #undef private #undef protected -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class SampleValueAdjacencyListTest : public UnitTest { - public: - SampleValueAdjacencyListTest (TestSuite* s) ; + public: + SampleValueAdjacencyListTest(TestSuite *s); - void setup (void) ; + void setup(void); - void testEquality (void) ; - void testQuicksort (void) ; + void testEquality(void); + void testQuicksort(void); - private: - SampleValueAdjacencyList DummySVAL ; - std::vector SVEmpty ; -} ; + private: + SampleValueAdjacencyList DummySVAL; + std::vector SVEmpty; +}; #endif // ndef SH_SAMPLEVALUEOPPOSITENEIGHBOURHOODTEST_H diff --git a/tests/steghide/SampleValueTest.cc b/tests/steghide/SampleValueTest.cc index 523e63c..68f0906 100644 --- a/tests/steghide/SampleValueTest.cc +++ b/tests/steghide/SampleValueTest.cc @@ -23,34 +23,32 @@ #include "SampleValue.h" -bool SampleValueTest::genericTestIsNeighbour (SampleValue* s1, SampleValue* s2, bool res) -{ - bool retval = ((s1->isNeighbour(s2) == s2->isNeighbour(s1)) && (s1->isNeighbour(s2) == res)) ; - if (ArgVerbose && !retval) { - std::cerr << std::endl << "---- FAILED: genericIsNeighbour ----" << std::endl ; - std::cerr << "is: " << s1->isNeighbour(s2) << ", shouldbe: " << res << std::endl ; - std::cerr << "distance of s1 (0x" << std::hex << s1->getKey() << ") and s2 (0x" ; - std::cerr << s2->getKey() << std::dec << ") is: " << s1->calcDistance(s2) << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - return retval ; +bool SampleValueTest::genericTestIsNeighbour(SampleValue *s1, SampleValue *s2, bool res) { + bool retval = ((s1->isNeighbour(s2) == s2->isNeighbour(s1)) && (s1->isNeighbour(s2) == res)); + if (ArgVerbose && !retval) { + std::cerr << std::endl << "---- FAILED: genericIsNeighbour ----" << std::endl; + std::cerr << "is: " << s1->isNeighbour(s2) << ", shouldbe: " << res << std::endl; + std::cerr << "distance of s1 (0x" << std::hex << s1->getKey() << ") and s2 (0x"; + std::cerr << s2->getKey() << std::dec << ") is: " << s1->calcDistance(s2) << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + return retval; } -bool SampleValueTest::genericTestDistance (SampleValue* s1, SampleValue* s2, UWORD32 dist) -{ - bool retval = ((s1->calcDistance(s2) == s2->calcDistance(s1)) && (s1->calcDistance(s2) == dist)) ; - if (ArgVerbose && !retval) { - std::cerr << std::endl << "---- FAILED: genericTestDistance ----" << std::endl ; - std::cerr << "distance of s1 (0x" << std::hex << s1->getKey() << ") and s2 (0x" ; - std::cerr << s2->getKey() << std::dec << ") is: " << s1->calcDistance(s2) << std::endl ; - std::cerr << "should be: " << dist << std::endl ; - std::cerr << "-------------------------------------" << std::endl ; - } - return retval ; +bool SampleValueTest::genericTestDistance(SampleValue *s1, SampleValue *s2, UWORD32 dist) { + bool retval = + ((s1->calcDistance(s2) == s2->calcDistance(s1)) && (s1->calcDistance(s2) == dist)); + if (ArgVerbose && !retval) { + std::cerr << std::endl << "---- FAILED: genericTestDistance ----" << std::endl; + std::cerr << "distance of s1 (0x" << std::hex << s1->getKey() << ") and s2 (0x"; + std::cerr << s2->getKey() << std::dec << ") is: " << s1->calcDistance(s2) << std::endl; + std::cerr << "should be: " << dist << std::endl; + std::cerr << "-------------------------------------" << std::endl; + } + return retval; } -bool SampleValueTest::genericTestEValue (SampleValue* s, EmbValue ev) -{ - bool retval = (s->getEmbeddedValue() == ev) ; - return retval ; +bool SampleValueTest::genericTestEValue(SampleValue *s, EmbValue ev) { + bool retval = (s->getEmbeddedValue() == ev); + return retval; } diff --git a/tests/steghide/SampleValueTest.h b/tests/steghide/SampleValueTest.h index db7fa6c..29939a4 100644 --- a/tests/steghide/SampleValueTest.h +++ b/tests/steghide/SampleValueTest.h @@ -25,38 +25,38 @@ #include "UnitTest.h" -class SampleValue ; +class SampleValue; class SampleValueTest : public UnitTest { - public: - SampleValueTest (std::string n, TestSuite* s) : UnitTest(n, s) {} ; - - protected: - /** - * generic distance test - * \param s1 a sample value - * \param s2 another sample value - * \param dist this should be the distance between s1 and s2 - * \return true iff distance is commutative and return dist - **/ - bool genericTestDistance (SampleValue* s1, SampleValue* s2, UWORD32 dist) ; - - /** - * generic neighbourhood test - * \param s1 a sample value - * \param s2 another sample value - * \param res true iff they are neighbours - * \return true iff calling isNeighbour (with reflexivity) equals res - **/ - bool genericTestIsNeighbour (SampleValue* s1, SampleValue* s2, bool res) ; - - /** - * generic evalue test - * \param s a sample value - * \param ev an embedded value - * \return true iff s->getEmbeddedValue() == ev - **/ - bool genericTestEValue (SampleValue* s, EmbValue ev) ; -} ; + public: + SampleValueTest(std::string n, TestSuite *s) : UnitTest(n, s){}; + + protected: + /** + * generic distance test + * \param s1 a sample value + * \param s2 another sample value + * \param dist this should be the distance between s1 and s2 + * \return true iff distance is commutative and return dist + **/ + bool genericTestDistance(SampleValue *s1, SampleValue *s2, UWORD32 dist); + + /** + * generic neighbourhood test + * \param s1 a sample value + * \param s2 another sample value + * \param res true iff they are neighbours + * \return true iff calling isNeighbour (with reflexivity) equals res + **/ + bool genericTestIsNeighbour(SampleValue *s1, SampleValue *s2, bool res); + + /** + * generic evalue test + * \param s a sample value + * \param ev an embedded value + * \return true iff s->getEmbeddedValue() == ev + **/ + bool genericTestEValue(SampleValue *s, EmbValue ev); +}; #endif // ndef SH_SAMPLEVALUETEST_H diff --git a/tests/steghide/SelectorTest.cc b/tests/steghide/SelectorTest.cc index 93b818c..9d41a3c 100644 --- a/tests/steghide/SelectorTest.cc +++ b/tests/steghide/SelectorTest.cc @@ -25,69 +25,65 @@ #include "SelectorTest.h" #include "TestCategoryCaller.h" -SelectorTest::SelectorTest (TestSuite* s) - : UnitTest ("Selector", s) -{ - ADDTESTCATEGORY (SelectorTest, testIsPermutation) ; - ADDTESTCATEGORY (SelectorTest, testIsIdentityPermutation) ; +SelectorTest::SelectorTest(TestSuite *s) : UnitTest("Selector", s) { + ADDTESTCATEGORY(SelectorTest, testIsPermutation); + ADDTESTCATEGORY(SelectorTest, testIsIdentityPermutation); } -void SelectorTest::setup () -{ - s1 = new Selector (10, "a passphrase") ; - s2 = new Selector (50, "another passphrase") ; - s3 = new Selector (10000, "a large Selector object") ; - s4 = new Selector (128, "a smaller object again") ; - sid1 = new Selector (16) ; - sid2 = new Selector (1234) ; +void SelectorTest::setup() { + s1 = new Selector(10, "a passphrase"); + s2 = new Selector(50, "another passphrase"); + s3 = new Selector(10000, "a large Selector object"); + s4 = new Selector(128, "a smaller object again"); + sid1 = new Selector(16); + sid2 = new Selector(1234); } -void SelectorTest::cleanup () -{ - delete s1 ; delete s2 ; delete s3 ; delete s4 ; - delete sid1 ; delete sid2 ; +void SelectorTest::cleanup() { + delete s1; + delete s2; + delete s3; + delete s4; + delete sid1; + delete sid2; } -void SelectorTest::testIsPermutation () -{ - addTestResult (genericTestIsPermutation (s1)) ; - addTestResult (genericTestIsPermutation (s2)) ; - addTestResult (genericTestIsPermutation (s3)) ; - addTestResult (genericTestIsPermutation (s4)) ; +void SelectorTest::testIsPermutation() { + addTestResult(genericTestIsPermutation(s1)); + addTestResult(genericTestIsPermutation(s2)); + addTestResult(genericTestIsPermutation(s3)); + addTestResult(genericTestIsPermutation(s4)); } -void SelectorTest::testIsIdentityPermutation () -{ - addTestResult (genericTestIsIdentityPermutation (sid1)) ; - addTestResult (genericTestIsIdentityPermutation (sid2)) ; +void SelectorTest::testIsIdentityPermutation() { + addTestResult(genericTestIsIdentityPermutation(sid1)); + addTestResult(genericTestIsIdentityPermutation(sid2)); } -bool SelectorTest::genericTestIsPermutation (Selector* s) -{ - std::vector hasoccurred (s->getRange()) ; // all set to false +bool SelectorTest::genericTestIsPermutation(Selector *s) { + std::vector hasoccurred(s->getRange()); // all set to false - bool range_ok = true ; - bool inj = true ; - for (UWORD32 i = 0 ; i < s->getRange() ; i++) { - UWORD32 value = (*s)[i] ; - range_ok = (value < s->getRange()) && range_ok ; - inj = !hasoccurred[value] && inj ; - hasoccurred[value] = true ; - } + bool range_ok = true; + bool inj = true; + for (UWORD32 i = 0; i < s->getRange(); i++) { + UWORD32 value = (*s)[i]; + range_ok = (value < s->getRange()) && range_ok; + inj = !hasoccurred[value] && inj; + hasoccurred[value] = true; + } - bool surj = true ; - for (UWORD32 i = 0 ; i < s->getRange() ; i++) { - surj = hasoccurred[i] && surj ; - } + bool surj = true; + for (UWORD32 i = 0; i < s->getRange(); i++) { + surj = hasoccurred[i] && surj; + } - return range_ok && inj && surj ; + return range_ok && inj && surj; } -bool SelectorTest::genericTestIsIdentityPermutation (Selector* s) -{ - bool ok = true ; - for (UWORD32 i = 0 ; i < s->getRange() ; i++) { - ok = ((*s)[i] == i) && ok ; - } - return ok ; +bool SelectorTest::genericTestIsIdentityPermutation(Selector *s) { + bool ok = true; + for (UWORD32 i = 0; i < s->getRange(); i++) { + ok = ((*s)[i] == i) && ok; + } + return ok; } diff --git a/tests/steghide/SelectorTest.h b/tests/steghide/SelectorTest.h index 5e56706..78e7bcf 100644 --- a/tests/steghide/SelectorTest.h +++ b/tests/steghide/SelectorTest.h @@ -21,27 +21,27 @@ #ifndef SH_SELECTORTEST_H #define SH_SELECTORTEST_H -class Selector ; +class Selector; -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class SelectorTest : public UnitTest { - public: - SelectorTest (TestSuite* s) ; + public: + SelectorTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testIsPermutation (void) ; - void testIsIdentityPermutation (void) ; + void testIsPermutation(void); + void testIsIdentityPermutation(void); - private: - Selector *s1, *s2, *s3, *s4 ; - Selector *sid1, *sid2 ; + private: + Selector *s1, *s2, *s3, *s4; + Selector *sid1, *sid2; - bool genericTestIsPermutation (Selector* s) ; - bool genericTestIsIdentityPermutation (Selector* s) ; -} ; + bool genericTestIsPermutation(Selector *s); + bool genericTestIsIdentityPermutation(Selector *s); +}; #endif // ndef SH_SELECTORTEST_H diff --git a/tests/steghide/Test.h b/tests/steghide/Test.h index 97ecaee..f2d81f3 100644 --- a/tests/steghide/Test.h +++ b/tests/steghide/Test.h @@ -23,27 +23,25 @@ #include -class TestSuite ; +class TestSuite; class Test { - public: - Test (void) : Name(std::string("unnamed test")), Suite(NULL) {} ; - Test (const std::string& n) : Name(n), Suite(NULL) {} ; - Test (const std::string& n, TestSuite* s) : Name(n), Suite(s) {} ; + public: + Test(void) : Name(std::string("unnamed test")), Suite(NULL){}; + Test(const std::string &n) : Name(n), Suite(NULL){}; + Test(const std::string &n, TestSuite *s) : Name(n), Suite(s){}; - virtual ~Test (void) {} ; + virtual ~Test(void){}; - const std::string& getName (void) - { return Name ; } ; + const std::string &getName(void) { return Name; }; - TestSuite* getSuite (void) - { return Suite ; } ; + TestSuite *getSuite(void) { return Suite; }; - virtual void run (void) = 0 ; + virtual void run(void) = 0; - private: - std::string Name ; - TestSuite* Suite ; -} ; + private: + std::string Name; + TestSuite *Suite; +}; #endif // ndef SH_TEST_H diff --git a/tests/steghide/TestCategory.h b/tests/steghide/TestCategory.h index 7214e78..a7c4bf7 100644 --- a/tests/steghide/TestCategory.h +++ b/tests/steghide/TestCategory.h @@ -24,8 +24,8 @@ #include "Test.h" class TestCategory : public Test { - public: - TestCategory (const std::string& n, TestSuite* s) : Test(n, s) {} ; -} ; + public: + TestCategory(const std::string &n, TestSuite *s) : Test(n, s){}; +}; #endif // ndef SH_TESTCATEGORY_H diff --git a/tests/steghide/TestCategoryCaller.h b/tests/steghide/TestCategoryCaller.h index d3732d7..67a66e7 100644 --- a/tests/steghide/TestCategoryCaller.h +++ b/tests/steghide/TestCategoryCaller.h @@ -23,21 +23,18 @@ #include "TestCategory.h" -template class TestCategoryCaller : public TestCategory { - public: - typedef void (UTType::*TCMType)(); +template class TestCategoryCaller : public TestCategory { + public: + typedef void (UTType::*TCMType)(); - TestCategoryCaller (std::string n, TestSuite* s, UTType* o, TCMType m) - : TestCategory(n,s), UTObject(o), TestMethod(m) {} ; + TestCategoryCaller(std::string n, TestSuite *s, UTType *o, TCMType m) + : TestCategory(n, s), UTObject(o), TestMethod(m){}; - void run (void) - { - (UTObject->*TestMethod)() ; - } + void run(void) { (UTObject->*TestMethod)(); } - private: - UTType* UTObject ; - TCMType TestMethod ; -} ; + private: + UTType *UTObject; + TCMType TestMethod; +}; #endif // ndef SH_TESTCALLER_H diff --git a/tests/steghide/TestSuite.cc b/tests/steghide/TestSuite.cc index d37aeeb..adb2ad0 100644 --- a/tests/steghide/TestSuite.cc +++ b/tests/steghide/TestSuite.cc @@ -22,119 +22,99 @@ #include "TestSuite.h" -TestSuite::TestSuite() - : Test() -{ - runningUnit = "__none__" ; - runningCategory = "__none__" ; - TestNumber = 0 ; - OutStream = &std::cout ; +TestSuite::TestSuite() : Test() { + runningUnit = "__none__"; + runningCategory = "__none__"; + TestNumber = 0; + OutStream = &std::cout; } -void TestSuite::addUnitTest (UnitTest* ut) -{ - UnitTests.push_back (ut) ; -} +void TestSuite::addUnitTest(UnitTest *ut) { UnitTests.push_back(ut); } -void TestSuite::run() -{ - SuiteOk = true ; - *OutStream << "-----------------------" << std::endl << std::endl ; - *OutStream << "Running Unit Tests....." << std::endl << std::endl ; - *OutStream << "-----------------------" << std::endl << std::endl ; - for (std::vector::iterator it = UnitTests.begin() ; it != UnitTests.end() ; it++) { - (*it)->setup() ; - (*it)->run() ; - (*it)->cleanup() ; - } +void TestSuite::run() { + SuiteOk = true; + *OutStream << "-----------------------" << std::endl << std::endl; + *OutStream << "Running Unit Tests....." << std::endl << std::endl; + *OutStream << "-----------------------" << std::endl << std::endl; + for (std::vector::iterator it = UnitTests.begin(); it != UnitTests.end(); it++) { + (*it)->setup(); + (*it)->run(); + (*it)->cleanup(); + } } -void TestSuite::startUnit (std::string n) -{ - if (runningUnit == "__none__") { - *OutStream << n << ":" << std::endl ; - runningUnit = n ; - } - else { - *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl ; - } +void TestSuite::startUnit(std::string n) { + if (runningUnit == "__none__") { + *OutStream << n << ":" << std::endl; + runningUnit = n; + } else { + *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl; + } } -void TestSuite::endUnit (std::string n) -{ - if (runningUnit == n) { - *OutStream << std::endl ; - runningUnit = "__none__" ; - } - else { - *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl ; - } +void TestSuite::endUnit(std::string n) { + if (runningUnit == n) { + *OutStream << std::endl; + runningUnit = "__none__"; + } else { + *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl; + } } - -void TestSuite::startCategory (std::string n) -{ - if (runningCategory == "__none__") { - *OutStream << " " << n ; - runningCategory = n ; - runningCategoryOk = true ; - OutStream->flush() ; - } - else { - *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl ; - } +void TestSuite::startCategory(std::string n) { + if (runningCategory == "__none__") { + *OutStream << " " << n; + runningCategory = n; + runningCategoryOk = true; + OutStream->flush(); + } else { + *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl; + } } -void TestSuite::endCategory (std::string n) -{ - if (runningCategory == n) { - if (runningCategoryOk) { - *OutStream << "ok" << std::endl ; - } - else { - *OutStream << " !! FAILED !!" << std::endl ; - } - runningCategory = "__none__" ; - } - else { - *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl ; - } +void TestSuite::endCategory(std::string n) { + if (runningCategory == n) { + if (runningCategoryOk) { + *OutStream << "ok" << std::endl; + } else { + *OutStream << " !! FAILED !!" << std::endl; + } + runningCategory = "__none__"; + } else { + *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl; + } } -void TestSuite::addTestResult (bool r) -{ - if (runningUnit == "__none__" || runningCategory == "__none__") { - *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl ; - } - else { - if (r) { - *OutStream << "." ; - } - else { - *OutStream << "F" ; - SuiteOk = false ; - } - runningCategoryOk &= r ; - OutStream->flush() ; - } +void TestSuite::addTestResult(bool r) { + if (runningUnit == "__none__" || runningCategory == "__none__") { + *OutStream << "UNEXPECTED ERROR in " << __FILE__ << ":" << __LINE__ << std::endl; + } else { + if (r) { + *OutStream << "."; + } else { + *OutStream << "F"; + SuiteOk = false; + } + runningCategoryOk &= r; + OutStream->flush(); + } } -void TestSuite::addTestResult (TestSuite::TESTRESULT r) -{ - switch (r) { - case NOTINSTALLED: - *OutStream << "not installed" << std::endl ; - runningCategory = "__none__" ; - break ; +void TestSuite::addTestResult(TestSuite::TESTRESULT r) { + switch (r) { + case NOTINSTALLED: + *OutStream << "not installed" << std::endl; + runningCategory = "__none__"; + break; - case KNOWNEXCEPTION: - *OutStream << "caught known exception:" << std::endl ; - runningCategory = "__none__" ; - break ; + case KNOWNEXCEPTION: + *OutStream << "caught known exception:" << std::endl; + runningCategory = "__none__"; + break; - case UNKNOWNEXCEPTION: - *OutStream << "caugh unknown exception (!!)" << std::endl ; - runningCategory = "__none__" ; - break ; - } + case UNKNOWNEXCEPTION: + *OutStream << "caugh unknown exception (!!)" << std::endl; + runningCategory = "__none__"; + break; + } } diff --git a/tests/steghide/TestSuite.h b/tests/steghide/TestSuite.h index 1ca8908..589853c 100644 --- a/tests/steghide/TestSuite.h +++ b/tests/steghide/TestSuite.h @@ -21,48 +21,50 @@ #ifndef SH_TESTSUITE_H #define SH_TESTSUITE_H +#include #include #include -#include #include "Test.h" #include "UnitTest.h" class TestSuite : public Test { - public: - enum TESTRESULT { NOTINSTALLED, // when something that is needed for the test is not installed on the current system - KNOWNEXCEPTION, - UNKNOWNEXCEPTION } ; + public: + enum TESTRESULT { + NOTINSTALLED, // when something that is needed for the test is not installed on the current + // system + KNOWNEXCEPTION, + UNKNOWNEXCEPTION + }; - TestSuite (void) ; + TestSuite(void); - void addUnitTest (UnitTest* ut) ; + void addUnitTest(UnitTest *ut); - void run (void) ; + void run(void); - /** - * \return true iff all tests were ok - **/ - bool getResult (void) - { return SuiteOk ; } ; + /** + * \return true iff all tests were ok + **/ + bool getResult(void) { return SuiteOk; }; - // used during testing - void startUnit (std::string n) ; - void endUnit (std::string n) ; - void startCategory (std::string n) ; - void endCategory (std::string n) ; - void addTestResult (bool r) ; - void addTestResult (TESTRESULT r) ; + // used during testing + void startUnit(std::string n); + void endUnit(std::string n); + void startCategory(std::string n); + void endCategory(std::string n); + void addTestResult(bool r); + void addTestResult(TESTRESULT r); - private: - std::vector UnitTests ; + private: + std::vector UnitTests; - std::string runningUnit ; - std::string runningCategory ; - bool runningCategoryOk ; - bool SuiteOk ; - unsigned short TestNumber ; - std::ostream* OutStream ; -} ; + std::string runningUnit; + std::string runningCategory; + bool runningCategoryOk; + bool SuiteOk; + unsigned short TestNumber; + std::ostream *OutStream; +}; #endif // ndef SH_TESTSUITE_H diff --git a/tests/steghide/UnitTest.cc b/tests/steghide/UnitTest.cc index e6d7024..eeb942e 100644 --- a/tests/steghide/UnitTest.cc +++ b/tests/steghide/UnitTest.cc @@ -21,52 +21,38 @@ #include "SteghideError.h" #include "TestCategory.h" -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" -UnitTest::~UnitTest() -{ - for (std::vector::const_iterator it = TestCategories.begin() ; it != TestCategories.end() ; it++) { - delete *it ; - } +UnitTest::~UnitTest() { + for (std::vector::const_iterator it = TestCategories.begin(); + it != TestCategories.end(); it++) { + delete *it; + } } -void UnitTest::setup () -{ - GlobsBackup = Globs ; +void UnitTest::setup() { GlobsBackup = Globs; } + +void UnitTest::run() { + getSuite()->startUnit(getName()); + for (std::vector::const_iterator it = TestCategories.begin(); + it != TestCategories.end(); it++) { + getSuite()->startCategory((*it)->getName()); + try { + (*it)->run(); + } catch (SteghideError &e) { + getSuite()->addTestResult(TestSuite::KNOWNEXCEPTION); + e.printMessage(); + } catch (...) { + getSuite()->addTestResult(TestSuite::UNKNOWNEXCEPTION); + } + getSuite()->endCategory((*it)->getName()); + } + getSuite()->endUnit(getName()); } -void UnitTest::run() -{ - getSuite()->startUnit (getName()) ; - for (std::vector::const_iterator it = TestCategories.begin() ; it != TestCategories.end() ; it++) { - getSuite()->startCategory ((*it)->getName()) ; - try { - (*it)->run() ; - } - catch (SteghideError& e) { - getSuite()->addTestResult (TestSuite::KNOWNEXCEPTION) ; - e.printMessage() ; - } - catch (...) { - getSuite()->addTestResult (TestSuite::UNKNOWNEXCEPTION) ; - } - getSuite()->endCategory ((*it)->getName()) ; - } - getSuite()->endUnit (getName()) ; -} +void UnitTest::cleanup() { Globs = GlobsBackup; } -void UnitTest::cleanup () -{ - Globs = GlobsBackup ; -} +void UnitTest::addTestCategory(TestCategory *tc) { TestCategories.push_back(tc); } -void UnitTest::addTestCategory (TestCategory* tc) -{ - TestCategories.push_back (tc) ; -} - -void UnitTest::addTestResult (bool r) -{ - getSuite()->addTestResult (r) ; -} +void UnitTest::addTestResult(bool r) { getSuite()->addTestResult(r); } diff --git a/tests/steghide/UnitTest.h b/tests/steghide/UnitTest.h index b4218c9..97a5177 100644 --- a/tests/steghide/UnitTest.h +++ b/tests/steghide/UnitTest.h @@ -29,50 +29,50 @@ #include "Test.h" #include "TestCategoryCaller.h" // declared here to avoid circulating includes -class TestCategory ; -class TestSuite ; +class TestCategory; +class TestSuite; -#define ADDTESTCATEGORY(UTCLASS,CMETHOD) \ - addTestCategory (new TestCategoryCaller (strip_test(#CMETHOD), getSuite(), this, &UTCLASS::CMETHOD)) +#define ADDTESTCATEGORY(UTCLASS, CMETHOD) \ + addTestCategory(new TestCategoryCaller(strip_test(#CMETHOD), getSuite(), this, \ + &UTCLASS::CMETHOD)) class UnitTest : public Test { - public: - /** - * \param n name of this unit test (probably the name of the tested class) - **/ - UnitTest (std::string n, TestSuite* s) : Test(n,s), GlobsBackup(NULL) {} ; + public: + /** + * \param n name of this unit test (probably the name of the tested class) + **/ + UnitTest(std::string n, TestSuite *s) : Test(n, s), GlobsBackup(NULL){}; - ~UnitTest (void) ; + ~UnitTest(void); - /** - * setup the unit test - called before run - * - * UnitTest::setup will (together with UnitTest::cleanup) save and restore the object - * stored in Globs so they should be called from the corresponding functions in the - * derived object if the derived unit test manipulates the Globs object. - **/ - virtual void setup (void) ; + /** + * setup the unit test - called before run + * + * UnitTest::setup will (together with UnitTest::cleanup) save and restore the object + * stored in Globs so they should be called from the corresponding functions in the + * derived object if the derived unit test manipulates the Globs object. + **/ + virtual void setup(void); - void run (void) ; + void run(void); - /** - * cleanup the unit test - called after run - **/ - virtual void cleanup (void) ; + /** + * cleanup the unit test - called after run + **/ + virtual void cleanup(void); - protected: - void addTestCategory (TestCategory *tc) ; + protected: + void addTestCategory(TestCategory *tc); - void addTestResult (bool r) ; + void addTestResult(bool r); - char *strip_test (char* s) - { return (s + 4) ; } ; + char *strip_test(char *s) { return (s + 4); }; - private: - std::vector TestCategories ; + private: + std::vector TestCategories; - /// servers as a backup for the Globals object stored in Globs - Globals GlobsBackup ; -} ; + /// servers as a backup for the Globals object stored in Globs + Globals GlobsBackup; +}; #endif // ndef SH_UNITTEST_H diff --git a/tests/steghide/WKSConstructionHeuristicTest.cc b/tests/steghide/WKSConstructionHeuristicTest.cc index ce2295a..ed79739 100644 --- a/tests/steghide/WKSConstructionHeuristicTest.cc +++ b/tests/steghide/WKSConstructionHeuristicTest.cc @@ -28,90 +28,103 @@ #include "DummyFile.h" #include "WKSConstructionHeuristicTest.h" -#define CREATEEDGE(G,V1,V2) (new Edge ((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) +#define CREATEEDGE(G, V1, V2) (new Edge((G)->getVertex(V1), 0, (G)->getVertex(V2), 1)) -WKSConstructionHeuristicTest::WKSConstructionHeuristicTest (TestSuite* s) - : UnitTest ("WKSConstructionHeuristic", s) -{ - ADDTESTCATEGORY (WKSConstructionHeuristicTest, testAlgorithm) ; +WKSConstructionHeuristicTest::WKSConstructionHeuristicTest(TestSuite *s) + : UnitTest("WKSConstructionHeuristic", s) { + ADDTESTCATEGORY(WKSConstructionHeuristicTest, testAlgorithm); } -void WKSConstructionHeuristicTest::setup () -{ - UnitTest::setup() ; +void WKSConstructionHeuristicTest::setup() { + UnitTest::setup(); - // a trivial case to start with - { - Globs.reset() ; - std::vector > adjlist (2) ; - adjlist[0].push_back(1) ; - DummyFile::createGraph (adjlist, &bs1, &f1, &s1) ; - g1 = new Graph (f1, *bs1, *s1) ; - m1 = new Matching (g1) ; - ch1 = new WKSConstructionHeuristic (g1, m1, 100.0) ; - gl1 = Globs ; - } + // a trivial case to start with + { + Globs.reset(); + std::vector> adjlist(2); + adjlist[0].push_back(1); + DummyFile::createGraph(adjlist, &bs1, &f1, &s1); + g1 = new Graph(f1, *bs1, *s1); + m1 = new Matching(g1); + ch1 = new WKSConstructionHeuristic(g1, m1, 100.0); + gl1 = Globs; + } - // first counterexample - will not find maximum matching - { - Globs.reset() ; - std::vector > adjlist (4) ; - adjlist[0].push_back(1) ; adjlist[0].push_back(2) ; adjlist[0].push_back(3) ; - adjlist[1].push_back(2) ; adjlist[1].push_back(3) ; - DummyFile::createGraph (adjlist, &bs2, &f2, &s2) ; - g2 = new Graph (f2, *bs2, *s2) ; - m2 = new Matching (g2) ; - ch2 = new WKSConstructionHeuristic (g2, m2, 100.0) ; - gl2 = Globs ; - } + // first counterexample - will not find maximum matching + { + Globs.reset(); + std::vector> adjlist(4); + adjlist[0].push_back(1); + adjlist[0].push_back(2); + adjlist[0].push_back(3); + adjlist[1].push_back(2); + adjlist[1].push_back(3); + DummyFile::createGraph(adjlist, &bs2, &f2, &s2); + g2 = new Graph(f2, *bs2, *s2); + m2 = new Matching(g2); + ch2 = new WKSConstructionHeuristic(g2, m2, 100.0); + gl2 = Globs; + } - // will find maximum matching here because of Deg1-rule - { - Globs.reset() ; - std::vector > adjlist (4) ; - adjlist[0].push_back(1) ; adjlist[0].push_back(2) ; - adjlist[1].push_back(3) ; - DummyFile::createGraph (adjlist, &bs3, &f3, &s3) ; - g3 = new Graph (f3, *bs3, *s3) ; - m3 = new Matching (g3) ; - ch3 = new WKSConstructionHeuristic (g3, m3, 100.0) ; - gl3 = Globs ; - } + // will find maximum matching here because of Deg1-rule + { + Globs.reset(); + std::vector> adjlist(4); + adjlist[0].push_back(1); + adjlist[0].push_back(2); + adjlist[1].push_back(3); + DummyFile::createGraph(adjlist, &bs3, &f3, &s3); + g3 = new Graph(f3, *bs3, *s3); + m3 = new Matching(g3); + ch3 = new WKSConstructionHeuristic(g3, m3, 100.0); + gl3 = Globs; + } } -void WKSConstructionHeuristicTest::cleanup () -{ - UnitTest::cleanup() ; +void WKSConstructionHeuristicTest::cleanup() { + UnitTest::cleanup(); - Globs = gl1 ; delete ch1 ; delete m1 ; delete g1 ; delete s1 ; delete bs1 ; delete f1 ; - Globs = gl2 ; delete ch2 ; delete m2 ; delete g2 ; delete s2 ; delete bs2 ; delete f2 ; - Globs = gl3 ; delete ch3 ; delete m3 ; delete g3 ; delete s3 ; delete bs3 ; delete f3 ; + Globs = gl1; + delete ch1; + delete m1; + delete g1; + delete s1; + delete bs1; + delete f1; + Globs = gl2; + delete ch2; + delete m2; + delete g2; + delete s2; + delete bs2; + delete f2; + Globs = gl3; + delete ch3; + delete m3; + delete g3; + delete s3; + delete bs3; + delete f3; } -void WKSConstructionHeuristicTest::testAlgorithm () -{ - { - Globs = gl1 ; - ch1->run() ; - addTestResult ( m1->isMatched((VertexLabel) 0) && - m1->isMatched((VertexLabel) 1)) ; - } +void WKSConstructionHeuristicTest::testAlgorithm() { + { + Globs = gl1; + ch1->run(); + addTestResult(m1->isMatched((VertexLabel)0) && m1->isMatched((VertexLabel)1)); + } - { - Globs = gl2 ; - ch2->run() ; - addTestResult ( m2->isMatched((VertexLabel) 0) && - m2->isMatched((VertexLabel) 1) && - m2->isExposed((VertexLabel) 2) && - m2->isExposed((VertexLabel) 3)) ; - } + { + Globs = gl2; + ch2->run(); + addTestResult(m2->isMatched((VertexLabel)0) && m2->isMatched((VertexLabel)1) && + m2->isExposed((VertexLabel)2) && m2->isExposed((VertexLabel)3)); + } - { - Globs = gl3 ; - ch3->run() ; - addTestResult ( m3->isMatched((VertexLabel) 0) && - m3->isMatched((VertexLabel) 1) && - m3->isMatched((VertexLabel) 2) && - m3->isMatched((VertexLabel) 3)) ; - } + { + Globs = gl3; + ch3->run(); + addTestResult(m3->isMatched((VertexLabel)0) && m3->isMatched((VertexLabel)1) && + m3->isMatched((VertexLabel)2) && m3->isMatched((VertexLabel)3)); + } } diff --git a/tests/steghide/WKSConstructionHeuristicTest.h b/tests/steghide/WKSConstructionHeuristicTest.h index a5b4e34..15df287 100644 --- a/tests/steghide/WKSConstructionHeuristicTest.h +++ b/tests/steghide/WKSConstructionHeuristicTest.h @@ -21,33 +21,33 @@ #ifndef SH_WKSCONSTRUCTIONHEURISTICTEST_H #define SH_WKSCONSTRUCTIONHEURISTICTEST_H -class BitString ; -class WKSConstructionHeuristic ; -class CvrStgFile ; -class Graph ; -class Matching ; -class Selector ; +class BitString; +class WKSConstructionHeuristic; +class CvrStgFile; +class Graph; +class Matching; +class Selector; -#include "UnitTest.h" #include "TestSuite.h" +#include "UnitTest.h" class WKSConstructionHeuristicTest : public UnitTest { - public: - WKSConstructionHeuristicTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testAlgorithm (void) ; - - private: - BitString *bs1, *bs2, *bs3 ; - CvrStgFile *f1, *f2, *f3 ; - Selector *s1, *s2, *s3 ; - Graph *g1, *g2, *g3 ; - WKSConstructionHeuristic *ch1, *ch2, *ch3 ; - Matching *m1, *m2, *m3 ; - Globals gl1, gl2, gl3 ; -} ; + public: + WKSConstructionHeuristicTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testAlgorithm(void); + + private: + BitString *bs1, *bs2, *bs3; + CvrStgFile *f1, *f2, *f3; + Selector *s1, *s2, *s3; + Graph *g1, *g2, *g3; + WKSConstructionHeuristic *ch1, *ch2, *ch3; + Matching *m1, *m2, *m3; + Globals gl1, gl2, gl3; +}; #endif // ndef SH_WKSCONSTRUCTIONHEURISTICTEST_H diff --git a/tests/steghide/WavFileTest.cc b/tests/steghide/WavFileTest.cc index 42fdf37..9f2d45d 100644 --- a/tests/steghide/WavFileTest.cc +++ b/tests/steghide/WavFileTest.cc @@ -26,88 +26,95 @@ #include "WavFileTest.h" #include "utcommon.h" -WavFileTest::WavFileTest (TestSuite* s) - : CvrStgFileTest("WavFile", s) -{ - ADDTESTCATEGORY (WavFileTest, testReadWrite) ; - ADDTESTCATEGORY (WavFileTest, testReadEmbedExtract) ; - ADDTESTCATEGORY (WavFileTest, testReadEmbedWriteReadExtract) ; - ADDTESTCATEGORY (WavFileTest, testPosition) ; - ADDTESTCATEGORY (WavFileTest, testSVALCalculation) ; - ADDTESTCATEGORY (WavFileTest, testEmbeddedValue) ; +WavFileTest::WavFileTest(TestSuite *s) : CvrStgFileTest("WavFile", s) { + ADDTESTCATEGORY(WavFileTest, testReadWrite); + ADDTESTCATEGORY(WavFileTest, testReadEmbedExtract); + ADDTESTCATEGORY(WavFileTest, testReadEmbedWriteReadExtract); + ADDTESTCATEGORY(WavFileTest, testPosition); + ADDTESTCATEGORY(WavFileTest, testSVALCalculation); + ADDTESTCATEGORY(WavFileTest, testEmbeddedValue); } -void WavFileTest::setup () -{ - UnitTest::setup() ; - - Globs.reset() ; - f1 = CvrStgFile::readFile (std::string(DATADIR) + "pcm8_std.wav") ; - bs1 = new BitString (std::string ("this is a test string for the WavFile")) ; - s1 = new Selector (bs1->getLength() * f1->getSamplesPerVertex(), std::string ("a passphrase")) ; - g1 = new Graph (f1, *bs1, *s1) ; - gl1 = Globs ; - - Globs.reset() ; - f2 = CvrStgFile::readFile (std::string(DATADIR) + "pcm16_std.wav") ; - bs2 = new BitString (std::string ("this is another test - this time a little longer, but also for the WavFile unit test")) ; - s2 = new Selector (bs2->getLength() * f2->getSamplesPerVertex(), std::string ("another passphrase")) ; - g2 = new Graph (f2, *bs2, *s2) ; - gl2 = Globs ; +void WavFileTest::setup() { + UnitTest::setup(); + + Globs.reset(); + f1 = CvrStgFile::readFile(std::string(DATADIR) + "pcm8_std.wav"); + bs1 = new BitString(std::string("this is a test string for the WavFile")); + s1 = new Selector(bs1->getLength() * f1->getSamplesPerVertex(), std::string("a passphrase")); + g1 = new Graph(f1, *bs1, *s1); + gl1 = Globs; + + Globs.reset(); + f2 = CvrStgFile::readFile(std::string(DATADIR) + "pcm16_std.wav"); + bs2 = new BitString(std::string("this is another test - this time a little " + "longer, but also for the WavFile unit test")); + s2 = new Selector(bs2->getLength() * f2->getSamplesPerVertex(), + std::string("another passphrase")); + g2 = new Graph(f2, *bs2, *s2); + gl2 = Globs; } -void WavFileTest::cleanup () -{ - UnitTest::cleanup() ; - - delete g1 ; delete g2 ; - delete s1 ; delete s2 ; - delete bs1 ; delete bs2 ; - delete f1 ; delete f2 ; +void WavFileTest::cleanup() { + UnitTest::cleanup(); + + delete g1; + delete g2; + delete s1; + delete s2; + delete bs1; + delete bs2; + delete f1; + delete f2; } -void WavFileTest::testReadWrite() -{ - Globs = gl1 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "pcm8_std.wav")) ; - Globs = gl2 ; addTestResult (genericTestReadWrite (std::string(DATADIR) + "pcm16_std.wav")) ; +void WavFileTest::testReadWrite() { + Globs = gl1; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "pcm8_std.wav")); + Globs = gl2; + addTestResult(genericTestReadWrite(std::string(DATADIR) + "pcm16_std.wav")); } -void WavFileTest::testReadEmbedExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "pcm8_std.wav", *bs1)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedExtract (std::string(DATADIR) + "pcm16_std.wav", *bs2)) ; +void WavFileTest::testReadEmbedExtract() { + Globs = gl1; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "pcm8_std.wav", *bs1)); + Globs = gl2; + addTestResult(genericTestReadEmbedExtract(std::string(DATADIR) + "pcm16_std.wav", *bs2)); } -void WavFileTest::testReadEmbedWriteReadExtract() -{ - Globs = gl1 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "pcm8_std.wav", *bs2)) ; - Globs = gl2 ; addTestResult (genericTestReadEmbedWriteReadExtract (std::string(DATADIR) + "pcm16_std.wav", *bs1)) ; +void WavFileTest::testReadEmbedWriteReadExtract() { + Globs = gl1; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "pcm8_std.wav", *bs2)); + Globs = gl2; + addTestResult( + genericTestReadEmbedWriteReadExtract(std::string(DATADIR) + "pcm16_std.wav", *bs1)); } -void WavFileTest::testPosition() -{ - Globs = gl1 ; - addTestResult (genericTestPosition (f1, 0, new WavPCMSampleValue (122))) ; - addTestResult (genericTestPosition (f1, 22, new WavPCMSampleValue (127))) ; +void WavFileTest::testPosition() { + Globs = gl1; + addTestResult(genericTestPosition(f1, 0, new WavPCMSampleValue(122))); + addTestResult(genericTestPosition(f1, 22, new WavPCMSampleValue(127))); - Globs = gl2 ; - addTestResult (genericTestPosition (f2, 0, new WavPCMSampleValue (-425))) ; - addTestResult (genericTestPosition (f2, 15, new WavPCMSampleValue (136))) ; + Globs = gl2; + addTestResult(genericTestPosition(f2, 0, new WavPCMSampleValue(-425))); + addTestResult(genericTestPosition(f2, 15, new WavPCMSampleValue(136))); } -void WavFileTest::testReadExtractCompare () -{ - // TODO +void WavFileTest::testReadExtractCompare() { + // TODO } -void WavFileTest::testSVALCalculation () -{ - Globs = gl1 ; addTestResult (genericTestSVALCalculation (f1, g1)) ; - Globs = gl2 ; addTestResult (genericTestSVALCalculation (f2, g2)) ; +void WavFileTest::testSVALCalculation() { + Globs = gl1; + addTestResult(genericTestSVALCalculation(f1, g1)); + Globs = gl2; + addTestResult(genericTestSVALCalculation(f2, g2)); } -void WavFileTest::testEmbeddedValue () -{ - Globs = gl1 ; addTestResult (genericTestEmbeddedValue (f1)) ; - Globs = gl2 ; addTestResult (genericTestEmbeddedValue (f2)) ; +void WavFileTest::testEmbeddedValue() { + Globs = gl1; + addTestResult(genericTestEmbeddedValue(f1)); + Globs = gl2; + addTestResult(genericTestEmbeddedValue(f2)); } diff --git a/tests/steghide/WavFileTest.h b/tests/steghide/WavFileTest.h index d7da504..97effa2 100644 --- a/tests/steghide/WavFileTest.h +++ b/tests/steghide/WavFileTest.h @@ -26,26 +26,26 @@ #include "Selector.h" class WavFileTest : public CvrStgFileTest { - public: - WavFileTest (TestSuite* s) ; - - void setup (void) ; - void cleanup (void) ; - - void testReadWrite (void) ; - void testReadEmbedExtract (void) ; - void testReadEmbedWriteReadExtract (void) ; - void testPosition (void) ; - void testReadExtractCompare (void) ; - void testSVALCalculation (void) ; - void testEmbeddedValue (void) ; - - private: - BitString *bs1, *bs2 ; - CvrStgFile *f1, *f2 ; - Graph *g1, *g2 ; - Selector *s1, *s2 ; - Globals gl1, gl2 ; -} ; + public: + WavFileTest(TestSuite *s); + + void setup(void); + void cleanup(void); + + void testReadWrite(void); + void testReadEmbedExtract(void); + void testReadEmbedWriteReadExtract(void); + void testPosition(void); + void testReadExtractCompare(void); + void testSVALCalculation(void); + void testEmbeddedValue(void); + + private: + BitString *bs1, *bs2; + CvrStgFile *f1, *f2; + Graph *g1, *g2; + Selector *s1, *s2; + Globals gl1, gl2; +}; #endif // ndef SH_BMPWINFILETEST_H diff --git a/tests/steghide/WavPCMSampleValueTest.cc b/tests/steghide/WavPCMSampleValueTest.cc index e6cb8dd..d642036 100644 --- a/tests/steghide/WavPCMSampleValueTest.cc +++ b/tests/steghide/WavPCMSampleValueTest.cc @@ -21,65 +21,66 @@ #include "WavPCMSampleValueTest.h" #include "utcommon.h" -#include "WavPCMSampleValue.h" #include "CvrStgFile.h" +#include "WavPCMSampleValue.h" -WavPCMSampleValueTest::WavPCMSampleValueTest (TestSuite* s) - : SampleValueTest ("WavPCMSampleValue", s) -{ - ADDTESTCATEGORY (WavPCMSampleValueTest, testDistance) ; - ADDTESTCATEGORY (WavPCMSampleValueTest, testIsNeighbour) ; +WavPCMSampleValueTest::WavPCMSampleValueTest(TestSuite *s) + : SampleValueTest("WavPCMSampleValue", s) { + ADDTESTCATEGORY(WavPCMSampleValueTest, testDistance); + ADDTESTCATEGORY(WavPCMSampleValueTest, testIsNeighbour); } -void WavPCMSampleValueTest::setup () -{ - UnitTest::setup() ; +void WavPCMSampleValueTest::setup() { + UnitTest::setup(); - Globs.reset() ; - f_WavPCM8 = CvrStgFile::readFile (std::string(DATADIR) + "pcm8_std.wav") ; - sv_WavPCM8_0 = new WavPCMSampleValue (0) ; - sv_WavPCM8_1 = new WavPCMSampleValue (1) ; - sv_WavPCM8_45 = new WavPCMSampleValue (45) ; - gl_WavPCM8 = Globs ; + Globs.reset(); + f_WavPCM8 = CvrStgFile::readFile(std::string(DATADIR) + "pcm8_std.wav"); + sv_WavPCM8_0 = new WavPCMSampleValue(0); + sv_WavPCM8_1 = new WavPCMSampleValue(1); + sv_WavPCM8_45 = new WavPCMSampleValue(45); + gl_WavPCM8 = Globs; - Globs.reset() ; - f_WavPCM16 = CvrStgFile::readFile (std::string(DATADIR) + "pcm16_std.wav") ; - sv_WavPCM16_m32768 = new WavPCMSampleValue (-32768) ; - sv_WavPCM16_32767 = new WavPCMSampleValue (32767) ; - sv_WavPCM16_0 = new WavPCMSampleValue (0) ; - sv_WavPCM16_15 = new WavPCMSampleValue (15) ; - gl_WavPCM16 = Globs ; + Globs.reset(); + f_WavPCM16 = CvrStgFile::readFile(std::string(DATADIR) + "pcm16_std.wav"); + sv_WavPCM16_m32768 = new WavPCMSampleValue(-32768); + sv_WavPCM16_32767 = new WavPCMSampleValue(32767); + sv_WavPCM16_0 = new WavPCMSampleValue(0); + sv_WavPCM16_15 = new WavPCMSampleValue(15); + gl_WavPCM16 = Globs; } -void WavPCMSampleValueTest::cleanup () -{ - UnitTest::cleanup() ; +void WavPCMSampleValueTest::cleanup() { + UnitTest::cleanup(); - delete f_WavPCM8 ; delete f_WavPCM16 ; - delete sv_WavPCM8_0 ; delete sv_WavPCM8_1 ; delete sv_WavPCM8_45 ; - delete sv_WavPCM16_m32768 ; delete sv_WavPCM16_32767 ; delete sv_WavPCM16_0 ; delete sv_WavPCM16_15 ; + delete f_WavPCM8; + delete f_WavPCM16; + delete sv_WavPCM8_0; + delete sv_WavPCM8_1; + delete sv_WavPCM8_45; + delete sv_WavPCM16_m32768; + delete sv_WavPCM16_32767; + delete sv_WavPCM16_0; + delete sv_WavPCM16_15; } -void WavPCMSampleValueTest::testDistance () -{ - Globs = gl_WavPCM8 ; - addTestResult (genericTestDistance (sv_WavPCM8_0, sv_WavPCM8_1, 1)) ; - addTestResult (genericTestDistance (sv_WavPCM8_1, sv_WavPCM8_45, 44)) ; +void WavPCMSampleValueTest::testDistance() { + Globs = gl_WavPCM8; + addTestResult(genericTestDistance(sv_WavPCM8_0, sv_WavPCM8_1, 1)); + addTestResult(genericTestDistance(sv_WavPCM8_1, sv_WavPCM8_45, 44)); - Globs = gl_WavPCM16 ; - addTestResult (genericTestDistance (sv_WavPCM16_0, sv_WavPCM16_15, 15)) ; - addTestResult (genericTestDistance (sv_WavPCM16_15, sv_WavPCM16_32767, 32752)) ; - addTestResult (genericTestDistance (sv_WavPCM16_m32768, sv_WavPCM16_32767, 65535)) ; + Globs = gl_WavPCM16; + addTestResult(genericTestDistance(sv_WavPCM16_0, sv_WavPCM16_15, 15)); + addTestResult(genericTestDistance(sv_WavPCM16_15, sv_WavPCM16_32767, 32752)); + addTestResult(genericTestDistance(sv_WavPCM16_m32768, sv_WavPCM16_32767, 65535)); } -void WavPCMSampleValueTest::testIsNeighbour () -{ - Globs = gl_WavPCM8 ; - addTestResult (genericTestIsNeighbour (sv_WavPCM8_0, sv_WavPCM8_1, true)) ; - addTestResult (genericTestIsNeighbour (sv_WavPCM8_0, sv_WavPCM8_45, false)) ; +void WavPCMSampleValueTest::testIsNeighbour() { + Globs = gl_WavPCM8; + addTestResult(genericTestIsNeighbour(sv_WavPCM8_0, sv_WavPCM8_1, true)); + addTestResult(genericTestIsNeighbour(sv_WavPCM8_0, sv_WavPCM8_45, false)); - Globs = gl_WavPCM16 ; - addTestResult (genericTestIsNeighbour (sv_WavPCM16_0, sv_WavPCM16_15, true)) ; - addTestResult (genericTestIsNeighbour (sv_WavPCM16_m32768, sv_WavPCM16_0, false)) ; - addTestResult (genericTestIsNeighbour (sv_WavPCM16_m32768, sv_WavPCM16_32767, false)) ; + Globs = gl_WavPCM16; + addTestResult(genericTestIsNeighbour(sv_WavPCM16_0, sv_WavPCM16_15, true)); + addTestResult(genericTestIsNeighbour(sv_WavPCM16_m32768, sv_WavPCM16_0, false)); + addTestResult(genericTestIsNeighbour(sv_WavPCM16_m32768, sv_WavPCM16_32767, false)); } diff --git a/tests/steghide/WavPCMSampleValueTest.h b/tests/steghide/WavPCMSampleValueTest.h index e3125d2..82d9d6f 100644 --- a/tests/steghide/WavPCMSampleValueTest.h +++ b/tests/steghide/WavPCMSampleValueTest.h @@ -23,22 +23,23 @@ #include "SampleValueTest.h" -class CvrStgFile ; +class CvrStgFile; class WavPCMSampleValueTest : public SampleValueTest { - public: - WavPCMSampleValueTest (TestSuite* s) ; + public: + WavPCMSampleValueTest(TestSuite *s); - void setup (void) ; - void cleanup (void) ; + void setup(void); + void cleanup(void); - void testDistance (void) ; - void testIsNeighbour (void) ; + void testDistance(void); + void testIsNeighbour(void); - private: - CvrStgFile *f_WavPCM8, *f_WavPCM16 ; - SampleValue *sv_WavPCM8_0, *sv_WavPCM8_1, *sv_WavPCM8_45, *sv_WavPCM16_m32768, *sv_WavPCM16_32767, *sv_WavPCM16_0, *sv_WavPCM16_15 ; - Globals gl_WavPCM8, gl_WavPCM16 ; -} ; + private: + CvrStgFile *f_WavPCM8, *f_WavPCM16; + SampleValue *sv_WavPCM8_0, *sv_WavPCM8_1, *sv_WavPCM8_45, *sv_WavPCM16_m32768, + *sv_WavPCM16_32767, *sv_WavPCM16_0, *sv_WavPCM16_15; + Globals gl_WavPCM8, gl_WavPCM16; +}; #endif // ndef SH_WAVPCMSAMPLEVALUETEST_H diff --git a/tests/steghide/main.cc b/tests/steghide/main.cc index 138a318..14b41d4 100644 --- a/tests/steghide/main.cc +++ b/tests/steghide/main.cc @@ -22,142 +22,141 @@ #include "common.h" -#include "TestSuite.h" -#include "AudioSampleValueTest.h" -#include "AuFileTest.h" #include "AUtilsTest.h" +#include "AuFileTest.h" +#include "AudioSampleValueTest.h" #include "BFSAPHeuristicTest.h" #include "BitStringTest.h" #include "BmpFileTest.h" -#include "BmpRGBSampleValueTest.h" -#include "BmpPaletteSampleValueTest.h" #include "BmpOS2FileTest.h" +#include "BmpPaletteSampleValueTest.h" +#include "BmpRGBSampleValueTest.h" #include "BmpWinFileTest.h" #include "DFSAPHeuristicTest.h" #include "EdgeIteratorTest.h" #include "EmbDataTest.h" -#include "WKSConstructionHeuristicTest.h" #include "GraphTest.h" #include "JpegFileTest.h" #include "JpegSampleValueTest.h" -#include "MatchingTest.h" #include "MCryptPPTest.h" #include "MHashKeyGenTest.h" #include "MHashPPTest.h" +#include "MatchingTest.h" #include "SampleValueAdjacencyListTest.h" #include "SelectorTest.h" +#include "TestSuite.h" +#include "WKSConstructionHeuristicTest.h" #include "WavFileTest.h" #include "WavPCMSampleValueTest.h" -bool ArgVerbose ; +bool ArgVerbose; -int main (int argc, char *argv[]) -{ - ArgVerbose = false ; +int main(int argc, char *argv[]) { + ArgVerbose = false; - unsigned short argi = 1 ; - while (argi < argc) { - if (std::string(argv[argi]) == "-v" || std::string(argv[argi]) == "--verbose") { - ArgVerbose = true ; - } + unsigned short argi = 1; + while (argi < argc) { + if (std::string(argv[argi]) == "-v" || std::string(argv[argi]) == "--verbose") { + ArgVerbose = true; + } #ifdef DEBUG - else if (std::string(argv[argi]) == "--debuglevel") { - argi++ ; - unsigned int tmp = 0 ; - sscanf (argv[argi], "%u", &tmp) ; - Args.DebugLevel.setValue (tmp) ; - } + else if (std::string(argv[argi]) == "--debuglevel") { + argi++; + unsigned int tmp = 0; + sscanf(argv[argi], "%u", &tmp); + Args.DebugLevel.setValue(tmp); + } #endif - else { - std::cerr << "unknown argument: " << argv[argi] << std::endl ; - exit (EXIT_FAILURE) ; - } - argi++ ; - } + else { + std::cerr << "unknown argument: " << argv[argi] << std::endl; + exit(EXIT_FAILURE); + } + argi++; + } - TestSuite ts ; + TestSuite ts; - // basic classes - AUtilsTest at (&ts) ; - ts.addUnitTest (&at) ; + // basic classes + AUtilsTest at(&ts); + ts.addUnitTest(&at); - BitStringTest bst (&ts) ; - ts.addUnitTest (&bst) ; + BitStringTest bst(&ts); + ts.addUnitTest(&bst); - SelectorTest st (&ts) ; - ts.addUnitTest (&st) ; + SelectorTest st(&ts); + ts.addUnitTest(&st); - EmbDataTest edt (&ts) ; - ts.addUnitTest (&edt) ; + EmbDataTest edt(&ts); + ts.addUnitTest(&edt); - // mlibs - MHashPPTest mht (&ts) ; - ts.addUnitTest (&mht) ; + // mlibs + MHashPPTest mht(&ts); + ts.addUnitTest(&mht); - MHashKeyGenTest mhkgt (&ts) ; - ts.addUnitTest (&mhkgt) ; + MHashKeyGenTest mhkgt(&ts); + ts.addUnitTest(&mhkgt); - MCryptPPTest mct (&ts) ; - ts.addUnitTest (&mct) ; + MCryptPPTest mct(&ts); + ts.addUnitTest(&mct); - // SampleValues - AudioSampleValueTest asvt (&ts) ; - ts.addUnitTest (&asvt) ; + // SampleValues + AudioSampleValueTest asvt(&ts); + ts.addUnitTest(&asvt); - BmpRGBSampleValueTest rgbsvt (&ts) ; - ts.addUnitTest (&rgbsvt) ; + BmpRGBSampleValueTest rgbsvt(&ts); + ts.addUnitTest(&rgbsvt); - BmpPaletteSampleValueTest palsvt (&ts) ; - ts.addUnitTest (&palsvt) ; + BmpPaletteSampleValueTest palsvt(&ts); + ts.addUnitTest(&palsvt); - JpegSampleValueTest jsvt (&ts) ; - ts.addUnitTest (&jsvt) ; + JpegSampleValueTest jsvt(&ts); + ts.addUnitTest(&jsvt); - WavPCMSampleValueTest wavsvt (&ts) ; - ts.addUnitTest (&wavsvt) ; + WavPCMSampleValueTest wavsvt(&ts); + ts.addUnitTest(&wavsvt); - // CvrStgFiles - AuFileTest aut (&ts) ; - ts.addUnitTest (&aut) ; + // CvrStgFiles + AuFileTest aut(&ts); + ts.addUnitTest(&aut); - BmpFileTest bmpt (&ts) ; - ts.addUnitTest (&bmpt) ; + BmpFileTest bmpt(&ts); + ts.addUnitTest(&bmpt); - BmpOS2FileTest bmpot (&ts) ; - ts.addUnitTest (&bmpot) ; + BmpOS2FileTest bmpot(&ts); + ts.addUnitTest(&bmpot); - BmpWinFileTest bmpwt (&ts) ; - ts.addUnitTest (&bmpwt) ; + BmpWinFileTest bmpwt(&ts); + ts.addUnitTest(&bmpwt); - JpegFileTest jft (&ts) ; - ts.addUnitTest (&jft) ; + JpegFileTest jft(&ts); + ts.addUnitTest(&jft); - WavFileTest wt (&ts) ; - ts.addUnitTest (&wt) ; + WavFileTest wt(&ts); + ts.addUnitTest(&wt); - // graph-theoretic stuff - SampleValueAdjacencyListTest svalt (&ts) ; - ts.addUnitTest (&svalt) ; + // graph-theoretic stuff + SampleValueAdjacencyListTest svalt(&ts); + ts.addUnitTest(&svalt); - GraphTest gt (&ts) ; - ts.addUnitTest (>) ; + GraphTest gt(&ts); + ts.addUnitTest(>); - EdgeIteratorTest eitt (&ts) ; - ts.addUnitTest (&eitt) ; + EdgeIteratorTest eitt(&ts); + ts.addUnitTest(&eitt); - MatchingTest mt (&ts) ; - ts.addUnitTest (&mt) ; + MatchingTest mt(&ts); + ts.addUnitTest(&mt); - WKSConstructionHeuristicTest cht (&ts) ; - ts.addUnitTest (&cht) ; + WKSConstructionHeuristicTest cht(&ts); + ts.addUnitTest(&cht); - BFSAPHeuristicTest bfsapht (&ts) ; - ts.addUnitTest (&bfsapht) ; + BFSAPHeuristicTest bfsapht(&ts); + ts.addUnitTest(&bfsapht); - DFSAPHeuristicTest dfsapht (&ts) ; - ts.addUnitTest (&dfsapht) ; + DFSAPHeuristicTest dfsapht(&ts); + ts.addUnitTest(&dfsapht); - ts.run() ; + ts.run(); - return (ts.getResult() ? 0 : -1) ; + return (ts.getResult() ? 0 : -1); } diff --git a/tests/steghide/utcommon.h b/tests/steghide/utcommon.h index a90d472..c170eed 100644 --- a/tests/steghide/utcommon.h +++ b/tests/steghide/utcommon.h @@ -22,10 +22,10 @@ #define SH_UTCOMMON_H #define DATADIR "./data/" -#define REMOVE "rm -f" -#define COMPARE "cmp -s" +#define REMOVE "rm -f" +#define COMPARE "cmp -s" #define COPY "cp" -extern bool ArgVerbose ; +extern bool ArgVerbose; #endif // ndef SH_UTCOMMON_H