The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1159 lines
43KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace
  20. {
  21. //==============================================================================
  22. /** Allows a block of data to be accessed as a stream of OSC data.
  23. The memory is shared and will be neither copied nor owned by the OSCInputStream.
  24. This class is implementing the Open Sound Control 1.0 Specification for
  25. interpreting the data.
  26. Note: some older implementations of OSC may omit the OSC Type Tag string
  27. in OSC messages. This class will treat such OSC messages as format errors.
  28. */
  29. class OSCInputStream
  30. {
  31. public:
  32. /** Creates an OSCInputStream.
  33. @param sourceData the block of data to use as the stream's source
  34. @param sourceDataSize the number of bytes in the source data block
  35. */
  36. OSCInputStream (const void* sourceData, size_t sourceDataSize)
  37. : input (sourceData, sourceDataSize, false)
  38. {}
  39. //==============================================================================
  40. /** Returns a pointer to the source data block from which this stream is reading. */
  41. const void* getData() const noexcept { return input.getData(); }
  42. /** Returns the number of bytes of source data in the block from which this stream is reading. */
  43. size_t getDataSize() const noexcept { return input.getDataSize(); }
  44. /** Returns the current position of the stream. */
  45. uint64 getPosition() { return uint64 (input.getPosition()); }
  46. /** Attempts to set the current position of the stream. Returns true if this was successful. */
  47. bool setPosition (int64 pos) { return input.setPosition (pos); }
  48. /** Returns the total amount of data in bytes accessible by this stream. */
  49. int64 getTotalLength() { return input.getTotalLength(); }
  50. /** Returns true if the stream has no more data to read. */
  51. bool isExhausted() { return input.isExhausted(); }
  52. //==============================================================================
  53. int32 readInt32()
  54. {
  55. if (input.getNumBytesRemaining() < 4)
  56. throw OSCFormatError ("OSC input stream exhausted while reading int32");
  57. return input.readIntBigEndian();
  58. }
  59. uint64 readUint64()
  60. {
  61. if (input.getNumBytesRemaining() < 8)
  62. throw OSCFormatError ("OSC input stream exhausted while reading uint64");
  63. return (uint64) input.readInt64BigEndian();
  64. }
  65. float readFloat32()
  66. {
  67. if (input.getNumBytesRemaining() < 4)
  68. throw OSCFormatError ("OSC input stream exhausted while reading float");
  69. return input.readFloatBigEndian();
  70. }
  71. String readString()
  72. {
  73. if (input.getNumBytesRemaining() < 4)
  74. throw OSCFormatError ("OSC input stream exhausted while reading string");
  75. const size_t posBegin = (size_t) getPosition();
  76. String s (input.readString());
  77. const size_t posEnd = (size_t) getPosition();
  78. if (static_cast<const char*> (getData()) [posEnd - 1] != '\0')
  79. throw OSCFormatError ("OSC input stream exhausted before finding null terminator of string");
  80. size_t bytesRead = posEnd - posBegin;
  81. readPaddingZeros (bytesRead);
  82. return s;
  83. }
  84. MemoryBlock readBlob()
  85. {
  86. if (input.getNumBytesRemaining() < 4)
  87. throw OSCFormatError ("OSC input stream exhausted while reading blob");
  88. const size_t blobDataSize = (size_t) input.readIntBigEndian();
  89. if ((size_t) input.getNumBytesRemaining() < (blobDataSize + 3) % 4)
  90. throw OSCFormatError ("OSC input stream exhausted before reaching end of blob");
  91. MemoryBlock blob;
  92. const size_t bytesRead = input.readIntoMemoryBlock (blob, (ssize_t) blobDataSize);
  93. readPaddingZeros (bytesRead);
  94. return blob;
  95. }
  96. OSCTimeTag readTimeTag()
  97. {
  98. if (input.getNumBytesRemaining() < 8)
  99. throw OSCFormatError ("OSC input stream exhausted while reading time tag");
  100. return OSCTimeTag (uint64 (input.readInt64BigEndian()));
  101. }
  102. OSCAddress readAddress()
  103. {
  104. return OSCAddress (readString());
  105. }
  106. OSCAddressPattern readAddressPattern()
  107. {
  108. return OSCAddressPattern (readString());
  109. }
  110. //==============================================================================
  111. OSCTypeList readTypeTagString()
  112. {
  113. OSCTypeList typeList;
  114. if (input.getNumBytesRemaining() < 4)
  115. throw OSCFormatError ("OSC input stream exhausted while reading type tag string");
  116. if (input.readByte() != ',')
  117. throw OSCFormatError ("OSC input stream format error: expected type tag string");
  118. for (;;)
  119. {
  120. if (isExhausted())
  121. throw OSCFormatError ("OSC input stream exhausted while reading type tag string");
  122. const OSCType type = input.readByte();
  123. if (type == 0)
  124. break; // encountered null terminator. list is complete.
  125. if (! OSCTypes::isSupportedType (type))
  126. throw OSCFormatError ("OSC input stream format error: encountered unsupported type tag");
  127. typeList.add (type);
  128. }
  129. auto bytesRead = (size_t) typeList.size() + 2;
  130. readPaddingZeros (bytesRead);
  131. return typeList;
  132. }
  133. //==============================================================================
  134. OSCArgument readArgument (OSCType type)
  135. {
  136. switch (type)
  137. {
  138. case OSCTypes::int32: return OSCArgument (readInt32());
  139. case OSCTypes::float32: return OSCArgument (readFloat32());
  140. case OSCTypes::string: return OSCArgument (readString());
  141. case OSCTypes::blob: return OSCArgument (readBlob());
  142. default:
  143. // You supplied an invalid OSCType when calling readArgument! This should never happen.
  144. jassertfalse;
  145. throw OSCInternalError ("OSC input stream: internal error while reading message argument");
  146. }
  147. }
  148. //==============================================================================
  149. OSCMessage readMessage()
  150. {
  151. OSCAddressPattern ap = readAddressPattern();
  152. OSCTypeList types = readTypeTagString();
  153. OSCMessage msg (ap);
  154. for (auto& type : types)
  155. msg.addArgument (readArgument (type));
  156. return msg;
  157. }
  158. //==============================================================================
  159. OSCBundle readBundle (size_t maxBytesToRead = std::numeric_limits<size_t>::max())
  160. {
  161. // maxBytesToRead is only passed in here in case this bundle is a nested
  162. // bundle, so we know when to consider the next element *not* part of this
  163. // bundle anymore (but part of the outer bundle) and return.
  164. if (input.getNumBytesRemaining() < 16)
  165. throw OSCFormatError ("OSC input stream exhausted while reading bundle");
  166. if (readString() != "#bundle")
  167. throw OSCFormatError ("OSC input stream format error: bundle does not start with string '#bundle'");
  168. OSCBundle bundle (readTimeTag());
  169. size_t bytesRead = 16; // already read "#bundle" and timeTag
  170. auto pos = getPosition();
  171. while (! isExhausted() && bytesRead < maxBytesToRead)
  172. {
  173. bundle.addElement (readElement());
  174. auto newPos = getPosition();
  175. bytesRead += newPos - pos;
  176. pos = newPos;
  177. }
  178. return bundle;
  179. }
  180. //==============================================================================
  181. OSCBundle::Element readElement()
  182. {
  183. if (input.getNumBytesRemaining() < 4)
  184. throw OSCFormatError ("OSC input stream exhausted while reading bundle element size");
  185. auto elementSize = (size_t) readInt32();
  186. if (elementSize < 4)
  187. throw OSCFormatError ("OSC input stream format error: invalid bundle element size");
  188. return readElementWithKnownSize (elementSize);
  189. }
  190. //==============================================================================
  191. OSCBundle::Element readElementWithKnownSize (size_t elementSize)
  192. {
  193. if ((uint64) input.getNumBytesRemaining() < elementSize)
  194. throw OSCFormatError ("OSC input stream exhausted while reading bundle element content");
  195. auto firstContentChar = static_cast<const char*> (getData()) [getPosition()];
  196. if (firstContentChar == '/') return OSCBundle::Element (readMessageWithCheckedSize (elementSize));
  197. if (firstContentChar == '#') return OSCBundle::Element (readBundleWithCheckedSize (elementSize));
  198. throw OSCFormatError ("OSC input stream: invalid bundle element content");
  199. }
  200. private:
  201. MemoryInputStream input;
  202. //==============================================================================
  203. void readPaddingZeros (size_t bytesRead)
  204. {
  205. size_t numZeros = ~(bytesRead - 1) & 0x03;
  206. while (numZeros > 0)
  207. {
  208. if (isExhausted() || input.readByte() != 0)
  209. throw OSCFormatError ("OSC input stream format error: missing padding zeros");
  210. --numZeros;
  211. }
  212. }
  213. OSCBundle readBundleWithCheckedSize (size_t size)
  214. {
  215. auto begin = (size_t) getPosition();
  216. auto maxBytesToRead = size - 4; // we've already read 4 bytes (the bundle size)
  217. OSCBundle bundle (readBundle (maxBytesToRead));
  218. if (getPosition() - begin != size)
  219. throw OSCFormatError ("OSC input stream format error: wrong element content size encountered while reading");
  220. return bundle;
  221. }
  222. OSCMessage readMessageWithCheckedSize (size_t size)
  223. {
  224. auto begin = (size_t) getPosition();
  225. OSCMessage message (readMessage());
  226. if (getPosition() - begin != size)
  227. throw OSCFormatError ("OSC input stream format error: wrong element content size encountered while reading");
  228. return message;
  229. }
  230. };
  231. } // namespace
  232. //==============================================================================
  233. struct OSCReceiver::Pimpl : private Thread,
  234. private MessageListener
  235. {
  236. Pimpl()
  237. : Thread ("Juce OSC server"),
  238. formatErrorHandler (nullptr)
  239. {
  240. }
  241. ~Pimpl()
  242. {
  243. disconnect();
  244. }
  245. //==============================================================================
  246. bool connectToPort (int portNum)
  247. {
  248. if (! disconnect())
  249. return false;
  250. portNumber = portNum;
  251. socket = new DatagramSocket (false);
  252. if (! socket->bindToPort (portNumber))
  253. return false;
  254. startThread();
  255. return true;
  256. }
  257. bool disconnect()
  258. {
  259. if (socket != nullptr)
  260. {
  261. signalThreadShouldExit();
  262. socket->shutdown();
  263. waitForThreadToExit (10000);
  264. socket = nullptr;
  265. }
  266. return true;
  267. }
  268. //==============================================================================
  269. void addListener (Listener<MessageLoopCallback>* listenerToAdd)
  270. {
  271. listeners.add (listenerToAdd);
  272. }
  273. void addListener (Listener<RealtimeCallback>* listenerToAdd)
  274. {
  275. realtimeListeners.add (listenerToAdd);
  276. }
  277. void addListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToAdd,
  278. OSCAddress addressToMatch)
  279. {
  280. addListenerWithAddress (listenerToAdd, addressToMatch, listenersWithAddress);
  281. }
  282. void addListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToAdd,
  283. OSCAddress addressToMatch)
  284. {
  285. addListenerWithAddress (listenerToAdd, addressToMatch, realtimeListenersWithAddress);
  286. }
  287. void removeListener (Listener<MessageLoopCallback>* listenerToRemove)
  288. {
  289. listeners.remove (listenerToRemove);
  290. }
  291. void removeListener (Listener<RealtimeCallback>* listenerToRemove)
  292. {
  293. realtimeListeners.remove (listenerToRemove);
  294. }
  295. void removeListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToRemove)
  296. {
  297. removeListenerWithAddress (listenerToRemove, listenersWithAddress);
  298. }
  299. void removeListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToRemove)
  300. {
  301. removeListenerWithAddress (listenerToRemove, realtimeListenersWithAddress);
  302. }
  303. //==============================================================================
  304. struct CallbackMessage : public Message
  305. {
  306. CallbackMessage (OSCBundle::Element oscElement) : content (oscElement) {}
  307. // the payload of the message. Can be either an OSCMessage or an OSCBundle.
  308. OSCBundle::Element content;
  309. };
  310. //==============================================================================
  311. void handleBuffer (const char* data, size_t dataSize)
  312. {
  313. OSCInputStream inStream (data, dataSize);
  314. try
  315. {
  316. OSCBundle::Element content = inStream.readElementWithKnownSize (dataSize);
  317. // realtime listeners should receive the OSC content first - and immediately
  318. // on this thread:
  319. callRealtimeListeners (content);
  320. if (content.isMessage())
  321. callRealtimeListenersWithAddress (content.getMessage());
  322. // now post the message that will trigger the handleMessage callback
  323. // dealing with the non-realtime listeners.
  324. if (listeners.size() > 0 || listenersWithAddress.size() > 0)
  325. postMessage (new CallbackMessage (content));
  326. }
  327. catch (OSCFormatError)
  328. {
  329. if (formatErrorHandler != nullptr)
  330. formatErrorHandler (data, (int) dataSize);
  331. }
  332. }
  333. //==============================================================================
  334. void registerFormatErrorHandler (OSCReceiver::FormatErrorHandler handler)
  335. {
  336. formatErrorHandler = handler;
  337. }
  338. private:
  339. //==============================================================================
  340. void run() override
  341. {
  342. while (! threadShouldExit())
  343. {
  344. jassert (socket != nullptr);
  345. char buffer[oscBufferSize];
  346. socket->waitUntilReady (true, -1);
  347. if (threadShouldExit())
  348. return;
  349. auto bytesRead = (size_t) socket->read (buffer, (int) sizeof (buffer), false);
  350. if (bytesRead >= 4)
  351. handleBuffer (buffer, bytesRead);
  352. }
  353. }
  354. //==============================================================================
  355. template <typename ListenerType>
  356. void addListenerWithAddress (ListenerType* listenerToAdd,
  357. OSCAddress address,
  358. Array<std::pair<OSCAddress, ListenerType*> >& array)
  359. {
  360. for (auto& i : array)
  361. if (address == i.first && listenerToAdd == i.second)
  362. return;
  363. array.add (std::make_pair (address, listenerToAdd));
  364. }
  365. //==============================================================================
  366. template <typename ListenerType>
  367. void removeListenerWithAddress (ListenerType* listenerToRemove,
  368. Array<std::pair<OSCAddress, ListenerType*> >& array)
  369. {
  370. for (int i = 0; i < array.size(); ++i)
  371. {
  372. if (listenerToRemove == array.getReference (i).second)
  373. {
  374. // aarrgh... can't simply call array.remove (i) because this
  375. // requires a default c'tor to be present for OSCAddress...
  376. // luckily, we don't care about methods preserving element order:
  377. array.swap (i, array.size() - 1);
  378. array.removeLast();
  379. break;
  380. }
  381. }
  382. }
  383. //==============================================================================
  384. void handleMessage (const Message& msg) override
  385. {
  386. if (auto* callbackMessage = dynamic_cast<const CallbackMessage*> (&msg))
  387. {
  388. auto& content = callbackMessage->content;
  389. callListeners (content);
  390. if (content.isMessage())
  391. callListenersWithAddress (content.getMessage());
  392. }
  393. }
  394. //==============================================================================
  395. void callListeners (const OSCBundle::Element& content)
  396. {
  397. typedef OSCReceiver::Listener<OSCReceiver::MessageLoopCallback> Listener;
  398. if (content.isMessage())
  399. listeners.call (&Listener::oscMessageReceived, content.getMessage());
  400. else if (content.isBundle())
  401. listeners.call (&Listener::oscBundleReceived, content.getBundle());
  402. }
  403. void callRealtimeListeners (const OSCBundle::Element& content)
  404. {
  405. typedef OSCReceiver::Listener<OSCReceiver::RealtimeCallback> Listener;
  406. if (content.isMessage())
  407. realtimeListeners.call (&Listener::oscMessageReceived, content.getMessage());
  408. else if (content.isBundle())
  409. realtimeListeners.call (&Listener::oscBundleReceived, content.getBundle());
  410. }
  411. //==============================================================================
  412. void callListenersWithAddress (const OSCMessage& message)
  413. {
  414. for (auto& entry : listenersWithAddress)
  415. if (auto* listener = entry.second)
  416. if (message.getAddressPattern().matches (entry.first))
  417. listener->oscMessageReceived (message);
  418. }
  419. void callRealtimeListenersWithAddress (const OSCMessage& message)
  420. {
  421. for (auto& entry : realtimeListenersWithAddress)
  422. if (auto* listener = entry.second)
  423. if (message.getAddressPattern().matches (entry.first))
  424. listener->oscMessageReceived (message);
  425. }
  426. //==============================================================================
  427. ListenerList<OSCReceiver::Listener<OSCReceiver::MessageLoopCallback> > listeners;
  428. ListenerList<OSCReceiver::Listener<OSCReceiver::RealtimeCallback> > realtimeListeners;
  429. Array<std::pair<OSCAddress, OSCReceiver::ListenerWithOSCAddress<OSCReceiver::MessageLoopCallback>* > > listenersWithAddress;
  430. Array<std::pair<OSCAddress, OSCReceiver::ListenerWithOSCAddress<OSCReceiver::RealtimeCallback>* > > realtimeListenersWithAddress;
  431. ScopedPointer<DatagramSocket> socket;
  432. int portNumber = 0;
  433. OSCReceiver::FormatErrorHandler formatErrorHandler;
  434. enum { oscBufferSize = 4098 };
  435. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  436. };
  437. //==============================================================================
  438. OSCReceiver::OSCReceiver() : pimpl (new Pimpl())
  439. {
  440. }
  441. OSCReceiver::~OSCReceiver()
  442. {
  443. pimpl = nullptr;
  444. }
  445. bool OSCReceiver::connect (int portNumber)
  446. {
  447. return pimpl->connectToPort (portNumber);
  448. }
  449. bool OSCReceiver::disconnect()
  450. {
  451. return pimpl->disconnect();
  452. }
  453. void OSCReceiver::addListener (Listener<MessageLoopCallback>* listenerToAdd)
  454. {
  455. pimpl->addListener (listenerToAdd);
  456. }
  457. void OSCReceiver::addListener (Listener<RealtimeCallback>* listenerToAdd)
  458. {
  459. pimpl->addListener (listenerToAdd);
  460. }
  461. void OSCReceiver::addListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToAdd, OSCAddress addressToMatch)
  462. {
  463. pimpl->addListener (listenerToAdd, addressToMatch);
  464. }
  465. void OSCReceiver::addListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToAdd, OSCAddress addressToMatch)
  466. {
  467. pimpl->addListener (listenerToAdd, addressToMatch);
  468. }
  469. void OSCReceiver::removeListener (Listener<MessageLoopCallback>* listenerToRemove)
  470. {
  471. pimpl->removeListener (listenerToRemove);
  472. }
  473. void OSCReceiver::removeListener (Listener<RealtimeCallback>* listenerToRemove)
  474. {
  475. pimpl->removeListener (listenerToRemove);
  476. }
  477. void OSCReceiver::removeListener (ListenerWithOSCAddress<MessageLoopCallback>* listenerToRemove)
  478. {
  479. pimpl->removeListener (listenerToRemove);
  480. }
  481. void OSCReceiver::removeListener (ListenerWithOSCAddress<RealtimeCallback>* listenerToRemove)
  482. {
  483. pimpl->removeListener (listenerToRemove);
  484. }
  485. void OSCReceiver::registerFormatErrorHandler (FormatErrorHandler handler)
  486. {
  487. pimpl->registerFormatErrorHandler (handler);
  488. }
  489. //==============================================================================
  490. //==============================================================================
  491. #if JUCE_UNIT_TESTS
  492. class OSCInputStreamTests : public UnitTest
  493. {
  494. public:
  495. OSCInputStreamTests() : UnitTest ("OSCInputStream class") {}
  496. void runTest()
  497. {
  498. beginTest ("reading OSC addresses");
  499. {
  500. const char buffer[16] = {
  501. '/', 't', 'e', 's', 't', '/', 'f', 'a',
  502. 'd', 'e', 'r', '7', '\0', '\0', '\0', '\0' };
  503. // reading a valid osc address:
  504. {
  505. OSCInputStream inStream (buffer, sizeof (buffer));
  506. OSCAddress address = inStream.readAddress();
  507. expect (inStream.getPosition() == sizeof (buffer));
  508. expectEquals (address.toString(), String ("/test/fader7"));
  509. }
  510. // check various possible failures:
  511. {
  512. // zero padding is present, but size is not modulo 4:
  513. OSCInputStream inStream (buffer, 15);
  514. expectThrowsType (inStream.readAddress(), OSCFormatError)
  515. }
  516. {
  517. // zero padding is missing:
  518. OSCInputStream inStream (buffer, 12);
  519. expectThrowsType (inStream.readAddress(), OSCFormatError)
  520. }
  521. {
  522. // pattern does not start with a forward slash:
  523. OSCInputStream inStream (buffer + 4, 12);
  524. expectThrowsType (inStream.readAddress(), OSCFormatError)
  525. }
  526. }
  527. beginTest ("reading OSC address patterns");
  528. {
  529. const char buffer[20] = {
  530. '/', '*', '/', '*', 'p', 'u', 't', '/',
  531. 'f', 'a', 'd', 'e', 'r', '[', '0', '-',
  532. '9', ']', '\0', '\0' };
  533. // reading a valid osc address pattern:
  534. {
  535. OSCInputStream inStream (buffer, sizeof (buffer));
  536. expectDoesNotThrow (inStream.readAddressPattern());
  537. }
  538. {
  539. OSCInputStream inStream (buffer, sizeof (buffer));
  540. OSCAddressPattern ap = inStream.readAddressPattern();
  541. expect (inStream.getPosition() == sizeof (buffer));
  542. expectEquals (ap.toString(), String ("/*/*put/fader[0-9]"));
  543. expect (ap.containsWildcards());
  544. }
  545. // check various possible failures:
  546. {
  547. // zero padding is present, but size is not modulo 4:
  548. OSCInputStream inStream (buffer, 19);
  549. expectThrowsType (inStream.readAddressPattern(), OSCFormatError)
  550. }
  551. {
  552. // zero padding is missing:
  553. OSCInputStream inStream (buffer, 16);
  554. expectThrowsType (inStream.readAddressPattern(), OSCFormatError)
  555. }
  556. {
  557. // pattern does not start with a forward slash:
  558. OSCInputStream inStream (buffer + 4, 16);
  559. expectThrowsType (inStream.readAddressPattern(), OSCFormatError)
  560. }
  561. }
  562. beginTest ("reading OSC time tags");
  563. {
  564. char buffer[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
  565. OSCInputStream inStream (buffer, sizeof (buffer));
  566. OSCTimeTag tag = inStream.readTimeTag();
  567. expect (tag.isImmediately());
  568. }
  569. {
  570. char buffer[8] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  571. OSCInputStream inStream (buffer, sizeof (buffer));
  572. OSCTimeTag tag = inStream.readTimeTag();
  573. expect (! tag.isImmediately());
  574. }
  575. beginTest ("reading OSC arguments");
  576. {
  577. // test data:
  578. int testInt = -2015;
  579. const uint8 testIntRepresentation[] = { 0xFF, 0xFF, 0xF8, 0x21 }; // big endian two's complement
  580. float testFloat = 345.6125f;
  581. const uint8 testFloatRepresentation[] = { 0x43, 0xAC, 0xCE, 0x66 }; // big endian IEEE 754
  582. String testString = "Hello, World!";
  583. const char testStringRepresentation[] = {
  584. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  585. 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0' }; // padded to size % 4 == 0
  586. const uint8 testBlobData[] = { 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  587. const MemoryBlock testBlob (testBlobData, sizeof (testBlobData));
  588. const uint8 testBlobRepresentation[] = {
  589. 0x00, 0x00, 0x00, 0x05,
  590. 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00 }; // size prefixed + padded to size % 4 == 0
  591. // read:
  592. {
  593. {
  594. // int32:
  595. OSCInputStream inStream (testIntRepresentation, sizeof (testIntRepresentation));
  596. OSCArgument arg = inStream.readArgument (OSCTypes::int32);
  597. expect (inStream.getPosition() == 4);
  598. expect (arg.isInt32());
  599. expectEquals (arg.getInt32(), testInt);
  600. }
  601. {
  602. // float32:
  603. OSCInputStream inStream (testFloatRepresentation, sizeof (testFloatRepresentation));
  604. OSCArgument arg = inStream.readArgument (OSCTypes::float32);
  605. expect (inStream.getPosition() == 4);
  606. expect (arg.isFloat32());
  607. expectEquals (arg.getFloat32(), testFloat);
  608. }
  609. {
  610. // string:
  611. OSCInputStream inStream (testStringRepresentation, sizeof (testStringRepresentation));
  612. OSCArgument arg = inStream.readArgument (OSCTypes::string);
  613. expect (inStream.getPosition() == sizeof (testStringRepresentation));
  614. expect (arg.isString());
  615. expectEquals (arg.getString(), testString);
  616. }
  617. {
  618. // blob:
  619. OSCInputStream inStream (testBlobRepresentation, sizeof (testBlobRepresentation));
  620. OSCArgument arg = inStream.readArgument (OSCTypes::blob);
  621. expect (inStream.getPosition() == sizeof (testBlobRepresentation));
  622. expect (arg.isBlob());
  623. expect (arg.getBlob() == testBlob);
  624. }
  625. }
  626. // read invalid representations:
  627. {
  628. // not enough bytes
  629. {
  630. const uint8 rawData[] = { 0xF8, 0x21 };
  631. OSCInputStream inStream (rawData, sizeof (rawData));
  632. expectThrowsType (inStream.readArgument (OSCTypes::int32), OSCFormatError);
  633. expectThrowsType (inStream.readArgument (OSCTypes::float32), OSCFormatError);
  634. }
  635. // test string not being padded to multiple of 4 bytes:
  636. {
  637. const char rawData[] = {
  638. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  639. 'o', 'r', 'l', 'd', '!', '\0' }; // padding missing
  640. OSCInputStream inStream (rawData, sizeof (rawData));
  641. expectThrowsType (inStream.readArgument (OSCTypes::string), OSCFormatError);
  642. }
  643. {
  644. const char rawData[] = {
  645. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  646. 'o', 'r', 'l', 'd', '!', '\0', 'x', 'x' }; // padding with non-zero chars
  647. OSCInputStream inStream (rawData, sizeof (rawData));
  648. expectThrowsType (inStream.readArgument (OSCTypes::string), OSCFormatError);
  649. }
  650. // test blob not being padded to multiple of 4 bytes:
  651. {
  652. const uint8 rawData[] = { 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; // padding missing
  653. OSCInputStream inStream (rawData, sizeof (rawData));
  654. expectThrowsType (inStream.readArgument (OSCTypes::blob), OSCFormatError);
  655. }
  656. // test blob having wrong size
  657. {
  658. const uint8 rawData[] = { 0x00, 0x00, 0x00, 0x12, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  659. OSCInputStream inStream (rawData, sizeof (rawData));
  660. expectThrowsType (inStream.readArgument (OSCTypes::blob), OSCFormatError);
  661. }
  662. }
  663. }
  664. beginTest ("reading OSC messages (type tag string)");
  665. {
  666. {
  667. // valid empty message
  668. const char data[] = {
  669. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  670. ',', '\0', '\0', '\0' };
  671. OSCInputStream inStream (data, sizeof (data));
  672. OSCMessage msg = inStream.readMessage();
  673. expect (msg.getAddressPattern().toString() == "/test");
  674. expect (msg.size() == 0);
  675. }
  676. {
  677. // invalid message: no type tag string
  678. const char data[] = {
  679. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  680. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
  681. 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0' };
  682. OSCInputStream inStream (data, sizeof (data));
  683. expectThrowsType (inStream.readMessage(), OSCFormatError);
  684. }
  685. {
  686. // invalid message: no type tag string and also empty
  687. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0' };
  688. OSCInputStream inStream (data, sizeof (data));
  689. expectThrowsType (inStream.readMessage(), OSCFormatError);
  690. }
  691. // invalid message: wrong padding
  692. {
  693. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0', ',', '\0', '\0', '\0' };
  694. OSCInputStream inStream (data, sizeof (data) - 1);
  695. expectThrowsType (inStream.readMessage(), OSCFormatError);
  696. }
  697. // invalid message: says it contains an arg, but doesn't
  698. {
  699. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0', ',', 'i', '\0', '\0' };
  700. OSCInputStream inStream (data, sizeof (data));
  701. expectThrowsType (inStream.readMessage(), OSCFormatError);
  702. }
  703. // invalid message: binary size does not match size deducted from type tag string
  704. {
  705. const char data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0', ',', 'i', 'f', '\0' };
  706. OSCInputStream inStream (data, sizeof (data));
  707. expectThrowsType (inStream.readMessage(), OSCFormatError);
  708. }
  709. }
  710. beginTest ("reading OSC messages (contents)");
  711. {
  712. // valid non-empty message.
  713. {
  714. int32 testInt = -2015;
  715. float testFloat = 345.6125f;
  716. String testString = "Hello, World!";
  717. const uint8 testBlobData[] = { 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  718. const MemoryBlock testBlob (testBlobData, sizeof (testBlobData));
  719. uint8 data[] = {
  720. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  721. ',', 'i', 'f', 's', 'b', '\0', '\0', '\0',
  722. 0xFF, 0xFF, 0xF8, 0x21,
  723. 0x43, 0xAC, 0xCE, 0x66,
  724. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  725. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00
  726. };
  727. OSCInputStream inStream (data, sizeof (data));
  728. OSCMessage msg = inStream.readMessage();
  729. expectEquals (msg.getAddressPattern().toString(), String ("/test"));
  730. expectEquals (msg.size(), 4);
  731. expectEquals (msg[0].getType(), OSCTypes::int32);
  732. expectEquals (msg[1].getType(), OSCTypes::float32);
  733. expectEquals (msg[2].getType(), OSCTypes::string);
  734. expectEquals (msg[3].getType(), OSCTypes::blob);
  735. expectEquals (msg[0].getInt32(), testInt);
  736. expectEquals (msg[1].getFloat32(), testFloat);
  737. expectEquals (msg[2].getString(), testString);
  738. expect (msg[3].getBlob() == testBlob);
  739. }
  740. }
  741. beginTest ("reading OSC messages (handling of corrupted messages)");
  742. {
  743. // invalid messages
  744. {
  745. OSCInputStream inStream (nullptr, 0);
  746. expectThrowsType (inStream.readMessage(), OSCFormatError);
  747. }
  748. {
  749. const uint8 data[] = { 0x00 };
  750. OSCInputStream inStream (data, 0);
  751. expectThrowsType (inStream.readMessage(), OSCFormatError);
  752. }
  753. {
  754. uint8 data[] = {
  755. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  756. ',', 'i', 'f', 's', 'b', // type tag string not padded
  757. 0xFF, 0xFF, 0xF8, 0x21,
  758. 0x43, 0xAC, 0xCE, 0x66,
  759. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  760. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00
  761. };
  762. OSCInputStream inStream (data, sizeof (data));
  763. expectThrowsType (inStream.readMessage(), OSCFormatError);
  764. }
  765. {
  766. uint8 data[] = {
  767. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  768. ',', 'i', 'f', 's', 'b', '\0', '\0', '\0',
  769. 0xFF, 0xFF, 0xF8, 0x21,
  770. 0x43, 0xAC, 0xCE, 0x66,
  771. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0' // rest of message cut off
  772. };
  773. OSCInputStream inStream (data, sizeof (data));
  774. expectThrowsType (inStream.readMessage(), OSCFormatError);
  775. }
  776. }
  777. beginTest ("reading OSC messages (handling messages without type tag strings)");
  778. {
  779. {
  780. uint8 data[] = { '/', 't', 'e', 's', 't', '\0', '\0', '\0' };
  781. OSCInputStream inStream (data, sizeof (data));
  782. expectThrowsType (inStream.readMessage(), OSCFormatError);
  783. }
  784. {
  785. uint8 data[] = {
  786. '/', 't', 'e', 's', 't', '\0', '\0', '\0',
  787. 0xFF, 0xFF, 0xF8, 0x21,
  788. 0x43, 0xAC, 0xCE, 0x66,
  789. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  790. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00
  791. };
  792. OSCInputStream inStream (data, sizeof (data));
  793. expectThrowsType (inStream.readMessage(), OSCFormatError);
  794. }
  795. }
  796. beginTest ("reading OSC bundles");
  797. {
  798. // valid bundle (empty)
  799. {
  800. uint8 data[] = {
  801. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  802. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
  803. };
  804. OSCInputStream inStream (data, sizeof (data));
  805. OSCBundle bundle = inStream.readBundle();
  806. expect (bundle.getTimeTag().isImmediately());
  807. expect (bundle.size() == 0);
  808. }
  809. // valid bundle (containing both messages and other bundles)
  810. {
  811. int32 testInt = -2015;
  812. float testFloat = 345.6125f;
  813. String testString = "Hello, World!";
  814. const uint8 testBlobData[] = { 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  815. const MemoryBlock testBlob (testBlobData, sizeof (testBlobData));
  816. uint8 data[] = {
  817. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  818. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  819. 0x00, 0x00, 0x00, 0x34,
  820. '/', 't', 'e', 's', 't', '/', '1', '\0',
  821. ',', 'i', 'f', 's', 'b', '\0', '\0', '\0',
  822. 0xFF, 0xFF, 0xF8, 0x21,
  823. 0x43, 0xAC, 0xCE, 0x66,
  824. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0',
  825. 0x00, 0x00, 0x00, 0x05, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x00, 0x00,
  826. 0x00, 0x00, 0x00, 0x0C,
  827. '/', 't', 'e', 's', 't', '/', '2', '\0',
  828. ',', '\0', '\0', '\0',
  829. 0x00, 0x00, 0x00, 0x10,
  830. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  831. 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
  832. };
  833. OSCInputStream inStream (data, sizeof (data));
  834. OSCBundle bundle = inStream.readBundle();
  835. expect (bundle.getTimeTag().isImmediately());
  836. expect (bundle.size() == 3);
  837. OSCBundle::Element* elements = bundle.begin();
  838. expect (elements[0].isMessage());
  839. expect (elements[0].getMessage().getAddressPattern().toString() == "/test/1");
  840. expect (elements[0].getMessage().size() == 4);
  841. expect (elements[0].getMessage()[0].isInt32());
  842. expect (elements[0].getMessage()[1].isFloat32());
  843. expect (elements[0].getMessage()[2].isString());
  844. expect (elements[0].getMessage()[3].isBlob());
  845. expectEquals (elements[0].getMessage()[0].getInt32(), testInt);
  846. expectEquals (elements[0].getMessage()[1].getFloat32(), testFloat);
  847. expectEquals (elements[0].getMessage()[2].getString(), testString);
  848. expect (elements[0].getMessage()[3].getBlob() == testBlob);
  849. expect (elements[1].isMessage());
  850. expect (elements[1].getMessage().getAddressPattern().toString() == "/test/2");
  851. expect (elements[1].getMessage().size() == 0);
  852. expect (elements[2].isBundle());
  853. expect (! elements[2].getBundle().getTimeTag().isImmediately());
  854. }
  855. // invalid bundles.
  856. {
  857. uint8 data[] = {
  858. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  859. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  860. 0x00, 0x00, 0x00, 0x34, // wrong bundle element size (too large)
  861. '/', 't', 'e', 's', 't', '/', '1', '\0',
  862. ',', 's', '\0', '\0',
  863. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0'
  864. };
  865. OSCInputStream inStream (data, sizeof (data));
  866. expectThrowsType (inStream.readBundle(), OSCFormatError);
  867. }
  868. {
  869. uint8 data[] = {
  870. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  871. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  872. 0x00, 0x00, 0x00, 0x08, // wrong bundle element size (too small)
  873. '/', 't', 'e', 's', 't', '/', '1', '\0',
  874. ',', 's', '\0', '\0',
  875. 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0', '\0', '\0'
  876. };
  877. OSCInputStream inStream (data, sizeof (data));
  878. expectThrowsType (inStream.readBundle(), OSCFormatError);
  879. }
  880. {
  881. uint8 data[] = {
  882. '#', 'b', 'u', 'n', 'd', 'l', 'e', '\0',
  883. 0x00, 0x00, 0x00, 0x00 // incomplete time tag
  884. };
  885. OSCInputStream inStream (data, sizeof (data));
  886. expectThrowsType (inStream.readBundle(), OSCFormatError);
  887. }
  888. {
  889. uint8 data[] = {
  890. '#', 'b', 'u', 'n', 'x', 'l', 'e', '\0', // wrong initial string
  891. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  892. };
  893. OSCInputStream inStream (data, sizeof (data));
  894. expectThrowsType (inStream.readBundle(), OSCFormatError);
  895. }
  896. {
  897. uint8 data[] = {
  898. '#', 'b', 'u', 'n', 'd', 'l', 'e', // padding missing from string
  899. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  900. };
  901. OSCInputStream inStream (data, sizeof (data));
  902. expectThrowsType (inStream.readBundle(), OSCFormatError);
  903. }
  904. }
  905. }
  906. };
  907. static OSCInputStreamTests OSCInputStreamUnitTests;
  908. #endif // JUCE_UNIT_TESTS